common.cpp 11.7 KB
Newer Older
1 2 3
#include "./common.h"

#include <pybind11/operators.h>
4
#include <pybind11/pytypes.h>
5

M
Megvii Engine Team 已提交
6 7
#include "./helper.h"
#include "./numpy_dtypes.h"
8 9 10
#include "megbrain/comp_node.h"
#include "megbrain/graph.h"
#include "megbrain/imperative/physical_tensor.h"
11
#include "megbrain/version.h"
12 13 14
#if MGB_ENABLE_OPR_MM
#include "megbrain/opr/mm_handler.h"
#endif
15

16 17 18 19
#if MEGDNN_WITH_CUDA
#include "cuda_sm_gen.h"
#endif

20 21 22 23
namespace py = pybind11;
using namespace mgb;
using namespace imperative;

M
Megvii Engine Team 已提交
24 25
namespace {

M
Megvii Engine Team 已提交
26
template <typename XTensorND>
M
Megvii Engine Team 已提交
27 28
auto def_TensorND(py::object parent, const char* name) {
    return py::class_<XTensorND>(parent, name)
M
Megvii Engine Team 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42
            .def_property_readonly(
                    "shape", py::overload_cast<>(&XTensorND::shape, py::const_))
            .def_property_readonly(
                    "dtype", py::overload_cast<>(&XTensorND::dtype, py::const_))
            .def_property_readonly(
                    "comp_node", py::overload_cast<>(&XTensorND::comp_node, py::const_))
            .def("copy_from", &XTensorND::template copy_from<DeviceTensorStorage>)
            .def("copy_from", &XTensorND::template copy_from<HostTensorStorage>)
            .def("copy_from_fixlayout",
                 py::overload_cast<const DeviceTensorND&>(
                         &XTensorND::template copy_from_fixlayout<DeviceTensorStorage>))
            .def("copy_from_fixlayout",
                 py::overload_cast<const HostTensorND&>(
                         &XTensorND::template copy_from_fixlayout<HostTensorStorage>));
M
Megvii Engine Team 已提交
43 44
}

45 46
std::string default_device = "xpux";

M
Megvii Engine Team 已提交
47
}  // namespace
M
Megvii Engine Team 已提交
48

M
Megvii Engine Team 已提交
49
void set_default_device(const std::string& device) {
50 51 52
    default_device = device;
}

53 54 55 56 57 58 59 60 61 62 63 64
void init_nccl_env(const std::string& ip, int port, int nranks, int rank, int root) {
#if MGB_ENABLE_OPR_MM
    auto&& help = mgb::opr::BatchSendRecvHelper::getInstance();
    bool res = help->init(nranks, rank, ip, port, root);
    auto p = help->get(std::string("init_all_cards"));
#else
    mgb_throw(
            MegBrainError,
            "MegEngine compiled without MM opr, doesn't support init_nccl_env");
#endif
}

65 66 67 68
std::string get_default_device() {
    return default_device;
}

69 70
py::handle py_comp_node_type;

