tensor_utils.cpp 66.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include "megbrain/common.h"
#include "megbrain/dtype.h"
#include "megbrain/imperative/ops/autogen.h"
#include "megbrain/imperative/ops/backward_graph.h"
#include "megbrain/imperative/ops/utility.h"
#include "megbrain/imperative/profiler.h"
#include "megbrain/imperative/transformations/eval.h"
#include "megbrain/imperative/transformations/lazy.h"
#include "megbrain/imperative/transformations/scalar.h"
#include "megbrain/imperative/transformations/symbol.h"
#include "megbrain/imperative/transformations/trace.h"
#include "megbrain/imperative/utils/map.h"
#include "megbrain/opr/io.h"
#include "megbrain/plugin/profiler.h"

#include "./common.h"
#include "./grad.h"
#include "./graph_rt.h"
#include "./helper.h"
#include "./module_trace.h"
#include "./numpy_dtypes.h"
#include "./tensor.h"
#include "./tensor_utils.h"
#include "./transformation.h"

#include <object.h>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/pytypes.h>
#include <pyerrors.h>
#include <range/v3/all.hpp>
#include <string>

#include <unordered_map>

#include "../../src/impl/mgb_cg_impl.h"

namespace py = pybind11;
namespace views = ranges::views;

namespace mgb::imperative::python {

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
/* ============== convert inputs ============== */

// map numpy.dtype.kind to priority
inline uint8_t category_priority(char c) {
    switch (c) {
        case 'f':
            return 3;  // floating-point
        case 'i':
            return 2;  // signed integer
        case 'u':
            return 2;  // unsigned integer
        case 'b':
            return 1;  // boolean
        default:
            return 0;
    }
}

// Returns the maximum value of the priority of each type in the list `types`.
uint8_t max_priority(SmallVector<PyArray_Descr*> types) {
    if (types.size() == 0) {
        return 0;
    } else {
        uint8_t max_p = 0;
        for (auto&& desc : types) {
            max_p = std::max(max_p, category_priority(desc->kind));
        }
        return max_p;
    }
}

// Returns the data type with sufficient size to hold all types of
// category `cat` in the list `types`.
PyArray_Descr* promote_types(SmallVector<PyArray_Descr*> types, uint8_t cat) {
    // Return value: New reference
    SmallVector<PyArray_Descr*> used_types;
    for (auto&& desc : types) {
        auto&& v = category_priority(desc->kind);
        if (v == cat) {
            used_types.emplace_back(desc);
        }
    }
    mgb_assert(used_types.size() > 0, "size of used_types is 0");
    PyArray_Descr* res = used_types[0];
    Py_INCREF(res);

    for (size_t i = 1; i < used_types.size(); ++i) {
        PyArray_Descr* tmp = PyArray_PromoteTypes(used_types[i], res);
        Py_DECREF(res);
        res = tmp;
    }
    return res;
}

PyArray_Descr* scalar2dtype(PyObject* arg) {
    // Return value: New reference
    if (PyBool_Check(arg)) {
        auto&& descr = PyArray_DescrFromType(NPY_BOOL);
        return descr;
    }
    if (PyLong_CheckExact(arg)) {
        auto&& descr = PyArray_DescrFromType(NPY_INT32);
        return descr;
    }
    if (PyFloat_CheckExact(arg)) {
        auto&& descr = PyArray_DescrFromType(NPY_FLOAT32);
        return descr;
    }
    return nullptr;
}

PyArray_Descr* _dtype_promotion(PyObject* const* args, size_t nargs) {
    // Return value: New reference
    SmallVector<PyArray_Descr*> tensors;
    SmallVector<PyArray_Descr*> scalars;

    bool is_tuple = false;
    PyObject* tuple = nullptr;
    if (nargs == 1 && (PyTuple_Check(args[0]) || PyList_Check(args[0]))) {
        if (PyList_Check(args[0])) {
            tuple = PyList_AsTuple(args[0]);
        } else {
            tuple = args[0];
            Py_INCREF(tuple);
        }
        nargs = PyTuple_Size(tuple);
        is_tuple = true;
    }

    for (size_t i = 0; i < nargs; ++i) {
        PyObject* handle = is_tuple ? PyTuple_GetItem(tuple, i) : args[i];
        if (handle == Py_None)
            continue;
        TensorWrapper* tw = TensorWrapper::try_cast(handle);
        if (tw) {
            mgb::DType type = tw->m_tensor->dtype();
            auto&& descr = npy::dtype_mgb2np_descr(type);
            Py_INCREF(descr.get());
            tensors.emplace_back(descr.get());
        } else {
            if (PyArray_Check(handle) || PyArray_CheckScalar(handle)) {
                auto&& descr = PyArray_DescrFromObject(handle, nullptr);
                tensors.emplace_back(descr);
                continue;
            }

            PyArray_Descr* descr = scalar2dtype(handle);
            if (descr) {
                scalars.emplace_back(descr);
                continue;
            }
        }
    }

    auto max_pri_scalars = max_priority(scalars);
    auto max_pri_tensors = max_priority(tensors);

    if (max_pri_scalars <= 0 && max_pri_tensors <= 0) {
        throw py::value_error("invalid input, no dtype avaliable");
    }
    PyArray_Descr* res;
    if (max_pri_scalars > max_pri_tensors) {
        res = promote_types(scalars, max_pri_scalars);
    } else {
        res = promote_types(tensors, max_pri_tensors);
    }
    for (auto* p : tensors) {
        Py_DECREF(p);
    }
    for (auto* p : scalars) {
        Py_DECREF(p);
    }
    Py_XDECREF(tuple);
    return res;
}

179 180
// if all the inputs are not megengine tensor, return get_default_device()
// else check whether all input tensors have the same device
181 182 183
CompNode _get_device(PyObject* const* args, size_t nargs) {
    bool is_tuple = false;
    PyObject* tuple = nullptr;
184
    // convert input args to a tuple
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    if (nargs == 1 && (PyTuple_Check(args[0]) || PyList_Check(args[0]))) {
        if (PyList_Check(args[0])) {
            tuple = PyList_AsTuple(args[0]);
        } else {
            tuple = args[0];
            Py_INCREF(tuple);
        }
        nargs = PyTuple_Size(tuple);
        is_tuple = true;
    }
    bool valid = false;
    CompNode cn;
    for (size_t i = 0; i < nargs; ++i) {
        PyObject* handle = is_tuple ? PyTuple_GetItem(tuple, i) : args[i];
        TensorWrapper* tw = TensorWrapper::try_cast(handle);

201
        if (tw) {
202
            if (!valid) {
203
                cn = tw->m_tensor->comp_node();
204 205
                valid = true;
            } else {
206
                CompNode cn1 = tw->m_tensor->comp_node();
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                if (cn1 != cn) {
                    throw py::value_error(ssprintf(
                            "ambiguous device: %s (from %s) vs %s (from %s)",
                            cn.to_string().c_str(), cn.to_string_logical().c_str(),
                            cn1.to_string().c_str(), cn1.to_string_logical().c_str()));
                }
            }
        }
    }
    if (!valid) {
        return CompNode::load(get_default_device());
    }
    Py_XDECREF(tuple);
    return cn;
}

// Returns the dtype that would result from performing an arithmetic
// operation on the provided input tensors and scalars.
PyObject* dtype_promotion(PyObject* self, PyObject* const* args, size_t nargs) {
    if (!nargs) {
        PyErr_SetString(PyExc_TypeError, "empty input is not allowed");
        return nullptr;
    }
    try {
        PyArray_Descr* res = _dtype_promotion(args, nargs);
        return py::cast(npy::dtype_np2mgb_descr(res)).release().ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

PyObject* get_device(PyObject* self, PyObject* const* args, size_t nargs) {
    if (!nargs) {
        PyErr_SetString(PyExc_TypeError, "empty input is not allowed");
        return nullptr;
    }
    try {
        CompNode cn = _get_device(args, nargs);
        return py::cast(cn).release().ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
bool is_scalar(PyObject* tensor) {
    auto* tw = TensorWrapper::try_cast(tensor);
    if (tw) {
        return tw->m_tensor->is_scalar();
    }
    return PyArray_CheckAnyScalar(tensor);
}

bool is_bool_list(PyObject* arg) {
    if (!PyList_Check(arg)) {
        return false;
    }
    size_t sz = PyList_Size(arg);
    if (!sz) {
        return false;
    }
    for (size_t i = 0; i < sz; ++i) {
        PyObject* handle = PyList_GetItem(arg, i);
        if (!PyBool_Check(handle)) {
            return false;
        }
    }
    return true;
}

bool is_bool_dtype(PyObject* args) {
    if (!PyObject_HasAttrString(args, "dtype"))
        return false;
    PyObject* dobj = PyObject_GetAttrString(args, "dtype");
    PyArray_Descr* dtype;
    PyArray_DescrConverter(dobj, &dtype);
    bool ret = (dtype->kind == 'b');
    Py_XDECREF(dtype);
    Py_XDECREF(dobj);
    return ret;
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
py::object device2obj(py::handle device, bool mapping = false) {
    if (device.ptr() == Py_None) {
        return py::cast(CompNode::load(get_default_device()));
    } else if (py::isinstance<py::str>(device)) {
        if (mapping) {
            py::object dmap = getattr(
                    py::reinterpret_borrow<py::object>((PyObject*)py_tensor_type),
                    "dmap_callback");
            if (dmap.ptr() != Py_None) {
                return device2obj(dmap(device), false);
            }
        }
        return py::cast(CompNode::load(device.cast<std::string>()));

    } else if (py::isinstance<CompNode>(device)) {
        return py::reinterpret_borrow<py::object>(device);
    } else {
        return getattr(device, "_cn");
    }
}

307
py::object _Const(py::handle value, py::handle dtype, py::handle device) {
308 309 310 311 312 313 314 315 316 317 318 319
    py::object val = py::reinterpret_borrow<py::object>(value);
    if (PyArray_Check(value.ptr())) {
        py::tuple strides =
                py::reinterpret_borrow<py::tuple>(getattr(value, "strides"));
        bool need_squeeze = false;
        for (size_t i = 0; i < strides.size(); ++i) {
            if (strides[i].cast<ptrdiff_t>() == 0) {
                need_squeeze = true;
            }
        }
        if (need_squeeze) {
            val = py::reinterpret_borrow<py::array>(value);
320
            py::object orig_shp = val.attr("shape");
321
            val = val.attr("squeeze")();
322
            val = val.attr("reshape")(orig_shp);
323 324
        }
    }
325
    py::object device_obj = device2obj(device, true);
326 327
    py::tuple tup =
            py::make_tuple(val, dtype, device_obj, true, false, py::none(), py::none());
328 329 330 331 332 333 334
    return TensorWrapper::make(py_tensor_type, tup.ptr(), nullptr);
}

py::tuple _make_shape_tuple(py::handle shape) {
    py::list orig;
    py::list ret(0);
    auto solve_one = [&](py::handle val) {
335
        if (TensorWrapper::try_cast(val.ptr())) {
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
            py::object np = getattr(val, "numpy")();
            PyArrayObject* arr = (PyArrayObject*)np.ptr();
            PyObject* maybe_list = PyArray_ToList(arr);
            if (PyList_Check(maybe_list)) {
                py::list may = py::reinterpret_steal<py::list>(maybe_list);
                for (size_t i = 0; i < may.size(); ++i) {
                    ret.append(may[i]);
                }
            } else {
                mgb_assert(PyLong_Check(maybe_list));
                ret.append(PyLong_AsLong(maybe_list));
                Py_XDECREF(maybe_list);
            }
        } else if (PyArray_Check(val.ptr())) {
            ret.append(PyArray_PyIntAsInt(val.ptr()));
        } else {
            ret.append(PyLong_AsLong(val.ptr()));
        }
    };
    if (PyArray_Check(shape.ptr()) && !PyArray_CheckAnyScalar(shape.ptr())) {
        orig = py::reinterpret_steal<py::list>(
                PyArray_ToList((PyArrayObject*)shape.ptr()));
        for (size_t i = 0; i < orig.size(); ++i) {
            solve_one(orig[i]);
        }
    } else if (PyList_Check(shape.ptr())) {
        orig = py::reinterpret_borrow<py::list>(shape);
        for (size_t i = 0; i < orig.size(); ++i) {
            solve_one(orig[i]);
        }
    } else if (PyTuple_Check(shape.ptr())) {
        py::tuple tup = py::reinterpret_borrow<py::tuple>(shape);
        for (size_t i = 0; i < tup.size(); ++i) {
            solve_one(tup[i]);
        }
    } else {
        solve_one(shape);
    }
    return py::reinterpret_steal<py::tuple>(PyList_AsTuple(ret.ptr()));
}

377 378
bool is_tensor(py::handle arg) {
    return bool(TensorWrapper::try_cast(arg.ptr()));
379 380 381
}

bool is_py_sequence(py::handle arg) {
382
    if (PyArray_Check(arg.ptr()) || TensorWrapper::try_cast(arg.ptr())) {
383 384 385 386 387
        return false;
    }
    return PySequence_Check(arg.ptr());
}

388 389 390 391 392 393 394 395 396 397 398
py::object get_res_by_refhdl(
        py::handle value, py::handle dtype, py::handle device, py::handle ref_hdl) {
    py::object res = _Const(value, dtype, device);
    py::object ref;
    if (py::isinstance<py::tuple>(ref_hdl)) {
        py::tuple tup = py::reinterpret_borrow<py::tuple>(ref_hdl);
        if (tup.size()) {
            ref = tup[0];
        } else {
            ref = py::none();
        }
399
    } else {
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
        ref = py::reinterpret_borrow<py::object>(ref_hdl);
    }
    if (PyObject_TypeCheck(ref.ptr(), py_varnode_type)) {
        ComputingGraph* graph = getattr(ref, "graph").cast<ComputingGraph*>();
        cg::VarNode* node = getattr(ref, "var").cast<cg::VarNode*>();
        CompNode cn;
        if (device.ptr() == Py_None) {
            cn = node->comp_node();
        } else {
            cn = device2obj(device).cast<CompNode>();
        }
        OperatorNodeConfig config(cn);
        auto hv = npy::np2tensor(
                value.ptr(), npy::Meth::borrow(cn), dtype.cast<mgb::DType>());
        auto typeobj = ref.get_type();
        return typeobj(opr::ImmutableTensor::make(*graph, hv, config).node());
416
    }
417 418 419 420 421 422
    return res;
}

mgb::DType _get_dtype(py::handle tensor) {
    auto tw = TensorWrapper::try_cast(tensor.ptr());
    return tw->m_tensor->dtype();
423 424 425 426
}

py::object _astype_cpp(py::handle tensor, py::handle dtype_hdl) {
    PyArray_Descr* descr;
427
    py::object ret;
428 429 430 431 432
    if (!PyArray_DescrConverter(dtype_hdl.ptr(), &descr)) {
        throw py::value_error(ssprintf(
                "can not convert to numpy.dtype from %s",
                dtype_hdl.ptr()->ob_type->tp_name));
    }
433 434
    auto&& cur = npy::dtype_mgb2np_descr(_get_dtype(tensor));
    if (!dtype_equal(cur.get(), descr)) {
435 436
        std::shared_ptr<OpDef> op = TypeCvt::make(npy::dtype_np2mgb_descr(descr));
        py::object Op = py::cast(op);
437
        PyObject* p[2] = {Op.ptr(), tensor.ptr()};
438 439
        py::tuple apply_res = py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
        ret = apply_res[0];
440
    } else {
441
        ret = py::reinterpret_borrow<py::object>(tensor);
442
    }
443 444
    Py_DECREF(descr);
    return ret;
445 446 447 448
}

py::object _convert_single_value_cpp(
        py::handle value, py::handle dtype, py::handle device) {
449
    if (is_tensor(value)) {
450 451 452 453
        if (_get_dtype(value).category() != DTypeCategory::QUANTIZED) {
            return _astype_cpp(value, dtype);
        }
    } else {
454
        return _Const(value, dtype, device);
455 456 457 458 459 460 461 462 463 464 465 466 467
    }
    return py::reinterpret_borrow<py::object>(value);
}

py::object _convert_inputs_cpp(
        PyObject* const* args, size_t nargs, py::object dtype, py::object device) {
    ComputingGraph* graph = nullptr;
    py::handle typeobj;
    py::list lis;
    for (size_t i = 0; i < nargs; ++i) {
        py::handle h = py::handle(args[i]);
        lis.append(h);
    }
468

469
    auto convert = [&](py::object value) {
470
        if (value.is_none()) {
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
            return value;
        }
        return _convert_single_value_cpp(value, dtype, device);
    };
    for (size_t i = 0; i < lis.size(); ++i) {
        lis[i] = convert(lis[i]);
    }
    return py::reinterpret_steal<py::tuple>(PyList_AsTuple(lis.ptr()));
}

py::object _astensor1d_cpp(
        py::handle value, py::handle dtype, py::handle device, py::handle ref) {
    py::object ret;
    py::object device_obj = py::none();
    py::object ndim_obj = py::none();
    if (device.ptr() != Py_None) {
        device_obj = device2obj(device);
    }
489 490

    if (PyObject_TypeCheck(value.ptr(), py_varnode_type)) {
491 492 493 494 495 496 497 498 499 500 501
        try {
            getattr(value, "ndim");
        } catch (py::error_already_set& err) {
            if (dtype.ptr() != Py_None) {
                ret = _astype_cpp(value, dtype);
            } else {
                ret = py::reinterpret_borrow<py::object>(value);
            }
            if (device.ptr() != Py_None) {
                std::shared_ptr<OpDef> op = Copy::make(device_obj.cast<CompNode>());
                py::object Op = py::cast(op);
502 503 504
                PyObject* p[2] = {Op.ptr(), ret.ptr()};
                py::tuple copy_ret =
                        py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
505 506 507 508 509
                return copy_ret[0];
            }
            return ret;
        }
    }
510

511 512 513 514 515 516
    size_t ndim = 999;
    if (hasattr(value, "ndim")) {
        ndim = getattr(value, "ndim").cast<size_t>();
        if (ndim != 0 && ndim != 1) {
            throw py::value_error("ndim != 1 or 0, get : " + std::to_string(ndim));
        }
517 518
        if (!is_tensor(value)) {
            return get_res_by_refhdl(value, dtype, device, ref);
519 520 521 522 523 524 525 526 527 528
        } else {
            return py::reinterpret_borrow<py::object>(value);
        }
    }
    if (!is_py_sequence(value)) {
        throw py::type_error();
    }
    py::list lis = py::reinterpret_steal<py::list>(PySequence_List(value.ptr()));
    bool need_concat = false;
    for (size_t i = 0; i < lis.size(); ++i) {
529
        if (is_tensor(lis[i])) {
530 531 532 533 534
            need_concat = true;
            break;
        }
    }
    if (!need_concat) {
535
        return get_res_by_refhdl(value, dtype, device, ref);
536 537
    }
    if (lis.size() > 1) {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        py::list flat_list;
        for (auto item : lis) {
            if (!PyList_Check(item.ptr())) {
                flat_list.append(item);
            } else {
                py::list sub_lis =
                        py::reinterpret_steal<py::list>(PySequence_List(item.ptr()));
                for (auto sub_item : sub_lis) {
                    flat_list.append(sub_item);
                }
            }
        }
        std::vector<PyObject*> c_args(flat_list.size() + 1);
        for (size_t i = 0; i < flat_list.size(); ++i) {
            c_args[i] = flat_list[i].ptr();
553
        }
554
        c_args[flat_list.size()] = Py_None;
555 556
        py::tuple inp_tup = py::reinterpret_steal<py::tuple>(
                convert_inputs_cpp(NULL, c_args.data(), c_args.size()));
557
        if (device_obj.is_none()) {
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
            std::vector<PyObject*> inp(inp_tup.size());
            for (size_t i = 0; i < inp_tup.size(); ++i) {
                inp[i] = inp_tup[i].ptr();
            }
            device_obj = py::cast(_get_device(inp.data(), inp.size()));
        }
        std::shared_ptr<OpDef> op = Concat::make(0, device_obj.cast<CompNode>());
        py::object Op = py::cast(op);
        std::vector<PyObject*> p;
        p.resize(inp_tup.size() + 1);
        p[0] = Op.ptr();
        for (size_t i = 0; i < inp_tup.size(); ++i) {
            p[i + 1] = inp_tup[i].ptr();
        }
        py::tuple concat_ret =
                py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
        ret = concat_ret[0];
    } else {
        ret = lis[0];
    }
    if (dtype.ptr() != Py_None) {
        return _astype_cpp(ret, dtype);
    } else {
        return ret;
    }
}

585
py::object _get_index(py::object tensor, py::object src) {
586
    if (!TensorWrapper::try_cast(tensor.ptr())) {
587
        auto get_const = [&](mgb::DType dtype) -> py::object {
588
            return _Const(tensor, py::cast(dtype), src.attr("device"));
589 590 591 592 593 594 595 596 597 598 599 600 601 602
        };
        if (is_bool_list(tensor.ptr()) || is_bool_dtype(tensor.ptr())) {
            tensor = get_const(dtype::Bool());
        } else {
            tensor = get_const(dtype::Int32());
        }
        if (!is_bool_dtype(tensor.ptr())) {
            return tensor;
        }
    } else {
        if (!is_bool_dtype(tensor.ptr())) {
            return tensor;
        }
    }
603
    std::shared_ptr<OpDef> op = CondTake::make();
604
    py::object Op = py::cast(op);
605 606
    PyObject* p[3] = {Op.ptr(), tensor.ptr(), tensor.ptr()};
    py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 3));
607 608 609 610 611 612 613 614 615 616 617 618 619 620
    return ret[1];
}

py::tuple _try_cond_take(py::handle tensor, py::handle index) {
    if (!hasattr(index, "dtype") || !hasattr(index, "shape")) {
        return py::tuple();
    }
    if (!is_bool_dtype(index.ptr()) ||
        _make_shape_tuple(getattr(index, "shape"))
                .not_equal(_make_shape_tuple(getattr(tensor, "shape")))) {
        return py::tuple();
    }
    py::object iobj;
    if (PyArray_Check(index.ptr())) {
621 622
        iobj = _Const(
                index, py::cast((mgb::DType)dtype::Bool()), getattr(tensor, "device"));
623 624 625
    } else {
        iobj = py::reinterpret_borrow<py::object>(index);
    }
626
    std::shared_ptr<OpDef> op = CondTake::make();
627
    py::object Op = py::cast(op);
628 629
    PyObject* p[3] = {Op.ptr(), tensor.ptr(), iobj.ptr()};
    py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 3));
630 631 632 633 634 635 636 637 638 639
    return ret;
}

py::tuple _remove_ellipsis(py::object tensor, py::tuple tuple_val) {
    size_t tuple_size = tuple_val.size();
    size_t ndim_sum = 0, cur_sum = 0;
    int pos = -1;
    bool has_unknown_ndim_bool_index = false;
    for (size_t i = 0; i < tuple_size; ++i) {
        py::object handle = tuple_val[i];
640 641 642
        if (handle.is_none()) {
            continue;
        } else if (handle.ptr() == Py_Ellipsis) {
643 644 645 646 647 648 649 650 651 652 653
            pos = static_cast<int>(i);
            for (size_t j = 0; j < i; ++j) {
                py::object t = tuple_val[j];
                if (t.ptr() == Py_Ellipsis) {
                    throw py::index_error("only one ellipsis is allowed.");
                }
            }
        } else {
            size_t ndim_incr = 1;
            if (hasattr(handle, "dtype") && is_bool_dtype(handle.ptr()) &&
                hasattr(handle, "ndim")) {
654 655 656 657 658 659
                py::object ndim;
                try {
                    ndim = getattr(handle, "ndim");
                } catch (py::error_already_set& err) {
                    has_unknown_ndim_bool_index = true;
                }
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
                if (PyLong_Check(ndim.ptr())) {
                    ndim_incr = PyLong_AsLong(ndim.ptr());
                } else {
                    has_unknown_ndim_bool_index = true;
                }
            }
            cur_sum += ndim_incr;
        }
    }
    if (pos == -1) {
        return tuple_val;
    } else {
        if (has_unknown_ndim_bool_index) {
            throw py::index_error(
                    "does not support bool index with unknown shape when using "
                    "Ellipsis.");
        }
        try {
            ndim_sum = getattr(tensor, "ndim").cast<size_t>();
        } catch (py::error_already_set& err) {
            throw py::index_error(
                    "does not support Ellipsis when tensor's ndim is unknown.");
        }
        py::tuple ret(ndim_sum - cur_sum + tuple_size - 1);
        size_t idx = 0;
        for (size_t i = 0; i < tuple_size; ++i) {
            if (i == pos) {
                for (size_t j = cur_sum; j < ndim_sum; ++j) {
                    ret[idx++] = PySlice_New(NULL, NULL, NULL);
                }
            } else {
                ret[idx++] = tuple_val[i];
            }
        }
        return ret;
    }
}

698 699
py::object _reshape_cpp(py::handle inp_hdl, py::handle args);

700 701 702 703 704 705
py::tuple _expand_bool_dim(py::object tensor, py::tuple tuple_val) {
    py::tuple cur_shape = _make_shape_tuple(py::handle(getattr(tensor, "shape")));
    py::list new_tuple_val(0);

    size_t offset = 0;
    size_t tdim = 0;
706
    size_t nonedim = 0;
707 708
    for (size_t i = 0; i < tuple_val.size(); ++i) {
        py::handle k = tuple_val[i];
709 710 711 712 713
        if (k.ptr() == Py_None) {
            nonedim++;
            new_tuple_val.append(k);
            continue;
        }
714 715 716 717 718 719 720 721
        if (is_bool_dtype(k.ptr())) {
            size_t ndim = getattr(k, "ndim").cast<size_t>();
            if (ndim > 1) {
                py::tuple ishape = _make_shape_tuple(py::handle(getattr(k, "shape")));
                for (size_t j = 0; j < ndim; ++j) {
                    if (cur_shape[tdim + j - offset].cast<size_t>() !=
                        ishape[j].cast<size_t>()) {
                        std::string msg =
722 723
                                "boolean index did not match tensor along "
                                "dimension " +
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
                                std::to_string(tdim + j) + "; dimension is " +
                                std::to_string(
                                        cur_shape[tdim + j - offset].cast<size_t>()) +
                                " but corresponding boolean dimension is " +
                                std::to_string(ishape[j].cast<size_t>());
                        throw py::index_error(msg.c_str());
                    }
                }
                py::object new_k = getattr(k, "reshape")(-1);
                py::object kshape = getattr(new_k, "shape");
                py::list new_shape(0);
                PyObject* sym = PyObject_CallObject(cpp_use_symbolic_shape, nullptr);
                bool is_sym = (sym == Py_True);
                Py_XDECREF(sym);
                if (is_sym) {
                    py::object tshape = getattr(tensor, "shape");
740
                    for (size_t j = 0; j < i - nonedim; ++j) {
741 742 743 744 745 746
                        new_shape.append(tshape[py::int_(j)]);
                    }
                    new_shape.append(kshape[py::int_(0)]);
                    for (size_t j = tdim + ndim - offset; j < cur_shape.size(); ++j) {
                        new_shape.append(cur_shape[j]);
                    }
747 748 749 750
                    py::object shape_tensor = _astensor1d_cpp(
                            new_shape, py::none(), py::none(), py::none());
                    tensor = _reshape_cpp(tensor, shape_tensor);
                    cur_shape = _make_shape_tuple(shape_tensor);
751
                } else {
752
                    for (size_t j = 0; j < i - nonedim; ++j) {
753 754 755 756 757 758 759
                        new_shape.append(cur_shape[j]);
                    }
                    new_shape.append(py::reinterpret_borrow<py::tuple>(kshape)[0]);
                    for (size_t j = tdim + ndim - offset; j < cur_shape.size(); ++j) {
                        new_shape.append(cur_shape[j]);
                    }
                    cur_shape = new_shape;
760
                    tensor = _reshape_cpp(tensor, cur_shape);
761 762 763 764 765 766 767 768 769 770 771 772 773
                }
                offset++;
                tdim += ndim;
            }
            new_tuple_val.append(k);
        } else {
            new_tuple_val.append(k);
            tdim++;
        }
    }
    return py::make_tuple(tensor, py::reinterpret_borrow<py::tuple>(new_tuple_val));
}

774 775 776 777 778 779 780 781 782 783 784 785
std::pair<size_t, bool> get_ndim_safe(py::handle tensor) {
    if (auto p = TensorWrapper::try_cast(tensor.ptr())) {
        return {p->m_tensor->shape()->ndim, true};
    }

    try {
        return {getattr(tensor, "ndim").cast<size_t>(), true};
    } catch (py::error_already_set& err) {
        return {0, false};
    }
}

786
py::tuple _unpack_indexes(py::handle inp_hdl, py::tuple tuple_val) {
787 788 789 790 791 792 793 794
    py::object inp = py::reinterpret_borrow<py::object>(inp_hdl);

    bool use_subtensor = true;
    bool need_remove_ellipsis = false;
    bool need_expand_bool_dim = false;
    size_t idx_ndim = 0;
    for (size_t i = 0; i < tuple_val.size(); ++i) {
        py::object k = tuple_val[i];
795 796
        if (k.is_none()) {
            continue;
797 798 799 800
        } else if (k.ptr() == Py_Ellipsis) {
            need_remove_ellipsis = true;
        } else {
            if (is_bool_dtype(k.ptr()) && hasattr(k, "ndim")) {
801
                size_t ndim = get_ndim_safe(k).first;
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
                idx_ndim += ndim;
                if (ndim > 1) {
                    need_expand_bool_dim = true;
                }
            } else {
                idx_ndim++;
            }
        }
    }
    try {
        size_t inp_ndim = getattr(inp, "ndim").cast<size_t>();
        if (idx_ndim > inp_ndim) {
            std::string msg = "too many indices for tensor: tensor is " +
                              std::to_string(inp_ndim) + "-dimensional, but " +
                              std::to_string(idx_ndim) + " were indexed";
            throw py::index_error(msg.c_str());
        }
    } catch (py::error_already_set& err) {
        ;  // ignore
    }
    if (need_remove_ellipsis) {
        tuple_val = _remove_ellipsis(inp, tuple_val);
    }

    if (need_expand_bool_dim) {
        py::object shape = getattr(inp, "shape");
        if (shape.ptr() != Py_None) {
            py::tuple ret = _expand_bool_dim(inp, tuple_val);
            inp = ret[0];
            tuple_val = ret[1];
        }
    }

835 836 837 838 839 840 841 842 843 844 845 846 847 848
    std::vector<int32_t> axis;
    for (size_t i = 0; i < tuple_val.size(); ++i) {
        if (tuple_val[i].is_none()) {
            axis.push_back(i);
        }
    }
    if (axis.size()) {
        std::shared_ptr<OpDef> op = AddAxis::make(axis);
        py::object Op = py::cast(op);
        PyObject* p[2] = {Op.ptr(), inp.ptr()};
        py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
        inp = ret[0];
    }

849 850 851 852 853 854 855
    py::list items;
    py::list tensors;
    int cur_axis = -1;

    for (size_t i = 0; i < tuple_val.size(); ++i) {
        py::object handle = tuple_val[i];
        cur_axis++;
856 857 858
        if (handle.is_none()) {
            continue;
        }
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
        if (!is_scalar(handle.ptr()) && !PySlice_Check(handle.ptr())) {
            use_subtensor = false;
        }
        py::list item;
        item.append(cur_axis);
        auto push = [&](PyObject* v) {
            if (v == Py_None) {
                item.append(false);
            } else {
                item.append(true);
                tensors.append(_get_index(py::reinterpret_borrow<py::object>(v), inp));
            }
        };

        if (PySlice_Check(handle.ptr())) {
            PySliceObject* s = (PySliceObject*)handle.ptr();
            if (s->start == Py_None && s->stop == Py_None && s->step == Py_None) {
                continue;
            }
            push(s->start);
            push(s->stop);
            push(s->step);
            item.append(false);
        } else {
            for (size_t j = 0; j < 3; j++)
                item.append(false);
            push(handle.ptr());
        }
        items.append(item);
    }

    return py::make_tuple(inp, tensors, items, use_subtensor, need_expand_bool_dim);
}

893 894 895
py::object _expand_args(py::handle args) {
    if (!PyTuple_Check(args.ptr())) {
        return py::reinterpret_borrow<py::object>(args);
896
    }
897
    py::tuple args_tup = py::reinterpret_borrow<py::tuple>(args.ptr());
898 899
    if (args_tup.size() == 1 &&
        (PySequence_Check(args_tup[0].ptr()) || is_tensor(args_tup[0].ptr()))) {
900
        return py::reinterpret_borrow<py::object>(args_tup[0]);
901
    } else {
902
        return py::reinterpret_steal<py::list>(PySequence_List(args_tup.ptr()));
903 904 905
    }
}

906 907 908 909
std::tuple<std::vector<int32_t>, bool> tuple2vector(py::object shape) {
    std::vector<int32_t> shp;
    if (!PyTuple_Check(shape.ptr())) {
        return {shp, false};
910
    }
911 912 913
    py::tuple tup = py::reinterpret_borrow<py::tuple>(shape);
    for (size_t i = 0; i < tup.size(); ++i) {
        if (!PyLong_Check(tup[i].ptr())) {
914
            shp.clear();
915 916 917 918
            return {shp, false};
        } else {
            shp.push_back(tup[i].cast<int32_t>());
        }
919
    }
920 921 922 923
    return {shp, true};
}

bool enable_fastpath(py::handle inp) {
924 925
    auto&& tm_tr = TransformationManager::get_instance()
                           .segments[TransformationManager::Segment::ModuleTrace];
926 927
    bool is_varnode = PyObject_TypeCheck(inp.ptr(), py_varnode_type);
    if (is_varnode ||
928 929 930
        TransformationManager::get_instance()
                        .segments[TransformationManager::Segment::Trace]
                        .size() > 0 ||
931 932
        (tm_tr.size() > 0 &&
         reinterpret_cast<ModuleTraceTransformation*>(tm_tr[0].get())->enabled())) {
933
        return false;
934
    }
935 936
    return true;
}
937

938 939 940 941 942 943 944 945 946 947 948 949 950 951
bool subtensor_fastpath(py::handle inp_hdl, py::tuple tuple_val) {
    bool use_fastpath = true;
    for (size_t i = 0; i < tuple_val.size(); ++i) {
        PyObject* obj = tuple_val[i].ptr();
        if ((!is_scalar(obj) && !PySlice_Check(obj) && obj != Py_Ellipsis &&
             obj != Py_None) ||
            (PyObject_TypeCheck(obj, py_varnode_type))) {
            use_fastpath = false;
            break;
        }
    }
    return use_fastpath && enable_fastpath(inp_hdl);
}

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
py::object _broadcast_cpp(py::handle input, py::handle args) {
    py::object shape = _expand_args(args);
    py::list dims;
    bool all_imm;
    if (PyList_Check(shape.ptr()) || PyTuple_Check(shape.ptr())) {
        dims = py::reinterpret_steal<py::list>(PySequence_List(shape.ptr()));
        mgb_assert(!dims.is_none());
        all_imm = true;
        py::object inp_shape = py::none();
        size_t inp_ndim;
        for (size_t i = 0; i < dims.size(); ++i) {
            py::object dim = dims[i];
            if (dim.is_none()) {
                ptrdiff_t right = (ptrdiff_t)i - dims.size();
                if (inp_shape.is_none()) {
                    inp_shape = input.attr("shape");
                    mgb_assert(!inp_shape.is_none());
                    inp_ndim = py::len(inp_shape);
970
                }
971 972
                if ((ptrdiff_t)inp_ndim + right < 0) {
                    throw py::value_error("size connot be `None` for new axis");
973
                }
974 975 976 977 978 979 980 981 982
                dim = inp_shape.attr("__getitem__")(right);
                dims[i] = dim;
            }
            if (py::int_::check_(dim)) {
                if (dim.cast<long>() < 0) {
                    throw py::value_error(ssprintf(
                            "expect shape[%zu] >= 0 or use `None` to auto infer, got "
                            "%s",
                            i, py::repr(dims[i]).cast<std::string>().c_str()));
983
                }
984 985
            } else {
                all_imm = false;
986 987
            }
        }
988 989 990
        shape = dims;
    } else {
        all_imm = false;
991
    }
992 993 994 995 996
    bool fastpath = all_imm && enable_fastpath(input);
    if ((!fastpath) && (!is_tensor(shape))) {
        shape = _astensor1d_cpp(
                shape, py::cast((mgb::DType)dtype::Int32()), input.attr("device"),
                input);
997 998
    }
    std::shared_ptr<OpDef> op;
999
    SmallVector<PyObject*> p(2);
1000
    if (fastpath) {
1001 1002 1003 1004 1005
        std::vector<int32_t> shape_vec;
        for (auto&& dim : dims) {
            shape_vec.push_back(dim.cast<long>());
        }
        op = Broadcast::make(shape_vec);
1006 1007
    } else {
        op = Broadcast::make();
1008
        p.push_back(shape.ptr());
1009
    }
1010 1011 1012
    py::object py_op = py::cast(op);
    p[0] = py_op.ptr();
    p[1] = input.ptr();
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    py::tuple ret =
            py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
    return ret[0];
}

py::object _reshape_cpp(py::handle inp_hdl, py::handle args) {
    py::object shape_hdl = _expand_args(args);
    py::object shape_tuple;
    try {
        shape_tuple = _make_shape_tuple(shape_hdl);
    } catch (py::error_already_set& err) {
        shape_tuple = py::reinterpret_borrow<py::object>(shape_hdl);
    }
    int32_t unspec_axis = -1;
    if (PyTuple_Check(shape_tuple.ptr())) {
        py::tuple tup = py::reinterpret_borrow<py::tuple>(shape_tuple);
        for (size_t i = 0; i < tup.size(); ++i) {
            py::object obj = py::reinterpret_borrow<py::object>(tup[i]);
            if (obj < py::int_(0)) {
                if (obj.not_equal(py::int_(-1))) {
                    throw py::value_error(
                            "expect shape [" + std::to_string(i) + "] >= -1, got " +
                            repr(obj).cast<std::string>());
                }
                if (unspec_axis >= 0) {
                    throw py::value_error(
                            "multiple -1 in shape: " + std::to_string(unspec_axis) +
                            " & " + std::to_string(i));
                }
                unspec_axis = i;
            }
        }
    }
    auto [shape, fastpath] = tuple2vector(shape_tuple);
    fastpath &= enable_fastpath(inp_hdl);
    std::shared_ptr<OpDef> op;
    std::vector<PyObject*> p;
    py::object shape_tensor;
    if (fastpath) {
        if (unspec_axis >= 0) {
            op = Reshape::make(unspec_axis, shape);
        } else {
            op = Reshape::make(::megdnn::param::OptionalAxisV1::INVALID_AXIS, shape);
        }
        p.resize(2);
    } else {
        shape.clear();
        if (unspec_axis >= 0) {
            op = Reshape::make(unspec_axis, shape);
        } else {
            op = Reshape::make();
        }
        shape_tensor = _astensor1d_cpp(
                shape_hdl, py::cast((mgb::DType)dtype::Int32()),
                getattr(inp_hdl, "device"), inp_hdl);
        p.resize(3);
        p[2] = shape_tensor.ptr();
    }
    py::object Op = py::cast(op);
    p[0] = Op.ptr();
    p[1] = inp_hdl.ptr();
    py::tuple ret =
            py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
    return ret[0];
}

1079 1080 1081 1082
py::object _adaptive_pool2d_cpp(
        py::handle inp_hdl, py::handle shape_val_hdl, py::handle pool_mode_hdl) {
    py::object shape_hdl = py::reinterpret_borrow<py::object>(shape_val_hdl);
    py::list shps(0);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
    auto mode_string = pool_mode_hdl.cast<std::string>();
    ::megdnn::param::AdaptivePooling::Mode pool_mode =
            ::megdnn::param::AdaptivePooling::Mode::MAX;
    if (mode_string.compare(std::string("AVERAGE")) == 0) {
        pool_mode = ::megdnn::param::AdaptivePooling::Mode::AVERAGE;
    }
    std::shared_ptr<OpDef> op;
    std::vector<PyObject*> p;
    auto pool_format = ::megdnn::param::AdaptivePooling::Format::NCHW;
    auto inp_format = getattr(inp_hdl, "format").cast<std::string>();
    if (inp_format == "nhwc") {
        pool_format = ::megdnn::param::AdaptivePooling::Format::NHWC;
    }
    if (TensorWrapper::try_cast(shape_val_hdl.ptr())) {
        std::vector<int32_t> shp;
        op = AdaptivePooling::make(pool_mode, pool_format, shp);
        py::object Op = py::cast(op);
        p.resize(3);
        p[0] = Op.ptr();
        p[1] = inp_hdl.ptr();
        p[2] = shape_val_hdl.ptr();
        py::tuple ret =
                py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
        return ret[0];
    } else if (!PyTuple_Check(shape_val_hdl.ptr())) {
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
        shps.append(PyLong_AsLong(shape_val_hdl.ptr()));
        shps.append(PyLong_AsLong(shape_val_hdl.ptr()));

        shape_hdl = py::reinterpret_borrow<py::object>(shps);
    }
    py::object shape_tuple;
    try {
        shape_tuple = _make_shape_tuple(shape_hdl);
    } catch (py::error_already_set& err) {
        shape_tuple = py::reinterpret_borrow<py::object>(shape_hdl);
    }
1119

1120 1121 1122
    auto [shape, fastpath] = tuple2vector(shape_tuple);
    fastpath &= enable_fastpath(inp_hdl);
    py::object shape_tensor;
1123
    op = AdaptivePooling::make(pool_mode, pool_format, shape);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    if (fastpath) {
        p.resize(2);
    } else {
        p.resize(3);
        shape_tensor = _astensor1d_cpp(
                shape_hdl, py::cast((mgb::DType)dtype::Int32()),
                getattr(inp_hdl, "device"), inp_hdl);
        p[2] = shape_tensor.ptr();
    }
    py::object Op = py::cast(op);
    p[0] = Op.ptr();
    p[1] = inp_hdl.ptr();
    py::tuple ret =
            py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
    return ret[0];
}

1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
py::object _fastpath_getitem_cpp(py::handle inp_hdl, py::tuple tuple_val) {
    py::object inp = py::reinterpret_borrow<py::object>(inp_hdl);
    int ax = 0;
    bool use_ellipsis = false;
    size_t special_dim = 0;

    for (size_t i = 0; i < tuple_val.size(); ++i) {
        PyObject* obj = tuple_val[i].ptr();
        if (obj == Py_Ellipsis) {
            use_ellipsis = true;
            for (size_t j = i + 1; j < tuple_val.size(); j++) {
                PyObject* obj_last = tuple_val[j].ptr();
                if (obj_last == Py_Ellipsis) {
                    throw py::index_error("only one ellipsis is allowed.");
                }
            }
        }
        if (obj != Py_None && obj != Py_Ellipsis && obj != Py_True && obj != Py_False) {
            special_dim++;
        }
    }

    size_t ndim = 0;
    try {
        ndim = getattr(inp_hdl, "ndim").cast<size_t>();
    } catch (py::error_already_set& err) {
        if (use_ellipsis) {
            throw py::index_error(
                    "does not support Ellipsis when tensor's ndim is unknown.");
        };
    }

    std::vector<std::tuple<int8_t, bool, bool, bool, bool>> cpp_items;
    std::vector<std::tuple<int32_t, int32_t, int32_t, int32_t>> slice_items;
    std::vector<int32_t> expand_items;

    for (size_t i = 0; i < tuple_val.size(); ++i) {
        py::object t = tuple_val[i];
        if (t.ptr() == Py_Ellipsis) {
            ax += ndim - special_dim;
        } else if (PySlice_Check(t.ptr())) {
            PySliceObject* s = (PySliceObject*)t.ptr();
            std::vector<int> items;
            std::vector<bool> idx_items;
            auto push = [&](PyObject* v, int default_value) {
                if (v == Py_None) {
                    items.push_back(default_value);
                    idx_items.push_back(false);
                } else {
                    auto obj = py::reinterpret_borrow<py::object>(v);
                    items.push_back(obj.cast<int>());
                    idx_items.push_back(true);
                }
            };
            push(s->start, INT_MIN);
            push(s->stop, INT_MAX);
            push(s->step, INT_MAX);
            if (idx_items[0] || idx_items[1] || idx_items[2]) {
                cpp_items.push_back(
                        {ax, idx_items[0], idx_items[1], idx_items[2], false});
                slice_items.push_back({items[0], items[1], items[2], INT_MAX});
            }
            ax += 1;
        } else if (PyLong_Check(t.ptr()) && !PyBool_Check(t.ptr())) {
            cpp_items.push_back({ax, false, false, false, true});
            slice_items.push_back({INT_MIN, INT_MAX, INT_MAX, t.cast<int>()});
            ax += 1;
        } else if (PyBool_Check(t.ptr())) {
            expand_items.push_back(ax);
1210 1211 1212 1213 1214
            if (t.ptr() == Py_False) {
                cpp_items.push_back({ax, true, true, true, false});
                slice_items.push_back({0, 0, 1, INT_MAX});
            }
            ax += 1;
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
        } else if (t.ptr() == Py_None) {
            expand_items.push_back(ax);
            ax += 1;
        } else if (is_scalar(t.ptr())) {
            cpp_items.push_back({ax, false, false, false, true});
            slice_items.push_back({INT_MIN, INT_MAX, INT_MAX, t.cast<int>()});
            ax += 1;
        } else {
            throw py::value_error("fast path subtensor index not impl");
        }
    }

    if (expand_items.size()) {
        std::shared_ptr<OpDef> op = AddAxis::make(expand_items);
        py::object Op = py::cast(op);
        PyObject* p[2] = {Op.ptr(), inp.ptr()};
        py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
        inp = ret[0];
    }

    std::shared_ptr<OpDef> op;
    op = Subtensor::make(cpp_items, slice_items);

    std::vector<PyObject*> p;
    p.resize(2);
    py::object Op = py::cast(op);
    p[0] = Op.ptr();
    p[1] = inp.ptr();

    py::tuple ret =
            py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
    return ret[0];
}

1249 1250 1251 1252 1253
py::object _getitem_cpp(py::handle inp_hdl, py::handle idx_hdl) {
    py::tuple try_res = _try_cond_take(inp_hdl, idx_hdl);
    if (try_res.size() == 2) {
        return try_res[0];
    }
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    py::tuple tuple_val;
    if (py::isinstance<py::tuple>(idx_hdl)) {
        tuple_val = py::reinterpret_borrow<py::tuple>(idx_hdl);
    } else {
        tuple_val = py::make_tuple(idx_hdl);
    }
    if (subtensor_fastpath(inp_hdl, tuple_val)) {
        return _fastpath_getitem_cpp(inp_hdl, tuple_val);
    }
    py::tuple up = _unpack_indexes(inp_hdl, tuple_val);
1264 1265 1266 1267
    py::object tensor = py::reinterpret_borrow<py::object>(up[0]);
    py::list tensors = py::reinterpret_borrow<py::list>(up[1]);
    py::list py_items = py::reinterpret_borrow<py::list>(up[2]);
    std::vector<std::tuple<int8_t, bool, bool, bool, bool>> cpp_items;
1268
    std::vector<std::tuple<int32_t, int32_t, int32_t, int32_t>> slice_items;
1269 1270 1271 1272 1273 1274
    for (size_t i = 0; i < py_items.size(); ++i) {
        py::list item = py::reinterpret_borrow<py::list>(py_items[i]);
        cpp_items.push_back(
                {item[0].cast<int8_t>(), item[1].cast<bool>(), item[2].cast<bool>(),
                 item[3].cast<bool>(), item[4].cast<bool>()});
    }
1275
    std::shared_ptr<OpDef> op;
1276
    if (up[3].cast<bool>()) {
1277
        op = Subtensor::make(cpp_items, slice_items);
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    } else {
        op = IndexingMultiAxisVec::make(cpp_items);
    }
    std::vector<PyObject*> p;
    p.resize(tensors.size() + 2);
    py::object Op = py::cast(op);
    p[0] = Op.ptr();
    p[1] = tensor.ptr();
    for (size_t i = 0; i < tensors.size(); ++i) {
        p[i + 2] = tensors[i].ptr();
    }
    py::tuple ret =
            py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
    return ret[0];
}

py::object _setitem_cpp(py::handle inp_hdl, py::handle idx_hdl, py::handle val_hdl) {
    py::object org_shape = getattr(inp_hdl, "shape");
    py::object val = py::reinterpret_borrow<py::object>(val_hdl);
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    bool is_val_scalar = false;
    float value;
    if (PyLong_Check(val.ptr())) {
        is_val_scalar = true;
        value = static_cast<float>(PyLong_AsDouble(val.ptr()));
    }
    if (PyFloat_Check(val.ptr())) {
        is_val_scalar = true;
        value = static_cast<float>(PyFloat_AsDouble(val.ptr()));
    }
    if (TensorWrapper::try_cast(idx_hdl.ptr()) && is_bool_dtype(idx_hdl.ptr()) &&
        is_val_scalar && enable_fastpath(inp_hdl)) {
        std::vector<PyObject*> q(3);
        std::shared_ptr<OpDef> Op = MaskedFill::make(value);
        py::object maskedfill = py::cast(Op);
        q[0] = maskedfill.ptr();
        q[1] = inp_hdl.ptr();
        q[2] = idx_hdl.ptr();
        py::tuple result =
                py::reinterpret_steal<py::object>(py_apply(NULL, q.data(), q.size()));
        py::object res = result[0];
        return res;
    }
1320 1321
    if (!TensorWrapper::try_cast(val.ptr())) {
        val = _Const(val_hdl, getattr(inp_hdl, "dtype"), getattr(inp_hdl, "device"));
1322 1323
    }

1324 1325 1326 1327 1328 1329 1330
    py::tuple tuple_val;
    if (py::isinstance<py::tuple>(idx_hdl)) {
        tuple_val = py::reinterpret_borrow<py::tuple>(idx_hdl);
    } else {
        tuple_val = py::make_tuple(idx_hdl);
    }
    py::tuple up = _unpack_indexes(inp_hdl, tuple_val);
1331 1332 1333 1334
    py::object tensor = py::reinterpret_borrow<py::object>(up[0]);
    py::list tensors = py::reinterpret_borrow<py::list>(up[1]);
    py::list py_items = py::reinterpret_borrow<py::list>(up[2]);
    std::vector<std::tuple<int8_t, bool, bool, bool, bool>> cpp_items;
1335
    std::vector<std::tuple<int32_t, int32_t, int32_t, int32_t>> slice_items;
1336 1337 1338 1339 1340 1341
    for (size_t i = 0; i < py_items.size(); ++i) {
        py::list item = py::reinterpret_borrow<py::list>(py_items[i]);
        cpp_items.push_back(
                {item[0].cast<int8_t>(), item[1].cast<bool>(), item[2].cast<bool>(),
                 item[3].cast<bool>(), item[4].cast<bool>()});
    }
1342
    std::shared_ptr<OpDef> op, set_op;
1343
    if (up[3].cast<bool>()) {
1344
        op = Subtensor::make(cpp_items, slice_items);
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    } else {
        op = IndexingMultiAxisVec::make(cpp_items);
    }
    std::vector<PyObject*> p;
    p.resize(tensors.size() + 2);
    py::object Op = py::cast(op);
    p[0] = Op.ptr();
    p[1] = tensor.ptr();
    for (size_t i = 0; i < tensors.size(); ++i) {
        p[i + 2] = tensors[i].ptr();
    }
    py::tuple ret =
            py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
    py::object tmp_result = ret[0];

    try {
        py::tuple value_shape =
                py::reinterpret_borrow<py::tuple>(val.attr("_tuple_shape"));
        py::tuple tmp_result_shape =
                py::reinterpret_borrow<py::tuple>(tmp_result.attr("_tuple_shape"));
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
        for (size_t i = 0; i < value_shape.size() && i < tmp_result_shape.size(); ++i) {
            size_t vs = value_shape[value_shape.size() - i - 1].cast<size_t>();
            size_t ts =
                    tmp_result_shape[tmp_result_shape.size() - i - 1].cast<size_t>();
            if (vs != 1 && vs != ts) {
                std::string lhs = "", rhs = "";
                for (size_t j = 0; j < tmp_result_shape.size(); ++j) {
                    lhs += std::to_string(tmp_result_shape[j].cast<size_t>());
                    if (j)
                        lhs += ",";
                }
                for (size_t j = 0; j < value_shape.size(); ++j) {
                    rhs += std::to_string(value_shape[j].cast<size_t>());
                    if (j)
                        rhs += ",";
                }
                throw py::value_error(
                        "cannot copy tensor with shape (" + rhs +
                        ") to subtensor with shape (" + lhs + ")");
            }
        }
    } catch (py::error_already_set& err) {
        ;
    }
1389
    val = _broadcast_cpp(val, getattr(tmp_result, "shape"));
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
    if (up[3].cast<bool>()) {
        set_op = SetSubtensor::make(cpp_items);
    } else {
        set_op = IndexingSetMultiAxisVec::make(cpp_items);
    }

    std::vector<PyObject*> q;
    q.resize(tensors.size() + 3);
    py::object Set_Op = py::cast(set_op);
    q[0] = Set_Op.ptr();
    q[1] = tensor.ptr();
    q[2] = val.ptr();
    for (size_t i = 0; i < tensors.size(); ++i) {
        q[i + 3] = tensors[i].ptr();
    }
    py::tuple result =
            py::reinterpret_steal<py::object>(py_apply(NULL, q.data(), q.size()));
    py::object res = result[0];

    if (up[4].cast<bool>()) {
1410
        res = _reshape_cpp(res, org_shape);
1411 1412 1413 1414 1415
    }

    return res;
}

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
py::object _split_cpp(
        py::handle inp_hdl, py::handle nsplits_or_sections_hdl, py::handle axis_hdl) {
    py::object shape_obj = getattr(inp_hdl, "shape");
    py::object n_total = shape_obj[axis_hdl];
    int ndim = shape_obj.attr("__len__")().cast<int>();
    int axis = axis_hdl.cast<int>();
    if (axis >= ndim) {
        throw py::value_error("Invalid axis " + std::to_string(axis));
    }
    int n_sections;
    bool is_array;
    if (is_py_sequence(nsplits_or_sections_hdl)) {
        n_sections = PySequence_Length(nsplits_or_sections_hdl.ptr()) + 1;
        is_array = true;
    } else {
        n_sections = getattr(nsplits_or_sections_hdl, "__int__")().cast<int>();
        is_array = false;
    }
    py::list partitions;
    std::shared_ptr<OpDef> op;
    std::vector<PyObject*> p;
    if (is_array) {
        py::list div_points;
        py::list sections = py::reinterpret_borrow<py::object>(nsplits_or_sections_hdl);
        div_points.append(0);
        for (size_t i = 0; i < sections.size(); ++i) {
            div_points.append(sections[i]);
        }
        div_points.append(n_total);
        for (size_t i = 1; i < div_points.size(); ++i) {
            if (div_points[i - 1] > div_points[i]) {
                throw py::value_error(
                        "Invalid nsplits_or_secions: " +
                        repr(nsplits_or_sections_hdl).cast<std::string>());
            }
            py::object pos = div_points[i] - div_points[i - 1];
1452
            if (is_tensor(pos)) {
1453 1454 1455 1456
                partitions.append(pos);
            } else {
                partitions.append(
                        _Const(pos, py::cast((mgb::DType)dtype::Int32()),
1457
                               getattr(inp_hdl, "device")));
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
            }
        }
        op = Split::make(axis, 0);
        p.resize(partitions.size() + 2);
        for (size_t i = 0; i < partitions.size(); ++i) {
            p[i + 2] = partitions[i].ptr();
        }
    } else {
        if (n_sections <= 0) {
            throw py::value_error("Number sections must be larger than 0");
        }
        if (py::int_(n_sections) > n_total) {
            throw py::value_error(
                    "The size " + repr(n_total).cast<std::string>() + " at dim " +
                    std::to_string(axis) + " cannot be split into " +
                    std::to_string(n_sections) + " sections");
        }
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
        if (enable_fastpath(inp_hdl)) {
            op = Split::make(axis, n_sections);
            p.resize(2);
        } else {
            size_t n_total_ = n_total.cast<int>();
            for (size_t i = 0; i < n_sections; ++i) {
                auto section_size = (n_total_ + n_sections - i - 1) / n_sections;
                partitions.append(_Const(
                        py::int_(section_size), py::cast((mgb::DType)dtype::Int32()),
                        getattr(inp_hdl, "device")));
            }
            op = Split::make(axis, 0);
            p.resize(partitions.size() + 2);
            for (size_t i = 0; i < partitions.size(); ++i) {
                p[i + 2] = partitions[i].ptr();
            }
        }
1492 1493 1494 1495 1496 1497 1498
    }
    py::object Op = py::cast(op);
    p[0] = Op.ptr();
    p[1] = inp_hdl.ptr();
    return py::reinterpret_steal<py::object>(py_apply(NULL, p.data(), p.size()));
}

1499
std::vector<int32_t> list2vector(py::handle li) {
1500
    std::vector<int32_t> axis;
1501
    if (is_py_sequence(li)) {
1502
        py::list tmp_list = py::reinterpret_steal<py::list>(PySequence_List(li.ptr()));
1503 1504 1505 1506
        for (size_t i = 0; i < tmp_list.size(); ++i) {
            axis.push_back(tmp_list[i].attr("__int__")().cast<int32_t>());
        }
    } else {
1507
        axis.push_back(getattr(li, "__int__")().cast<int32_t>());
1508
    }
1509 1510 1511 1512 1513
    return axis;
}

py::object _expand_dims_cpp(py::handle inp_hdl, py::handle axis_hdl) {
    std::vector<int32_t> axis = list2vector(axis_hdl);
1514 1515 1516 1517 1518 1519 1520 1521 1522
    bool unknown_ndim = true;
    size_t ndim = axis.size();
    if (auto p = TensorWrapper::try_cast(inp_hdl.ptr())) {
        auto&& shape = p->m_tensor->shape();
        if (shape) {
            unknown_ndim = false;
            ndim += shape->ndim;
        }
    } else {
1523 1524
        auto&& inp_ndim = get_ndim_safe(inp_hdl);
        ndim += inp_ndim.first;
1525
        unknown_ndim &= !inp_ndim.second;
1526 1527 1528 1529 1530 1531 1532 1533
    }
    for (size_t i = 0; i < axis.size(); ++i) {
        if (axis[i] < 0) {
            if (unknown_ndim) {
                throw py::index_error(
                        "Does not support negative index when tensor's ndim is "
                        "unknown");
            }
1534
            axis[i] += static_cast<int32_t>(ndim);
1535 1536 1537 1538 1539 1540 1541 1542
        }
    }
    if (!axis.size()) {
        throw py::index_error("axis could not be empty");
    }
    std::sort(axis.begin(), axis.end());
    std::shared_ptr<OpDef> op = AddAxis::make(axis = axis);
    py::object Op = py::cast(op);
1543 1544
    PyObject* p[2] = {Op.ptr(), inp_hdl.ptr()};
    py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
1545 1546 1547
    return ret[0];
}

1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
py::object _squeeze_cpp(py::handle inp_hdl, py::handle axis_hdl) {
    std::vector<int32_t> axis;
    size_t ndim;
    if (axis_hdl.ptr() != Py_None) {
        axis = list2vector(axis_hdl);
    }
    if (auto p = TensorWrapper::try_cast(inp_hdl.ptr())) {
        auto&& shape = p->m_tensor->shape();
        if (shape) {
            ndim = shape->ndim;
            if (axis_hdl.ptr() == Py_None) {
                for (size_t i = 0; i < shape->ndim; ++i) {
                    if (shape->shape[i] == 1) {
                        axis.push_back(i);
                    }
                }
            }
        }
    } else {
1567 1568 1569 1570 1571 1572 1573
        py::tuple shape =
                py::reinterpret_borrow<py::tuple>(getattr(inp_hdl, "_tuple_shape"));
        ndim = shape.size();
        if (axis_hdl.ptr() == Py_None) {
            for (size_t i = 0; i < shape.size(); ++i) {
                if (shape[i].cast<size_t>() == 1) {
                    axis.push_back(i);
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
                }
            }
        }
    }
    for (size_t i = 0; i < axis.size(); ++i) {
        if (axis[i] < 0) {
            axis[i] += static_cast<int32_t>(ndim);
        }
    }
    std::sort(axis.begin(), axis.end());
    for (size_t i = 0; i < axis.size(); ++i) {
        axis[i] -= static_cast<int32_t>(i);
    }
    std::shared_ptr<OpDef> op = RemoveAxis::make(axis = axis);
    py::object Op = py::cast(op);
1589 1590
    PyObject* p[2] = {Op.ptr(), inp_hdl.ptr()};
    py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
1591 1592
    return ret[0];
}
1593

1594 1595 1596
py::object _transpose_cpp(py::handle inp_hdl, py::handle args) {
    py::object obj = _expand_args(args);
    py::list lis;
1597
    if (!is_tensor(obj.ptr()) && PySequence_Check(obj.ptr())) {
1598 1599 1600 1601 1602 1603 1604 1605 1606
        lis = py::reinterpret_steal<py::list>(PySequence_List(obj.ptr()));
    } else {
        py::object np = getattr(obj, "numpy")();
        PyArrayObject* arr = (PyArrayObject*)np.ptr();
        PyObject* maybe_list = PyArray_ToList(arr);
        if (PyList_Check(maybe_list)) {
            lis = py::reinterpret_steal<py::list>(maybe_list);
        }
    }
1607
    if (get_ndim_safe(inp_hdl).first == 0) {
1608
        if (lis.size() != 0) {
1609 1610 1611 1612 1613 1614
            throw py::index_error(
                    "transpose for scalar does not accept additional args");
        }
        return getattr(inp_hdl, "to")(getattr(inp_hdl, "device"));
    }
    std::vector<int32_t> pattern;
1615
    if (!lis.size()) {
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
        size_t ndim = getattr(inp_hdl, "ndim").cast<size_t>();
        for (size_t i = 0; i < ndim; ++i) {
            pattern.push_back(ndim - i - 1);
        }
    } else {
        for (size_t i = 0; i < lis.size(); ++i) {
            if (PyLong_Check(lis[i].ptr())) {
                pattern.push_back(lis[i].cast<int32_t>());
            } else {
                if (lis[i].cast<std::string>() == "x") {
                    pattern.push_back(-1);
                }
            }
        }
    }
    std::shared_ptr<OpDef> op = Dimshuffle::make(pattern);
    py::object Op = py::cast(op);
1633 1634
    PyObject* p[2] = {Op.ptr(), inp_hdl.ptr()};
    py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
1635 1636 1637
    return ret[0];
}

1638 1639 1640
py::object _matmul_cpp(
        py::handle inp1, py::handle inp2, py::handle dim1, py::handle dim2,
        py::handle transpose_a, py::handle transpose_b, py::handle compute_mode,
1641
        py::handle profile, py::handle deterministic) {
1642 1643 1644 1645 1646 1647 1648 1649 1650
    ::megdnn::param::MatrixMul::ComputeMode mode =
            ::megdnn::param::MatrixMul::ComputeMode::DEFAULT;
    if (compute_mode.cast<std::string>().compare(std::string("float32")) == 0) {
        mode = ::megdnn::param::MatrixMul::ComputeMode::FLOAT32;
    }
    ::megdnn::param::ExecutionPolicy::Strategy cstrategy =
            static_cast<::megdnn::param::ExecutionPolicy::Strategy>(0);
    if (profile.cast<bool>()) {
        cstrategy |= ::megdnn::param::ExecutionPolicy::Strategy::PROFILE;
1651
    } else {
1652
        cstrategy |= ::megdnn::param::ExecutionPolicy::Strategy::HEURISTIC;
1653
    }
1654
    if (deterministic.cast<bool>()) {
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
        cstrategy |= ::megdnn::param::ExecutionPolicy::Strategy::REPRODUCIBLE;
    }
    std::shared_ptr<OpDef> op = MatrixMul::make(
            transpose_a.cast<bool>(), transpose_b.cast<bool>(), mode,
            ::megdnn::param::MatrixMul::Format::DEFAULT, cstrategy, UINT64_MAX,
            dim1.cast<uint32_t>(), dim2.cast<uint32_t>());

    py::object Op = py::cast(op);
    PyObject* p[3] = {Op.ptr(), inp1.ptr(), inp2.ptr()};
    py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 3));
    return ret[0];
1666 1667 1668 1669 1670
}

