dnn_op_helper.h 11.3 KB
Newer Older
1 2 3 4
#include <optional>
#include <type_traits>

#include "algo_chooser.h"
5
#include "megbrain/comp_node.h"
M
Megvii Engine Team 已提交
6
#include "megbrain/comp_node_env.h"
7
#include "megbrain/imperative/blob_manager.h"
8
#include "megbrain/imperative/physical_tensor.h"
9 10
#include "megbrain/imperative/utils/helper.h"
#include "megbrain/imperative/utils/platform.h"
11
#include "megbrain/rdnn/management.h"
12
#include "megdnn/basic_types.h"
13 14 15 16 17

namespace mgb {
namespace imperative {

/*!
18
 * /brief Helps deduce layout and dtype
19
 */
M
Megvii Engine Team 已提交
20
template <typename Opr>
21 22 23
class DnnOprDeducer {
private:
    Opr* m_opr;
24

25 26
public:
    DnnOprDeducer(Opr* opr) : m_opr(opr) { mgb_assert(opr); }
27

28 29 30
    // FIXME: maybe in-place style deduction works better
    template <typename... TArgs>
    TensorLayout deduce_layout(TArgs&&... args) {
31
        // static_assert((std::is_convertible_v<TArgs, TensorLayout> && ...));
32 33 34
        TensorLayout output_layout;
        m_opr->deduce_layout(args..., output_layout);
        return output_layout;
35 36
    }

37 38
    template <typename... TArgs>
    TensorLayout deduce_layout_fallible(TArgs&&... args) {
39
        // static_assert((std::is_convertible_v<TArgs, TensorLayout> && ...));
40 41 42 43 44 45
        TensorLayout output_layout;
        bool success = (args.ndim * ...) > 0;
        if (success) {
            m_opr->deduce_layout(args..., output_layout);
        } else {
            m_opr->deduce_dtype(args.dtype..., output_layout.dtype);
46
        }
47
        return output_layout;
48
    }
49

50 51
    template <size_t nr_outputs, typename... TArgs>
    std::array<TensorLayout, nr_outputs> deduce_layouts(TArgs&&... args) {
52
        // static_assert((std::is_convertible_v<TArgs, TensorLayout> && ...));
53 54 55 56 57 58 59 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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        std::array<TensorLayout, nr_outputs> layouts;
        std::apply(
                [&](auto&&... outputs) { m_opr->deduce_layout(args..., outputs...); },
                layouts);
        return layouts;
    }
};

/*!
 * /brief Declare an abstract operator and initialize it's param
 */
template <typename Opr>
class DnnOprStub {
private:
    // TODO: make opr concrete
    std::aligned_storage_t<sizeof(Opr), alignof(Opr)> m_storage;

    using Param = typename Opr::Param;

private:
    DnnOprStub() { new (&param()) Param(); }

public:
    DnnOprStub(const Param& param) { this->param() = param; }

    // undefined behavior
    Opr& opr() { return *reinterpret_cast<Opr*>(&m_storage); }

    auto& param() { return opr().param(); }

    auto& param() const { return opr().param(); }

    ~DnnOprStub() { param().~Param(); }
};

/*!
 * /brief Deduce layout without create concrete opr
 */
template <typename Opr>
class DnnOprHelper : public DnnOprStub<Opr>, public DnnOprDeducer<Opr> {
private:
    using Stub = DnnOprStub<Opr>;
    using Deducer = DnnOprDeducer<Opr>;

public:
    DnnOprHelper(const typename Opr::Param& param)
            : Stub(param), Deducer(&Stub::opr()) {}
};

// hold a concrete operator in given comp_node
template <typename Opr>
class DnnOprHolder {
private:
    CompNode m_comp_node;
    opr::intl::UniqPtrWithCN<Opr> m_opr =
            opr::intl::create_megdnn_opr<Opr>(m_comp_node);

public:
    DnnOprHolder(CompNode comp_node) : m_comp_node(comp_node) {}

    auto& op() { return m_opr; }

    auto comp_node() { return m_comp_node; }

    auto& param() { return m_opr->param(); }

    auto& param() const { return m_opr->param(); }

