common.cpp 10.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 11
#include "megbrain/comp_node.h"
#include "megbrain/graph.h"
#include "megbrain/imperative/physical_tensor.h"

12 13 14 15
#if MEGDNN_WITH_CUDA
#include "cuda_sm_gen.h"
#endif

16 17 18 19
namespace py = pybind11;
using namespace mgb;
using namespace imperative;

M
Megvii Engine Team 已提交
20 21
namespace {

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

41 42
std::string default_device = "xpux";

M
Megvii Engine Team 已提交
43
}  // namespace
M
Megvii Engine Team 已提交
44

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

std::string get_default_device() {
    return default_device;
}

53 54
py::handle py_comp_node_type;

55
void init_common(py::module m) {
M
Megvii Engine Team 已提交
56 57 58 59 60 61 62 63 64 65
    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",
66
                            [](const CompNode& cn) { return cn.to_string_physical(); })
M
Megvii Engine Team 已提交
67 68 69 70 71
                    .def_property_readonly(
                            "get_mem_status_bytes",
                            [](const CompNode& cn) {
                                return cn.get_mem_status_bytes();
                            })
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
                    .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 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
                    .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); }));
115

116 117
    py_comp_node_type = PyCompNode.inc_ref();

M
Megvii Engine Team 已提交
118
    py::class_<CompNode::Event, std::shared_ptr<CompNode::Event>>(PyCompNode, "Event")
M
Megvii Engine Team 已提交
119 120
            .def("record", &CompNode::Event::record)
            .def("wait", &CompNode::Event::host_wait);
M
Megvii Engine Team 已提交
121

122 123
    py::implicitly_convertible<std::string, CompNode>();

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    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 已提交
141
    def_TensorND<DeviceTensorND>(m, "DeviceTensorND")
M
Megvii Engine Team 已提交
142
            .def("numpy", [](const DeviceTensorND& self) {
143 144
                HostTensorND hv;
                hv.copy_from(self).sync();
145
                return py::reinterpret_steal<py::object>(
M
Megvii Engine Team 已提交
146
                        npy::ndarray_from_tensor(hv, npy::ShareType::TRY_SHARE));
147 148
            });

M
Megvii Engine Team 已提交
149
    def_TensorND<HostTensorND>(m, "HostTensorND")
M
Megvii Engine Team 已提交
150
            .def(py::init([](py::array data, CompNode cn, DType dtype) {
M
Megvii Engine Team 已提交
151 152 153 154 155
                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 已提交
156 157 158
            .def("numpy", [](const HostTensorND& self) {
                return py::reinterpret_steal<py::object>(
                        npy::ndarray_from_tensor(self, npy::ShareType::TRY_SHARE));
M
Megvii Engine Team 已提交
159 160
            });

161
    py::class_<cg::OperatorNodeConfig>(m, "OperatorNodeConfig")
M
Megvii Engine Team 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 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
            .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);
                    });
207 208

    py::class_<LogicalTensorDesc>(m, "TensorAttr")
M
Megvii Engine Team 已提交
209 210 211
            .def(py::init())
            .def(py::init([](const TensorShape& shape, const DType& dtype,
                             const CompNode& comp_node) {
212 213
                return LogicalTensorDesc{TensorLayout{shape, dtype}, comp_node};
            }))
M
Megvii Engine Team 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226
            .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);
227 228 229 230

    py::enum_<CompNode::DeviceType>(m, "DeviceType")
            .value("UNSPEC", CompNode::DeviceType::UNSPEC)
            .value("CUDA", CompNode::DeviceType::CUDA)
231
            .value("ROCM", CompNode::DeviceType::ROCM)
232
            .value("CPU", CompNode::DeviceType::CPU)
233 234
            .value("CAMBRICON", CompNode::DeviceType::CAMBRICON)
            .value("ATLAS", CompNode::DeviceType::ATLAS)
235 236 237
            .value("MULTITHREAD", CompNode::DeviceType::MULTITHREAD)
            .value("MAX_DEVICE_ID", CompNode::DeviceType::MAX_DEVICE_ID);

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

241 242 243
    m.def("get_device_prop", &CompNode::get_device_prop);

    m.def("get_supported_sm_versions", []() {
244
#if MEGDNN_WITH_CUDA
245
        static const char* mge_gen_code = MGE_CUDA_GENCODE;
246 247 248
#else
        static const char* mge_gen_code = "-1";
#endif
249 250
        return mge_gen_code;
    });
251

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

255 256
    init_npy_num_bfloat16(m);
    init_npy_num_intbx(m);
257
    init_dtypes(m);
258
}