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 30 kB

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

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