tensor.cpp 47.2 KB
Newer Older
1 2 3 4
/**
 * \file imperative/python/src/tensor.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

12
#include "megbrain/common.h"
M
Megvii Engine Team 已提交
13
#include "megbrain/dtype.h"
14
#include "megbrain/imperative/ops/autogen.h"
M
Megvii Engine Team 已提交
15 16
#include "megbrain/imperative/ops/backward_graph.h"
#include "megbrain/imperative/ops/utility.h"
17
#include "megbrain/imperative/profiler.h"
18
#include "megbrain/imperative/transformations/dtype_promote.h"
19 20 21 22 23 24
#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"
25
#include "megbrain/imperative/utils/stats.h"
26
#include "megbrain/opr/io.h"
27
#include "megbrain/plugin/profiler.h"
28

29
#include "./common.h"
M
Megvii Engine Team 已提交
30
#include "./grad.h"
31
#include "./graph_rt.h"
32
#include "./helper.h"
M
Megvii Engine Team 已提交
33 34 35
#include "./module_trace.h"
#include "./numpy_dtypes.h"
#include "./tensor.h"
36
#include "./tensor_utils.h"
37
#include "./transformation.h"
38

39
#include <object.h>
40 41
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
42 43
#include <pybind11/pytypes.h>
#include <pyerrors.h>
44
#include <range/v3/all.hpp>
45
#include <string>
46 47 48

#include <unordered_map>

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

51
namespace py = pybind11;
52
namespace views = ranges::views;
53 54 55

namespace mgb::imperative::python {

56 57
namespace {
WeakKeyMap<ValueWeakRef, py::object> module_trace_info_map;
58 59 60

struct SymbolVarContext {
    TransformationContext context;
61 62
    std::shared_ptr<SymbolTransformation> symbol_tsf;
    std::shared_ptr<ScalarTransformation> scalar_tsf;
63
    std::shared_ptr<DTypePromoteTransformation> dtype_promote_tsf;
64

65 66 67
    SymbolVarContext(cg::ComputingGraph* graph) {
        symbol_tsf = std::make_shared<SymbolTransformation>(graph);
        scalar_tsf = std::make_shared<ScalarTransformation>();
68
        dtype_promote_tsf = std::make_shared<DTypePromoteTransformation>();
69 70 71 72
        Transformation::swap_context(context);
    }

    void init() {
73 74
        symbol_tsf->register_at(Transformation::top());
        scalar_tsf->register_at(Transformation::top());
75
        dtype_promote_tsf->register_at(Transformation::top());
76 77
    }

78 79 80 81 82 83 84 85
    ValueRef symvar2val(py::handle py_symbol_var) {
        auto* symbol_var = py_symbol_var.cast<PySymbolVar*>();
        ValueRef value = symbol_tsf->value_type().make(symbol_var->m_node);
        if (symbol_var->is_scalar) {
            value = scalar_tsf->value_type().make(value);
        }
        return value;
    }
86

87 88 89 90 91 92 93 94 95 96 97
    py::object val2symvar(py::handle typeobj, ValueRef value) {
        bool is_scalar = false;
        if (auto* scalar_value = value.as(scalar_tsf->value_type())) {
            value = scalar_value->value();
            is_scalar = true;
        }
        auto* node = value.cast(symbol_tsf->value_type()).node();
        auto py_symbol_var =
                typeobj(pybind11::cast(node, pybind11::return_value_policy::automatic));
        py_symbol_var.cast<PySymbolVar*>()->is_scalar = is_scalar;
        return py_symbol_var;
98 99
    }

100 101
    ~SymbolVarContext() { Transformation::swap_context(context); }
};
102

103 104
}  // namespace

105 106
interpreter::Interpreter::Channel* interpreter_for_py = nullptr;
PyTypeObject* py_tensor_type = nullptr;
107 108 109 110 111 112 113 114 115
PyObject *cpp_use_symbolic_shape, *cpp_astensor1d;

#define REGISTE_APPLY_FUNC(mode) \
    void set_##mode(py::object pyf) { mode = pyf.ptr(); }

REGISTE_APPLY_FUNC(cpp_use_symbolic_shape)
REGISTE_APPLY_FUNC(cpp_astensor1d)

#undef REGISTE_APPLY_FUNC
116

117 118 119
PyArray_Descr* _dtype_promotion(PyObject* const* args, size_t nargs);
CompNode _get_device(PyObject* const* args, size_t nargs);

M
Megvii Engine Team 已提交
120 121
PyObject* py_apply(
        PyObject* self, PyObject* const* args, size_t nargs /* , PyObject* kwnames */) {
122 123 124 125 126
    try {
        // if (kwnames && PyTuple_GET_SIZE(kwnames)) {
        //     PyErr_SetString(PyExc_TypeError, "keyword argument not allowed");
        //     return nullptr;
        // }
127
        if (nargs < 2) {
M
Megvii Engine Team 已提交
128 129 130 131
            PyErr_SetString(
                    PyExc_TypeError,
                    "py_apply expects one Op and at least one tensor "
                    "as argument");
132 133
            return nullptr;
        }
134

135
        auto* py_op = args[0];
136

137 138 139
        ++args;
        --nargs;

140
        auto op = py::handle(py_op).cast<std::shared_ptr<OpDef>>();
141
        SmallVector<ValueRef, 8> tensors(nargs);
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 179 180
        SmallVector<bool, 8> is_symbol_var(nargs, false);
        ComputingGraph* cg = nullptr;
        for (size_t i = 0; i < nargs; ++i) {
            if ((!TensorWrapper::try_cast(args[i])) &&
                py::isinstance<PySymbolVar>(py::handle(args[i]))) {
                is_symbol_var[i] = true;
                ComputingGraph* cur_cg =
                        py::handle(args[i]).cast<PySymbolVar*>()->m_node->owner_graph();
                if (cg == nullptr) {
                    cg = cur_cg;
                } else {
                    mgb_assert(cg == cur_cg);
                }
            }
        }

        mgb::CompNode target_cn;
        mgb::DType target_dtype;

        auto convert_pyinput_to_tensor = [&](size_t i) -> ValueRef {
            if (!target_dtype.valid()) {
                target_dtype = npy::dtype_np2mgb_descr(_dtype_promotion(args, nargs));
                target_cn = _get_device(args, nargs);
            }
            HostTensorND ht(target_cn);
            ht = npy::np2tensor(args[i], npy::Meth::copy_into(&ht), target_dtype);
            if (PyArray_Check(args[i])) {  // non scaler
                return imperative::apply(
                        CreateTensor(CreateTensor::Const, target_cn, ht.layout()),
                        HostStorage::make(ht.storage()))[0];
            } else {  // scaler
                return imperative::apply(
                        CreateTensor(CreateTensor::Const, target_cn, target_dtype, {}),
                        HostStorage::make(ht.storage()))[0];
            }
        };

        if (cg != nullptr) {
181
            // swap to a special context to reuse scalar handle
182 183
            size_t symbol_var_idx = 8;
            SymbolVarContext context(cg);
184
            context.init();
185
            for (size_t i = 0; i < nargs; ++i) {
186 187 188 189 190 191
                if (is_symbol_var[i]) {
                    symbol_var_idx = i;
                    tensors[i] = context.symvar2val(args[i]);
                } else {
                    tensors[i] = convert_pyinput_to_tensor(i);
                }
192
            }
193
            auto outputs = imperative::apply(*op, tensors);
194
            auto ret = pybind11::tuple(outputs.size());
195
            auto typeobj = py::handle(args[symbol_var_idx]).get_type();
196
            for (size_t i = 0; i < outputs.size(); ++i) {
197
                ret[i] = context.val2symvar(typeobj, outputs[i]);
198 199 200
            }
            return ret.release().ptr();
        }
201 202

        for (size_t i = 0; i < nargs; ++i) {
203
            if (TensorWrapper* tw = TensorWrapper::try_cast(args[i])) {
204
                tensors[i] = tw->m_tensor->data();
205
            } else {
206
                tensors[i] = convert_pyinput_to_tensor(i);
207 208 209
            }
        }

210
        auto outputs = [&] { return imperative::apply(*op, tensors); }();
211 212 213
        size_t nout = outputs.size();
        auto ret = py::tuple(nout);
        for (size_t i = 0; i < nout; ++i) {
214
            ret[i] = TensorWrapper::make(py_tensor_type, std::move(outputs[i]));
215 216
        }
        return ret.release().ptr();
M
Megvii Engine Team 已提交
217 218
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
219 220 221 222 223 224 225 226 227 228 229
}

TensorWrapper::TensorWrapper(PyObject* args, PyObject* kwargs) {
    if (kwargs && PyDict_Size(kwargs)) {
        throw py::type_error("keyword argument not allowed");
    }
    auto nargs = PyTuple_Size(args);
    auto tup = py::reinterpret_borrow<py::tuple>(args);
    if (nargs == 0) {
        throw py::type_error("too few arguments");
    }
230
    if (auto* t = try_cast(tup[0].ptr())) {
231 232 233
        if (nargs > 1) {
            throw py::type_error("expect 1 argument");
        }
234
        m_tensor = t->m_tensor->copy();
235
    } else {
236 237
        if (nargs == 1) {
            auto arg0 = PyTuple_GetItem(args, 0);
238 239 240 241 242 243
            // for DeviceTensorND
            if (strstr(arg0->ob_type->tp_name, "DeviceTensorND")) {
                auto dv = py::handle(arg0).cast<DeviceTensorND>();
                m_tensor = std::make_shared<Tensor>(imperative::apply(
                        CreateTensor(CreateTensor::Common, dv.comp_node(), dv.layout()),
                        DeviceStorage::make(dv.storage()))[0]);
244
            } else {
245 246
                throw py::type_error(
                        "single argument is not tensor, varnode or devicetensor");
247
            }
248
        } else {
M
Megvii Engine Team 已提交
249
            py::detail::loader_life_support life_sup;  // FIXME!!!required to cast DType
250 251
            if (nargs != 5 && nargs != 6) {
                throw py::type_error("expect 5 or 6 arguments");
252
            }
253 254 255 256
            auto data = tup[0].cast<py::array>();
            DType dtype = tup[1].cast<DType>();
            CompNode cn = tup[2].cast<CompNode>();
            bool is_const = tup[3].cast<bool>();
257
            bool no_cache = nargs == 6 ? tup[4].cast<bool>() : false;
258
            std::string name;
M
Megvii Engine Team 已提交
259 260
            if (tup[nargs - 1].ptr() != Py_None)
                name = tup[nargs - 1].cast<std::string>();
261 262

            // const op
263
            {
264 265 266
                CreateTensor::Kind kind = is_const ? CreateTensor::Const
                                        : no_cache ? CreateTensor::Unique
                                                   : CreateTensor::Common;
267
                HostTensorND ret(cn);
268 269 270 271 272 273 274 275 276 277 278
                ret = npy::np2tensor(data.ptr(), npy::Meth::copy_into(&ret), dtype);
                mgb_assert(
                        ret.layout().is_empty() || ret.layout().is_contiguous(),
                        "host value should be continuous");
                ValueShape shape;
                for (size_t i = 0; i < data.ndim(); ++i) {
                    shape[shape.ndim++] = data.shape(i);
                }
                m_tensor = std::make_shared<Tensor>(imperative::apply(
                        CreateTensor(kind, cn, ret.dtype(), shape),
                        HostStorage::make(ret.storage()))[0]);
279 280
            }

281 282 283
            if (!name.empty()) {
                m_tensor->reset(
                        imperative::apply(RenameValue(name), m_tensor->data())[0]);
284
            }
285 286
        }
    }
287
    mgb_assert(m_tensor->data());
288 289
}

290
PyObject* TensorWrapper::module_trace_info() {
291
    if (auto module_trace_info = module_trace_info_map.try_get(m_tensor->data())) {
292 293 294
        if (module_trace_info->ptr()) {
            return module_trace_info->inc_ref().ptr();
        }
295
    }
296 297 298 299 300
    PyErr_SetString(
            PyExc_AttributeError,
            "Has no attribute named \'_NodeMixin__node\', please "
            "set it first");
    return nullptr;
301 302 303
}

void TensorWrapper::set_module_trace_info(PyObject* obj) {
304
    // TODO: erase when obj == nullptr
305
    module_trace_info_map[m_tensor->data()] = py::reinterpret_borrow<py::object>(obj);
306 307
}

308 309 310 311 312
void TensorWrapper::_set_name(PyObject* dest) {
    auto py_dest = py::reinterpret_borrow<py::object>(dest);
    auto name = py_dest.cast<std::string>();
    m_tensor->set_name(name);
}
313

314 315
PyObject* TensorWrapper::_detail() {
    return py::str(m_tensor->data().unwrap().to_string()).release().ptr();
316 317
}

318 319
void TensorWrapper::_watch() {
    m_tensor->data().watch();
320 321
}

322
PyObject* TensorWrapper::shape() {
323
    auto shape = m_tensor->shape();
324

325
    if (!shape) {
326 327
        Py_RETURN_NONE;
    }
328 329 330
    py::tuple ret(shape->ndim);
    for (size_t i = 0; i < shape->ndim; ++i) {
        ret[i] = shape->at(i);
331 332 333 334 335 336 337 338 339 340 341 342 343
    }
    return ret.release().ptr();
}

PyObject* TensorWrapper::dtype() {
    return py::cast(m_tensor->dtype()).release().ptr();
}

PyObject* TensorWrapper::device() {
    return py::cast(m_tensor->comp_node()).release().ptr();
}

PyObject* TensorWrapper::numpy() {
344
    auto hv = m_tensor->numpy();
345
    if (!hv) {
346 347 348
        PyErr_SetString(PyExc_ValueError, "tensor invalid");
        return nullptr;
    }
349 350
    auto arr = py::reinterpret_steal<py::array>(
            npy::ndarray_from_tensor(hv->as_nd(true), npy::ShareType::TRY_SHARE));
351
    if (hv->shape().is_scalar()) {
352 353 354 355 356 357 358
        mgb_assert(PyArray_Check(arr.ptr()));
        return PyArray_Squeeze(reinterpret_cast<PyArrayObject*>(arr.ptr()));
    }
    return arr.release().ptr();
}

void TensorWrapper::reset(PyObject* tensor) {
359
    TensorWrapper* t = TensorWrapper::try_cast(tensor);
360 361 362
    if (!t) {
        throw py::type_error("expect Tensor");
    }
363
    m_tensor->reset(t->m_tensor->data());
364 365
}

366
PyObject* TensorWrapper::detach() {
367 368
    auto detached = imperative::apply(DetachGrad(), m_tensor->data())[0];
    return TensorWrapper::make(py_tensor_type, detached).release().ptr();
369 370
}

M
Megvii Engine Team 已提交
371
PyObject* TensorWrapper::_dev_tensor() {
372 373 374
    auto dv = m_tensor->data().dev_tensor();
    // TODO: handle scalar
    return py::cast(dv->as_nd(true)).release().ptr();
375 376 377
}

void TensorWrapper::_drop() {
378
    imperative::apply(DTRCommand(DTRCommand::Drop), m_tensor->data());
379 380
}

381
PyObject* TensorWrapper::isscalar() {
382
    if (m_tensor->is_scalar()) {
383 384 385 386 387 388 389 390 391 392 393 394 395
        Py_RETURN_TRUE;
    } else {
        Py_RETURN_FALSE;
    }
}

struct TensorWeakRef {
    std::weak_ptr<Tensor> wptr;

    TensorWeakRef(const TensorWrapper& tw) : wptr(tw.m_tensor) {}

    py::object operator()() {
        if (auto p = wptr.lock()) {
396
            return TensorWrapper::make(py_tensor_type, p);
397 398 399
        }
        return py::none();
    }
400
    int _use_cnt() { return wptr.use_count(); }
401 402
};

403 404 405 406 407
/* ============== convert inputs ============== */

// map numpy.dtype.kind to priority
inline uint8_t category_priority(char c) {
    switch (c) {
M
Megvii Engine Team 已提交
408 409 410 411 412 413 414 415 416 417
        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;
418 419 420 421 422 423 424 425 426
    }
}

// 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;
M
Megvii Engine Team 已提交
427
        for (auto&& desc : types) {
428 429 430 431 432 433
            max_p = std::max(max_p, category_priority(desc->kind));
        }
        return max_p;
    }
}

