tensor.h 4.9 KB
Newer Older
1 2 3 4
/**
 * \file imperative/python/src/tensor.h
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11 12
 *
 * 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.
 */

#pragma once
13
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
14 15 16

#include <variant>

17
#include <string>
18
#include <unordered_map>
M
Megvii Engine Team 已提交
19 20
#include "megbrain/imperative/interpreter.h"
#include "pybind11/pybind11.h"
21 22

#include "./pyext17.h"
23 24
#include "megbrain/imperative/dispatch.h"
#include "megbrain/imperative/utils/span.h"
25 26 27

namespace mgb::imperative::python {

M
Megvii Engine Team 已提交
28
template <typename T, typename B = pybind11::object>
29 30
struct ObjectPtr : B {
    using B::B;
M
Megvii Engine Team 已提交
31 32
    T& operator*() { return reinterpret_cast<T&>(*B::ptr()); }
    T* operator->() { return reinterpret_cast<T*>(B::ptr()); }
33 34
};

M
Megvii Engine Team 已提交
35
}  // namespace mgb::imperative::python
36 37 38

namespace mgb::imperative::python {

39
extern interpreter::Interpreter::Channel* interpreter_for_py;
40
extern PyTypeObject* py_tensor_type;
41 42
extern PyObject* cpp_use_symbolic_shape;
extern PyObject* cpp_astensor1d;
43

44
struct Tensor : NonCopyableObj {
45
private:
46 47
    std::string m_name;
    ValueRef m_data;
M
Megvii Engine Team 已提交
48

49
public:
50 51
    using Handle = interpreter::Interpreter::Handle;

52
    inline explicit Tensor(ValueRef data) : m_data{data} {}
53

54 55 56
    ~Tensor() = default;

    inline std::shared_ptr<Tensor> copy() {
57
        auto ret = std::make_shared<Tensor>(m_data);
58
        ret->m_name = m_name;
59 60 61
        return ret;
    }

62 63 64 65 66 67
    inline DType dtype() { return *data().dtype(); }
    inline CompNode comp_node() { return *data().device(); }
    inline std::optional<ValueShape> shape() {
        auto shape = data().shape();
        if (!shape) {
            return {};
68
        }
69
        return *shape;
70
    }
71 72 73 74 75
    inline HostValue::ref_t numpy() { return data().numpy(); }
    inline void reset(ValueRef value) {
        m_data = value;
        if (!m_name.empty()) {
            set_name(m_name);
76 77
        }
    }
78 79 80 81 82 83 84 85
    inline ValueRef data() { return m_data.unwrap(); }
    bool is_scalar() { return data().is_scalar(); }
    inline std::string name() { return m_name; }
    inline void set_name(std::string name) {
        m_name = name;
        if (!name.empty()) {
            auto output = imperative::apply(RenameValue(name), m_data)[0];
            m_data = output;
86 87
        }
    }
88 89 90
};

struct TensorWrapper {
91
public:
92 93
    std::shared_ptr<Tensor> m_tensor;

M
Megvii Engine Team 已提交
94
    inline TensorWrapper(std::shared_ptr<Tensor> tensor = {})
95 96 97 98 99
            : m_tensor(std::move(tensor)) {
        mgb_assert(tensor, "empty storage");
    }

    inline TensorWrapper(ValueRef value) : m_tensor(std::make_shared<Tensor>(value)) {}
100 101 102 103 104 105 106 107
    TensorWrapper(PyObject* args, PyObject* kwargs);
    ~TensorWrapper() = default;

    static constexpr auto tp_name = pybind11::detail::_("Tensor");

    using wrap_t = pyext17::wrap<TensorWrapper>;
    friend wrap_t;

M
Megvii Engine Team 已提交
108 109 110
    inline static TensorWrapper* cast(PyObject* obj) {
        return reinterpret_cast<wrap_t*>(obj)->inst();
    }
111
    inline static TensorWrapper* try_cast(PyObject* obj) {
M
Megvii Engine Team 已提交
112 113
        if (!wrap_t::type().isinstance(obj))
            return nullptr;
114
        return cast(obj);
115
    }
M
Megvii Engine Team 已提交
116 117 118
    inline ObjectPtr<TensorWrapper, pybind11::handle> self() {
        return wrap_t::pycast(this);
    }
119 120 121 122 123 124 125 126 127

    template <typename... Args>
    static ObjectPtr<Tensor> make(Args&&... args) {
        auto* op = wrap_t::cnew(std::forward<Args>(args)...);
        return pybind11::reinterpret_steal<ObjectPtr<Tensor>>(op);
    }

    template <typename... Args>
    static ObjectPtr<Tensor> make(PyTypeObject* pytype, Args&&... args) {
M
Megvii Engine Team 已提交
128
        auto* op = wrap_t::cnew_with_type(pytype, std::forward<Args>(args)...);
129 130 131 132 133 134 135 136
        return pybind11::reinterpret_steal<ObjectPtr<Tensor>>(op);
    }

    PyObject* shape();
    PyObject* dtype();
    PyObject* device();
    PyObject* numpy();
    void reset(PyObject*);
137
    PyObject* detach();
138
    PyObject* isscalar();
139 140
    PyObject* _dev_tensor();
    void _drop();
141
    PyObject* varnode();
142
    PyObject* recording();
143
    PyObject* copied();
144
    PyObject* module_trace_info();
M
Megvii Engine Team 已提交
145
    void set_module_trace_info(PyObject*);
146
    void _set_name(PyObject*);
147
    PyObject* _use_cnt() { return PyLong_FromSize_t(m_tensor.use_count()); };
148 149
    PyObject* _detail();
    void _watch();
150 151
};

152 153 154 155
struct PySymbolVar {
    cg::VarNode* m_node = nullptr;
    bool is_scalar = false;
    PySymbolVar() = default;
M
Megvii Engine Team 已提交
156
    PySymbolVar(VarNode* m) : m_node(m) {}
157
};
158

M
Megvii Engine Team 已提交
159 160
PyObject* py_apply(
        PyObject* self, PyObject* const* args, size_t nargs /* , PyObject* kwnames */);
161

162 163
void init_tensor(pybind11::module);

M
Megvii Engine Team 已提交
164
extern PyObject* cpp_apply_module_trace;
165

M
Megvii Engine Team 已提交
166
}  // namespace mgb::imperative::python
167 168 169

namespace pybind11::detail {

M
Megvii Engine Team 已提交
170 171 172
template <>
struct type_caster<mgb::imperative::python::TensorWrapper>
        : mgb::imperative::python::TensorWrapper::wrap_t::caster {};
173

M
Megvii Engine Team 已提交
174
}  // namespace pybind11::detail