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.

helper.h 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /**
  2. * \file imperative/python/src/helper.h
  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. #pragma once
  12. #include "megbrain/graph.h"
  13. #include "megbrain/utils/persistent_cache.h"
  14. #include <Python.h>
  15. #include <string>
  16. #include <iterator>
  17. #if __cplusplus > 201703L
  18. #include <ranges>
  19. #endif
  20. #include <pybind11/pybind11.h>
  21. #include <pybind11/stl.h>
  22. #include <pybind11/numpy.h>
  23. #include <pybind11/functional.h>
  24. pybind11::module submodule(pybind11::module parent, const char* name, const char* doc = nullptr);
  25. pybind11::module rel_import(pybind11::str name, pybind11::module m, int level);
  26. #if __cplusplus > 201703L
  27. using std::ranges::range_value_t;
  28. #else
  29. template<typename T>
  30. using range_value_t = std::remove_cv_t<std::remove_reference_t<decltype(*std::declval<T>().begin())>>;
  31. #endif
  32. template<typename T>
  33. auto to_list(const T& x) {
  34. using elem_t = range_value_t<T>;
  35. std::vector<elem_t> ret(x.begin(), x.end());
  36. return pybind11::cast(ret);
  37. }
  38. template<typename T>
  39. auto to_tuple(const T& x, pybind11::return_value_policy policy = pybind11::return_value_policy::automatic) {
  40. auto ret = pybind11::tuple(x.size());
  41. for (size_t i = 0; i < x.size(); ++i) {
  42. ret[i] = pybind11::cast(x[i], policy);
  43. }
  44. return ret;
  45. }
  46. template<typename T>
  47. auto to_tuple(T begin, T end, pybind11::return_value_policy policy = pybind11::return_value_policy::automatic) {
  48. auto ret = pybind11::tuple(end - begin);
  49. for (size_t i = 0; begin < end; ++begin, ++i) {
  50. ret[i] = pybind11::cast(*begin, policy);
  51. }
  52. return ret;
  53. }
  54. class PyTaskDipatcher {
  55. struct Queue : mgb::AsyncQueueSC<std::function<void(void)>, Queue> {
  56. using Task = std::function<void(void)>;
  57. void process_one_task(Task& f) {
  58. if (!Py_IsInitialized()) return;
  59. pybind11::gil_scoped_acquire _;
  60. f();
  61. }
  62. void on_async_queue_worker_thread_start() override {
  63. mgb::sys::set_thread_name("py_task_worker");
  64. }
  65. };
  66. Queue queue;
  67. bool finalized = false;
  68. public:
  69. template<typename T>
  70. void add_task(T&& task) {
  71. // CPython never dlclose an extension so
  72. // finalized means the interpreter has been shutdown
  73. if (!finalized) {
  74. queue.add_task(std::forward<T>(task));
  75. }
  76. }
  77. void wait_all_task_finish() {
  78. queue.wait_all_task_finish();
  79. }
  80. ~PyTaskDipatcher() {
  81. finalized = true;
  82. queue.wait_all_task_finish();
  83. }
  84. };
  85. extern PyTaskDipatcher py_task_q;
  86. class GILManager {
  87. PyGILState_STATE gstate;
  88. public:
  89. GILManager():
  90. gstate(PyGILState_Ensure())
  91. {
  92. }
  93. ~GILManager() {
  94. PyGILState_Release(gstate);
  95. }
  96. };
  97. #define PYTHON_GIL GILManager __gil_manager
  98. //! wraps a shared_ptr and decr PyObject ref when destructed
  99. class PyObjRefKeeper {
  100. std::shared_ptr<PyObject> m_ptr;
  101. public:
  102. static void deleter(PyObject* p) {
  103. if (p) {
  104. py_task_q.add_task([p](){Py_DECREF(p);});
  105. }
  106. }
  107. PyObjRefKeeper() = default;
  108. PyObjRefKeeper(PyObject* p) : m_ptr{p, deleter} {}
  109. PyObject* get() const { return m_ptr.get(); }
  110. //! create a shared_ptr as an alias of the underlying ptr
  111. template <typename T>
  112. std::shared_ptr<T> make_shared(T* ptr) const {
  113. return {m_ptr, ptr};
  114. }
  115. };
  116. //! exception to be thrown when python callback fails
  117. class PyExceptionForward : public std::exception {
  118. PyObject *m_type, *m_value, *m_traceback;
  119. std::string m_msg;
  120. PyExceptionForward(PyObject* type, PyObject* value, PyObject* traceback,
  121. const std::string& msg)
  122. : m_type{type},
  123. m_value{value},
  124. m_traceback{traceback},
  125. m_msg{msg} {}
  126. public:
  127. PyExceptionForward(const PyExceptionForward&) = delete;
  128. PyExceptionForward& operator=(const PyExceptionForward&) = delete;
  129. ~PyExceptionForward();
  130. PyExceptionForward(PyExceptionForward&& rhs)
  131. : m_type{rhs.m_type},
  132. m_value{rhs.m_value},
  133. m_traceback{rhs.m_traceback},
  134. m_msg{std::move(rhs.m_msg)} {
  135. rhs.m_type = rhs.m_value = rhs.m_traceback = nullptr;
  136. }
  137. //! throw PyExceptionForward from current python error state
  138. static void throw_() __attribute__((noreturn));
  139. //! restore python error
  140. void restore();
  141. const char* what() const noexcept override { return m_msg.c_str(); }
  142. };
  143. //! numpy utils
  144. namespace npy {
  145. //! convert tensor shape to raw vector
  146. static inline std::vector<size_t> shape2vec(const mgb::TensorShape &shape) {
  147. return {shape.shape, shape.shape + shape.ndim};
  148. }
  149. //! change numpy dtype to megbrain supported dtype
  150. PyObject* to_mgb_supported_dtype(PyObject *dtype);
  151. //! convert raw vector to tensor shape
  152. mgb::TensorShape vec2shape(const std::vector<size_t> &vec);
  153. //! convert megbrain dtype to numpy dtype object; return new reference
  154. PyObject* dtype_mgb2np(mgb::DType dtype);
  155. //! convert numpy dtype object or string to megbrain dtype
  156. mgb::DType dtype_np2mgb(PyObject *obj);
  157. //! buffer sharing type
  158. enum class ShareType {
  159. MUST_SHARE, //!< must be shared
  160. MUST_UNSHARE, //!< must not be shared
  161. TRY_SHARE //!< share if possible
  162. };
  163. //! get ndarray from HostTensorND
  164. PyObject* ndarray_from_tensor(const mgb::HostTensorND &val,
  165. ShareType share_type);
  166. //! specify how to convert numpy array to tensor
  167. struct Meth {
  168. bool must_borrow_ = false;
  169. mgb::HostTensorND *dest_tensor_ = nullptr;
  170. mgb::CompNode dest_cn_;
  171. //! make a Meth that allows borrowing numpy array memory
  172. static Meth borrow(
  173. mgb::CompNode dest_cn = mgb::CompNode::default_cpu()) {
  174. return {false, nullptr, dest_cn};
  175. }
  176. //! make a Meth that requires the numpy array to be borrowed
  177. static Meth must_borrow(
  178. mgb::CompNode dest_cn = mgb::CompNode::default_cpu()) {
  179. return {true, nullptr, dest_cn};
  180. }
  181. //! make a Meth that requires copying the value into another
  182. //! tensor
  183. static Meth copy_into(mgb::HostTensorND *tensor) {
  184. return {false, tensor, tensor->comp_node()};
  185. }
  186. };
  187. /*!
  188. * \brief convert an object to megbrain tensor
  189. * \param meth specifies how the conversion should take place
  190. * \param dtype desired dtype; it can be set as invalid to allow arbitrary
  191. * dtype
  192. */
  193. mgb::HostTensorND np2tensor(PyObject *obj, const Meth &meth,
  194. mgb::DType dtype);
  195. }
  196. // Note: following macro was copied from pybind11/detail/common.h
  197. // Robust support for some features and loading modules compiled against different pybind versions
  198. // requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute on
  199. // the main `pybind11` namespace.
  200. #if !defined(PYBIND11_NAMESPACE)
  201. # ifdef __GNUG__
  202. # define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
  203. # else
  204. # define PYBIND11_NAMESPACE pybind11
  205. # endif
  206. #endif
  207. namespace PYBIND11_NAMESPACE {
  208. namespace detail {
  209. template<typename T, unsigned N> struct type_caster<megdnn::SmallVector<T, N>>
  210. : list_caster<megdnn::SmallVector<T, N>, T> {};
  211. template <> struct type_caster<mgb::DType> {
  212. PYBIND11_TYPE_CASTER(mgb::DType, _("DType"));
  213. public:
  214. bool load(handle src, bool convert) {
  215. auto obj = reinterpret_borrow<object>(src);
  216. if (!convert && !isinstance<dtype>(obj)) {
  217. return false;
  218. }
  219. if (obj.is_none()) {
  220. return true;
  221. }
  222. try {
  223. obj = pybind11::dtype::from_args(obj);
  224. } catch (pybind11::error_already_set&) {
  225. return false;
  226. }
  227. try {
  228. value = npy::dtype_np2mgb(obj.ptr());
  229. } catch (...) {
  230. return false;
  231. }
  232. return true;
  233. }
  234. static handle cast(mgb::DType dt, return_value_policy /* policy */, handle /* parent */) {
  235. // ignore policy and parent because we always return a pure python object
  236. return npy::dtype_mgb2np(std::move(dt));
  237. }
  238. };
  239. template <> struct type_caster<mgb::TensorShape> {
  240. PYBIND11_TYPE_CASTER(mgb::TensorShape, _("TensorShape"));
  241. public:
  242. bool load(handle src, bool convert) {
  243. auto obj = reinterpret_borrow<object>(src);
  244. if (!convert && !isinstance<tuple>(obj)) {
  245. return false;
  246. }
  247. if (obj.is_none()) {
  248. return true;
  249. }
  250. value.ndim = len(obj);
  251. mgb_assert(value.ndim <= mgb::TensorShape::MAX_NDIM);
  252. size_t i = 0;
  253. for (auto v : obj) {
  254. mgb_assert(i < value.ndim);
  255. value.shape[i] = reinterpret_borrow<object>(v).cast<size_t>();
  256. ++i;
  257. }
  258. return true;
  259. }
  260. static handle cast(mgb::TensorShape shape, return_value_policy /* policy */, handle /* parent */) {
  261. // ignore policy and parent because we always return a pure python object
  262. return to_tuple(shape.shape, shape.shape + shape.ndim).release();
  263. }
  264. };
  265. // hack to make custom object implicitly convertible from None
  266. template <typename T> struct from_none_caster : public type_caster_base<T> {
  267. using base = type_caster_base<T>;
  268. bool load(handle src, bool convert) {
  269. if (!convert || !src.is_none()) {
  270. return base::load(src, convert);
  271. }
  272. // adapted from pybind11::implicitly_convertible
  273. auto temp = reinterpret_steal<object>(PyObject_Call(
  274. (PyObject*) this->typeinfo->type, tuple().ptr(), nullptr));
  275. if (!temp) {
  276. PyErr_Clear();
  277. return false;
  278. }
  279. // adapted from pybind11::detail::type_caster_generic
  280. if (base::load(temp, false)) {
  281. loader_life_support::add_patient(temp);
  282. return true;
  283. }
  284. return false;
  285. }
  286. };
  287. template<> struct type_caster<mgb::CompNode> : public from_none_caster<mgb::CompNode> {};
  288. template <> struct type_caster<mgb::PersistentCache::Blob> {
  289. PYBIND11_TYPE_CASTER(mgb::PersistentCache::Blob, _("Blob"));
  290. public:
  291. bool load(handle src, bool convert) {
  292. if (!isinstance<bytes>(src)) {
  293. return false;
  294. }
  295. value.ptr = PYBIND11_BYTES_AS_STRING(src.ptr());
  296. value.size = PYBIND11_BYTES_SIZE(src.ptr());
  297. return true;
  298. }
  299. static handle cast(mgb::PersistentCache::Blob blob, return_value_policy /* policy */, handle /* parent */) {
  300. return bytes((const char*)blob.ptr, blob.size);
  301. }
  302. };
  303. template <typename T> struct type_caster<mgb::Maybe<T>> {
  304. using value_conv = make_caster<T>;
  305. PYBIND11_TYPE_CASTER(mgb::Maybe<T>, _("Optional[") + value_conv::name + _("]"));
  306. public:
  307. bool load(handle src, bool convert) {
  308. if(!src) {
  309. return false;
  310. }
  311. if (src.is_none()) {
  312. return true;
  313. }
  314. value_conv inner_caster;
  315. if (!inner_caster.load(src, convert)) {
  316. return false;
  317. }
  318. value.emplace(cast_op<T&&>(std::move(inner_caster)));
  319. return true;
  320. }
  321. static handle cast(mgb::Maybe<T> src, return_value_policy policy, handle parent) {
  322. if(!src.valid()) {
  323. return none().inc_ref();
  324. }
  325. return pybind11::cast(src.val(), policy, parent);
  326. }
  327. };
  328. } // detail
  329. } // PYBIND11_NAMESPACE
  330. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

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