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.

ops.cpp 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /**
  2. * \file imperative/python/src/ops.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 "./ops.h"
  12. #include "megbrain/imperative.h"
  13. #include "megbrain/imperative/ops/backward_graph.h"
  14. #include "megbrain/imperative/ops/opr_attr.h"
  15. #include "megbrain/imperative/ops/utility.h"
  16. #include "megbrain/imperative/ops/autogen.h"
  17. #include <Python.h>
  18. #include <unordered_map>
  19. namespace py = pybind11;
  20. using namespace mgb::imperative;
  21. namespace {
  22. auto normalize_enum(const std::string& in) {
  23. std::string ret;
  24. for (auto&& c : in) {
  25. ret += toupper(c);
  26. }
  27. return ret;
  28. }
  29. } // anonymous namespace
  30. namespace {
  31. #define PyOp(name) Py##name
  32. #define PyOpType(name) PyOp(name)::py_type
  33. #define PyOpDefBegin(name) \
  34. struct PyOp(name) : PyOpDef { \
  35. using Ty = name; \
  36. Ty& inst() { return op->cast_final_safe<Ty>(); } \
  37. static PyTypeObject py_type;
  38. #define PyOpDefEnd(name) \
  39. }; \
  40. PyTypeObject PyOpType(name);
  41. #define RETURN_RICHCOMPARE(val1, val2, op) \
  42. do { \
  43. switch (op) { \
  44. case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  45. case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  46. case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  47. case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  48. case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  49. case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  50. default: \
  51. Py_FatalError("Unreachable C code path reached"); \
  52. } \
  53. } while (0)
  54. template<typename T, typename SFINAE=void>
  55. struct pyobj_convert_generic {
  56. static T from(PyObject* obj) {
  57. // TODO: remove this guard which is used for pybind11 implicit conversion
  58. py::detail::loader_life_support guard{};
  59. return py::cast<T>(py::handle(obj));
  60. }
  61. template<typename U,
  62. typename = std::enable_if_t<std::is_same_v<T, std::decay_t<U>>>>
  63. static PyObject* to(U&& t) {
  64. return py::cast(std::forward<U>(t)).release().ptr();
  65. }
  66. };
  67. template<typename T>
  68. PyObject* py_new_generic(PyTypeObject* type, PyObject*, PyObject*) {
  69. PyObject* obj = type->tp_alloc(type, 0);
  70. T* self = reinterpret_cast<T*>(obj);
  71. if (self != NULL) {
  72. self->op = T::Ty::make();
  73. }
  74. return obj;
  75. }
  76. template<typename T>
  77. void py_dealloc_generic(PyObject* obj) {
  78. reinterpret_cast<T*>(obj)->op.reset();
  79. Py_TYPE(obj)->tp_free(obj);
  80. }
  81. template<typename T, typename U, U T::Ty::*attr>
  82. PyObject* py_get_generic_impl(PyObject* obj, void* /* closure */) {
  83. auto& op = reinterpret_cast<T*>(obj)->inst();
  84. return pyobj_convert_generic<U>::to(op.*attr);
  85. }
  86. #define py_get_generic(name, attr) \
  87. py_get_generic_impl<PyOp(name), decltype(std::declval<name>().attr), &name::attr>
  88. template<typename T, typename U, U T::Ty::*attr>
  89. int py_set_generic_impl(PyObject* obj, PyObject* value, void* /* closure */) {
  90. if (value == NULL) {
  91. PyErr_SetString(PyExc_TypeError, "Cannot delete the attribute");
  92. return -1;
  93. }
  94. auto& op = reinterpret_cast<T*>(obj)->inst();
  95. try {
  96. op.*attr = pyobj_convert_generic<U>::from(value);
  97. return 0;
  98. } catch(py::error_already_set& e) {
  99. e.restore();
  100. } catch(py::builtin_exception& e) {
  101. e.set_error();
  102. } catch(...) {
  103. PyErr_SetString(PyExc_RuntimeError, "Unknown Error");
  104. }
  105. return -1;
  106. }
  107. #define py_set_generic(name, attr) \
  108. py_set_generic_impl<PyOp(name), decltype(std::declval<name>().attr), &name::attr>
  109. struct PyOpDef {
  110. PyObject_HEAD
  111. std::shared_ptr<OpDef> op;
  112. static PyTypeObject py_type;
  113. static std::unordered_map<mgb::Typeinfo*, PyTypeObject*> ctype2pytype;
  114. static Py_hash_t tp_hash(PyObject *obj);
  115. static PyObject* tp_richcompare(PyObject *self, PyObject *other, int op);
  116. };
  117. PyTypeObject PyOpType(OpDef);
  118. std::unordered_map<mgb::Typeinfo*, PyTypeObject*> PyOp(OpDef)::ctype2pytype;
  119. Py_hash_t PyOp(OpDef)::tp_hash(PyObject *obj) {
  120. return static_cast<Py_hash_t>(
  121. reinterpret_cast<PyOp(OpDef)*>(obj)->op->hash());
  122. }
  123. PyObject* PyOp(OpDef)::tp_richcompare(PyObject *self, PyObject *other, int op) {
  124. bool same = reinterpret_cast<PyOp(OpDef)*>(self)->op->is_same(
  125. *reinterpret_cast<PyOp(OpDef)*>(other)->op);
  126. if (op == Py_EQ || op == Py_NE) {
  127. RETURN_RICHCOMPARE(same, true, op);
  128. }
  129. Py_RETURN_NOTIMPLEMENTED;
  130. }
  131. template<typename T>
  132. struct EnumWrapper {
  133. static_assert(std::is_enum_v<T>);
  134. PyObject_HEAD
  135. T value;
  136. static const char* name;
  137. static PyTypeObject type;
  138. static std::unordered_map<T, std::string> type2str;
  139. static std::unordered_map<std::string, T> str2type;
  140. EnumWrapper() = default;
  141. EnumWrapper(T v): value(v) {}
  142. EnumWrapper(std::string&& str): EnumWrapper(str2type.at(normalize_enum(str))) {}
  143. std::string to_string() const {
  144. return type2str.at(value);
  145. }
  146. static PyObject* py_repr(PyObject* self) {
  147. return pyobj_convert_generic<std::string>::to(
  148. std::string(name) + "." + reinterpret_cast<EnumWrapper*>(self)->to_string());
  149. }
  150. static PyObject* tp_richcompare(PyObject *self, PyObject *other, int op) {
  151. T lhs = reinterpret_cast<EnumWrapper*>(self)->value,
  152. rhs = reinterpret_cast<EnumWrapper*>(other)->value;
  153. if (op == Py_EQ || op == Py_NE) {
  154. RETURN_RICHCOMPARE(lhs, rhs, op);
  155. }
  156. Py_RETURN_NOTIMPLEMENTED;
  157. }
  158. };
  159. template<typename T>
  160. struct pyobj_convert_generic<T,
  161. std::enable_if_t<std::is_enum_v<std::decay_t<T>>>> {
  162. using Wrapper = EnumWrapper<T>;
  163. static T from(PyObject* obj) {
  164. if (PyObject_TypeCheck(obj, &Wrapper::type)) {
  165. return reinterpret_cast<Wrapper*>(obj)->value;
  166. }
  167. // try as string
  168. // TODO: type checkcd
  169. return Wrapper(pyobj_convert_generic<std::string>::from(obj)).value;
  170. }
  171. static PyObject* to(T t) {
  172. PyTypeObject* pytype = &Wrapper::type;
  173. PyObject* obj = pytype->tp_alloc(pytype, 0);
  174. reinterpret_cast<Wrapper*>(obj)->value = t;
  175. return obj;
  176. }
  177. };
  178. void _init_py_op_def(py::module m) {
  179. auto& py_type = PyOpType(OpDef);
  180. py_type = {PyVarObject_HEAD_INIT(NULL, 0)};
  181. py_type.tp_name = "megengine.core._imperative_rt.OpDef";
  182. py_type.tp_basicsize = sizeof(PyOp(OpDef));
  183. py_type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  184. py_type.tp_doc = "OpDef";
  185. py_type.tp_base = &PyBaseObject_Type;
  186. py_type.tp_hash = PyOp(OpDef)::tp_hash;
  187. py_type.tp_richcompare = PyOp(OpDef)::tp_richcompare;
  188. mgb_assert(PyType_Ready(&py_type) >= 0);
  189. m.add_object("OpDef", reinterpret_cast<PyObject*>(&py_type));
  190. }
  191. /*********** begin of hand-write opdefs **************/
  192. PyOpDefBegin(BackwardGraph) // {{
  193. // };
  194. PyOpDefEnd(BackwardGraph)
  195. void _init_py_backward_graph(py::module m) {
  196. using py_op = PyOp(BackwardGraph);
  197. auto& py_type = PyOpType(BackwardGraph);
  198. py_type = {PyVarObject_HEAD_INIT(NULL, 0)};
  199. py_type.tp_name = "megengine.core._imperative_rt.ops.BackwardGraph";
  200. py_type.tp_basicsize = sizeof(PyOp(BackwardGraph));
  201. py_type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  202. py_type.tp_doc = "BackwardGraph";
  203. py_type.tp_base = &PyOpType(OpDef);
  204. py_type.tp_dealloc = py_dealloc_generic<py_op>;
  205. py_type.tp_new = py_new_generic<py_op>;
  206. mgb_assert(PyType_Ready(&py_type) >= 0);
  207. // FIXME: rewrite interpret function in cpython instead wrap directly by pybind11::cppfunction
  208. auto interpret = py::cpp_function(
  209. [](OpDef& self, py::object pyf, py::object pyc,
  210. const mgb::SmallVector<py::object>& inputs) {
  211. auto f = [pyf](OpDef& op, const mgb::SmallVector<py::object>& inputs) {
  212. return py::cast<mgb::SmallVector<py::object>>(pyf(op.shared_from_this(), inputs));
  213. };
  214. auto c = [pyc](const TensorPtr& tensor) {
  215. return pyc(tensor->dev_tensor());
  216. };
  217. return self.cast_final_safe<BackwardGraph>().graph().interpret<py::object>(f, c, inputs);
  218. });
  219. mgb_assert(PyDict_SetItemString(
  220. py_type.tp_dict, "interpret", interpret.release().ptr()) >= 0);
  221. PyType_Modified(&py_type);
  222. m.add_object("BackwardGraph", reinterpret_cast<PyObject*>(&py_type));
  223. mgb_assert(PyOp(OpDef)::ctype2pytype.emplace(BackwardGraph::typeinfo(), &py_type).second);
  224. }
  225. struct PyOpBase : PyOpDef {
  226. static PyTypeObject py_type;
  227. static PyObject* tp_new(PyTypeObject* type, PyObject*, PyObject*) {
  228. auto* obj = type->tp_alloc(type, 0);
  229. if (obj) {
  230. auto* self = reinterpret_cast<PyOpBase*>(obj);
  231. new(&self->op) decltype(self->op);
  232. }
  233. return obj;
  234. }
  235. };
  236. PyTypeObject PyOpBase::py_type;
  237. void _init_py_op_base(py::module m) {
  238. using py_op = PyOpBase;
  239. auto& py_type = PyOpBase::py_type;
  240. py_type = {PyVarObject_HEAD_INIT(NULL, 0)};
  241. py_type.tp_name = "megengine.core._imperative_rt.ops.PyOpBase";
  242. py_type.tp_basicsize = sizeof(py_op);
  243. py_type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
  244. py_type.tp_doc = "PyOpBase";
  245. py_type.tp_base = &PyOpType(OpDef);
  246. py_type.tp_dealloc = py_dealloc_generic<py_op>;
  247. py_type.tp_new = py_op::tp_new;
  248. mgb_assert(PyType_Ready(&py_type) >= 0);
  249. m.add_object("PyOpBase", reinterpret_cast<PyObject*>(&py_type));
  250. }
  251. /*********** end of hand-write opdefs **************/
  252. // auto generated opdefs
  253. #include "opdef.cpy.inl"
  254. } // anonymous namespace
  255. namespace PYBIND11_NAMESPACE {
  256. namespace detail {
  257. bool type_caster<OpDef>::load(handle src, bool convert) {
  258. PyObject* obj = src.ptr();
  259. if (!PyObject_TypeCheck(obj, &PyOpType(OpDef))) {
  260. return false;
  261. }
  262. value = reinterpret_cast<PyOp(OpDef)*>(obj)->op;
  263. if (!value) {
  264. // opdef only defined in Python
  265. value = std::make_shared<GenericPyOp>(reinterpret_borrow<object>(src));
  266. }
  267. return true;
  268. }
  269. handle type_caster<OpDef>::cast(const OpDef& op, return_value_policy, handle) {
  270. if (auto* pyop = op.try_cast_final<GenericPyOp>()) {
  271. return object(pyop->obj).release();
  272. }
  273. PyTypeObject* pytype;
  274. auto& c2p = PyOp(OpDef)::ctype2pytype;
  275. auto&& iter = c2p.find(op.dyn_typeinfo());
  276. if (iter != c2p.end()) { // FIXME: should always meet this condition
  277. pytype = iter->second;
  278. } else { // which means unregistered op type, jsut make it as an opaque op type
  279. // currently, only OprAttr goes into this branch
  280. pytype = &PyOpType(OpDef);
  281. }
  282. PyObject* obj = pytype->tp_alloc(pytype, 0);
  283. mgb_assert(PyObject_TypeCheck(obj, &PyOpType(OpDef)));
  284. reinterpret_cast<PyOp(OpDef)*>(obj)->op = const_cast<OpDef&>(op).shared_from_this();
  285. return py::handle(obj);
  286. }
  287. } // detail
  288. } // PYBIND11_NAMESPACE
  289. void init_ops(py::module m) {
  290. _init_py_op_def(m);
  291. _init_py_backward_graph(m);
  292. _init_py_op_base(m);
  293. INIT_ALL_OP(m)
  294. }

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