434
// Returns the data type with sufficient size to hold all types of
435 436 437 438
// 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;
M
Megvii Engine Team 已提交
439
    for (auto&& desc : types) {
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        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;
}

M
Megvii Engine Team 已提交
474
PyArray_Descr* _dtype_promotion(PyObject* const* args, size_t nargs) {
475 476 477 478 479
    // Return value: New reference
    SmallVector<PyArray_Descr*> tensors;
    SmallVector<PyArray_Descr*> scalars;

    bool is_tuple = false;
480
    PyObject* tuple = nullptr;
481 482 483 484 485 486 487 488 489 490 491 492
    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) {
M
Megvii Engine Team 已提交
493 494 495
        PyObject* handle = is_tuple ? PyTuple_GetItem(tuple, i) : args[i];
        if (handle == Py_None)
            continue;
496
        TensorWrapper* tw = TensorWrapper::try_cast(handle);
497 498 499 500 501
        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());
M
Megvii Engine Team 已提交
502
        } else {
503 504 505 506 507
            if (PyArray_Check(handle) || PyArray_CheckScalar(handle)) {
                auto&& descr = PyArray_DescrFromObject(handle, nullptr);
                tensors.emplace_back(descr);
                continue;
            }
508

M
Megvii Engine Team 已提交
509
            if (py::isinstance<PySymbolVar>(py::handle(handle))) {
510 511
                auto var = py::handle(handle).cast<PySymbolVar*>();
                mgb::DType type = var->m_node->dtype();
M
Megvii Engine Team 已提交
512
                auto&& descr = npy::dtype_mgb2np_descr(type);
513 514 515 516 517
                Py_INCREF(descr.get());
                tensors.emplace_back(descr.get());
                continue;
            }

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
            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);