py::object _batched_matmul_cpp(
        py::handle inp1, py::handle inp2, py::handle dim1, py::handle dim2,
        py::handle transpose_a, py::handle transpose_b, py::handle compute_mode,
1671
        py::handle profile, py::handle deterministic) {
1672 1673 1674 1675 1676 1677 1678 1679 1680
    ::megdnn::param::MatrixMul::ComputeMode mode =
            ::megdnn::param::MatrixMul::ComputeMode::DEFAULT;
    if (compute_mode.cast<std::string>().compare(std::string("float32")) == 0) {
        mode = ::megdnn::param::MatrixMul::ComputeMode::FLOAT32;
    }
    ::megdnn::param::ExecutionPolicy::Strategy cstrategy =
            static_cast<::megdnn::param::ExecutionPolicy::Strategy>(0);
    if (profile.cast<bool>()) {
        cstrategy |= ::megdnn::param::ExecutionPolicy::Strategy::PROFILE;
1681
    } else {
1682
        cstrategy |= ::megdnn::param::ExecutionPolicy::Strategy::HEURISTIC;
1683
    }
1684
    if (deterministic.cast<bool>()) {
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
        cstrategy |= ::megdnn::param::ExecutionPolicy::Strategy::REPRODUCIBLE;
    }
    std::shared_ptr<OpDef> op = BatchedMatrixMul::make(
            transpose_a.cast<bool>(), transpose_b.cast<bool>(), mode,
            ::megdnn::param::MatrixMul::Format::DEFAULT, cstrategy, UINT64_MAX,
            dim1.cast<uint32_t>(), dim2.cast<uint32_t>());

    py::object Op = py::cast(op);
    PyObject* p[3] = {Op.ptr(), inp1.ptr(), inp2.ptr()};
    py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 3));
    return ret[0];
