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

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

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