M
Megvii Engine Team 已提交
535
    } else {
536 537
        res = promote_types(tensors, max_pri_tensors);
    }
M
Megvii Engine Team 已提交
538 539 540 541 542 543
    for (auto* p : tensors) {
        Py_DECREF(p);
    }
    for (auto* p : scalars) {
        Py_DECREF(p);
    }
544
    Py_XDECREF(tuple);
545 546 547
    return res;
}

M
Megvii Engine Team 已提交
548
CompNode _get_device(PyObject* const* args, size_t nargs) {
549
    bool is_tuple = false;
550
    PyObject* tuple = nullptr;
551 552 553 554 555 556 557 558 559 560 561 562 563
    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) {
564
        PyObject* handle = is_tuple ? PyTuple_GetItem(tuple, i) : args[i];
565
        TensorWrapper* tw = TensorWrapper::try_cast(handle);
566

567 568
        bool is_symvar = py::isinstance<PySymbolVar>(py::handle(handle));
        if (tw || is_symvar) {
569
            if (!valid) {
570
                cn = tw ? tw->m_tensor->comp_node()
M
Megvii Engine Team 已提交
571
                        : py::handle(handle).cast<PySymbolVar*>()->m_node->comp_node();
572 573
                valid = true;
            } else {
574 575 576 577
                CompNode cn1 = tw ? tw->m_tensor->comp_node()
                                  : py::handle(handle)
                                               .cast<PySymbolVar*>()
                                               ->m_node->comp_node();
578
                if (cn1 != cn) {
M
Megvii Engine Team 已提交
579
                    throw py::value_error(ssprintf(
580 581 582
                            "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()));
583 584 585 586 587
                }
            }
        }
    }
    if (!valid) {
588
        return CompNode::load(get_default_device());
589
    }
590
    Py_XDECREF(tuple);
591 592 593 594 595
    return cn;
}

// Returns the dtype that would result from performing an arithmetic
// operation on the provided input tensors and scalars.
M
Megvii Engine Team 已提交
596
PyObject* dtype_promotion(PyObject* self, PyObject* const* args, size_t nargs) {
597 598 599 600 601 602 603
    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();
M
Megvii Engine Team 已提交
604 605
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
606 607
}

M
Megvii Engine Team 已提交
608
PyObject* get_device(PyObject* self, PyObject* const* args, size_t nargs) {
609 610 611 612 613 614 615
    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();
M
Megvii Engine Team 已提交
616 617
    }
    PYEXT17_TRANSLATE_EXC_RET(nullptr)
618
}
619

