common.cpp 12.8 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
std::string device_type2str(CompNode::DeviceType type) {
    using DT = CompNode::DeviceType;
    switch (type) {
        case DT::UNSPEC:
            return "xpu";
        case DT::CUDA:
            return "gpu";
        case DT::CPU:
            return "cpu";
        case DT::ATLAS:
            return "atlas";
        case DT::ROCM:
            return "rocm";
        case DT::CAMBRICON:
            return "cambricon";
        case DT::MULTITHREAD:
            return "multithread";
        default:
            mgb_throw(MegBrainError, "bad device type");
    }
}

91 92
py::handle py_comp_node_type;

93
void init_common(py::module m) {
M
Megvii Engine Team 已提交
94 95 96 97 98 99 100 101 102 103
    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",
104
                            [](const CompNode& cn) { return cn.to_string_physical(); })
105 106 107 108 109 110 111 112 113 114
                    .def_property_readonly(
                            "physical_locator",
                            [](const CompNode& cn) {
                                py::list res;
                                auto locator = cn.locator();
                                res.append(device_type2str(locator.type));
                                res.append(locator.device);
                                res.append(locator.stream);
                                return res;
                            })
M
Megvii Engine Team 已提交
115 116 117 118 119
                    .def_property_readonly(
                            "get_mem_status_bytes",
                            [](const CompNode& cn) {
                                return cn.get_mem_status_bytes();
                            })
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
                    .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 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
                    .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); }));
163

164 165
    py_comp_node_type = PyCompNode.inc_ref();

M
Megvii Engine Team 已提交
166
    py::class_<CompNode::Event, std::shared_ptr<CompNode::Event>>(PyCompNode, "Event")
M
Megvii Engine Team 已提交
167 168
            .def("record", &CompNode::Event::record)
            .def("wait", &CompNode::Event::host_wait);
M
Megvii Engine Team 已提交
169

170 171
    py::implicitly_convertible<std::string, CompNode>();

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    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 已提交
189
    def_TensorND<DeviceTensorND>(m, "DeviceTensorND")
M
Megvii Engine Team 已提交
190
            .def("numpy", [](const DeviceTensorND& self) {
191 192
                HostTensorND hv;
                hv.copy_from(self).sync();
193
                return py::reinterpret_steal<py::object>(
M
Megvii Engine Team 已提交
194
                        npy::ndarray_from_tensor(hv, npy::ShareType::TRY_SHARE));
195 196
            });

M
Megvii Engine Team 已提交
197
    def_TensorND<HostTensorND>(m, "HostTensorND")
M
Megvii Engine Team 已提交
198
            .def(py::init([](py::array data, CompNode cn, DType dtype) {
M
Megvii Engine Team 已提交
199 200 201 202 203
                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 已提交
204 205 206
            .def("numpy", [](const HostTensorND& self) {
                return py::reinterpret_steal<py::object>(
                        npy::ndarray_from_tensor(self, npy::ShareType::TRY_SHARE));
M
Megvii Engine Team 已提交
207 208
            });

209
    py::class_<cg::OperatorNodeConfig>(m, "OperatorNodeConfig")
M
Megvii Engine Team 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
            .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);
                    });
255 256

    py::class_<LogicalTensorDesc>(m, "TensorAttr")
M
Megvii Engine Team 已提交
257 258 259
            .def(py::init())
            .def(py::init([](const TensorShape& shape, const DType& dtype,
                             const CompNode& comp_node) {
260 261
                return LogicalTensorDesc{TensorLayout{shape, dtype}, comp_node};
            }))
M
Megvii Engine Team 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274
            .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);
275 276 277 278

    py::enum_<CompNode::DeviceType>(m, "DeviceType")
            .value("UNSPEC", CompNode::DeviceType::UNSPEC)
            .value("CUDA", CompNode::DeviceType::CUDA)
279
            .value("ROCM", CompNode::DeviceType::ROCM)
280
            .value("CPU", CompNode::DeviceType::CPU)
281 282
            .value("CAMBRICON", CompNode::DeviceType::CAMBRICON)
            .value("ATLAS", CompNode::DeviceType::ATLAS)
283 284 285
            .value("MULTITHREAD", CompNode::DeviceType::MULTITHREAD)
            .value("MAX_DEVICE_ID", CompNode::DeviceType::MAX_DEVICE_ID);

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

289 290 291
    m.def("get_device_prop", &CompNode::get_device_prop);

    m.def("get_supported_sm_versions", []() {
292
#if MEGDNN_WITH_CUDA
293
        static const char* mge_gen_code = MGE_CUDA_GENCODE;
294 295 296
#else
        static const char* mge_gen_code = "-1";
#endif
297 298
        return mge_gen_code;
    });
299

300 301 302
    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(); });
303
    m.def("get_cuda_driver_version", []() { return mgb::get_cuda_driver_version(); });
304

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

308 309
    m.def("init_nccl_env", &init_nccl_env);

310 311
    init_npy_num_bfloat16(m);
    init_npy_num_intbx(m);
312
    init_dtypes(m);
313
}