You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tensor.cpp 35 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. /**
  2. * \file imperative/python/src/tensor.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #include "megbrain/dtype.h"
  12. #include "megbrain/common.h"
  13. #include "megbrain/imperative/ops/utility.h"
  14. #include "megbrain/imperative/ops/backward_graph.h"
  15. #include "./tensor.h"
  16. #include "./grad.h"
  17. #include "./trace.h"
  18. #include "./common.h"
  19. #include "./numpy_dtypes.h"
  20. #include "./graph_rt.h"
  21. #include "./helper.h"
  22. #include <pybind11/numpy.h>
  23. #include <pybind11/operators.h>
  24. #include <range/v3/all.hpp>
  25. #include <string>
  26. #include <unordered_map>
  27. namespace py = pybind11;
  28. namespace views = ranges::views;
  29. namespace mgb::imperative::python {
  30. interpreter::Interpreter::Channel* interpreter_for_py;
  31. PyObject *cpp_apply_with_tracing, *cpp_apply_const_with_tracing;
  32. PyObject *cpp_apply_backward_varnode;
  33. #define REGISTE_APPLY_FUNC(mode) \
  34. void set_##mode(py::object pyf) { \
  35. mode = pyf.ptr(); \
  36. }
  37. REGISTE_APPLY_FUNC(cpp_apply_with_tracing)
  38. REGISTE_APPLY_FUNC(cpp_apply_const_with_tracing)
  39. REGISTE_APPLY_FUNC(cpp_apply_backward_varnode)
  40. #undef REGISTE_APPLY_FUNC
  41. Tensor::flags_t ApplyContext::global_disable = 0;
  42. Tensor::flags_t ApplyContext::global_enable = 0;
  43. void set_tracing() { ApplyContext::global_enable |= Tensor::Flags::TRACE; }
  44. void unset_tracing() { ApplyContext::global_enable &= ~Tensor::Flags::TRACE; }
  45. bool skip_tracing = false;
  46. apply_result_t apply(ApplyContext& ctx) {
  47. // emulating scalar should be put to specific op's apply, e.g.,
  48. // elementwise, reduce, typecvt. Currently it's still handled at python
  49. // side. It could be move to C++ side if it has an impact on performance
  50. auto flags = ctx.flags & ~ApplyContext::global_disable;
  51. flags = flags | ApplyContext::global_enable;
  52. if (flags & Tensor::Flags::SCALAR) {
  53. // TODO: emulate scalar
  54. }
  55. if (flags & Tensor::Flags::GRAD) {
  56. return apply_grad(ctx);
  57. }
  58. if (auto* op = ctx.op->try_cast_final<GenericPyOp>()) {
  59. py::tuple pyin(ctx.nargs);
  60. for (size_t i = 0; i < ctx.nargs; ++i) {
  61. pyin[i] = TensorWrapper::make(ctx.pytype, ctx.args[i]->shared_from_this());
  62. }
  63. auto f = py::getattr(op->obj, "_default_rule");
  64. auto pyout = py::reinterpret_steal<py::object>(PyObject_Call(f.ptr(), pyin.ptr(), nullptr));
  65. if (!pyout) throw py::error_already_set();
  66. if (auto* tw = TensorWrapper::try_cast(pyout.ptr())) {
  67. return {tw->m_tensor};
  68. }
  69. apply_result_t ret;
  70. ret.reserve(py::len(pyout));
  71. for (auto&& i : pyout) {
  72. auto* tw = TensorWrapper::try_cast(i.ptr());
  73. mgb_assert(tw);
  74. ret.push_back(tw->m_tensor);
  75. }
  76. return ret;
  77. }
  78. if (flags & Tensor::Flags::TRACE) {
  79. return apply_trace(ctx);
  80. } else {
  81. SmallVector<interpreter::Interpreter::Handle> handles(ctx.nargs);
  82. for (size_t i = 0; i < ctx.nargs; ++i) {
  83. handles[i] = ctx.args[i]->m_handle.get();
  84. }
  85. apply_result_t outputs;
  86. // fast copy without really applying
  87. if (ctx.op->same_type<FastpathCopy>()) {
  88. mgb_assert(ctx.nargs == 1);
  89. outputs.reserve(ctx.nargs);
  90. outputs.emplace_back(std::make_shared<Tensor>(ctx.args[0]->m_handle));
  91. return outputs;
  92. }
  93. auto output_handles = interpreter_for_py->apply_op(ctx.op, handles);
  94. outputs.reserve(output_handles.size());
  95. for (auto h : output_handles) {
  96. outputs.emplace_back(std::make_shared<Tensor>(h));
  97. }
  98. return outputs;
  99. }
  100. mgb_assert(0);
  101. }
  102. PyObject* py_apply(PyObject* self, PyObject*const* args, size_t nargs/* , PyObject* kwnames */) {
  103. try {
  104. // if (kwnames && PyTuple_GET_SIZE(kwnames)) {
  105. // PyErr_SetString(PyExc_TypeError, "keyword argument not allowed");
  106. // return nullptr;
  107. // }
  108. if (nargs < 2) {
  109. PyErr_SetString(PyExc_TypeError,
  110. "py_apply expects one Op and at least one tensor "
  111. "as argument");
  112. return nullptr;
  113. }
  114. auto* op = args[0];
  115. PyTypeObject* pytype = args[1]->ob_type;
  116. // check if pytype is Parameter(and all other python Tensor's derived class),
  117. // if yes, using it's tp_base(python Tensor)
  118. if (TensorWrapper::wrap_t::type().same_pytype(pytype->tp_base->tp_base)) {
  119. pytype = pytype->tp_base;
  120. }
  121. ++args;
  122. --nargs;
  123. ApplyContext ctx;
  124. ctx.flags = 0;
  125. ctx.op = py::handle(op).cast<std::shared_ptr<OpDef>>();
  126. SmallVector<Tensor*, 64> tensors(nargs);
  127. ctx.args = &tensors[0];
  128. ctx.nargs = nargs;
  129. ctx.pytype = pytype;
  130. if (py::isinstance<PySymbolVar>(py::handle(args[0]))){
  131. SmallVector<cg::VarNode*> vinputs(nargs);
  132. for (size_t i = 0; i < nargs; ++i) {
  133. vinputs[i] = py::handle(args[i]).cast<PySymbolVar*>()->m_node;
  134. }
  135. auto op = ctx.op.get();
  136. auto rst = OpDef::apply_on_var_node(*op, vinputs);
  137. auto ret = pybind11::tuple(rst.size());
  138. auto typeobj = py::handle(args[0]).get_type();
  139. for (size_t i = 0; i<rst.size(); ++i) {
  140. ret[i] = typeobj(pybind11::cast(rst[i], pybind11::return_value_policy::automatic));
  141. }
  142. return ret.release().ptr();
  143. }
  144. for (size_t i = 0; i < nargs; ++i) {
  145. if (TensorWrapper* tw = TensorWrapper::try_cast(args[i])) {
  146. auto* t = tensors[i] = tw->m_tensor.get();
  147. ctx.flags |= t->m_flags;
  148. } else {
  149. PyErr_SetString(PyExc_TypeError,
  150. ssprintf("op %s expect type Tensor as inputs, got %s actually",
  151. ctx.op->make_name().c_str(), Py_TYPE(args[i])->tp_name).c_str());
  152. return nullptr;
  153. }
  154. }
  155. auto outputs = apply(ctx);
  156. size_t nout = outputs.size();
  157. auto ret = py::tuple(nout);
  158. for (size_t i = 0; i < nout; ++i) {
  159. ret[i] = TensorWrapper::make(pytype, std::move(outputs[i]));
  160. }
  161. return ret.release().ptr();
  162. } catch (std::exception& e) {
  163. PyErr_SetString(PyExc_RuntimeError, e.what());
  164. return nullptr;
  165. }
  166. }
  167. TensorWrapper::TensorWrapper(PyObject* args, PyObject* kwargs) {
  168. if (kwargs && PyDict_Size(kwargs)) {
  169. throw py::type_error("keyword argument not allowed");
  170. }
  171. auto nargs = PyTuple_Size(args);
  172. auto tup = py::reinterpret_borrow<py::tuple>(args);
  173. if (nargs == 0) {
  174. throw py::type_error("too few arguments");
  175. }
  176. if (auto* t = try_cast(tup[0].ptr())) {
  177. if (nargs > 1) {
  178. throw py::type_error("expect 1 argument");
  179. }
  180. m_tensor = t->m_tensor;
  181. } else {
  182. if (nargs == 1) {
  183. auto arg0 = PyTuple_GetItem(args, 0);
  184. // for lazy_eval_tensor
  185. if (strstr(arg0->ob_type->tp_name, "VarNode")) {
  186. if (PyObject_HasAttrString(arg0, "_node")) {
  187. arg0 = PyObject_GetAttrString(arg0, "_node");
  188. }
  189. m_tensor = std::make_shared<Tensor>(py::handle(arg0).cast<cg::VarNode *>());
  190. } else {
  191. // for DeviceTensorND
  192. if (strstr(arg0->ob_type->tp_name, "DeviceTensorND")) {
  193. auto dv = py::handle(arg0).cast<DeviceTensorND>();
  194. interpreter::Interpreter::Handle handle = interpreter_for_py->put(dv);
  195. m_tensor = std::make_shared<Tensor>(handle);
  196. } else {
  197. throw py::type_error("single argument is not tensor, varnode or devicetensor");
  198. }
  199. }
  200. } else {
  201. py::detail::loader_life_support life_sup; // FIXME!!!required to cast DType
  202. if (nargs != 5 && nargs != 6) {
  203. throw py::type_error("expect 5 or 6 arguments");
  204. }
  205. auto data = tup[0].cast<py::array>();
  206. DType dtype = tup[1].cast<DType>();
  207. CompNode cn = tup[2].cast<CompNode>();
  208. bool is_const = tup[3].cast<bool>();
  209. bool no_cache = nargs == 6 ? tup[4].cast<bool>() : false;
  210. std::string name;
  211. if (tup[nargs - 1].ptr() != Py_None) name = tup[nargs - 1].cast<std::string>();
  212. // const op
  213. if (is_const && (ApplyContext::global_enable == Tensor::Flags::TRACE)) {
  214. auto py_ret = PyObject_Call(cpp_apply_const_with_tracing, tup.ptr(), nullptr);
  215. if (!py_ret) throw py::error_already_set();
  216. auto py_list = py::reinterpret_steal<py::list>(py_ret);
  217. if (auto* t = try_cast(py_list[0].ptr())) {
  218. m_tensor = t->m_tensor;
  219. }
  220. return;
  221. }
  222. interpreter::Interpreter::Handle handle;
  223. {
  224. HostTensorND ret(cn);
  225. handle = interpreter_for_py->put(npy::np2tensor(data.ptr(), npy::Meth::copy_into(&ret), dtype), no_cache);
  226. }
  227. m_tensor = std::make_shared<Tensor>(handle);
  228. m_tensor->user_custom_name = name;
  229. if (data.ndim() == 0) {
  230. m_tensor->m_flags |= Tensor::Flags::SCALAR;
  231. }
  232. }
  233. }
  234. }
  235. #define REGISTE_TENSORWRAPPER_FUNC(type, member) \
  236. PyObject* TensorWrapper::member() { \
  237. return py::cast(m_tensor->m_trace_info.member).release().ptr(); \
  238. } \
  239. void TensorWrapper::set_##member(PyObject* dest) { \
  240. auto py_dest = py::reinterpret_borrow<py::object>(dest); \
  241. type real_dest = py_dest.cast<type>(); \
  242. m_tensor->m_trace_info.member = real_dest; \
  243. }
  244. REGISTE_TENSORWRAPPER_FUNC(int64_t, mixin_handle)
  245. REGISTE_TENSORWRAPPER_FUNC(bool, recording)
  246. #undef REGISTE_TENSORWRAPPER_FUNC
  247. #define REGISTE_TENSORWRAPPER_PYOBJECT_FUNC(member) \
  248. PyObject* TensorWrapper::member() { \
  249. if (m_tensor->m_trace_info.member) { \
  250. return m_tensor->m_trace_info.member; \
  251. } else { \
  252. Py_RETURN_NONE; \
  253. } \
  254. } \
  255. void TensorWrapper::set_##member(PyObject* dest) { \
  256. if (dest == Py_None) { \
  257. Py_XDECREF(m_tensor->m_trace_info.member); \
  258. m_tensor->m_trace_info.member = nullptr; \
  259. } else { \
  260. Py_INCREF(dest); \
  261. m_tensor->m_trace_info.member = dest; \
  262. } \
  263. }
  264. REGISTE_TENSORWRAPPER_PYOBJECT_FUNC(compiled_info)
  265. REGISTE_TENSORWRAPPER_PYOBJECT_FUNC(trace_mixin_info)
  266. #undef REGISTE_TENSORWRAPPER_PYOBJECT_FUNC
  267. #define SET_GET_NAME(member) \
  268. PyObject* TensorWrapper::member() { \
  269. return py::cast(m_tensor->member).release().ptr(); \
  270. } \
  271. void TensorWrapper::set_##member(PyObject* dest) { \
  272. auto py_dest = py::reinterpret_borrow<py::object>(dest); \
  273. m_tensor->member = py_dest.cast<std::string>(); \
  274. }
  275. SET_GET_NAME(user_custom_name)
  276. SET_GET_NAME(automatic_name)
  277. #undef SET_GET_NAME
  278. PyObject* TensorWrapper::handle() {
  279. return py::cast(m_tensor->m_handle).release().ptr();
  280. }
  281. void TensorWrapper::set_handle(PyObject* dest) {
  282. auto py_dest = py::reinterpret_borrow<py::object>(dest);
  283. SharedHandle real_dest = py_dest.cast<SharedHandle>();
  284. m_tensor->m_handle = std::move(real_dest);
  285. }
  286. PyObject* TensorWrapper::shape() {
  287. // if it's tracing compiled mode, get value from compiled_info
  288. if (m_tensor->m_trace_info.compiled_info != nullptr) {
  289. if (m_tensor->m_flags & Tensor::Flags::SCALAR) {
  290. return PyTuple_New(0);
  291. }
  292. PyObject *shp = PyObject_GetAttrString(m_tensor->m_trace_info.compiled_info, "shape");
  293. if (shp == Py_None) {
  294. throw TraceReadError("shape of this tensor is not read in trace");
  295. }
  296. return shp;
  297. }
  298. // inside trace, if tensor shape is useful for other operations, set shape_read = true
  299. if (m_tensor->m_trace_info.recording && !skip_tracing) {
  300. PyObject_SetAttrString(m_tensor->m_trace_info.trace_mixin_info, "shape_read", py::cast(true).release().ptr());
  301. }
  302. if (m_tensor->m_flags & Tensor::Flags::SCALAR) {
  303. return PyTuple_New(0);
  304. }
  305. TensorShape shape;
  306. if (m_tensor->m_var) { // get shape from m_var
  307. auto&& mgr = m_tensor->m_var->owner_graph()->static_infer_manager();
  308. auto *tshp = mgr.infer_shape_fallible(m_tensor->m_var);
  309. if (!tshp) {
  310. Py_RETURN_NONE;
  311. }
  312. shape = *tshp;
  313. } else {
  314. shape = m_tensor->shape();
  315. }
  316. if (!shape.ndim) {
  317. Py_RETURN_NONE;
  318. }
  319. py::tuple ret(shape.ndim);
  320. for (size_t i = 0; i < shape.ndim; ++i) {
  321. ret[i] = shape[i];
  322. }
  323. return ret.release().ptr();
  324. }
  325. PyObject* TensorWrapper::dtype() {
  326. if (m_tensor->m_var) {
  327. return py::cast(m_tensor->m_var->dtype()).release().ptr();
  328. }
  329. return py::cast(m_tensor->dtype()).release().ptr();
  330. }
  331. PyObject* TensorWrapper::device() {
  332. if (m_tensor->m_var) {
  333. return py::cast(m_tensor->m_var->comp_node()).release().ptr();
  334. }
  335. return py::cast(m_tensor->comp_node()).release().ptr();
  336. }
  337. PyObject* TensorWrapper::numpy() {
  338. if (m_tensor->m_trace_info.compiled_info != nullptr) {
  339. PyObject* np_val = PyObject_CallMethod(m_tensor->m_trace_info.compiled_info, "numpy", nullptr);
  340. if (!np_val) throw py::error_already_set();
  341. if (np_val == Py_None) {
  342. throw TraceReadError("value of this tensor is not read in trace");
  343. }
  344. if (m_tensor->m_flags & Tensor::Flags::SCALAR) {
  345. PyObject *np_scalar = PyArray_Squeeze(reinterpret_cast<PyArrayObject*>(np_val));
  346. Py_DECREF(np_val);
  347. return np_scalar;
  348. }
  349. return np_val;
  350. }
  351. if (m_tensor->m_trace_info.recording && !skip_tracing) {
  352. PyObject_SetAttrString(m_tensor->m_trace_info.trace_mixin_info, "value_read", py::cast(true).release().ptr());
  353. }
  354. if (m_tensor->m_handle.get() == nullptr && m_tensor->m_var != nullptr) {
  355. auto&& mgr = m_tensor->m_var->owner_graph()->static_infer_manager();
  356. auto&& type = mgr.get_infer_type(m_tensor->m_var);
  357. using InferType = cg::static_infer::InferType;
  358. if (!(type.value & (InferType::CONST | InferType::RT_STATIC))) {
  359. PyErr_SetString(PyExc_ValueError, "tensor invalid");
  360. return nullptr;
  361. }
  362. auto* val = mgr.infer_value_fallible(m_tensor->m_var);
  363. if (!val) {
  364. PyErr_SetString(PyExc_ValueError, "tensor invalid");
  365. return nullptr;
  366. }
  367. auto np_val = py::cast(*val).attr("numpy")();
  368. if (m_tensor->m_flags & Tensor::Flags::SCALAR) {
  369. return PyArray_Squeeze(reinterpret_cast<PyArrayObject*>(np_val.release().ptr()));
  370. }
  371. return np_val.release().ptr();
  372. }
  373. auto&& hv = [&]() {
  374. py::gil_scoped_release _;
  375. return interpreter_for_py->get_value(m_tensor->m_handle.get());
  376. }();
  377. auto arr = py::reinterpret_steal<py::array>(npy::ndarray_from_tensor(hv, npy::ShareType::TRY_SHARE));
  378. if (!arr) {
  379. PyErr_SetString(PyExc_ValueError, "tensor invalid");
  380. return nullptr;
  381. }
  382. if (m_tensor->m_flags & Tensor::Flags::SCALAR) {
  383. mgb_assert(PyArray_Check(arr.ptr()));
  384. return PyArray_Squeeze(reinterpret_cast<PyArrayObject*>(arr.ptr()));
  385. }
  386. return arr.release().ptr();
  387. }
  388. PyObject* TensorWrapper::varnode() {
  389. if (m_tensor->m_var) {
  390. return py::cast(m_tensor->m_var).release().ptr();
  391. }
  392. Py_RETURN_NONE;
  393. }
  394. void TensorWrapper::reset(PyObject* tensor) {
  395. TensorWrapper* t = TensorWrapper::try_cast(tensor);
  396. if (!t) {
  397. throw py::type_error("expect Tensor");
  398. }
  399. std::string user_custom_name = m_tensor->user_custom_name;
  400. std::string automatic_name = m_tensor->automatic_name;
  401. m_tensor = t->m_tensor;
  402. m_tensor->user_custom_name = user_custom_name;
  403. m_tensor->automatic_name = automatic_name;
  404. }
  405. void TensorWrapper::reset_varnode() {
  406. m_tensor->m_var = nullptr;
  407. }
  408. PyObject* TensorWrapper::detach() {
  409. PyObject* self = wrap_t::pycast(this);
  410. PyTypeObject* pytype = self->ob_type;
  411. std::shared_ptr<Tensor> new_tensor;
  412. if (m_tensor->m_handle.get()) {
  413. new_tensor = std::make_shared<Tensor>(m_tensor->m_handle);
  414. } else {
  415. new_tensor = std::make_shared<Tensor>(m_tensor->m_var);
  416. }
  417. new_tensor->m_trace_info = m_tensor->m_trace_info;
  418. new_tensor->m_flags = m_tensor->m_flags;
  419. auto ret = TensorWrapper::make(pytype, std::move(new_tensor));
  420. return ret.release().ptr();
  421. }
  422. PyObject* TensorWrapper::_dev_tensor(){
  423. if (m_tensor->m_trace_info.compiled_info != nullptr) {
  424. auto *dev_tensor = PyObject_CallMethod(m_tensor->m_trace_info.compiled_info, "_dev_tensor", nullptr);
  425. if (!dev_tensor) throw py::error_already_set();
  426. if (dev_tensor == Py_None) {
  427. throw TraceReadError("raw data of this tensor is not read in trace");
  428. }
  429. // set m_handle to make it a real tensor
  430. auto py_dev_tensor = py::reinterpret_borrow<py::object>(dev_tensor);
  431. auto sh = interpreter_for_py->put(py_dev_tensor.cast<DeviceTensorND>());
  432. m_tensor->m_handle = std::move(SharedHandle(sh));
  433. // compiled info is useless after m_handle is set
  434. Py_DECREF(m_tensor->m_trace_info.compiled_info);
  435. m_tensor->m_trace_info.compiled_info = nullptr;
  436. return dev_tensor;
  437. }
  438. if (m_tensor->m_trace_info.recording && !skip_tracing) {
  439. PyObject_SetAttrString(m_tensor->m_trace_info.trace_mixin_info, "data_read", py::cast(true).release().ptr());
  440. }
  441. auto dev_tensor = [&](){
  442. py::gil_scoped_release _;
  443. return interpreter_for_py->get_dev_tensor(m_tensor->m_handle.get());
  444. }();
  445. return py::cast(dev_tensor).release().ptr();
  446. }
  447. void TensorWrapper::_swap_out() {
  448. interpreter_for_py->swap_out(m_tensor->m_handle.get());
  449. }
  450. void TensorWrapper::_swap_in() {
  451. interpreter_for_py->swap_in(m_tensor->m_handle.get());
  452. }
  453. void TensorWrapper::_drop() {
  454. interpreter_for_py->drop(m_tensor->m_handle.get());
  455. }
  456. PyObject* TensorWrapper::isscalar() {
  457. if(m_tensor->m_flags & Tensor::Flags::SCALAR) {
  458. Py_RETURN_TRUE;
  459. } else {
  460. Py_RETURN_FALSE;
  461. }
  462. }
  463. void TensorWrapper::setscalar() {
  464. m_tensor->m_flags |= Tensor::Flags::SCALAR;
  465. }
  466. void TensorWrapper::unsetscalar() {
  467. m_tensor->m_flags &= ~Tensor::Flags::SCALAR;
  468. }
  469. struct TensorWeakRef {
  470. std::weak_ptr<Tensor> wptr;
  471. TensorWeakRef(const TensorWrapper& tw) : wptr(tw.m_tensor) {}
  472. py::object operator()() {
  473. if (auto p = wptr.lock()) {
  474. return TensorWrapper::make(p);
  475. }
  476. return py::none();
  477. }
  478. int _use_cnt() { return wptr.use_count(); }
  479. };
  480. /* ============== convert inputs ============== */
  481. // map numpy.dtype.kind to priority
  482. inline uint8_t category_priority(char c) {
  483. switch (c) {
  484. case 'f': return 3; // floating-point
  485. case 'i': return 2; // signed integer
  486. case 'u': return 2; // unsigned integer
  487. case 'b': return 1; // boolean
  488. default: return 0;
  489. }
  490. }
  491. // Returns the maximum value of the priority of each type in the list `types`.
  492. uint8_t max_priority(SmallVector<PyArray_Descr*> types) {
  493. if (types.size() == 0) {
  494. return 0;
  495. } else {
  496. uint8_t max_p = 0;
  497. for (auto&& desc: types) {
  498. max_p = std::max(max_p, category_priority(desc->kind));
  499. }
  500. return max_p;
  501. }
  502. }
  503. // Returns the data type with sufficient size to hold all types of
  504. // category `cat` in the list `types`.
  505. PyArray_Descr* promote_types(SmallVector<PyArray_Descr*> types, uint8_t cat) {
  506. // Return value: New reference
  507. SmallVector<PyArray_Descr*> used_types;
  508. for (auto&& desc: types) {
  509. auto&& v = category_priority(desc->kind);
  510. if (v == cat) {
  511. used_types.emplace_back(desc);
  512. }
  513. }
  514. mgb_assert(used_types.size() > 0, "size of used_types is 0");
  515. PyArray_Descr* res = used_types[0];
  516. Py_INCREF(res);
  517. for (size_t i = 1; i < used_types.size(); ++i) {
  518. PyArray_Descr* tmp = PyArray_PromoteTypes(used_types[i], res);
  519. Py_DECREF(res);
  520. res = tmp;
  521. }
  522. return res;
  523. }
  524. PyArray_Descr* scalar2dtype(PyObject* arg) {
  525. // Return value: New reference
  526. if (PyBool_Check(arg)) {
  527. auto&& descr = PyArray_DescrFromType(NPY_BOOL);
  528. return descr;
  529. }
  530. if (PyLong_CheckExact(arg)) {
  531. auto&& descr = PyArray_DescrFromType(NPY_INT32);
  532. return descr;
  533. }
  534. if (PyFloat_CheckExact(arg)) {
  535. auto&& descr = PyArray_DescrFromType(NPY_FLOAT32);
  536. return descr;
  537. }
  538. return nullptr;
  539. }
  540. PyArray_Descr* _dtype_promotion(PyObject*const* args, size_t nargs) {
  541. // Return value: New reference
  542. SmallVector<PyArray_Descr*> tensors;
  543. SmallVector<PyArray_Descr*> scalars;
  544. bool is_tuple = false;
  545. PyObject* tuple = nullptr;
  546. if (nargs == 1 && (PyTuple_Check(args[0]) || PyList_Check(args[0]))) {
  547. if (PyList_Check(args[0])) {
  548. tuple = PyList_AsTuple(args[0]);
  549. } else {
  550. tuple = args[0];
  551. Py_INCREF(tuple);
  552. }
  553. nargs = PyTuple_Size(tuple);
  554. is_tuple = true;
  555. }
  556. for (size_t i = 0; i < nargs; ++i) {
  557. PyObject* handle = is_tuple ? PyTuple_GetItem(tuple, i): args[i];
  558. if (handle == Py_None) continue;
  559. TensorWrapper* tw = TensorWrapper::try_cast(handle);
  560. if (tw) {
  561. mgb::DType type = tw->m_tensor->dtype();
  562. auto&& descr = npy::dtype_mgb2np_descr(type);
  563. Py_INCREF(descr.get());
  564. tensors.emplace_back(descr.get());
  565. }else{
  566. if (PyArray_Check(handle) || PyArray_CheckScalar(handle)) {
  567. auto&& descr = PyArray_DescrFromObject(handle, nullptr);
  568. tensors.emplace_back(descr);
  569. continue;
  570. }
  571. if (py::isinstance<PySymbolVar>(py::handle(handle))){
  572. auto var = py::handle(handle).cast<PySymbolVar*>();
  573. mgb::DType type = var->m_node->dtype();
  574. auto && descr = npy::dtype_mgb2np_descr(type);
  575. Py_INCREF(descr.get());
  576. tensors.emplace_back(descr.get());
  577. continue;
  578. }
  579. PyArray_Descr* descr = scalar2dtype(handle);
  580. if (descr) {
  581. scalars.emplace_back(descr);
  582. continue;
  583. }
  584. }
  585. }
  586. auto max_pri_scalars = max_priority(scalars);
  587. auto max_pri_tensors = max_priority(tensors);
  588. if (max_pri_scalars <= 0 && max_pri_tensors <= 0) {
  589. throw py::value_error("invalid input, no dtype avaliable");
  590. }
  591. PyArray_Descr* res;
  592. if (max_pri_scalars > max_pri_tensors) {
  593. res = promote_types(scalars, max_pri_scalars);
  594. }else{
  595. res = promote_types(tensors, max_pri_tensors);
  596. }
  597. for (auto *p: tensors) { Py_DECREF(p); }
  598. for (auto *p: scalars) { Py_DECREF(p); }
  599. Py_XDECREF(tuple);
  600. return res;
  601. }
  602. CompNode _get_device(PyObject*const* args, size_t nargs) {
  603. bool is_tuple = false;
  604. PyObject* tuple = nullptr;
  605. if (nargs == 1 && (PyTuple_Check(args[0]) || PyList_Check(args[0]))) {
  606. if (PyList_Check(args[0])) {
  607. tuple = PyList_AsTuple(args[0]);
  608. } else {
  609. tuple = args[0];
  610. Py_INCREF(tuple);
  611. }
  612. nargs = PyTuple_Size(tuple);
  613. is_tuple = true;
  614. }
  615. bool valid = false;
  616. CompNode cn;
  617. for (size_t i = 0; i < nargs; ++i) {
  618. PyObject* handle = is_tuple ? PyTuple_GetItem(tuple, i) : args[i];
  619. TensorWrapper* tw = TensorWrapper::try_cast(handle);
  620. bool is_symvar = py::isinstance<PySymbolVar>(py::handle(handle));
  621. if (tw || is_symvar) {
  622. if (!valid) {
  623. cn = tw ? tw->m_tensor->comp_node()
  624. : py::handle(handle)
  625. .cast<PySymbolVar*>()
  626. ->m_node->comp_node();
  627. valid = true;
  628. } else {
  629. CompNode cn1 = tw ? tw->m_tensor->comp_node()
  630. : py::handle(handle)
  631. .cast<PySymbolVar*>()
  632. ->m_node->comp_node();
  633. if (cn1 != cn) {
  634. throw py::value_error(ssprintf("ambiguous device: %s vs %s",
  635. cn.to_string().c_str(),
  636. cn1.to_string().c_str()));
  637. }
  638. }
  639. }
  640. }
  641. if (!valid) {
  642. return CompNode::load(get_default_device());
  643. }
  644. Py_XDECREF(tuple);
  645. return cn;
  646. }
  647. // Returns the dtype that would result from performing an arithmetic
  648. // operation on the provided input tensors and scalars.
  649. PyObject* dtype_promotion(PyObject* self, PyObject*const* args, size_t nargs) {
  650. if (!nargs) {
  651. PyErr_SetString(PyExc_TypeError, "empty input is not allowed");
  652. return nullptr;
  653. }
  654. try {
  655. PyArray_Descr* res = _dtype_promotion(args, nargs);
  656. return py::cast(npy::dtype_np2mgb_descr(res)).release().ptr();
  657. } catch (std::exception& e) {
  658. PyErr_SetString(PyExc_RuntimeError, e.what());
  659. return nullptr;
  660. }
  661. }
  662. PyObject* get_device(PyObject* self, PyObject*const* args, size_t nargs) {
  663. if (!nargs) {
  664. PyErr_SetString(PyExc_TypeError, "empty input is not allowed");
  665. return nullptr;
  666. }
  667. try {
  668. CompNode cn = _get_device(args, nargs);
  669. return py::cast(cn).release().ptr();
  670. } catch (std::exception& e) {
  671. PyErr_SetString(PyExc_RuntimeError, e.what());
  672. return nullptr;
  673. }
  674. }
  675. #ifdef METH_FASTCALL
  676. #define MGE_PY_INTERFACE(NAME, FUNC) \
  677. { #NAME, (PyCFunction)FUNC, METH_FASTCALL, nullptr }
  678. #else
  679. #define WRAP_FUNC_PY35(FUNC) \
  680. PyObject* py35_##FUNC(PyObject* self, PyObject* args) { \
  681. auto* arr = &PyTuple_GET_ITEM(args, 0); \
  682. auto size = PyTuple_GET_SIZE(args); \
  683. return FUNC(self, arr, size); \
  684. }
  685. WRAP_FUNC_PY35(py_apply);
  686. WRAP_FUNC_PY35(dtype_promotion);
  687. WRAP_FUNC_PY35(get_device);
  688. #undef WRAP_FUNC_PY35
  689. #define MGE_PY_INTERFACE(NAME, FUNC) \
  690. { #NAME, (PyCFunction)py35_##FUNC, METH_VARARGS, nullptr }
  691. #endif
  692. void init_tensor(py::module m) {
  693. imperative::Tensor::static_initialize();
  694. static auto sl_interpreter_for_py = interpreter::Interpreter::inst().create_channel();
  695. interpreter_for_py = sl_interpreter_for_py.get();
  696. auto* tensor_type = TensorWrapper::wrap_t::type()
  697. .def<&TensorWrapper::numpy>("numpy")
  698. .def_getset<&TensorWrapper::shape>("shape")
  699. .def_getset<&TensorWrapper::dtype>("dtype")
  700. .def_getset<&TensorWrapper::device>("device")
  701. .def<&TensorWrapper::reset>("_reset")
  702. .def<&TensorWrapper::isscalar>("_isscalar")
  703. .def<&TensorWrapper::setscalar>("_setscalar")
  704. .def<&TensorWrapper::unsetscalar>("_unsetscalar")
  705. .def<&TensorWrapper::detach>("detach")
  706. .def<&TensorWrapper::_dev_tensor>("_dev_tensor")
  707. .def<&TensorWrapper::_swap_out>("_swap_out")
  708. .def<&TensorWrapper::_swap_in>("_swap_in")
  709. .def<&TensorWrapper::_drop>("_drop")
  710. .def<&TensorWrapper::reset_varnode>("_reset_varnode")
  711. .def<&TensorWrapper::_use_cnt>("_use_cnt")
  712. .def_getset<&TensorWrapper::varnode>("_varnode")
  713. .def_getset<&TensorWrapper::mixin_handle, &TensorWrapper::set_mixin_handle>("_mixin_handle")
  714. .def_getset<&TensorWrapper::recording, &TensorWrapper::set_recording>("_recording")
  715. .def_getset<&TensorWrapper::handle, &TensorWrapper::set_handle>("_handle")
  716. .def_getset<&TensorWrapper::compiled_info, &TensorWrapper::set_compiled_info>("_compiled_info")
  717. .def_getset<&TensorWrapper::trace_mixin_info, &TensorWrapper::set_trace_mixin_info>("_trace_mixin_info")
  718. .def_getset<&TensorWrapper::user_custom_name, &TensorWrapper::set_user_custom_name>("c_name")
  719. .def_getset<&TensorWrapper::automatic_name, &TensorWrapper::set_automatic_name>("_name")
  720. .finalize();
  721. if (!tensor_type) throw py::error_already_set();
  722. py::setattr(m, "Tensor", tensor_type);
  723. py::class_<TensorWeakRef>(m, "TensorWeakRef")
  724. .def(py::init<const TensorWrapper&>())
  725. .def("__call__", &TensorWeakRef::operator())
  726. .def("_use_cnt", &TensorWeakRef::_use_cnt);
  727. py::class_<PySymbolVar, std::shared_ptr<PySymbolVar>>(m, "SymbolVar")
  728. .def_property_readonly(
  729. "dtype", [](PySymbolVar* v) { return v->m_node->dtype(); })
  730. .def_property("var", [](PySymbolVar* v) { return v->m_node; },
  731. [](PySymbolVar* s, cg::VarNode* v) { s->m_node = v; })
  732. .def_property_readonly(
  733. "device",
  734. [](PySymbolVar* v) { return v->m_node->comp_node(); })
  735. .def_property_readonly(
  736. "graph",
  737. [](PySymbolVar* v) { return v->m_node->owner_graph(); })
  738. .def_property_readonly(
  739. "shape",
  740. [](PySymbolVar* v) -> const TensorShape* {
  741. auto&& mgr = v->m_node->owner_graph()
  742. ->static_infer_manager();
  743. return mgr.infer_shape_fallible(v->m_node);
  744. })
  745. .def("_isscalar", [](PySymbolVar* v) { return v->is_scalar; })
  746. .def("_setscalar",
  747. [](PySymbolVar* v) { return v->is_scalar = true; })
  748. .def(py::init([](cg::VarNode* node) {
  749. return std::make_shared<PySymbolVar>(node);
  750. }),
  751. py::arg() = nullptr);
  752. static PyMethodDef method_defs[] = {
  753. MGE_PY_INTERFACE(apply, py_apply),
  754. MGE_PY_INTERFACE(dtype_promotion, dtype_promotion),
  755. MGE_PY_INTERFACE(get_device, get_device),
  756. {nullptr, nullptr, 0, nullptr}};
  757. for (auto&& def: method_defs) {
  758. if (def.ml_meth != nullptr) {
  759. auto* func = PyCFunction_NewEx(&def, nullptr, nullptr);
  760. if (!func) throw py::error_already_set();
  761. py::setattr(m, def.ml_name, func);
  762. }
  763. }
  764. static constexpr auto sync_py_task_q = []{
  765. py::gil_scoped_release _;
  766. py_task_q.wait_all_task_finish();
  767. };
  768. m.def("set_option",
  769. [](std::string name, size_t value){ interpreter_for_py->set_option(name, value); });
  770. m.def("get_option",
  771. [](std::string name){ return interpreter_for_py->get_option(name); });
  772. m.def("_set_swap_flag",
  773. [](bool flag) { interpreter_for_py->set_option("enable_swap", flag); });
  774. m.def("_set_drop_flag",
  775. [](bool flag) { interpreter_for_py->set_option("enable_drop", flag); });
  776. m.def("config_async_level",
  777. [](int level) {
  778. mgb_assert(level >= 0 and level <= 2, "async_level should be 0, 1 or 2");
  779. interpreter_for_py->set_option("async_level", level);
  780. });
  781. m.def("get_async_level",
  782. []() { return interpreter_for_py->get_option("async_level"); });
  783. m.def("set_buffer_length",
  784. [](int length) {
  785. mgb_assert(length >= 0 and length < 100, "buffer_length should be in [0, 100)");
  786. interpreter_for_py->set_option("buffer_length", length);
  787. });
  788. m.def("push_scope",
  789. [](std::string name) { interpreter_for_py->push_scope(name); });
  790. m.def("pop_scope",
  791. [](std::string name) { interpreter_for_py->pop_scope(name); });
  792. m.def("start_profile",
  793. [](std::unordered_map<std::string, int> option) { return interpreter_for_py->start_profile(option); });
  794. m.def("stop_profile",
  795. [](std::string basename, std::string format) { interpreter_for_py->stop_profile(basename, format); });
  796. m.def("sync",
  797. []() {
  798. interpreter_for_py->sync();
  799. sync_py_task_q();
  800. });
  801. m.def("full_sync",
  802. []() {
  803. interpreter_for_py->sync();
  804. CompNode::sync_all();
  805. sync_py_task_q();
  806. });
  807. m.def("close",
  808. []() {
  809. interpreter_for_py->close();
  810. sync_py_task_q();
  811. });
  812. py::handle grad_key_type = GradKeyWrapper::wrap_t::type()
  813. .def<&GradKeyWrapper::attach>("attach")
  814. .def<&GradKeyWrapper::is_attached_to>("is_attached_to")
  815. .def_getset<&GradKeyWrapper::get_name, &GradKeyWrapper::set_name>("name")
  816. .finalize();
  817. if (!grad_key_type) throw py::error_already_set();
  818. py::setattr(m, "GradKey", grad_key_type);
  819. m.def("backward", &GradKeyWrapper::backward);
  820. m.def("set_cpp_apply_with_tracing", &set_cpp_apply_with_tracing);
  821. m.def("set_cpp_apply_const_with_tracing", &set_cpp_apply_const_with_tracing);
  822. m.def("set_cpp_apply_backward_varnode", &set_cpp_apply_backward_varnode);
  823. m.attr("skip_tracing") = &skip_tracing;
  824. py::class_<SharedHandle>(m, "SharedHandle")
  825. .def(py::init<const SharedHandle&>())
  826. .def("__eq__", [](SharedHandle &thish, SharedHandle &thath) {
  827. return (thish.get() == thath.get());
  828. })
  829. .def("__hash__", [](SharedHandle &sh) {
  830. return reinterpret_cast<int64_t>(sh.get());
  831. })
  832. ;
  833. m.def("set_tracing", &set_tracing);
  834. m.def("unset_tracing", &unset_tracing);
  835. }
  836. #undef MGE_PY_INTERFACE
  837. } // namespace mgb::imperative::python

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台