common.cpp 9.1 KB
Newer Older
M
Megvii Engine Team 已提交
1 2 3 4
/**
 * \file imperative/python/src/common.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
M
Megvii Engine Team 已提交
6 7 8 9 10 11
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

12 13 14 15
#include "./common.h"

#include <pybind11/operators.h>

M
Megvii Engine Team 已提交
16 17
#include "./helper.h"
#include "./numpy_dtypes.h"
18 19 20 21 22 23 24 25
#include "megbrain/comp_node.h"
#include "megbrain/graph.h"
#include "megbrain/imperative/physical_tensor.h"

namespace py = pybind11;
using namespace mgb;
using namespace imperative;

M
Megvii Engine Team 已提交
26 27
namespace {

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

47 48
std::string default_device = "xpux";

M
Megvii Engine Team 已提交
49
}  // namespace
M
Megvii Engine Team 已提交
50

M
Megvii Engine Team 已提交
51
void set_default_device(const std::string& device) {
52 53 54 55 56 57 58
    default_device = device;
}

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

59
void init_common(py::module m) {
M
Megvii Engine Team 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    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",
                            [](const CompNode& cn) { return cn.to_string(); })
                    .def_property_readonly(
                            "get_mem_status_bytes",
                            [](const CompNode& cn) {
                                return cn.get_mem_status_bytes();
                            })
                    .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); }));
99

M
Megvii Engine Team 已提交
100
    py::class_<CompNode::Event, std::shared_ptr<CompNode::Event>>(PyCompNode, "Event")
M
Megvii Engine Team 已提交
101 102
            .def("record", &CompNode::Event::record)
            .def("wait", &CompNode::Event::host_wait);
M
Megvii Engine Team 已提交
103

104 105
    py::implicitly_convertible<std::string, CompNode>();

M
Megvii Engine Team 已提交
106
    def_TensorND<DeviceTensorND>(m, "DeviceTensorND")
M
Megvii Engine Team 已提交
107
            .def("numpy", [](const DeviceTensorND& self) {
108 109
                HostTensorND hv;
                hv.copy_from(self).sync();
M
Megvii Engine Team 已提交
110 111
                return py::handle(
                        npy::ndarray_from_tensor(hv, npy::ShareType::TRY_SHARE));
112 113
            });

M
Megvii Engine Team 已提交
114
    def_TensorND<HostTensorND>(m, "HostTensorND")
M
Megvii Engine Team 已提交
115
            .def(py::init([](py::array data, CompNode cn, DType dtype) {
M
Megvii Engine Team 已提交
116 117 118 119 120
                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 已提交
121 122 123
            .def("numpy", [](const HostTensorND& self) {
                return py::reinterpret_steal<py::object>(
                        npy::ndarray_from_tensor(self, npy::ShareType::TRY_SHARE));
M
Megvii Engine Team 已提交
124 125
            });

126
    py::class_<cg::OperatorNodeConfig>(m, "OperatorNodeConfig")
M
Megvii Engine Team 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
            .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);
                    });
172 173

    py::class_<LogicalTensorDesc>(m, "TensorAttr")
M
Megvii Engine Team 已提交
174 175 176
            .def(py::init())
            .def(py::init([](const TensorShape& shape, const DType& dtype,
                             const CompNode& comp_node) {
177 178
                return LogicalTensorDesc{TensorLayout{shape, dtype}, comp_node};
            }))
M
Megvii Engine Team 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191
            .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);
192 193 194 195

    py::enum_<CompNode::DeviceType>(m, "DeviceType")
            .value("UNSPEC", CompNode::DeviceType::UNSPEC)
            .value("CUDA", CompNode::DeviceType::CUDA)
196
            .value("ROCM", CompNode::DeviceType::ROCM)
197
            .value("CPU", CompNode::DeviceType::CPU)
198 199
            .value("CAMBRICON", CompNode::DeviceType::CAMBRICON)
            .value("ATLAS", CompNode::DeviceType::ATLAS)
200 201 202
            .value("MULTITHREAD", CompNode::DeviceType::MULTITHREAD)
            .value("MAX_DEVICE_ID", CompNode::DeviceType::MAX_DEVICE_ID);

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

206 207
    m.def("get_cuda_compute_capability", &CompNode::get_compute_capability);

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

211 212
    init_npy_num_bfloat16(m);
    init_npy_num_intbx(m);
213
    init_dtypes(m);
214
}