620 621 622 623 624 625 626 627 628 629 630 631 632
#ifdef METH_FASTCALL
#define MGE_PY_INTERFACE(NAME, FUNC) \
    { #NAME, (PyCFunction)FUNC, METH_FASTCALL, nullptr }
#else
#define WRAP_FUNC_PY35(FUNC)                                \
    PyObject* py35_##FUNC(PyObject* self, PyObject* args) { \
        auto* arr = &PyTuple_GET_ITEM(args, 0);             \
        auto size = PyTuple_GET_SIZE(args);                 \
        return FUNC(self, arr, size);                       \
    }
WRAP_FUNC_PY35(py_apply);
WRAP_FUNC_PY35(dtype_promotion);
WRAP_FUNC_PY35(get_device);
633 634 635
WRAP_FUNC_PY35(make_shape_tuple);
WRAP_FUNC_PY35(getitem_cpp);
WRAP_FUNC_PY35(setitem_cpp);
636
WRAP_FUNC_PY35(split_cpp);
637
WRAP_FUNC_PY35(expand_dims_cpp);
638 639 640 641 642
#undef WRAP_FUNC_PY35
#define MGE_PY_INTERFACE(NAME, FUNC) \
    { #NAME, (PyCFunction)py35_##FUNC, METH_VARARGS, nullptr }
#endif

643
void init_tensor(py::module m) {
644
    imperative::Tensor::static_initialize();
645 646 647 648 649

    static auto& transformations = TransformationManager::get_instance();

    using Segment = TransformationManager::Segment;

650 651 652 653 654 655
    using Channel = interpreter::Interpreter::Channel;

    auto* channel =
            imperative::ResourceManager::create_global<std::unique_ptr<Channel>>(
                    interpreter::Interpreter::inst().create_channel())
                    ->get();
656 657 658
    interpreter_for_py = channel;
    transformations.register_at<Segment::Eval>(
            std::make_shared<InterpreterTransformation>(
659
                    std::shared_ptr<Channel>(channel, [](Channel*) {})));
660 661
    transformations.register_at<Segment::Scalar>(
            std::make_shared<ScalarTransformation>());
662 663
    transformations.register_at<Segment::DTypePromote>(
            std::make_shared<DTypePromoteTransformation>());
664

M
Megvii Engine Team 已提交
665 666
    static py::exception<interpreter::AsyncError> py_async_error(
            m, "AsyncError", PyExc_RuntimeError);
667 668
    py::register_exception_translator([](std::exception_ptr p) {
        try {
M
Megvii Engine Team 已提交
669 670
            if (p)
                std::rethrow_exception(p);
671 672 673 674 675 676 677 678 679 680
        } catch (const interpreter::AsyncError& e) {
            pyext17::pybind11_translate_exception(e.nested_ptr());
            if (PyErr_Occurred()) {
                PyObject *exc, *val, *tb;
                PyErr_Fetch(&exc, &val, &tb);
                PyErr_NormalizeException(&exc, &val, &tb);
                if (tb) {
                    PyException_SetTraceback(val, tb);
                }
                auto val2 = py_async_error.py::object::operator()(
M
Megvii Engine Team 已提交
681 682
                        "An async error is reported. See above for the actual cause."
                        " Hint: This is where it is reported, not where it happened."
683
                        " You may call `megengine.config.async_level = 0 "
M
Megvii Engine Team 已提交
684 685 686
                        "to get better error reporting.");
                PyException_SetCause(
                        val2.ptr(), val);  // PyException_SetCause steals reference
687 688
                Py_XDECREF(exc);
                Py_XDECREF(tb);
M
Megvii Engine Team 已提交
689 690
                PyErr_Restore(
                        py_async_error.inc_ref().ptr(), val2.release().ptr(), nullptr);
691 692 693 694 695 696
            } else {
                py_async_error("Unkown async error");
            }
        }
    });

M
Megvii Engine Team 已提交
697 698 699 700 701 702 703 704 705
    auto* tensor_type =
            TensorWrapper::wrap_t::type()
                    .def<&TensorWrapper::numpy>("numpy")
                    .def_getset<&TensorWrapper::shape>("shape")
                    .def_getset<&TensorWrapper::dtype>("dtype")
                    .def_getset<&TensorWrapper::device>("device")
                    .def<&TensorWrapper::reset>("_reset")
                    .def<&TensorWrapper::isscalar>("_isscalar")
                    .def<&TensorWrapper::detach>("detach")
706
                    // TODO: remove this
M
Megvii Engine Team 已提交
707 708 709
                    .def<&TensorWrapper::_dev_tensor>("_dev_tensor")
                    .def<&TensorWrapper::_drop>("_drop")
                    .def<&TensorWrapper::_use_cnt>("_use_cnt")
710 711 712
                    .def<&TensorWrapper::_detail>("_detail")
                    .def<&TensorWrapper::_set_name>("_set_name")
                    .def<&TensorWrapper::_watch>("_watch")
M
Megvii Engine Team 已提交
713 714 715 716 717 718
                    .def_getset<
                            &TensorWrapper::module_trace_info,
                            &TensorWrapper::set_module_trace_info>("_NodeMixin__node")
                    .finalize();
    if (!tensor_type)
        throw py::error_already_set();
719 720 721
    py::setattr(m, "Tensor", tensor_type);

    py::class_<TensorWeakRef>(m, "TensorWeakRef")
M
Megvii Engine Team 已提交
722 723 724
            .def(py::init<const TensorWrapper&>())
            .def("__call__", &TensorWeakRef::operator())
            .def("_use_cnt", &TensorWeakRef::_use_cnt);
725

726 727 728
    py::class_<PySymbolVar, std::shared_ptr<PySymbolVar>>(m, "SymbolVar")
            .def_property_readonly(
                    "dtype", [](PySymbolVar* v) { return v->m_node->dtype(); })
M
Megvii Engine Team 已提交
729 730 731
            .def_property(
                    "var", [](PySymbolVar* v) { return v->m_node; },
                    [](PySymbolVar* s, cg::VarNode* v) { s->m_node = v; })
732
            .def_property_readonly(
M
Megvii Engine Team 已提交
733
                    "device", [](PySymbolVar* v) { return v->m_node->comp_node(); })
734
            .def_property_readonly(
M
Megvii Engine Team 已提交
735
                    "graph", [](PySymbolVar* v) { return v->m_node->owner_graph(); })
736 737 738
            .def_property_readonly(
                    "shape",
                    [](PySymbolVar* v) -> const TensorShape* {
M
Megvii Engine Team 已提交
739
                        auto&& mgr = v->m_node->owner_graph()->static_infer_manager();
740 741
                        return mgr.infer_shape_fallible(v->m_node);
                    })
M
Megvii Engine Team 已提交
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
            .def("numpy",
                 [](PySymbolVar* v) {
                     auto&& mgr = v->m_node->owner_graph()->static_infer_manager();
                     auto&& type = mgr.get_infer_type(v->m_node);
                     using InferType = cg::static_infer::InferType;
                     if (!(type.value & (InferType::CONST | InferType::RT_STATIC))) {
                         throw py::value_error("value invalid!");
                     }
                     auto* val = mgr.infer_value_fallible(v->m_node);
                     if (!val) {
                         throw py::value_error("value invalid!");
                     }
                     auto np_val = py::cast(*val).attr("numpy")();
                     return np_val;
                 })
757 758 759 760 761 762
            .def("_isscalar", [](PySymbolVar* v) { return v->is_scalar; })
            .def(py::init([](cg::VarNode* node) {
                     return std::make_shared<PySymbolVar>(node);
                 }),
                 py::arg() = nullptr);

763
    static PyMethodDef method_defs[] = {
764 765 766
            MGE_PY_INTERFACE(apply, py_apply),
            MGE_PY_INTERFACE(dtype_promotion, dtype_promotion),
            MGE_PY_INTERFACE(get_device, get_device),
767 768 769
            MGE_PY_INTERFACE(make_shape_tuple, make_shape_tuple),
            MGE_PY_INTERFACE(getitem_cpp, getitem_cpp),
            MGE_PY_INTERFACE(setitem_cpp, setitem_cpp),
770
            MGE_PY_INTERFACE(split_cpp, split_cpp),
771
            MGE_PY_INTERFACE(expand_dims_cpp, expand_dims_cpp),
772
            {nullptr, nullptr, 0, nullptr}};
M
Megvii Engine Team 已提交
773
    for (auto&& def : method_defs) {
774 775
        if (def.ml_meth != nullptr) {
            auto* func = PyCFunction_NewEx(&def, nullptr, nullptr);
M
Megvii Engine Team 已提交
776 777
            if (!func)
                throw py::error_already_set();
778 779 780
            py::setattr(m, def.ml_name, func);
        }
    }
781

782 783 784 785
    static constexpr auto sync_py_task_q = [] {
        py::gil_scoped_release _;
        py_task_q.wait_all_task_finish();
    };
786

787
    m.def("clear_candidates", [channel]() { channel->clear_candidates(); });
788 789
    m.def("set_option", [channel](std::string name, size_t value) {
        channel->set_option(name, value);
M
Megvii Engine Team 已提交
790
    });
791
    m.def("get_option",
792 793 794 795 796 797 798 799 800 801 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 835 836 837
          [channel](std::string name) { return channel->get_option(name); });
    m.def("push_scope", [channel](std::string name) {
        Transformation::push_scope(name);
        channel->push_scope(name);
    });
    m.def("pop_scope", [channel](std::string name) {
        channel->pop_scope(name);
        Transformation::pop_scope(name);
    });
    m.def("start_profile", [channel](imperative::Profiler::options_t options) {
        channel->sync();
        imperative::Profiler::load_options(std::move(options));
        imperative::Profiler::start_profile();
        channel->start_profile();
    });
    m.def("stop_profile", [channel]() -> std::function<void(std::string, std::string)> {
        channel->stop_profile();
        channel->sync();
        imperative::Profiler::stop_profile();
        auto results = std::make_shared<imperative::Profiler::bundle_t>(
                imperative::Profiler::collect());
        return [results = results](std::string basename, std::string format) mutable {
            imperative::Profiler::dump_profile(basename, format, std::move(*results));
            results = nullptr;
        };
    });
    m.def("sync", [channel]() {
        if (channel->check_available()) {
            channel->sync();
        }
        sync_py_task_q();
    });
    m.def("full_sync", [channel]() {
        if (channel->check_available()) {
            channel->sync();
        }
        CompNode::sync_all();
        CompNode::foreach ([](CompNode cn) {
            auto err = cn.check_async_error();
            mgb_assert(!err, "%s", err->what());
        });
        sync_py_task_q();
    });
    m.def("close", [channel]() {
        channel->close();
        sync_py_task_q();
M
Megvii Engine Team 已提交
838 839 840 841 842 843 844 845
    });

    py::handle grad_key_type =
            GradKeyWrapper::wrap_t::type()
                    .def<&GradKeyWrapper::attach>("attach")
                    .def<&GradKeyWrapper::is_attached_to>("is_attached_to")
                    .def_getset<&GradKeyWrapper::get_name, &GradKeyWrapper::set_name>(
                            "name")
846 847 848 849
                    .def<&GradKeyWrapper::enter>("enter")
                    .def<&GradKeyWrapper::exit>("exit")
                    .def<&GradKeyWrapper::suppress>("suppress")
                    .def<&GradKeyWrapper::resume>("resume")
M
Megvii Engine Team 已提交
850 851 852
                    .finalize();
    if (!grad_key_type)
        throw py::error_already_set();
853
    py::setattr(m, "GradKey", grad_key_type);
854
    m.def("backward", &GradKeyWrapper::backward);
855
    m.def("get_backward_closure", &GradKeyWrapper::get_backward_closure);
856

857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    m.def("set_py_tensor_type", [](py::object type_obj) {
        py_tensor_type = reinterpret_cast<PyTypeObject*>(type_obj.inc_ref().ptr());
    });

    /**
     * \brief trace proxy
     *
     */
    struct Trace {
        bool symbolic = false;
        bool no_exec = false;
        bool capture_as_const = false;
        bool profile = false;
        bool record_input_shapes = false;
        py::function options_visitor;
        std::shared_ptr<TracingTransformation> tracing;
        std::shared_ptr<CompiledTransformation> compiled;
        std::shared_ptr<LazyEvalTransformation> lazy_eval;
        std::pair<size_t, std::shared_ptr<GraphProfiler>> profiler;
        std::optional<TraceResult> trace_result;
        std::function<bool(py::object, py::object)> array_comparator;

        bool compare_value(ValueRef lhs, ValueRef rhs) {
880 881
            auto lvalue = lhs.cast_ref<HostValue>();
            auto rvalue = rhs.cast_ref<HostValue>();
882
            if (lvalue->shape() != rvalue->shape()) {
883 884
                return false;
            }
885
            if (lvalue->shape().total_nr_elems() == 1) {
886 887 888 889
                return lvalue->item() == rvalue->item();
            }
            HostTensorND lnd = lvalue->as_nd(true);
            HostTensorND rnd = rvalue->as_nd(true);
890
            auto larr = py::reinterpret_steal<py::array>(
891
                    npy::ndarray_from_tensor(lnd, npy::ShareType::TRY_SHARE));
892
            auto rarr = py::reinterpret_steal<py::array>(
893
                    npy::ndarray_from_tensor(rnd, npy::ShareType::TRY_SHARE));
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
            return array_comparator(larr, rarr);
        }

        void enter() {
            auto& self = *this;
            if (!self.trace_result) {  // untraced
                self.tracing = std::make_shared<TracingTransformation>(
                        self.capture_as_const, self.record_input_shapes);
                if (self.symbolic) {
                    self.lazy_eval =
                            std::make_shared<LazyEvalTransformation>(self.no_exec);
                    self.options_visitor(py::cast(&self.lazy_eval->options()));
                }
            } else if (!self.compiled) {  // traced but not compiled
                using namespace std::placeholders;
                self.compiled = std::make_shared<CompiledTransformation>(
                        *self.trace_result, self.record_input_shapes);
                self.compiled->set_value_comparator(
                        std::bind(&Trace::compare_value, this, _1, _2));
                self.options_visitor(py::cast(&self.compiled->options()));
                self.compiled->compile();
            }
            // register transformations
            if (self.compiled) {
                if (self.profile) {
                    auto& current_graph = self.compiled->graph();
                    if (self.profiler.first != self.compiled->graph().id()) {
                        // graph changed
                        self.profiler = std::make_pair(
                                current_graph.id(),
                                std::make_shared<GraphProfiler>(&current_graph));
                    }
                }
                transformations.register_at<Segment::Trace>(self.compiled);
                // start execute because InputCallback depends
                self.compiled->execute();
            } else if (self.tracing) {
                transformations.register_at<Segment::Trace>(self.tracing);
                if (self.lazy_eval) {
                    transformations.register_at<Segment::Eval>(self.lazy_eval);
                }
            } else {
                mgb_throw(MegBrainError, "invalid state: neither tracing nor compiled");
            }
        }

        void exit() {
            auto& self = *this;
            if (self.tracing) {
                transformations.unregister<Segment::Trace>(self.tracing);
                self.trace_result = self.tracing->get_result();
                self.tracing.reset();
                if (self.lazy_eval) {
                    auto lazy_eval = std::move(self.lazy_eval);
                    transformations.unregister<Segment::Eval>(lazy_eval);
                    lazy_eval->check_exception();
                }
            } else if (self.compiled) {
                transformations.unregister<Segment::Trace>(self.compiled);
                self.compiled->wait();
            } else {
                mgb_throw(MegBrainError, "invalid state: neither tracing nor compiled");
            }
        }

        VarNodeArray dump(
                std::shared_ptr<ComputingGraph> graph,
                std::vector<std::tuple<std::string, std::string, TensorShape>> inputs,
                std::vector<std::pair<std::string, std::string>> outputs,
                bool prefer_input_names) {
            auto& self = *this;
            mgb_assert(self.trace_result);
            // mark is like "arg_0", "kwarg_xxx", "output_0" ...
            std::unordered_map<std::string, size_t> mark2var;
            for (size_t i = 0; i < self.trace_result->vars.size(); ++i) {
                auto& name = self.trace_result->vars[i].mark;
                if (!name.empty()) {
                    mark2var[name] = i;
                }
            }
            std::vector<std::tuple<size_t, std::string, TensorShape>> input_vars;
            std::vector<std::pair<size_t, std::string>> output_vars;
            for (auto&& [input_mark, input_name, input_shape] : inputs) {
                mgb_assert(input_shape.ndim, "input shape invalid");
                input_vars.push_back(
                        {mark2var.at(input_mark), input_name, input_shape});
            }
            for (auto&& [output_name, repr] : outputs) {
                output_vars.push_back({mark2var.at(output_name), repr});
            }
            self.options_visitor(py::cast(&graph->options()));
            auto vars = self.trace_result->dump(
                    *graph, input_vars, output_vars, prefer_input_names);
            return vars;
        }
    };

    py::class_<Trace>(m, "Trace")
            .def(py::init<>())
            .def_readwrite("record_input_shapes", &Trace::record_input_shapes)
            .def_readwrite("array_comparator", &Trace::array_comparator)
            .def_readwrite("profile", &Trace::profile)
            .def_property_readonly(
                    "options",
                    [](Trace& self) {
                        if (self.compiled) {
                            return &self.compiled->options();
                        } else {
                            return (ComputingGraph::Options*)nullptr;
                        }
                    })
            .def("get_profile",
                 [](Trace& self) -> py::object {
                     if (self.profiler.second && self.compiled) {
                         auto json = self.profiler.second->to_json_full(
                                 self.compiled->graph().current_comp_seq());
                         return py::str(json->to_string());
                     } else {
                         return py::none();
                     }
                 })
            .def_readwrite("symbolic", &Trace::symbolic)
            .def_readwrite("capture_as_const", &Trace::capture_as_const)
            .def_readwrite("no_exec", &Trace::no_exec)
            .def_readwrite("options_visitor", &Trace::options_visitor)
            .def("enter", &Trace::enter)
            .def("exit", &Trace::exit)
            .def("dump", &Trace::dump)
            .def("begin_excluded_region",
                 [](Trace& self) {
                     mgb_assert(bool(self.tracing) ^ bool(self.compiled));
                     if (self.tracing) {
                         transformations.unregister<Segment::Trace>(self.tracing);
                     } else if (self.compiled) {
                         transformations.unregister<Segment::Trace>(self.compiled);
                     }
M
Megvii Engine Team 已提交
1030
                 })
1031 1032 1033 1034 1035 1036 1037 1038 1039
            .def("end_excluded_region", [](Trace& self) {
                mgb_assert(bool(self.tracing) ^ bool(self.compiled));
                if (self.tracing) {
                    transformations.register_at<Segment::Trace>(self.tracing);
                } else if (self.compiled) {
                    transformations.register_at<Segment::Trace>(self.compiled);
                }
            });

1040 1041 1042 1043 1044 1045 1046 1047
    m.def("reduce_to_scalar", [](py::object op, py::object tensor) -> py::object {
        auto reduce_to_scalar = [](const OpDef& op, const ValueRef& input) {
            auto make_scalar_shape = [&](CompNode device) {
                return imperative::apply(
                        CreateTensor(CreateTensor::Const, device, dtype::Int32(), {0}),
                        HostStorage::make(device))[0];
            };
            return imperative::apply(op, input, make_scalar_shape(*input.device()))[0];
1048
        };
1049 1050 1051 1052 1053
        if (py::isinstance<PySymbolVar>(tensor)) {
            auto* graph = tensor.cast<PySymbolVar*>()->m_node->owner_graph();
            SymbolVarContext context(graph);
            context.init();
            auto output = reduce_to_scalar(
1054
                    *op.cast<std::shared_ptr<OpDef>>(), context.symvar2val(tensor));
1055
            auto typeobj = tensor.get_type();
1056
            return context.val2symvar(typeobj, output);
1057 1058 1059 1060 1061 1062
        } else {
            auto* tw = TensorWrapper::try_cast(tensor.ptr());
            auto output = reduce_to_scalar(
                    *op.cast<std::shared_ptr<OpDef>>(), tw->m_tensor->data());
            return TensorWrapper::make(py_tensor_type, output);
        }
1063 1064
    });

1065 1066 1067 1068 1069 1070 1071
    m.def("name_tensor", [](std::string name, py::object tensor) {
        auto* tw = TensorWrapper::try_cast(tensor.ptr());
        auto output = imperative::apply(TraceMarkVar(name), tw->m_tensor->data())[0];
        tw->m_tensor->reset(output);
    });

    m.def("is_grad_attached", [](std::vector<py::object> tensors) -> bool {
1072
        SmallVector<ValueRef> values(tensors.size());
1073 1074
        for (size_t i = 0; i < tensors.size(); ++i) {
            values[i] = tensors[i].cast<TensorWrapper>().m_tensor->data();
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        }
        auto outputs = imperative::apply(GetGradKey(), values);
        if (outputs[0].is<GradKeyValue>()) {
            return true;
        } else {
            return false;
        }
    });

    m.def("get_grad_key", [](std::vector<py::object> tensors) -> py::object {
1085
        SmallVector<ValueRef> values(tensors.size());
1086 1087
        for (size_t i = 0; i < tensors.size(); ++i) {
            values[i] = tensors[i].cast<TensorWrapper>().m_tensor->data();
1088
        }
1089 1090
        auto output = imperative::apply(GetGradKey(), values)[0];
        if (!output) {
1091 1092
            return py::none();
        }
1093 1094
        return py::reinterpret_borrow<py::object>(GradKeyWrapper::wrap_t::pycast(
                GradKeyWrapper::get(output.cast<GradKeyValue>())));
1095 1096 1097 1098 1099 1100 1101 1102
    });

    m.def("set_grad", [](py::object py_key, py::function backward_fn,
                         std::vector<py::object> inputs,
                         std::vector<py::object> outputs) {
        mgb_assert(GradKeyWrapper::wrap_t::type().isinstance(py_key.ptr()));
        auto* key = reinterpret_cast<GradKeyWrapper::wrap_t*>(py_key.ptr())->inst();
        GenericFunction generic_backward_fn =
1103
                [backward_fn](Span<ValueRef> output_grads) -> ValueRefList {
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
            py::list output_grad_tws;
            for (auto&& output_grad : output_grads) {
                if (output_grad) {
                    output_grad_tws.append(
                            TensorWrapper::make(py_tensor_type, output_grad));
                } else {
                    output_grad_tws.append(py::none());
                }
            }
            py::tuple input_grad_tws = backward_fn(*output_grad_tws);
1114 1115 1116
            ValueRefList input_grads(input_grad_tws.size());
            for (size_t i = 0; i < input_grad_tws.size(); ++i) {
                auto input_grad_tw = input_grad_tws[i];
1117
                if (!input_grad_tw.is_none()) {
1118 1119
                    input_grads[i] =
                            py::cast<TensorWrapper>(input_grad_tw).m_tensor->data();
1120
                } else {
1121
                    input_grads[i] = {};
1122 1123 1124 1125
                }
            }
            return input_grads;
        };
1126
        SmallVector<ValueRef> values(inputs.size() + outputs.size());
1127 1128
        for (size_t i = 0; i < inputs.size(); ++i) {
            values[i] = inputs[i].cast<TensorWrapper>().m_tensor->data();
1129
        }
1130 1131 1132
        for (size_t i = 0; i < outputs.size(); ++i) {
            values[i + inputs.size()] =
                    outputs[i].cast<TensorWrapper>().m_tensor->data();
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
        }
        auto wrapped_output_values = imperative::apply(
                SetGrad(key->m_key, generic_backward_fn, inputs.size()), values);
        std::vector<py::object> wrapped_outputs;
        mgb_assert(wrapped_output_values.size() == outputs.size());
        for (auto&& output_value : wrapped_output_values) {
            wrapped_outputs.push_back(
                    TensorWrapper::make(py_tensor_type, output_value));
        }
        return wrapped_outputs;
    });

    static py::function module_trace_hook;

1147 1148
    static auto get_module_trace = [] {
        static std::shared_ptr<ModuleTraceTransformation> module_trace_transformation;
1149 1150 1151 1152
        if (!module_trace_transformation) {
            mgb_assert(module_trace_hook);
            module_trace_transformation =
                    std::make_shared<ModuleTraceTransformation>(module_trace_hook);
1153
            transformations.register_at<Segment::ModuleTrace>(
1154 1155
                    module_trace_transformation);
        }
1156 1157
        return module_trace_transformation;
    };
1158

1159 1160 1161 1162
    m.def("set_cpp_use_symbolic_shape", &set_cpp_use_symbolic_shape);

    m.def("set_cpp_astensor1d", &set_cpp_astensor1d);

1163 1164 1165
    m.def("set_module_tracing", [=] { get_module_trace()->enable(); });

    m.def("unset_module_tracing", [=] { get_module_trace()->disable(); });
1166

1167
    m.def("is_tracing_module", [=] { return get_module_trace()->enabled(); });
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

    m.def("set_module_trace_hook",
          [](py::function function) { module_trace_hook = function; });

    m.def("begin_record_values", [] { Value::begin_record_values(); });

    m.def("end_record_values", [] {
        std::vector<std::pair<size_t, std::string>> reprs;
        auto values = Value::end_record_values();
        for (auto&& value : values) {
            reprs.push_back({value.id(), value.to_string()});
        }
        return reprs;
    });

1183 1184 1185 1186
    m.def("print_stats", [] { imperative::Stats::print(); });

    m.def("reset_stats", [] { imperative::Stats::reset(); });

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 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
    m.def("_get_convert_inputs",
          []() -> bool { return DTypePromoteCfg::convert_input_enabled; });
    m.def("_set_convert_inputs", [](bool flag) -> bool {
        bool ret = DTypePromoteCfg::convert_input_enabled;
        DTypePromoteCfg::convert_input_enabled = flag;
        return ret;
    });
    m.def("_get_amp_dtype_autocast",
          []() -> bool { return DTypePromoteCfg::amp_dtype_autocast_enabled; });
    m.def("_set_amp_dtype_autocast", [](bool flag) -> bool {
        bool ret = DTypePromoteCfg::amp_dtype_autocast_enabled;
        DTypePromoteCfg::amp_dtype_autocast_enabled = flag;
        return ret;
    });

    static auto get_amp_prec_dtype = [](bool is_high) -> std::string {
        DType& target = is_high ? DTypePromoteCfg::amp_high_prec_dtype
                                : DTypePromoteCfg::amp_low_prec_dtype;
        mgb_assert(target.category() == DTypeCategory::FLOAT);
        std::string ret = target.name();
        transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
        return ret;
    };

    static auto set_amp_prec_dtype = [](bool is_high,
                                        std::string dtype_name) -> std::string {
        DType& target = is_high ? DTypePromoteCfg::amp_high_prec_dtype
                                : DTypePromoteCfg::amp_low_prec_dtype;
        std::string ret = target.name();

        if (dtype_name == "float32") {
            target = dtype::Float32();
        } else if (dtype_name == "float16") {
            target = dtype::Float16();
        } else if (dtype_name == "bfloat16") {
            target = dtype::BFloat16();
        } else {
            mgb_assert(
                    false, "casted type of amp should be float, but you give %s\n",
                    dtype_name.c_str());
        }

        transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
        return ret;
    };

    m.def("_get_amp_high_prec_dtype",
          []() -> std::string { return get_amp_prec_dtype(true); });
    m.def("_set_amp_high_prec_dtype", [](std::string dtype_name) -> std::string {
        return set_amp_prec_dtype(true, dtype_name);
    });
    m.def("_get_amp_low_prec_dtype",
          []() -> std::string { return get_amp_prec_dtype(false); });
    m.def("_set_amp_low_prec_dtype", [](std::string dtype_name) -> std::string {
        return set_amp_prec_dtype(false, dtype_name);
    });

1244
    py::register_exception<TraceError>(m, "TraceError");
1245 1246
}

1247 1248
#undef MGE_PY_INTERFACE

M
Megvii Engine Team 已提交
1249
}  // namespace mgb::imperative::python