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

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

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