op_trait.h 9.1 KB
Newer Older
1
/**
M
Megvii Engine Team 已提交
2 3
 * \file imperative/src/impl/op_trait.h
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
4
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6
 *
M
Megvii Engine Team 已提交
7 8 9
 * 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.
10 11 12 13 14
 */

#pragma once

#include "megbrain/imperative/op_def.h"
15
#include "megbrain/imperative/graph_cache.h"
16 17 18

namespace mgb {
namespace imperative {
19
namespace detail {
20
template <typename Tag, typename Signature>
21
struct OpMeth;
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
template<typename T>
struct ToVarNodeArray: std::false_type {};
template<>
struct ToVarNodeArray<SymbolVar>: std::true_type {
    VarNodeArray operator()(const SymbolVar& inp) {
        return {inp.node()};
    }
};
template<>
struct ToVarNodeArray<SymbolVarArray>: std::true_type {
    VarNodeArray operator()(const SymbolVarArray& inputs) {
        return cg::to_var_node_array(inputs);
    }
};
template<size_t N>
struct ToVarNodeArray<std::array<SymbolVar, N>>: std::true_type {
    VarNodeArray operator()(const std::array<SymbolVar, N>& inp) {
        return cg::to_var_node_array({inp.begin(), inp.end()});
    }
};
template<>
struct ToVarNodeArray<cg::OperatorNodeBase*>: std::true_type {
    VarNodeArray operator()(const cg::OperatorNodeBase* opr) {
        return opr->usable_output();
    }
};
49
}  // namespace detail
50

51 52 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
// clang-format off
#define OpMethType(TYPE, SIG)                     \
    namespace detail::op_meth_tag {               \
        struct TYPE {                             \
            constexpr static char name[] = #TYPE; \
        };                                        \
    }                                             \
    using TYPE = detail::OpMeth<detail::op_meth_tag::TYPE, SIG>

OpMethType(OpDefMaker,
           decltype(OpDef::make_from_op_node));

OpMethType(DecideDispatchMode,
           decltype(OpDef::decide_dispatch_mode));

OpMethType(ApplyOnPhysicalTensor,
           decltype(OpDef::apply_on_physical_tensor));

OpMethType(InferOutputMemDesc,
           decltype(OpDef::infer_output_mem_desc));

OpMethType(Execute,
           decltype(OpDef::execute));

OpMethType(ApplyOnDeviceTensorND,
           decltype(OpDef::apply_on_device_tensornd));

OpMethType(ApplyOnVarNode,
           decltype(OpDef::apply_on_var_node));

OpMethType(InferOutputAttrsFallible,
           decltype(OpDef::infer_output_attrs_fallible));

OpMethType(GradMaker,
           decltype(OpDef::make_backward_graph));

OpMethType(Props,
           decltype(OpDef::props));

OpMethType(HashFunc,
           size_t(const OpDef&));

OpMethType(IsSame,
           bool(const OpDef&, const OpDef&));

OpMethType(MakeNameFunc,
           std::string(const OpDef&));
98 99 100

OpMethType(GraphMaker,
           decltype(OpDef::make_forward_graph));
101 102 103
// clang-format on

namespace detail {
104 105 106 107 108 109

struct OpMethImplBase {
    template <typename Tag, typename RType, typename... Args>
    static void impl(thin_function<RType(Args...)>& func, Tag) {}
};

110 111 112 113 114 115 116 117
struct OpMethNotImpl {
    template <typename Tag, typename RType, typename... Args>
    static void impl(thin_function<RType(Args...)>& func, Tag) {
        func = [](Args... args) -> RType {
            mgb_throw(MegBrainError, "%s was not implemented yet", Tag::name);
        };
    }
};
118 119 120 121 122 123 124 125 126

struct OpMethFallback: OpMethImplBase {
    using OpMethImplBase::impl;
    static void impl(DecideDispatchMode& func, op_meth_tag::DecideDispatchMode);
    static void impl(MakeNameFunc& func, op_meth_tag::MakeNameFunc);
};

struct OpMethFallbackByProxyGraph: OpMethImplBase {
    using OpMethImplBase::impl;
127
    static void impl(ApplyOnPhysicalTensor& func,
128
                     op_meth_tag::ApplyOnPhysicalTensor);
129 130 131 132 133 134
    static void impl(Execute& func, op_meth_tag::Execute);
    static void impl(InferOutputMemDesc& func, op_meth_tag::InferOutputMemDesc);
    static void impl(InferOutputAttrsFallible& func,
                     op_meth_tag::InferOutputAttrsFallible);
    static void impl(GradMaker& func, op_meth_tag::GradMaker);
};
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

struct OpMethFallbackFromSubgraph: OpMethImplBase {
    using OpMethImplBase::impl;
    static void impl(ApplyOnPhysicalTensor& func,
                     op_meth_tag::ApplyOnPhysicalTensor);
    static void impl(InferOutputMemDesc& func, op_meth_tag::InferOutputMemDesc);
    static void impl(ApplyOnVarNode& func, op_meth_tag::ApplyOnVarNode);
    static void impl(InferOutputAttrsFallible& func,
                     op_meth_tag::InferOutputAttrsFallible);
    static void impl(GradMaker& func, op_meth_tag::GradMaker);
};

struct OpMethFallbackMode {
    static constexpr uint64_t None = 0;
    static constexpr uint64_t Default = 1;
    static constexpr uint64_t ByProxyGraph = 2;
    static constexpr uint64_t FromSubgraph = 4;
};

154 155 156
template <typename Tag, typename RType, typename... Args>
struct OpMeth<Tag, RType(Args...)> : public thin_function<RType(Args...)> {
    using Base = thin_function<RType(Args...)>;
157
    OpMeth() : Base{}{};
158
    explicit OpMeth(const Base& base) { this->Base::operator=(base); }
159
    using Base::operator bool;
160
    RType operator()(Args... args) const {
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        uint64_t mode_mask = ~uint64_t(0);
        auto match_mode = [&](uint64_t mode){
            if ((fallback_mode & mode_mask) & mode) {
                mode_mask &= ~mode;
                return true;
            }
            return false;
        };
        while (!this->Base::operator bool()) {
            using Mode = OpMethFallbackMode;
            if (match_mode(Mode::FromSubgraph)) {
                OpMethFallbackFromSubgraph::impl(*const_cast<OpMeth*>(this), Tag{});
            } else if (match_mode(Mode::ByProxyGraph)) {
                OpMethFallbackByProxyGraph::impl(*const_cast<OpMeth*>(this), Tag{});
            } else if (match_mode(Mode::Default)) {
176 177 178 179 180 181 182
                OpMethFallback::impl(*const_cast<OpMeth*>(this), Tag{});
            } else {
                OpMethNotImpl::impl(*const_cast<OpMeth*>(this), Tag{});
            }
        }
        return this->Base::operator()(std::forward<Args>(args)...);
    }
183
    uint64_t fallback_mode = OpMethFallbackMode::None;
184 185
};
}  // namespace detail
186 187 188 189

struct OpTrait {
    const char* name;
    OpDefMaker make_from_op_node;
190
    DecideDispatchMode decide_dispatch_mode;
191
    ApplyOnPhysicalTensor apply_on_physical_tensor;
192 193
    InferOutputMemDesc infer_output_mem_desc;
    Execute execute;
194
    ApplyOnDeviceTensorND apply_on_device_tensornd;
195 196 197
    ApplyOnVarNode apply_on_var_node;
    InferOutputAttrsFallible infer_output_attrs_fallible;
    GradMaker make_backward_graph;
198
    Props props;
199 200
    HashFunc hash;
    IsSame is_same_st;
201
    MakeNameFunc make_name;
202
    GraphMaker make_forward_graph;
203 204 205 206 207 208
    OpTrait(const char* name);
    static OpTrait* find_by_name(const char* name);
    static OpTrait* find_by_typeinfo(Typeinfo* type);
    static void for_each_trait(thin_function<void(OpTrait&)> visitor);
};

209 210 211 212 213 214 215 216 217
// clang-format off
#define FOR_EACH_OP_METH(cb)        \
    cb(make_from_op_node)           \
    cb(decide_dispatch_mode)        \
    cb(apply_on_physical_tensor)    \
    cb(infer_output_mem_desc)       \
    cb(execute)                     \
    cb(apply_on_device_tensornd)    \
    cb(apply_on_var_node)           \
218
    cb(infer_output_attrs_fallible) \
219 220 221 222
    cb(make_backward_graph)         \
    cb(props)                       \
    cb(hash)                        \
    cb(is_same_st)                  \
223 224 225
    cb(make_name)                   \
    cb(make_forward_graph)          \

226
// clang-format on
227

228 229
struct OpTraitRegistry {
    OpTrait* trait;
230 231 232 233 234 235
#define DECL(meth)                                                             \
    OpTraitRegistry& meth(decltype(OpTrait::meth)::Base f) {                   \
        mgb_assert(!trait->meth, "op %s has duplicate method %s", trait->name, \
                   #meth);                                                     \
        trait->meth.Base::operator=(f);                                        \
        return *this;                                                          \
236
    }
237 238 239
    FOR_EACH_OP_METH(DECL)
#undef DECL

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    OpTraitRegistry& fallback();

    template<typename T>
    void insert() {
        do_insert(T::typeinfo());
    }

    template<typename T0, typename T1, typename ...Ts>
    void insert() {
        insert<T0>();
        insert<T1, Ts...>();
    }

    template<typename ...Args>
    static OpTraitRegistry insert(const char* name) {
        auto&& ret = do_insert(name);
        ret.insert<Args...>();
        return ret;
    }

    void do_insert(Typeinfo* type);

    static OpTraitRegistry do_insert(const char* name);
263 264 265 266 267 268 269 270 271

    template<typename T,
        typename To = detail::ToVarNodeArray<T>,
        typename = std::enable_if_t<To::value>>
    OpTraitRegistry& apply_on_var_node(T (*f)(const OpDef&, const VarNodeArray&)) {
        return apply_on_var_node([=](const OpDef& opdef, const VarNodeArray& inputs) {
            return To()(f(opdef, inputs));
        });
    }
272 273
};

274
}  // namespace imperative
275 276 277 278
} // namespace mgb

#define OP_TRAIT_REG(name, ...) \
    static OpTraitRegistry __##name##_global_registry__ = \
279
        OpTraitRegistry::insert<__VA_ARGS__>(#name)
280 281

// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}