    ~DnnOprHolder() {
122
        using DT = CompNode::DeviceType;
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

        if (m_comp_node.device_type() == DT::CPU &&
            m_comp_node != CompNode::default_cpu()) {
            CompNodeEnv::from_comp_node(m_comp_node)
                    .cpu_env()
                    .dispatch([p = m_opr.release()] { delete p; });
        }
    }
};

/*!
 * /brief Prevent binary float
 */
class DnnOprCallerBase {
protected:
    static auto&& get_layout(const megdnn::TensorND& tensor) { return tensor.layout; }

    static auto get_layout(const megdnn::TensorNDArray& tensors) {
        SmallVector<TensorLayout> layouts;
        for (auto&& tensor : tensors) {
            layouts.push_back(tensor.layout);
144
        }
145
        return layouts;
146 147 148
    }
};

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
/*!
 * \brief A struct for safely calling DNN oprs
 *
 * In some cases, op may be released before the complete of the execution
 * This destructor will prevent this
 */
template <typename Opr>
class DnnOprCaller final : public DnnOprHolder<Opr>,
                           public DnnOprDeducer<Opr>,
                           public DnnOprCallerBase {
private:
    using Holder = DnnOprHolder<Opr>;
    using Deducer = DnnOprDeducer<Opr>;
    using Base = DnnOprCallerBase;

    std::optional<DnnTensorND> m_workspace;
    std::optional<megdnn::param::ExecutionPolicy> m_policy;
166

167 168 169 170 171 172 173 174 175 176 177 178 179
    megdnn::Workspace create_workspace(size_t sz) {
        mgb_assert(
                !m_workspace, "workspace asked more than once by op: %s",
                demangled_typename<Opr>());
        dt_byte* ptr = nullptr;
        if (sz) {
            TensorLayout layout({sz}, dtype::Byte());
            m_workspace.emplace(
                    Tensor::make(layout, Holder::comp_node())->dnn_tensor());
            ptr = reinterpret_cast<dt_byte*>(m_workspace->raw_ptr());
        }
        return {ptr, sz};
    }
180 181

public:
182 183 184 185 186 187 188 189 190 191 192
    using Param = typename Opr::Param;

    DnnOprCaller(CompNode cn) : Holder(cn), Deducer(Holder::op().get()) {}

    DnnOprCaller(CompNode cn, const Param& param) : DnnOprCaller(cn) {
        Holder::param() = param;
    }

    DnnOprCaller(CompNode cn, const Param& param, megdnn::param::ExecutionPolicy policy)
            : DnnOprCaller(cn, param) {
        m_policy.emplace(policy);
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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    /**
     * /brief Convert TensorPtr args to megdnn::TensorND and call f
     *
     */
    template <typename TFunctor, typename... TArgs>
    auto call_dnn(TFunctor&& f, TArgs&&... args) {
        std::optional<SmallVector<std::shared_ptr<dt_byte>>> input_ptrs;
        // recursive convert:
        // 1. TensorPtr to DnnTensorND (subclass of megdnn::TensorND) ;
        // 2. DeviceTensorND, HostTensorND to megdnn::TensorND ;
        // 3. SmallVector of above to SmallVector<megdnn::TensorND> .
        auto to_dnn = [&](auto&& arg, auto&& to_dnn) {
            using T = decltype(arg);
            if constexpr (std::is_convertible_v<T, TensorPtr>) {
                return arg->dnn_tensor();
            } else if constexpr (
                    std::is_convertible_v<T, DeviceTensorND> ||
                    std::is_convertible_v<T, HostTensorND>) {
                return arg.as_megdnn();
            } else if constexpr (
                    std::is_convertible_v<T, megdnn::TensorND> ||
                    std::is_convertible_v<T, SmallVector<megdnn::TensorND>>) {
                return std::forward<T>(arg);
            } else if constexpr (is_small_vector_v<std::decay_t<T>>) {
                using TItem = std::decay_t<decltype(to_dnn(arg[0], to_dnn))>;
                SmallVector<megdnn::TensorND> dnn_tensors;
                for (auto&& tensor : arg) {
                    if constexpr (std::is_same_v<TItem, DnnTensorND>) {
                        if (!input_ptrs) {
                            input_ptrs.emplace();
                        }
                        auto dnn_tensor = to_dnn(tensor, to_dnn);
                        input_ptrs->push_back(std::move(dnn_tensor.reference));
                        dnn_tensors.push_back(std::move(dnn_tensor));
                    } else if constexpr (std::is_same_v<TItem, megdnn::TensorND>) {
                        dnn_tensors.push_back(to_dnn(tensor, to_dnn));
                    } else {
                        static_assert(!std::is_same_v<TItem, TItem>);
                    }
                }
                return dnn_tensors;
            } else {
                static_assert(!std::is_same_v<T, T>);
            }
        };
        return f(to_dnn(std::forward<TArgs>(args), to_dnn)...);
241 242
    }

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    // common execution (opr->exec(inputs..., outputs...))
    template <typename... TArgs>
    void exec(TArgs&&... args) {
        call_dnn(
                [this](auto&&... args) {
                    Holder::op()->exec(std::forward<decltype(args)>(args)...);
                },
                std::forward<TArgs>(args)...);
    }

    // execution fastrun opr
    // (opr->exec(inputs..., outputs..., create_ws(setup_algo(...))))
    template <typename... TArgs>
    void exec_fastrun(TArgs&&... args) {
        call_dnn(
                [&](auto&&... args) {
                    using FixedTensorLayouts =
                            typename rdnn::AlgoChooser<Opr>::FixedTensorLayouts;
                    SmallVector<megdnn::TensorND> dnn_inputs = {args...};
                    mgb_assert(m_policy, "policy not set");
                    size_t workspace_size = setup_algo<Opr>(
                            FixedTensorLayouts{args.layout...}, Holder::op().get(), 0,
                            false, false, Holder::comp_node(), *m_policy, false,
                            &dnn_inputs);
                    Holder::op()->exec(
                            std::forward<decltype(args)>(args)...,
                            create_workspace(workspace_size));
                },
                std::forward<TArgs>(args)...);
    }

    // execute with fixed workspace
    // (opr->exec(input..., outputs..., create_ws(get_workspace_in_bytes(...))))
    template <typename... TArgs>
    void exec_with_ws(TArgs&&... args) {
        call_dnn(
                [&](auto&&... args) {
                    size_t workspace_size =
                            Holder::op()->get_workspace_in_bytes(get_layout(args)...);
                    Holder::op()->exec(
                            std::forward<decltype(args)>(args)...,
                            create_workspace(workspace_size));
                },
                std::forward<TArgs>(args)...);
    }
288

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    // execute dynamic out opr
    // (opr->exec(inputs..., outputs... create_ws(get_workspace_in_bytes(...)), alloc))
    template <size_t nr_out, typename... TArgs>
    auto exec_dynout(TArgs&&... args) {
        struct Alloc final : public megdnn::DynOutMallocPolicy {
            CompNode comp_node;
            std::array<TensorPtr, nr_out> output_tensors;
            std::array<std::optional<DnnTensorND>, nr_out> output_dnn_tensors;

        public:
            Alloc(CompNode comp_node) : comp_node(comp_node) {}
            megdnn::TensorND alloc_output(
                    size_t id, DType dtype, const TensorShape& shape,
                    void* user_data) override {
                TensorLayout layout(shape, dtype);
                output_tensors[id] = Tensor::make(layout, comp_node);
                output_dnn_tensors[id].emplace(
                        output_tensors[id]->dnn_tensor());  // pin output
                return *output_dnn_tensors[id];
            }

            void* alloc_workspace(size_t sz, void* user_data) override {
                mgb_assert(false);
            }

            void free_workspace(void* ptr, void* user_data) override {
                mgb_assert(false);
            }
        } alloc{Holder::comp_node()};
        call_dnn(
                [&](auto&&... args) {
                    size_t workspace_size =
                            Holder::op()->get_workspace_in_bytes(get_layout(args)...);
                    Holder::op()->exec(
                            std::forward<decltype(args)>(args)...,
                            create_workspace(workspace_size), &alloc);
                },
                std::forward<TArgs>(args)...);
        return alloc.output_tensors;
    }
329 330
};

M
Megvii Engine Team 已提交
331 332
}  // namespace imperative
}  // namespace mgb