1696 1697
}

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
py::object _pixel_shuffle_cpp(py::handle inp, py::handle val, py::handle func) {
    if (enable_fastpath(inp) && PyLong_Check(val.ptr())) {
        std::shared_ptr<OpDef> op = PixelShuffle::make(val.cast<int32_t>());
        py::object Op = py::cast(op);
        PyObject* p[2] = {Op.ptr(), inp.ptr()};
        py::tuple ret = py::reinterpret_steal<py::object>(py_apply(NULL, p, 2));
        return ret[0];
    } else {
        // fallback to traceable subgraph implement
        return func(inp, val);
    }
}

1711 1712
PyObject* make_shape_tuple(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1713
        return _make_shape_tuple(args[0]).release().ptr();
1714 1715 1716 1717 1718 1719
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

PyObject* getitem_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1720
        return _getitem_cpp(args[0], args[1]).release().ptr();
1721 1722 1723 1724 1725 1726
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

PyObject* setitem_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1727
        return _setitem_cpp(args[0], args[1], args[2]).release().ptr();
1728 1729 1730 1731
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1732 1733
PyObject* split_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1734
        return _split_cpp(args[0], args[1], args[2]).release().ptr();
1735 1736 1737 1738
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1739 1740
PyObject* expand_dims_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1741
        return _expand_dims_cpp(args[0], args[1]).release().ptr();
1742 1743 1744 1745
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1746 1747
PyObject* squeeze_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1748
        return _squeeze_cpp(args[0], args[1]).release().ptr();
1749 1750 1751 1752
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1753 1754
PyObject* transpose_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1755
        return _transpose_cpp(args[0], args[1]).release().ptr();
1756 1757 1758 1759
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1760 1761
PyObject* broadcast_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1762
        return _broadcast_cpp(args[0], args[1]).release().ptr();
1763 1764 1765 1766 1767 1768
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

PyObject* reshape_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
        mgb_assert(nargs == 2, "reshape should have 2 args but give %zu", nargs);
        PyObject* pyinp = args[0];
        PyObject* pyshp = args[1];

        if ((PyList_CheckExact(pyshp) || PyTuple_CheckExact(pyshp) ||
             PyLong_Check(pyshp)) &&
            enable_fastpath(pyinp)) {
            using OptionalAxisV1 = ::megdnn::param::OptionalAxisV1;
            int32_t unspec_axis = OptionalAxisV1::INVALID_AXIS;
            std::vector<int32_t> shape;
            bool is_int_arrays = true;

            // judge whether the target shape is int arrays like (int,), [int], int
            if (PyLong_Check(pyshp)) {
                shape.push_back(static_cast<int32_t>(PyLong_AsLong(pyshp)));
                if (shape[0] == -1) {
                    unspec_axis = 0;
                }
            } else {
                size_t len = PySequence_Fast_GET_SIZE(pyshp);
                shape.resize(len);
                for (size_t i = 0; i < len; ++i) {
                    auto obj = PySequence_Fast_GET_ITEM(pyshp, i);
                    if (!PyLong_Check(obj)) {
                        is_int_arrays = false;
                        break;
                    }
                    shape[i] = PyLong_AsLong(obj);
                    if (shape[i] == -1) {
                        mgb_assert(unspec_axis == OptionalAxisV1::INVALID_AXIS);
                        unspec_axis = i;
                    }
                }
            }
            // if the target shape is the int arrays, we dispatch directly
            if (is_int_arrays) {
                std::shared_ptr<OpDef> op = Reshape::make(unspec_axis, shape);
                std::vector<PyObject*> packed_param(2);

                py::object Op = py::cast(op);
                packed_param[0] = Op.ptr();
                packed_param[1] = pyinp;
                py::tuple ret = py::reinterpret_steal<py::object>(
                        py_apply(NULL, packed_param.data(), packed_param.size()));
                return py::object(ret[0]).release().ptr();
            }
        }
        // fallback
1817
        return _reshape_cpp(args[0], args[1]).release().ptr();
1818 1819 1820 1821
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1822 1823 1824 1825 1826 1827 1828
PyObject* adaptive_pool2d_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
        return _adaptive_pool2d_cpp(args[0], args[1], args[2]).release().ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1829 1830 1831 1832 1833 1834 1835
PyObject* pixel_shuffle_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
        return _pixel_shuffle_cpp(args[0], args[1], args[2]).release().ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1836 1837
PyObject* Const(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1838
        return _Const(args[0], args[1], args[2]).release().ptr();
1839 1840 1841 1842
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1843 1844
PyObject* astype_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1845
        return _astype_cpp(args[0], args[1]).release().ptr();
1846 1847 1848 1849
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1850 1851 1852 1853
PyObject* matmul_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
        return _matmul_cpp(
                       args[0], args[1], args[2], args[3], args[4], args[5], args[6],
1854
                       args[7], args[8])
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
                .release()
                .ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

PyObject* batched_matmul_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
        return _batched_matmul_cpp(
                       args[0], args[1], args[2], args[3], args[4], args[5], args[6],
1865
                       args[7], args[8])
1866 1867 1868 1869 1870 1871
                .release()
                .ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1872 1873 1874
PyObject* convert_single_value_cpp(
        PyObject* self, PyObject* const* args, size_t nargs) {
    try {
1875
        return _convert_single_value_cpp(args[0], args[1], args[2]).release().ptr();
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

PyObject* convert_inputs_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
        py::object dtype = py::reinterpret_steal<py::object>(
                dtype_promotion(self, args, nargs - 1));
        py::object device;
        if (args[nargs - 1] == Py_None) {
            device = py::reinterpret_steal<py::object>(
                    get_device(self, args, nargs - 1));
        } else {
            device = py::reinterpret_borrow<py::object>(args[nargs - 1]);
        }
        return _convert_inputs_cpp(args, nargs - 1, dtype, device).release().ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1896 1897 1898 1899 1900 1901 1902
PyObject* astensor1d_cpp(PyObject* self, PyObject* const* args, size_t nargs) {
    try {
        return _astensor1d_cpp(args[0], args[1], args[2], args[3]).release().ptr();
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
}

1903
}  // namespace mgb::imperative::python