common.cpp 11.4 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 12 13
#if MGB_ENABLE_OPR_MM
#include "megbrain/opr/mm_handler.h"
#endif
14

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

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

M
Megvii Engine Team 已提交
23 24
namespace {

M
Megvii Engine Team 已提交
25
template <typename XTensorND>
M
Megvii Engine Team 已提交
26 27
auto def_TensorND(py::object parent, const char* name) {
    return py::class_<XTensorND>(parent, name)
M
Megvii Engine Team 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41
            .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 已提交
42 43
}

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

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

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

52 53 54 55 56 57 58 59 60 61 62 63
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
}

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

68 69
py::handle py_comp_node_type;

70
void init_common(py::module m) {
M
Megvii Engine Team 已提交
71 72 73 74 75 76 77 78 79 80
    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",
81
                            [](const CompNode& cn) { return cn.to_string_physical(); })
M
Megvii Engine Team 已提交
82 83 84 85 86
                    .def_property_readonly(
                            "get_mem_status_bytes",
                            [](const CompNode& cn) {
                                return cn.get_mem_status_bytes();
                            })
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
                    .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 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
                    .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); }));
130

131 132
    py_comp_node_type = PyCompNode.inc_ref();

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

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

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    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 已提交
156
    def_TensorND<DeviceTensorND>(m, "DeviceTensorND")
M
Megvii Engine Team 已提交
157
            .def("numpy", [](const DeviceTensorND& self) {
158 159
                HostTensorND hv;
                hv.copy_from(self).sync();
160
                return py::reinterpret_steal<py::object>(
M
Megvii Engine Team 已提交
161
                        npy::ndarray_from_tensor(hv, npy::ShareType::TRY_SHARE));
162 163
            });

M
Megvii Engine Team 已提交
164
    def_TensorND<HostTensorND>(m, "HostTensorND")
M
Megvii Engine Team 已提交
165
            .def(py::init([](py::array data, CompNode cn, DType dtype) {
M
Megvii Engine Team 已提交
166 167 168 169 170
                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 已提交
171 172 173
            .def("numpy", [](const HostTensorND& self) {
                return py::reinterpret_steal<py::object>(
                        npy::ndarray_from_tensor(self, npy::ShareType::TRY_SHARE));
M
Megvii Engine Team 已提交
174 175
            });

176
    py::class_<cg::OperatorNodeConfig>(m, "OperatorNodeConfig")
M
Megvii Engine Team 已提交
177 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
            .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);
                    });
222 223

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

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

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

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

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

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

270 271
    m.def("init_nccl_env", &init_nccl_env);

272 273
    init_npy_num_bfloat16(m);
    init_npy_num_intbx(m);
274
    init_dtypes(m);
275
}