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.

common.cpp 6.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /**
  2. * \file imperative/python/src/common.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 "./common.h"
  12. #include <pybind11/operators.h>
  13. #include "megbrain/comp_node.h"
  14. #include "megbrain/graph.h"
  15. #include "megbrain/imperative/physical_tensor.h"
  16. #include "./numpy_dtypes.h"
  17. #include "./helper.h"
  18. namespace py = pybind11;
  19. using namespace mgb;
  20. using namespace imperative;
  21. namespace {
  22. template<typename XTensorND>
  23. auto def_TensorND(py::object parent, const char* name) {
  24. return py::class_<XTensorND>(parent, name)
  25. .def_property_readonly("shape", py::overload_cast<>(&XTensorND::shape, py::const_))
  26. .def_property_readonly("dtype", py::overload_cast<>(&XTensorND::dtype, py::const_))
  27. .def_property_readonly("comp_node", py::overload_cast<>(&XTensorND::comp_node, py::const_))
  28. .def("copy_from", &XTensorND::template copy_from<DeviceTensorStorage>)
  29. .def("copy_from", &XTensorND::template copy_from<HostTensorStorage>)
  30. .def("copy_from_fixlayout", py::overload_cast<const DeviceTensorND&>(
  31. &XTensorND::template copy_from_fixlayout<DeviceTensorStorage>))
  32. .def("copy_from_fixlayout", py::overload_cast<const HostTensorND&>(
  33. &XTensorND::template copy_from_fixlayout<HostTensorStorage>));
  34. }
  35. std::string default_device = "xpux";
  36. } // namespace
  37. void set_default_device(const std::string &device) {
  38. default_device = device;
  39. }
  40. std::string get_default_device() {
  41. return default_device;
  42. }
  43. void init_common(py::module m) {
  44. auto&& PyCompNode = py::class_<CompNode>(m, "CompNode")
  45. .def(py::init())
  46. .def(py::init(py::overload_cast<const std::string&>(&CompNode::load)))
  47. .def("create_event", &CompNode::create_event, py::arg("flags") = 0ul)
  48. .def("_set_default_device", &set_default_device)
  49. .def("_get_default_device", &get_default_device)
  50. .def("__str__", &CompNode::to_string_logical)
  51. .def_static("_sync_all", &CompNode::sync_all)
  52. .def(py::self == py::self)
  53. .def_static("_get_device_count", &CompNode::get_device_count,
  54. "Get total number of specific devices on this system")
  55. .def(py::pickle(
  56. [](const CompNode& cn) {
  57. return py::str(cn.to_string_logical());
  58. },
  59. [](py::str cn) {
  60. return CompNode::load(cn);
  61. }));
  62. py::class_<CompNode::Event, std::shared_ptr<CompNode::Event>>(PyCompNode, "Event")
  63. .def("record", &CompNode::Event::record)
  64. .def("wait", &CompNode::Event::host_wait);
  65. py::implicitly_convertible<std::string, CompNode>();
  66. def_TensorND<DeviceTensorND>(m, "DeviceTensorND")
  67. .def("numpy", [](const DeviceTensorND& self) {
  68. HostTensorND hv;
  69. hv.copy_from(self).sync();
  70. return py::handle(npy::ndarray_from_tensor(hv, npy::ShareType::TRY_SHARE));
  71. });
  72. def_TensorND<HostTensorND>(m, "HostTensorND")
  73. .def(py::init([](py::array data, CompNode cn, DType dtype) {
  74. if (!cn.valid()) {
  75. throw py::type_error("device must not be None");
  76. }
  77. return npy::np2tensor(data.ptr(), npy::Meth::borrow(cn), dtype);
  78. }))
  79. .def("numpy", [](const HostTensorND& self) {
  80. return py::reinterpret_steal<py::object>(npy::ndarray_from_tensor(self, npy::ShareType::TRY_SHARE));
  81. });
  82. py::class_<cg::OperatorNodeConfig>(m, "OperatorNodeConfig")
  83. .def(py::init())
  84. .def_property("name",
  85. [](const OperatorNodeConfig& config) -> py::object {
  86. auto name = config.name();
  87. if (name.valid()) {
  88. return py::str(name.val());
  89. } else {
  90. return py::none();
  91. }
  92. },
  93. [](OperatorNodeConfig& config, std::string name){
  94. config.name(std::move(name));
  95. })
  96. .def_property("dtype",
  97. [](const OperatorNodeConfig& config) {
  98. return config.output_dtype();
  99. },
  100. [](OperatorNodeConfig& config, DType dtype) {
  101. config.output_dtype(dtype);
  102. })
  103. .def_property("comp_node_arr",
  104. [](const OperatorNodeConfig& config) -> py::tuple {
  105. auto arr = config.comp_node();
  106. std::vector<CompNode> tmp(arr.begin(), arr.end());
  107. return py::cast(tmp);
  108. },
  109. [](OperatorNodeConfig& config, std::vector<CompNode> cns) {
  110. config.comp_node_arr({cns.begin(), cns.end()});
  111. })
  112. .def_property("comp_node",
  113. [](const OperatorNodeConfig& config) {
  114. auto arr = config.comp_node();
  115. if (arr.size() != 1) {
  116. throw py::value_error("invalid number of comp_node");
  117. }
  118. return arr[0];
  119. },
  120. [](OperatorNodeConfig& config, CompNode cn) {
  121. OperatorNodeConfig::CompNodeArray arr{cn};
  122. config.comp_node_arr(arr);
  123. });
  124. py::class_<LogicalTensorDesc>(m, "TensorAttr")
  125. .def(py::init())
  126. .def(py::init([](const TensorShape& shape, const DType& dtype, const CompNode& comp_node){
  127. return LogicalTensorDesc{TensorLayout{shape, dtype}, comp_node};
  128. }))
  129. .def_property("shape",
  130. [](const LogicalTensorDesc& desc) {
  131. return static_cast<TensorShape>(desc.layout);
  132. },
  133. [](LogicalTensorDesc& desc, TensorShape shape) {
  134. })
  135. .def_property("dtype",
  136. [](const LogicalTensorDesc& desc) {
  137. return desc.layout.dtype;
  138. },
  139. [](LogicalTensorDesc& desc, DType dtype) {
  140. desc.layout.dtype = dtype;
  141. })
  142. .def_readwrite("comp_node", &LogicalTensorDesc::comp_node);
  143. py::enum_<CompNode::DeviceType>(m, "DeviceType")
  144. .value("UNSPEC", CompNode::DeviceType::UNSPEC)
  145. .value("CUDA", CompNode::DeviceType::CUDA)
  146. .value("CPU", CompNode::DeviceType::CPU)
  147. .value("MULTITHREAD", CompNode::DeviceType::MULTITHREAD)
  148. .value("MAX_DEVICE_ID", CompNode::DeviceType::MAX_DEVICE_ID);
  149. m.def("set_prealloc_config", &CompNode::set_prealloc_config,
  150. "specifies how to pre-allocate from raw dev allocator");
  151. init_npy_num_bfloat16(m);
  152. init_npy_num_intbx(m);
  153. }

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