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.

utils.cpp 9.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /**
  2. * \file imperative/python/src/utils.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 "utils.h"
  12. #ifdef WIN32
  13. #include <stdio.h>
  14. #include <windows.h>
  15. #endif
  16. #include <pybind11/operators.h>
  17. #include <atomic>
  18. #include <cstdint>
  19. #include "./imperative_rt.h"
  20. #include "megbrain/common.h"
  21. #include "megbrain/comp_node.h"
  22. #include "megbrain/imperative/blob_manager.h"
  23. #include "megbrain/imperative/profiler.h"
  24. #include "megbrain/imperative/tensor_sanity_check.h"
  25. #include "megbrain/serialization/helper.h"
  26. #include "megbrain/utils/persistent_cache.h"
  27. #if MGB_ENABLE_OPR_MM
  28. #include "megbrain/opr/mm_handler.h"
  29. #endif
  30. namespace py = pybind11;
  31. namespace {
  32. bool g_global_finalized = false;
  33. class LoggerWrapper {
  34. public:
  35. using LogLevel = mgb::LogLevel;
  36. using LogHandler = mgb::LogHandler;
  37. static void set_log_handler(py::object logger_p) {
  38. logger = logger_p;
  39. mgb::set_log_handler(py_log_handler);
  40. }
  41. static LogLevel set_log_level(LogLevel log_level) {
  42. return mgb::set_log_level(log_level);
  43. }
  44. private:
  45. static py::object logger;
  46. static void py_log_handler(mgb::LogLevel level, const char* file,
  47. const char* func, int line, const char* fmt,
  48. va_list ap) {
  49. using mgb::LogLevel;
  50. MGB_MARK_USED_VAR(file);
  51. MGB_MARK_USED_VAR(func);
  52. MGB_MARK_USED_VAR(line);
  53. if (g_global_finalized)
  54. return;
  55. const char* py_type;
  56. switch (level) {
  57. case LogLevel::DEBUG:
  58. py_type = "debug";
  59. break;
  60. case LogLevel::INFO:
  61. py_type = "info";
  62. break;
  63. case LogLevel::WARN:
  64. py_type = "warning";
  65. break;
  66. case LogLevel::ERROR:
  67. py_type = "error";
  68. break;
  69. default:
  70. throw std::runtime_error("bad log level");
  71. }
  72. std::string msg = mgb::svsprintf(fmt, ap);
  73. auto do_log = [msg = msg, py_type]() {
  74. if (logger.is_none())
  75. return;
  76. py::object _call = logger.attr(py_type);
  77. _call(py::str(msg));
  78. };
  79. if (PyGILState_Check()) {
  80. do_log();
  81. } else {
  82. py_task_q.add_task(do_log);
  83. }
  84. }
  85. };
  86. py::object LoggerWrapper::logger = py::none{};
  87. uint32_t _get_dtype_num(py::object dtype) {
  88. return static_cast<uint32_t>(npy::dtype_np2mgb(dtype.ptr()).enumv());
  89. }
  90. py::bytes _get_serialized_dtype(py::object dtype) {
  91. std::string sdtype;
  92. auto write = [&sdtype](const void* data, size_t size) {
  93. auto pos = sdtype.size();
  94. sdtype.resize(pos + size);
  95. memcpy(&sdtype[pos], data, size);
  96. };
  97. mgb::serialization::serialize_dtype(npy::dtype_np2mgb(dtype.ptr()), write);
  98. return py::bytes(sdtype.data(), sdtype.size());
  99. }
  100. int fork_exec_impl(const std::string& arg0, const std::string& arg1,
  101. const std::string& arg2) {
  102. #ifdef WIN32
  103. STARTUPINFO si;
  104. PROCESS_INFORMATION pi;
  105. ZeroMemory(&si, sizeof(si));
  106. si.cb = sizeof(si);
  107. ZeroMemory(&pi, sizeof(pi));
  108. auto args_str = " " + arg1 + " " + arg2;
  109. // Start the child process.
  110. if (!CreateProcess(arg0.c_str(), // exe name
  111. const_cast<char*>(args_str.c_str()), // Command line
  112. NULL, // Process handle not inheritable
  113. NULL, // Thread handle not inheritable
  114. FALSE, // Set handle inheritance to FALSE
  115. 0, // No creation flags
  116. NULL, // Use parent's environment block
  117. NULL, // Use parent's starting directory
  118. &si, // Pointer to STARTUPINFO structure
  119. &pi) // Pointer to PROCESS_INFORMATION structure
  120. ) {
  121. mgb_log_warn("CreateProcess failed (%lu).\n", GetLastError());
  122. fprintf(stderr, "[megbrain] failed to execl %s [%s, %s]\n",
  123. arg0.c_str(), arg1.c_str(), arg2.c_str());
  124. __builtin_trap();
  125. }
  126. return pi.dwProcessId;
  127. #else
  128. auto pid = fork();
  129. if (!pid) {
  130. execl(arg0.c_str(), arg0.c_str(), arg1.c_str(), arg2.c_str(), nullptr);
  131. fprintf(stderr, "[megbrain] failed to execl %s [%s, %s]: %s\n",
  132. arg0.c_str(), arg1.c_str(), arg2.c_str(), std::strerror(errno));
  133. std::terminate();
  134. }
  135. mgb_assert(pid > 0, "failed to fork: %s", std::strerror(errno));
  136. return pid;
  137. #endif
  138. }
  139. } // namespace
  140. void init_utils(py::module m) {
  141. auto atexit = py::module::import("atexit");
  142. atexit.attr("register")(py::cpp_function([]() {
  143. g_global_finalized = true;
  144. }));
  145. py::class_<std::atomic<uint64_t>>(m, "AtomicUint64")
  146. .def(py::init<>())
  147. .def(py::init<uint64_t>())
  148. .def("load",
  149. [](const std::atomic<uint64_t>& self) { return self.load(); })
  150. .def("store", [](std::atomic<uint64_t>& self,
  151. uint64_t value) { return self.store(value); })
  152. .def("fetch_add",
  153. [](std::atomic<uint64_t>& self, uint64_t value) {
  154. return self.fetch_add(value);
  155. })
  156. .def("fetch_sub",
  157. [](std::atomic<uint64_t>& self, uint64_t value) {
  158. return self.fetch_sub(value);
  159. })
  160. .def(py::self += uint64_t())
  161. .def(py::self -= uint64_t());
  162. // FIXME!!! Should add a submodule instead of using a class for logger
  163. py::class_<LoggerWrapper> logger(m, "Logger");
  164. logger.def(py::init<>())
  165. .def_static("set_log_level", &LoggerWrapper::set_log_level)
  166. .def_static("set_log_handler", &LoggerWrapper::set_log_handler);
  167. py::enum_<LoggerWrapper::LogLevel>(logger, "LogLevel")
  168. .value("Debug", LoggerWrapper::LogLevel::DEBUG)
  169. .value("Info", LoggerWrapper::LogLevel::INFO)
  170. .value("Warn", LoggerWrapper::LogLevel::WARN)
  171. .value("Error", LoggerWrapper::LogLevel::ERROR);
  172. m.def("_get_dtype_num", &_get_dtype_num,
  173. "Convert numpy dtype to internal dtype");
  174. m.def("_get_serialized_dtype", &_get_serialized_dtype,
  175. "Convert numpy dtype to internal dtype for serialization");
  176. m.def("_get_device_count", &mgb::CompNode::get_device_count,
  177. "Get total number of specific devices on this system");
  178. using mgb::imperative::TensorSanityCheck;
  179. py::class_<TensorSanityCheck>(m, "TensorSanityCheckImpl")
  180. .def(py::init<>())
  181. .def("enable",
  182. [](TensorSanityCheck& checker) -> TensorSanityCheck& {
  183. checker.enable();
  184. return checker;
  185. })
  186. .def("disable",
  187. [](TensorSanityCheck& checker) {
  188. checker.disable();
  189. });
  190. #if MGB_ENABLE_OPR_MM
  191. m.def("create_mm_server", &create_zmqrpc_server, py::arg("addr"),
  192. py::arg("port") = 0);
  193. #else
  194. m.def("create_mm_server", []() {});
  195. #endif
  196. // Debug code, internal only
  197. m.def("_set_defrag", [](bool enable) {
  198. mgb::imperative::BlobManager::inst()->set_enable(enable);
  199. });
  200. m.def("_defrag", [](const mgb::CompNode& cn) {
  201. mgb::imperative::BlobManager::inst()->defrag(cn);
  202. });
  203. m.def("_set_fork_exec_path_for_timed_func", [](const std::string& arg0,
  204. const ::std::string arg1) {
  205. using namespace std::placeholders;
  206. mgb::sys::TimedFuncInvoker::ins().set_fork_exec_impl(std::bind(
  207. fork_exec_impl, std::string{arg0}, std::string{arg1}, _1));
  208. });
  209. m.def("_timed_func_exec_cb", [](const std::string& user_data){
  210. mgb::sys::TimedFuncInvoker::ins().fork_exec_impl_mainloop(user_data.c_str());
  211. });
  212. using mgb::PersistentCache;
  213. class PyPersistentCache: public mgb::PersistentCache{
  214. public:
  215. mgb::Maybe<Blob> get(const std::string& category, const Blob& key) override {
  216. PYBIND11_OVERLOAD_PURE(mgb::Maybe<Blob>, PersistentCache, get, category, key);
  217. }
  218. void put(const std::string& category, const Blob& key, const Blob& value) override {
  219. PYBIND11_OVERLOAD_PURE(void, PersistentCache, put, category, key, value);
  220. }
  221. };
  222. py::class_<PersistentCache, PyPersistentCache, std::shared_ptr<PersistentCache>>(m, "PersistentCache")
  223. .def(py::init<>())
  224. .def("get", &PersistentCache::get)
  225. .def("put", &PersistentCache::put)
  226. .def("reg", &PersistentCache::set_impl);
  227. }

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