71
void init_common(py::module m) {
M
Megvii Engine Team 已提交
72 73 74 75 76 77 78 79 80 81
    auto PyCompNode =
            py::class_<CompNode>(m, "CompNode")
                    .def(py::init())
                    .def(py::init(
                            py::overload_cast<const std::string&>(&CompNode::load)))
                    .def_property_readonly(
                            "logical_name",
                            [](const CompNode& cn) { return cn.to_string_logical(); })
                    .def_property_readonly(
                            "physical_name",
82
                            [](const CompNode& cn) { return cn.to_string_physical(); })
M
Megvii Engine Team 已提交
83 84 85 86 87
                    .def_property_readonly(
                            "get_mem_status_bytes",
                            [](const CompNode& cn) {
                                return cn.get_mem_status_bytes();
                            })
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
                    .def_property_readonly(
                            "get_used_memory",
                            [](const CompNode& cn) { return cn.get_used_memory(); })
                    .def_property_readonly(
                            "get_max_used_memory",
                            [](const CompNode& cn) { return cn.get_max_used_memory(); })
                    .def_property_readonly(
                            "get_reserved_memory",
                            [](const CompNode& cn) { return cn.get_reserved_memory(); })
                    .def_property_readonly(
                            "get_max_reserved_memory",
                            [](const CompNode& cn) {
                                return cn.get_max_reserved_memory();
                            })
                    .def_static(
                            "reset_max_memory_stats",
                            [](const CompNode& cn) {
                                cn.reset_max_used_memory();
                                cn.reset_max_reserved_memory();
                            })
M
Megvii Engine Team 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
                    .def("create_event", &CompNode::create_event,
                         py::arg("flags") = 0ul)
                    .def_static("_set_default_device", &set_default_device)
                    .def_static("_get_default_device", &get_default_device)
                    .def("__str__", &CompNode::to_string_logical)
                    .def("__repr__",
                         [](const CompNode& cn) {
                             return mgb::ssprintf(
                                     "CompNode(\"%s\" from \"%s\")",
                                     cn.to_string_physical().c_str(),
                                     cn.to_string_logical().c_str());
                         })
                    .def("__hash__", [](CompNode cn) { return mgb::hash(cn); })
                    .def_static("_sync_all", &CompNode::sync_all)
                    .def(py::self == py::self)
                    .def_static(
                            "_get_device_count", &CompNode::get_device_count,
                            "Get total number of specific devices on this system")
                    .def(py::pickle(
                            [](const CompNode& cn) {
                                return py::str(cn.to_string_logical());
                            },
                            [](py::str cn) { return CompNode::load(cn); }));
131

132 133
    py_comp_node_type = PyCompNode.inc_ref();

M
Megvii Engine Team 已提交
134
    py::class_<CompNode::Event, std::shared_ptr<CompNode::Event>>(PyCompNode, "Event")
M
Megvii Engine Team 已提交
135 136
            .def("record", &CompNode::Event::record)
            .def("wait", &CompNode::Event::host_wait);
M
Megvii Engine Team 已提交
137

138 139
    py::implicitly_convertible<std::string, CompNode>();

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    py::class_<CompNode::DeviceProperties>(m, "DeviceProperties")
            .def(py::init())
            .def_property_readonly(
                    "name",
                    [](const CompNode::DeviceProperties prop) { return prop.name; })
            .def_property_readonly(
                    "total_memory",
                    [](const CompNode::DeviceProperties prop) {
                        return prop.total_memory;
                    })
            .def_property_readonly(
                    "major",
                    [](const CompNode::DeviceProperties prop) { return prop.major; })
            .def_property_readonly("minor", [](const CompNode::DeviceProperties prop) {
                return prop.minor;
            });

M
Megvii Engine Team 已提交
157
    def_TensorND<DeviceTensorND>(m, "DeviceTensorND")
M
Megvii Engine Team 已提交
158
            .def("numpy", [](const DeviceTensorND& self) {
159 160
                HostTensorND hv;
                hv.copy_from(self).sync();
161
                return py::reinterpret_steal<py::object>(
M
Megvii Engine Team 已提交
162
                        npy::ndarray_from_tensor(hv, npy::ShareType::TRY_SHARE));
163 164
            });

M
Megvii Engine Team 已提交
165
    def_TensorND<HostTensorND>(m, "HostTensorND")
M
Megvii Engine Team 已提交
166
            .def(py::init([](py::array data, CompNode cn, DType dtype) {
M
Megvii Engine Team 已提交
167 168 169 170 171
                if (!cn.valid()) {
                    throw py::type_error("device must not be None");
                }
                return npy::np2tensor(data.ptr(), npy::Meth::borrow(cn), dtype);
            }))
M
Megvii Engine Team 已提交
172 173 174
            .def("numpy", [](const HostTensorND& self) {
                return py::reinterpret_steal<py::object>(
                        npy::ndarray_from_tensor(self, npy::ShareType::TRY_SHARE));
M
Megvii Engine Team 已提交
175 176
            });

177
    py::class_<cg::OperatorNodeConfig>(m, "OperatorNodeConfig")
M
Megvii Engine Team 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
            .def(py::init())
            .def_property(
                    "name",
                    [](const OperatorNodeConfig& config) -> py::object {
                        auto name = config.name();
                        if (name.valid()) {
                            return py::str(name.val());
                        } else {
                            return py::none();
                        }
                    },
                    [](OperatorNodeConfig& config, std::string name) {
                        config.name(std::move(name));
                    })
            .def_property(
                    "dtype",
                    [](const OperatorNodeConfig& config) {
                        return config.output_dtype();
                    },
                    [](OperatorNodeConfig& config, DType dtype) {
                        config.output_dtype(dtype);
                    })
            .def_property(
                    "comp_node_arr",
                    [](const OperatorNodeConfig& config) -> py::tuple {
                        auto arr = config.comp_node();
                        std::vector<CompNode> tmp(arr.begin(), arr.end());
                        return py::cast(tmp);
                    },
                    [](OperatorNodeConfig& config, std::vector<CompNode> cns) {
                        config.comp_node_arr({cns.begin(), cns.end()});
                    })
            .def_property(
                    "comp_node",
                    [](const OperatorNodeConfig& config) {
                        auto arr = config.comp_node();
                        if (arr.size() != 1) {
                            throw py::value_error("invalid number of comp_node");
                        }
                        return arr[0];
                    },
                    [](OperatorNodeConfig& config, CompNode cn) {
                        OperatorNodeConfig::CompNodeArray arr{cn};
                        config.comp_node_arr(arr);
                    });
223 224

    py::class_<LogicalTensorDesc>(m, "TensorAttr")
M
Megvii Engine Team 已提交
225 226 227
            .def(py::init())
            .def(py::init([](const TensorShape& shape, const DType& dtype,
                             const CompNode& comp_node) {
228 229
                return LogicalTensorDesc{TensorLayout{shape, dtype}, comp_node};
            }))
M
Megvii Engine Team 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242
            .def_property(
                    "shape",
                    [](const LogicalTensorDesc& desc) {
                        return static_cast<TensorShape>(desc.layout);
                    },
                    [](LogicalTensorDesc& desc, TensorShape shape) {})
            .def_property(
                    "dtype",
                    [](const LogicalTensorDesc& desc) { return desc.layout.dtype; },
                    [](LogicalTensorDesc& desc, DType dtype) {
                        desc.layout.dtype = dtype;
                    })
            .def_readwrite("comp_node", &LogicalTensorDesc::comp_node);
243 244 245 246

    py::enum_<CompNode::DeviceType>(m, "DeviceType")
            .value("UNSPEC", CompNode::DeviceType::UNSPEC)
            .value("CUDA", CompNode::DeviceType::CUDA)
247
            .value("ROCM", CompNode::DeviceType::ROCM)
248
            .value("CPU", CompNode::DeviceType::CPU)
249 250
            .value("CAMBRICON", CompNode::DeviceType::CAMBRICON)
            .value("ATLAS", CompNode::DeviceType::ATLAS)
251 252 253
            .value("MULTITHREAD", CompNode::DeviceType::MULTITHREAD)
            .value("MAX_DEVICE_ID", CompNode::DeviceType::MAX_DEVICE_ID);

M
Megvii Engine Team 已提交
254 255
    m.def("set_prealloc_config", &CompNode::set_prealloc_config,
          "specifies how to pre-allocate from raw dev allocator");
256

257 258 259
    m.def("get_device_prop", &CompNode::get_device_prop);

    m.def("get_supported_sm_versions", []() {
260
#if MEGDNN_WITH_CUDA
261
        static const char* mge_gen_code = MGE_CUDA_GENCODE;
262 263 264
#else
        static const char* mge_gen_code = "-1";
#endif
265 266
        return mge_gen_code;
    });
267

268 269 270
    m.def("get_cuda_version", []() { return mgb::get_cuda_version(); });
    m.def("get_cudnn_version", []() { return mgb::get_cudnn_version(); });
    m.def("get_tensorrt_version", []() { return mgb::get_tensorrt_version(); });
271
    m.def("get_cuda_driver_version", []() { return mgb::get_cuda_driver_version(); });
272

M
Megvii Engine Team 已提交
273 274
    m.def("what_is_xpu",
          [] { return CompNode::Locator::parse("xpux").to_physical().type; });
275

276 277
    m.def("init_nccl_env", &init_nccl_env);

278 279
    init_npy_num_bfloat16(m);
    init_npy_num_intbx(m);
280
    init_dtypes(m);
281
}