inference.cpp 91.3 KB
Newer Older
1 2 3 4
/**
 * \file src/gopt/impl/inference.cpp
 * 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 13
 *
 * 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.
 */

#include "megbrain/gopt/inference.h"
#include "megbrain/gopt/basic_arith.h"
M
Megvii Engine Team 已提交
14
#include "megbrain/gopt/gtrans.h"
15 16 17
#include "megbrain/graph/event.h"
#include "megbrain/opr/basic_arith.h"
#include "megbrain/opr/blas.h"
M
Megvii Engine Team 已提交
18 19
#include "megbrain/opr/dnn/batch_norm.h"
#include "megbrain/opr/dnn/convolution.h"
20
#include "megbrain/opr/dnn/images2neibs.h"
M
Megvii Engine Team 已提交
21
#include "megbrain/opr/dnn/local.h"
22 23
#include "megbrain/opr/dnn/pooling.h"
#include "megbrain/opr/imgproc.h"
M
Megvii Engine Team 已提交
24
#include "megbrain/opr/misc.h"
25
#include "megbrain/opr/nn_int.h"
M
Megvii Engine Team 已提交
26 27
#include "megbrain/opr/search_policy/algo_chooser_helper.h"
#include "megbrain/opr/search_policy/profiler.h"
28
#include "megbrain/opr/tensor_gen.h"
M
Megvii Engine Team 已提交
29 30 31
#include "megbrain/opr/tensor_manip.h"
#include "megbrain/opr/utility.h"
#include "megbrain/serialization/opr_shallow_copy.h"
32
#include "megbrain/utils/hash_ct.h"
M
Megvii Engine Team 已提交
33
#include "megbrain/utils/shared_set.h"
34 35 36 37 38 39

#include "megdnn/tensor_format.h"

#if MGB_ENABLE_TENSOR_RT
#include "megbrain/tensorrt/tensorrt_opr.h"
#endif
40 41 42
#if MGB_CUDA
#include <cudnn.h>
#endif
43 44 45

#include "megbrain/gopt/misc.h"

46 47 48 49
#include "megbrain/utils/hash_ct.h"
#include "midout.h"

MIDOUT_DECL(megbrain_inference)
M
Megvii Engine Team 已提交
50
#define MIDOUT_B(tag) MIDOUT_BEGIN(megbrain_inference, midout_iv(MGB_HASH_STR(tag))) {
51 52 53 54
#define MIDOUT_E \
    }            \
    MIDOUT_END();

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
using namespace mgb;
using namespace gopt;

namespace {

template <typename SharedDeviceTensor, typename MultipleDeviceTensorHolder>
void param_merge(OptState& opt_state) {
    auto rewriter = opt_state.graph().make_rewriter();
    ThinHashMap<OperatorNodeBase*, size_t> opr2idx;
    std::vector<OperatorNodeBase*> all_oprs;
    typename MultipleDeviceTensorHolder::ValueArray all_values;

    auto cb_find_opr = [&](cg::OperatorNodeBase* opr) {
        if (opr->same_type<SharedDeviceTensor>()) {
            auto p = &opr->cast_final<SharedDeviceTensor>();
            // ShredD may be manu
            opr2idx[p] = all_values.size();
            all_values.push_back(p->dev_data());
            all_oprs.push_back(p);
        }
    };
    opt_state.graph().iter(cb_find_opr);
    SymbolVarArray new_vars;
    auto cb_replace = [&](cg::OperatorNodeBase* opr) {
        auto iter = opr2idx.find(opr);
        if (iter == opr2idx.end()) {
            rewriter.auto_replace_outputs(opr);
        } else {
            if (new_vars.empty()) {
                // new oprs must be created in iter callback; so we populate
                // new_vars lazily
                new_vars = MultipleDeviceTensorHolder::make(
                        *opt_state.graph().comp_graph(), std::move(all_values),
                        {ssprintf("merged%zu", all_values.size())});
                for (size_t i = 0; i < new_vars.size(); ++i) {
                    auto src = all_oprs[i]->output(0);
                    if (src->has_name_set()) {
                        new_vars[i].rename(src->name());
                    }
                }
            }
            rewriter.replace_var(
                    opr->output(0), new_vars.at(iter->second).node(),
                    mgb_cstr_log("replace multi SharedDeviceTensor(Format) to "
                                 "MultipleDeviceTensorHolder(Format)"));
        }
    };
    opt_state.graph().iter(cb_replace);

    rewriter.apply_inplace();
}

107
}  // namespace
108 109 110 111

/* ================ global functions ================ */

SymbolVarArray gopt::optimize_for_inference(
M
Megvii Engine Team 已提交
112
        const SymbolVarArray& dest_vars, const OptimizeForInferenceOptions& opt) {
113
    return gopt::GraphOptimizer()
M
Megvii Engine Team 已提交
114 115
            .add_preset_passes(
                    false, &opt, &dest_vars[0].node()->owner_graph()->options())
116 117 118 119
            .apply({dest_vars})
            .endpoint_vars();
}

M
Megvii Engine Team 已提交
120 121
SymbolVarArray gopt::layout_transform(
        const SymbolVarArray& dest_vars, GraphTuningOptions::Target target) {
122 123 124 125 126 127 128 129 130
    GraphTuningOptions options;
    options.target = target;
    options.enable_layout_transform();
    return gopt::GraphOptimizer{}
            .add_passes_for_graph_tuning_options(options)
            .apply({dest_vars})
            .endpoint_vars();
}

131
namespace {
132
void modify_conv_strategy(
133 134
        opr::mixin::AlgoChooserHelper& conv,
        opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy strategy) {
135 136 137 138 139 140
    auto policy = conv.execution_policy_transient();
    policy.strategy = strategy;
    conv.set_execution_policy(policy);
}

template <typename Opr>
141 142
void inplace_conv_opr_modifier(
        OperatorNodeBase& opr,
143
        opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy strategy) {
M
Megvii Engine Team 已提交
144
    modify_conv_strategy(opr.cast_final_safe<Opr>(), strategy);
145 146
}

M
Megvii Engine Team 已提交
147 148
void modify_conv_policy_workspace_limit(
        opr::mixin::AlgoChooserHelper& conv, size_t workspace_limit) {
149 150 151 152 153 154
    auto policy = conv.execution_policy_transient();
    policy.workspace_limit = workspace_limit;
    conv.set_execution_policy(policy);
}

template <typename Opr>
M
Megvii Engine Team 已提交
155 156 157
void inplace_conv_opr_workspace_limit_modifier(
        OperatorNodeBase& opr, size_t workspace_limit) {
    modify_conv_policy_workspace_limit(opr.cast_final_safe<Opr>(), workspace_limit);
158 159 160 161
}

}  // anonymous namespace

162 163
void gopt::modify_opr_algo_strategy_inplace(
        const VarNodeArrayView& dest_vars,
164
        opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy strategy) {
165
#if !MGB_ENABLE_FASTRUN
166
    using S = opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy;
167
    if ((strategy & S::PROFILE) && !(strategy & S::HEURISTIC)) {
168 169 170
        mgb_throw(MegBrainError, "fastrun is disabled at compile time");
    }
#endif
M
Megvii Engine Team 已提交
171 172 173 174 175
    const ThinHashMap<Typeinfo*, std::function<void(OperatorNodeBase&)>> modifiers = {
#define CONV(t)          \
    {opr::t::typeinfo(), \
     std::bind(inplace_conv_opr_modifier<opr::t>, std::placeholders::_1, strategy)},
            MGB_FOREACH_FASTRUN_OPR(CONV)
176
#undef CONV
M
Megvii Engine Team 已提交
177
    };
178 179 180 181 182 183 184 185 186 187 188 189 190 191

    auto on_opr = [&](OperatorNodeBase* opr) {
        auto iter = modifiers.find(opr->dyn_typeinfo());
        if (iter != modifiers.end()) {
            iter->second(*opr);
        }
    };

    cg::DepOprIter dep_iter{on_opr};
    for (auto i : dest_vars) {
        dep_iter.add(i);
    }
}

M
Megvii Engine Team 已提交
192
void gopt::enable_opr_algo_profiling_inplace(const VarNodeArrayView& dest_vars) {
193 194 195
    modify_opr_algo_strategy_inplace(
            dest_vars,
            opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy::PROFILE);
196
}
197

M
Megvii Engine Team 已提交
198
void gopt::enable_opr_use_profiling_cache_inplace(const VarNodeArrayView& dest_vars) {
199 200
    using S = megdnn::param::ExecutionPolicy::Strategy;
    modify_opr_algo_strategy_inplace(dest_vars, S::PROFILE | S::HEURISTIC);
201 202 203 204
}

void gopt::set_opr_algo_workspace_limit_inplace(
        const VarNodeArrayView& dest_vars, size_t workspace_limit) {
M
Megvii Engine Team 已提交
205 206
    static const ThinHashMap<Typeinfo*, void (*)(OperatorNodeBase&, size_t)> modifiers =
            {
207
#define CONV(t) \
208
    {opr::t::typeinfo(), &inplace_conv_opr_workspace_limit_modifier<opr::t>},
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                    MGB_FOREACH_FASTRUN_OPR(CONV)
#undef CONV
            };

    auto on_opr = [&](OperatorNodeBase* opr) {
        auto iter = modifiers.find(opr->dyn_typeinfo());
        if (iter != modifiers.end()) {
            iter->second(*opr, workspace_limit);
        }
    };

    cg::DepOprIter dep_iter{on_opr};
    for (auto i : dest_vars) {
        dep_iter.add(i);
    }
}

/* ================ ParamRedistributePass ================ */
const char* ParamRedistributePass::name() const {
    return mgb_cstr_log("param_redistribute");
}

M
Megvii Engine Team 已提交
231
class ParamRedistributePass::Impl final : public RecursiveSubGraphRewriteHelper {
232 233 234 235 236 237 238 239
    ConstVarPropogate m_cvprop;
    UniqReaderCheck m_uniq_reader_check;
    //! oprs already processed in try_distribute_then_reassociate() should be
    //! skipped in on_new_opr_check_should_process()
    ThinHashSet<OperatorNodeBase*> m_opr_blacklist;
    std::string m_distribute_reasso_log_msg;

    //! try applying BinaryTrans20::associtive
M
Megvii Engine Team 已提交
240
    GTransResult try_reassociate(OperatorNodeBase* opr);
241 242

    //! try applying BinaryTrans20::distributive_add
M
Megvii Engine Team 已提交
243
    GTransResult try_distribute_add(OperatorNodeBase* opr);
244 245

    //! try distribute MUL/DIV over ADD/SUB and then apply
M
Megvii Engine Team 已提交
246
    GTransResult try_distribute_then_reassociate(OperatorNodeBase* opr);
247

M
Megvii Engine Team 已提交
248
    GTransResult process_opr(VarNode* out_var) override;
249 250

    bool on_new_opr_check_should_process(
M
Megvii Engine Team 已提交
251
            OperatorNodeBase* opr, OperatorNodeBase* repl_opr) override {
252 253
        m_uniq_reader_check.update_on_opr_auto_replace(opr, repl_opr);
        auto ins = m_cvprop.add_opr(opr);
M
Megvii Engine Team 已提交
254
        return ins.has_const_inp && !ins.all_const_inp && !m_opr_blacklist.count(opr);
255 256
    };

M
Megvii Engine Team 已提交
257 258 259
    void after_replace_var(VarNode* orig_var, VarNode* new_var) override {
        m_uniq_reader_check.update_on_opr_auto_replace(
                orig_var->owner_opr(), new_var->owner_opr());
260 261 262 263 264 265 266 267
    }

    /*!
     * \brief try to reorder opr inputs to a const one and a non-const one
     *
     * return true if it can be reformulated as f(nci, ci), where nci is
     * non-const and ci is const.
     */
M
Megvii Engine Team 已提交
268 269
    bool reorder_for_normconst(
            OperatorNodeBase* opr, bool& swap_inp, VarNode*& nci, VarNode*& ci);
270

M
Megvii Engine Team 已提交
271 272
public:
    Impl(OptState& state);
273 274
};

M
Megvii Engine Team 已提交
275
GTransResult ParamRedistributePass::Impl::process_opr(VarNode* out_var) {
276 277 278 279 280 281 282 283 284 285 286 287
    auto opr = out_var->owner_opr();
    auto trans = try_reassociate(opr);

    if (!trans.valid()) {
        trans = try_distribute_add(opr);
        if (!trans.valid())
            trans = try_distribute_then_reassociate(opr);
    }

    return trans;
}

M
Megvii Engine Team 已提交
288
GTransResult ParamRedistributePass::Impl::try_reassociate(OperatorNodeBase* opr) {
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    // apply BinaryAssociative0 if opr is the form f(g(a, b), c) and b and c are
    // const

    bool swap_fop_inp = false, swap_gop_inp = false;
    VarNode *a, *b, *c, *ab;
    if (!reorder_for_normconst(opr, swap_fop_inp, ab, c))
        return None;

    if (!m_uniq_reader_check(ab))
        return None;

    if (!reorder_for_normconst(ab->owner_opr(), swap_gop_inp, a, b))
        return None;

    return BinaryTrans20::associtive().apply(opr, swap_fop_inp, swap_gop_inp);
}

M
Megvii Engine Team 已提交
306
GTransResult ParamRedistributePass::Impl::try_distribute_add(OperatorNodeBase* opr) {
307 308 309 310 311 312 313 314 315 316 317
    if (opr->same_type<opr::Elemwise>() || opr->input().size() != 2)
        return None;

    if (!m_cvprop.is_const(opr->input(1)))
        return None;

    auto ab = as_elem_opr(opr->input(0)->owner_opr(), opr::Elemwise::Mode::ADD);
    if (ab) {
        bool swap;
        VarNode *a, *b;
        if (reorder_for_normconst(ab, swap, a, b)) {
M
Megvii Engine Team 已提交
318
            return BinaryTrans20::distributive_add().apply(opr, false, swap);
319 320 321 322 323 324
        }
    }
    return None;
}

GTransResult ParamRedistributePass::Impl::try_distribute_then_reassociate(
M
Megvii Engine Team 已提交
325
        OperatorNodeBase* opr) {
326 327 328 329 330 331 332 333 334 335 336 337
    if (!opr->same_type<opr::Elemwise>())
        return None;
    using Mode = opr::Elemwise::Mode;
    auto mode = opr->cast_final<opr::Elemwise>().param().mode;
    if (!(mode == Mode::MUL || mode == Mode::TRUE_DIV))
        return None;

    VarNode *a, *b;
    bool swap;
    if (!reorder_for_normconst(opr, swap, a, b))
        return None;

M
Megvii Engine Team 已提交
338
    auto chain_pred = [this](OperatorNodeBase* opr) {
339 340 341 342 343 344 345 346 347 348 349 350 351
        if (as_elem_opr(opr, Mode::ADD)) {
            auto var = opr->output(0);
            return m_uniq_reader_check(var) || m_cvprop.is_const(var);
        }
        return false;
    };
    auto chain = extract_opr_leaves(a, chain_pred);
    if (chain.size() <= 1)
        return None;
    std::unordered_map<VarNode*, VarNode*> repl_map;
    m_distribute_reasso_log_msg.clear();

    int nr_fail = 0, nr_succ = 0;
M
Megvii Engine Team 已提交
352
    for (auto&& var : chain) {
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        {
            auto iter = repl_map.find(var);
            if (iter != repl_map.end()) {
                var = iter->second;
                continue;
            }
        }

        auto vnew = (SymbolVar{var} * b).node();
        m_opr_blacklist.insert(vnew->owner_opr());
        if (!m_cvprop.is_const(var)) {
            auto trans = try_reassociate(vnew->owner_opr());
            if (!trans.valid()) {
                // allow at most one failed redistribution
                if (nr_fail)
                    return None;
M
Megvii Engine Team 已提交
369
                ++nr_fail;
370
            } else {
M
Megvii Engine Team 已提交
371
                ++nr_succ;
372 373 374 375 376 377 378 379 380 381 382 383
                vnew = trans->result;
                if (!m_distribute_reasso_log_msg.empty()) {
                    m_distribute_reasso_log_msg.append(mgb_cstr_log(";"));
                }
                m_distribute_reasso_log_msg.append(trans->msg);
            }
        }

        repl_map[var] = vnew;
        var = vnew;
    }
    if (nr_succ) {
M
Megvii Engine Team 已提交
384
        m_distribute_reasso_log_msg.insert(0, mgb_cstr_log("distribute_mul("));
385 386 387 388 389 390 391 392 393 394
        m_distribute_reasso_log_msg.append(mgb_cstr_log(")"));
        return GTransResultItem{
                elemwise_reduce_var_list(chain, Mode::ADD),
                m_distribute_reasso_log_msg.c_str(),
                {}};
    }
    return None;
}

bool ParamRedistributePass::Impl::reorder_for_normconst(
M
Megvii Engine Team 已提交
395
        OperatorNodeBase* opr, bool& swap_inp, VarNode*& nci, VarNode*& ci) {
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    if (opr->input().size() != 2)
        return false;

    nci = opr->input(0);
    ci = opr->input(1);
    if (!m_cvprop.is_const(ci)) {
        if (!is_commutable_binary(opr) || !m_cvprop.is_const(nci))
            return false;
        swap_inp = true;
        std::swap(nci, ci);
    } else {
        if (m_cvprop.is_const(nci))
            return false;
        swap_inp = false;
    }

    return true;
}

M
Megvii Engine Team 已提交
415 416 417 418
ParamRedistributePass::Impl::Impl(OptState& state)
        : RecursiveSubGraphRewriteHelper{state},
          m_cvprop{ConstVarType::IMMUTABLE_AND_PARAM},
          m_uniq_reader_check{state.graph()} {
419
    auto cg = state.graph().comp_graph();
M
Megvii Engine Team 已提交
420
    auto on_new_opr = [this](const cg::event::OprInserted& ev) {
421 422 423 424 425
        if (!ev.is_dedup && !ev.exc) {
            // call add_opr eagerly to avoid deep recursion
            m_cvprop.add_opr(ev.opr);
        }
    };
M
Megvii Engine Team 已提交
426
    auto hdl = cg->event().register_receiver<cg::event::OprInserted>(on_new_opr);
427 428 429
    apply();
}

M
Megvii Engine Team 已提交
430
void ParamRedistributePass::apply(OptState& state) const {
431
    MIDOUT_B("ParamRedistributePass::apply")
432
    Impl{state};
433
    MIDOUT_E
434 435 436 437 438 439 440 441 442
}

/* ================ ParamFusePass ================ */

/*!
 * \brief get name for new param
 */
class ParamFusePass::VarNamer {
#if MGB_BUILD_SLIM_SERVING
M
Megvii Engine Team 已提交
443 444 445 446 447
public:
    const std::string& name(VarNode*) {
        static std::string ret("fuse");
        return ret;
    }
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
#else
    using SrcSet = SharedSet<OperatorNodeBase*>;
    //! map from var to source SharedDeviceTensor/MultiSharedDeviceHolder oprs
    //! that it depends on
    ThinHashMap<OperatorNodeBase*, SrcSet> m_opr2srcs;
    std::string m_name_cache;
    std::vector<const char*> m_cur_name;

    SrcSet& get_src_set(OperatorNodeBase* opr) {
        auto opr_typeinfo = opr->dyn_typeinfo();

        auto iter = m_opr2srcs.find(opr);
        if (iter != m_opr2srcs.end()) {
            return iter->second;
        }
M
Megvii Engine Team 已提交
463
        auto&& ret = m_opr2srcs[opr];
464 465 466 467 468 469 470 471 472 473
        if (opr->input().empty()) {
            if (opr_typeinfo == opr::SharedDeviceTensor::typeinfo() ||
                opr_typeinfo == opr::MultipleDeviceTensorHolder::typeinfo()) {
                ret.insert(opr);
            } else {
                mgb_assert(opr_typeinfo == opr::ImmutableTensor::typeinfo());
            }
            return ret;
        }

M
Megvii Engine Team 已提交
474
        for (auto i : opr->input()) {
475 476 477 478 479
            ret.merge_from(get_src_set(i->owner_opr()));
        }
        return ret;
    }

M
Megvii Engine Team 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
public:
    const std::string& name(VarNode* var) {
        m_cur_name.clear();
        for (auto i : get_src_set(var->owner_opr())) {
            m_cur_name.push_back(i->cname());
        }

        auto cmp = [](const char* x, const char* y) { return strcmp(x, y) < 0; };
        std::sort(m_cur_name.begin(), m_cur_name.end(), cmp);
        m_name_cache.clear();
        m_name_cache.append(mgb_cstr_log("fuse("));
        bool first = true;
        for (auto i : m_cur_name) {
            if (first) {
                first = false;
            } else {
                m_name_cache.push_back(',');
497
            }
M
Megvii Engine Team 已提交
498
            m_name_cache.append(i);
499
        }
M
Megvii Engine Team 已提交
500 501 502 503
        m_name_cache.append(
                mgb_cstr_log(ssprintf("):%s@%zu", var->cname(), var->id())));
        return m_name_cache;
    }
504 505 506 507 508 509 510
#endif
};

const char* ParamFusePass::name() const {
    return mgb_cstr_log("param_fuse");
}

M
Megvii Engine Team 已提交
511
void ParamFusePass::apply(OptState& state) const {
512
    MIDOUT_B("ParamFusePass::apply")
513 514
    auto rewriter = state.graph().make_rewriter();
    auto cg = state.graph().comp_graph();
515 516

    ConstVarPropogate cvprop{ConstVarType::IMMUTABLE_AND_PARAM};
M
Megvii Engine Team 已提交
517
    state.graph().iter([&cvprop](OperatorNodeBase* opr) { cvprop.add_opr(opr); });
518

519 520 521
    ThinHashSet<VarNode*> processed_var;
    VarNamer var_namer;
    // reader: null if used as endvar
M
Megvii Engine Team 已提交
522
    auto replace_single_var = [&](VarNode* var, OperatorNodeBase* reader) {
523 524 525
        if (!processed_var.insert(var).second)
            return;

M
Megvii Engine Team 已提交
526 527
        auto inferred_val =
                std::make_shared<DeviceTensorND>(var->comp_node(), var->dtype());
528 529 530 531 532 533 534 535 536 537 538
        auto cb = [&](DeviceTensorND& val) {
            // retain format of val
            mgb_assert(val.format() == var->format());
            inferred_val->format(val.format())
                    .resize(val.shape())
                    .copy_from_fixlayout(val);
        };

        {
            auto orig_level = cg->options().log_level;
            cg->options().log_level = 0;
M
Megvii Engine Team 已提交
539 540
            MGB_TRY { cg->compile({{var, cb}})->execute(); }
            MGB_FINALLY(cg->options().log_level = orig_level);
541 542 543
        }

        SymbolVar new_var;
544
        bool is_default_format = var->format().is_default();
545
        bool is_lowbit_aligned = var->format().is_lowbit_aligned();
M
Megvii Engine Team 已提交
546
        if (cg::is_static_var_value(var) && (is_default_format || is_lowbit_aligned)) {
547 548 549 550 551 552
            // use ImmutableTensor for inferable vars
            HostTensorND hv;
            hv.copy_from(*inferred_val).sync();
            new_var = opr::ImmutableTensor::make(
                    *var->owner_graph(), hv, var_namer.name(var));
        } else {
553
            if (is_default_format || is_lowbit_aligned) {
554
                new_var = opr::SharedDeviceTensor::make_const(
555 556
                        *var->owner_graph(), inferred_val, var_namer.name(var));
            } else {
557
                new_var = opr::SharedDeviceTensorWithFormat::make_const(
558 559 560 561 562 563
                        *var->owner_graph(), inferred_val, var_namer.name(var));
            }
        }
        std::string log;
        if (reader) {
            log = mgb_ssprintf_log(
M
Megvii Engine Team 已提交
564 565
                    "due to read by %s{%s}", reader->cname(),
                    reader->dyn_typeinfo()->name);
566 567 568 569 570 571
        } else {
            log = mgb_cstr_log("as endpoint");
        }
        rewriter.replace_var(var, new_var.node(), log.c_str());
    };

572 573
    auto replace_opr = [&](OperatorNodeBase* opr) {
        auto add_ret = cvprop.opr_rst(opr);
574
        if (!add_ret.all_const_inp && add_ret.has_midconst_inp) {
M
Megvii Engine Team 已提交
575
            for (auto i : opr->input()) {
576
                if (cvprop.is_midconst(i)) {
M
Megvii Engine Team 已提交
577 578
                    state.call_with_opr(
                            i->owner_opr(), [&] { replace_single_var(i, opr); });
579 580 581 582
                }
            }
        }
        rewriter.auto_replace_outputs(opr);
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

        //! we should deal with midconst var after auto_replace_outputs, as
        //! on_midconst_opr will replace the endpoint output which may cause
        //! double replace.
        if (add_ret.all_const_inp) {
            for (auto var : opr->output()) {
                if (var->contain_flag(VarNode::Flag::VOLATILE_CONTENT))
                    continue;

                auto osize = ConstVarPropogate::var_mem_size(var);
                if (osize >= cvprop.max_size(opr) &&
                    osize - cvprop.max_size(opr) > m_param_grow_limit) {
                    return;
                }

                // const oprs should be evaluated when output is used by another
                // non-const opr or output is needed by the user
                if (state.graph().endpoint_contain(var)) {
                    replace_single_var(var, nullptr);
                }
            }
        }
605 606
    };

607
    state.graph().iter(replace_opr);
608
    rewriter.apply_inplace();
609
    MIDOUT_E
610 611 612 613 614 615 616 617
}

/* ================ One2OneOprReplacePass ================ */
const char* ConvertF32ToF16Pass::name() const {
    return mgb_cstr_log("convert_f32_to_f16");
}

void ConvertF32ToF16Pass::apply(OptState& state) const {
618
    MIDOUT_B("ConvertF32ToF16Pass::apply")
619 620 621 622
    state.set_var_replace_check_flag(m_var_replace_check_flag);
    auto rewriter = state.graph().make_rewriter();
    VarNodeArray new_inp_cache;

623 624 625 626 627 628 629 630
    // record original output dtype
    const SymbolVarArray& vars = state.graph().endpoint_vars();
    std::vector<DType> dtypes;
    for (size_t i = 0; i < vars.size(); i++) {
        dtypes.push_back(vars[i].node()->dtype());
    }

    auto on_opr = [this, &rewriter, &new_inp_cache](OperatorNodeBase* opr) {
631 632 633 634 635
        auto it = m_opr_replace_func.find(opr->dyn_typeinfo());
        if (it != m_opr_replace_func.end()) {
            auto&& new_inp = new_inp_cache;
            new_inp.clear();
            new_inp.reserve(opr->input().size());
M
Megvii Engine Team 已提交
636
            for (auto i : opr->input()) {
637 638 639 640 641
                new_inp.push_back(rewriter.get_var(i));
            }
            auto new_opr = (it->second)(opr, new_inp);

            auto &&origin_out = opr->output(), &&cur_out = new_opr->output();
M
Megvii Engine Team 已提交
642 643 644 645 646
            mgb_assert(
                    origin_out.size() == cur_out.size(),
                    "bad opr replace: src=%s{%s} dst=%s{%s}", opr->cname(),
                    opr->dyn_typeinfo()->name, new_opr->cname(),
                    new_opr->dyn_typeinfo()->name);
647
            for (size_t i = 0; i < origin_out.size(); i++) {
648
                rewriter.replace_var(origin_out[i], cur_out[i], nullptr);
649 650
            }
        } else {
651
            rewriter.auto_replace_outputs(opr);
652 653 654 655
        }
    };
    state.graph().iter(on_opr);
    rewriter.apply_inplace();
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

    // recover output dtype
    rewriter = state.graph().make_rewriter();
    const SymbolVarArray& endpoints = state.graph().endpoint_vars();
    auto replace_output = [&]() {
        for (size_t i = 0; i < endpoints.size(); i++) {
            VarNode* var = endpoints[i].node();
            if (var->dtype().enumv() != dtypes[i].enumv()) {
                auto new_var = opr::TypeCvt::make(var, dtypes[i]).node();
                rewriter.replace_var(var, new_var, nullptr);
            }
        }
    };
    mgb_assert(endpoints.size() > 0);
    auto opr = endpoints[0].node()->owner_opr();
    state.call_with_opr(opr, replace_output, OprPropertyFlag::NONE);
    rewriter.apply_inplace();
673
    MIDOUT_E
674 675
}

M
Megvii Engine Team 已提交
676
std::unique_ptr<ConvertF32ToF16Pass> ConvertF32ToF16Pass::make(bool use_f32_comp) {
677 678 679
#if MEGDNN_DISABLE_FLOAT16
    mgb_throw(SystemError, "float16 disabled at compile time.");
#else
M
Megvii Engine Team 已提交
680
    auto replace_h2d_opr = [](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
681 682 683
        mgb_assert(opr->input().size() == new_inp.size());
        auto& h2d_opr = opr->cast_final_safe<opr::Host2DeviceCopy>();
        if (h2d_opr.output(0)->dtype() == dtype::Float32()) {
M
Megvii Engine Team 已提交
684
            auto cvt_var = opr::TypeCvt::make(h2d_opr.output(0), dtype::Float16(), {});
685 686 687 688 689
            return cvt_var.node()->owner_opr();
        }
        return opr;
    };

M
Megvii Engine Team 已提交
690
    auto replace_sdt_opr = [](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
691 692 693
        mgb_assert(opr->input().size() == new_inp.size());
        auto& sdt_opr = opr->cast_final_safe<opr::SharedDeviceTensor>();
        if (sdt_opr.output(0)->dtype() == dtype::Float32()) {
M
Megvii Engine Team 已提交
694
            auto cvt_var = opr::TypeCvt::make(sdt_opr.output(0), dtype::Float16(), {});
695 696 697 698 699
            return cvt_var.node()->owner_opr();
        }
        return opr;
    };

M
Megvii Engine Team 已提交
700
    auto replace_imt_opr = [](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
701 702 703 704
        mgb_assert(opr->same_type<opr::ImmutableTensor>());
        mgb_assert(opr->input().size() == new_inp.size());
        auto& imt_opr = opr->cast_final_safe<opr::ImmutableTensor>();
        if (imt_opr.output(0)->dtype() == dtype::Float32()) {
M
Megvii Engine Team 已提交
705
            auto cvt_var = opr::TypeCvt::make(imt_opr.output(0), dtype::Float16(), {});
706 707 708 709 710
            return cvt_var.node()->owner_opr();
        }
        return opr;
    };

M
Megvii Engine Team 已提交
711
    auto replace_lsp_opr = [](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
712 713 714 715
        mgb_assert(opr->same_type<opr::Linspace>());
        mgb_assert(opr->input().size() == new_inp.size());
        auto& lsp_opr = opr->cast_final_safe<opr::Linspace>();
        if (lsp_opr.output(0)->dtype() != dtype::Float16()) {
M
Megvii Engine Team 已提交
716
            auto cvt_var = opr::TypeCvt::make(lsp_opr.output(0), dtype::Float16(), {});
717 718 719 720 721
            return cvt_var.node()->owner_opr();
        }
        return opr;
    };

M
Megvii Engine Team 已提交
722 723 724
    auto replace_conv_opr = [use_f32_comp](
                                    OperatorNodeBase* opr,
                                    const VarNodeArray& new_inp) {
725 726 727 728
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
        auto new_param = conv_opr.param();
        if (use_f32_comp) {
M
Megvii Engine Team 已提交
729 730 731 732 733 734 735 736 737 738
            new_param.compute_mode = megdnn::param::Convolution::ComputeMode::FLOAT32;
        }
        mgb_assert(
                new_inp[0]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[0]->dtype().name(), new_inp[0]->name().c_str(),
                new_inp[0]->owner_opr()->name().c_str());
        mgb_assert(
                new_inp[1]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[1]->dtype().name(), new_inp[1]->name().c_str(),
                new_inp[1]->owner_opr()->name().c_str());
739 740 741 742 743 744
        auto new_conv_opr = opr::Convolution::make(
                new_inp[0], new_inp[1], new_param, conv_opr.execution_policy(),
                conv_opr.config());
        return new_conv_opr.node()->owner_opr();
    };

M
Megvii Engine Team 已提交
745 746 747
    auto replace_deconv_opr = [use_f32_comp](
                                      OperatorNodeBase* opr,
                                      const VarNodeArray& new_inp) {
748 749 750 751
        mgb_assert(opr->input().size() == new_inp.size());
        auto& deconv_opr = opr->cast_final_safe<opr::ConvolutionBackwardData>();
        auto new_param = deconv_opr.param();
        if (use_f32_comp) {
M
Megvii Engine Team 已提交
752 753 754 755 756 757 758 759 760 761
            new_param.compute_mode = megdnn::param::Convolution::ComputeMode::FLOAT32;
        }
        mgb_assert(
                new_inp[0]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[0]->dtype().name(), new_inp[0]->name().c_str(),
                new_inp[0]->owner_opr()->name().c_str());
        mgb_assert(
                new_inp[1]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[1]->dtype().name(), new_inp[1]->name().c_str(),
                new_inp[1]->owner_opr()->name().c_str());
762
        auto new_deconv_opr = opr::ConvolutionBackwardData::make(
M
Megvii Engine Team 已提交
763 764
                new_inp[0], new_inp[1], new_param, deconv_opr.execution_policy(),
                deconv_opr.config());
765 766 767
        return new_deconv_opr.node()->owner_opr();
    };

M
Megvii Engine Team 已提交
768 769 770
    auto replace_convbias_opr = [use_f32_comp](
                                        OperatorNodeBase* opr,
                                        const VarNodeArray& new_inp) {
771 772 773
        auto& convbias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
        auto new_param = convbias_opr.param();
        if (use_f32_comp) {
M
Megvii Engine Team 已提交
774 775 776 777 778 779 780 781 782 783 784
            new_param.compute_mode = megdnn::param::ConvBias::ComputeMode::FLOAT32;
        }
        mgb_assert(
                new_inp[0]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[0]->dtype().name(), new_inp[0]->name().c_str(),
                new_inp[0]->owner_opr()->name().c_str());
        mgb_assert(
                new_inp[1]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[1]->dtype().name(), new_inp[1]->name().c_str(),
                new_inp[1]->owner_opr()->name().c_str());
        if (opr->input().size() == 2) {
785
            auto new_conv_opr = opr::ConvBias::make(
M
Megvii Engine Team 已提交
786 787
                    new_inp[0], new_inp[1], new_param, convbias_opr.execution_policy(),
                    convbias_opr.config());
788
            return new_conv_opr.node()->owner_opr();
M
Megvii Engine Team 已提交
789
        } else if (opr->input().size() == 3) {
790
            auto new_conv_opr = opr::ConvBias::make(
791 792
                    new_inp[0], new_inp[1], new_inp[2], new_param,
                    convbias_opr.execution_policy(), convbias_opr.config());
793 794
            return new_conv_opr.node()->owner_opr();
        } else {
M
Megvii Engine Team 已提交
795 796 797
            mgb_assert(
                    opr->input().size() == 4, "invalid input size %zu",
                    opr->input().size());
798
            auto new_conv_opr = opr::ConvBias::make(
799 800
                    new_inp[0], new_inp[1], new_inp[2], new_inp[3], new_param,
                    convbias_opr.execution_policy(), convbias_opr.config());
801 802 803 804
            return new_conv_opr.node()->owner_opr();
        }
    };

M
Megvii Engine Team 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818
    auto replace_matmul_opr =
            [use_f32_comp](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
                mgb_assert(opr->input().size() == new_inp.size());
                auto& matmul_opr = opr->cast_final_safe<opr::MatrixMul>();
                auto new_param = matmul_opr.param();
                if (use_f32_comp) {
                    new_param.compute_mode =
                            megdnn::param::MatrixMul::ComputeMode::FLOAT32;
                }
                auto new_matmul_opr = opr::MatrixMul::make(
                        new_inp[0], new_inp[1], new_param,
                        matmul_opr.execution_policy(), matmul_opr.config());
                return new_matmul_opr.node()->owner_opr();
            };
819

820 821 822 823 824 825 826
    auto replace_batched_matmul_opr = [use_f32_comp](
                                              OperatorNodeBase* opr,
                                              const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        auto& matmul_opr = opr->cast_final_safe<opr::BatchedMatrixMul>();
        auto new_param = matmul_opr.param();
        if (use_f32_comp) {
M
Megvii Engine Team 已提交
827 828 829 830 831 832 833 834 835 836
            new_param.compute_mode = megdnn::param::MatrixMul::ComputeMode::FLOAT32;
        }
        mgb_assert(
                new_inp[0]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[0]->dtype().name(), new_inp[0]->name().c_str(),
                new_inp[0]->owner_opr()->name().c_str());
        mgb_assert(
                new_inp[1]->dtype() == dtype::Float16(), "inp %s:%s, owner_opr:%s",
                new_inp[1]->dtype().name(), new_inp[1]->name().c_str(),
                new_inp[1]->owner_opr()->name().c_str());
837
        auto new_matmul_opr = opr::BatchedMatrixMul::make(
M
Megvii Engine Team 已提交
838 839
                new_inp[0], new_inp[1], new_param, matmul_opr.execution_policy(),
                matmul_opr.config());
840 841 842
        return new_matmul_opr.node()->owner_opr();
    };

M
Megvii Engine Team 已提交
843 844 845
    auto replace_reduce_opr = [use_f32_comp](
                                      OperatorNodeBase* opr,
                                      const VarNodeArray& new_inp) {
846 847 848
        auto& reduce_opr = opr->cast_final_safe<opr::Reduce>();
        auto new_param = reduce_opr.param();
        if (use_f32_comp) {
M
Megvii Engine Team 已提交
849
            new_param.data_type = megdnn::param::Reduce::DataType::FLOAT_O16xC32;
850 851
        }
        if (opr->input().size() == 1) {
M
Megvii Engine Team 已提交
852 853
            auto new_matmul_opr =
                    opr::Reduce::make(new_inp[0], new_param, {}, reduce_opr.config());
854 855
            return new_matmul_opr.node()->owner_opr();
        } else {
M
Megvii Engine Team 已提交
856 857 858
            mgb_assert(
                    opr->input().size() == 2, "invalid input size %zu",
                    opr->input().size());
859 860 861 862 863 864
            auto new_matmul_opr = opr::Reduce::make(
                    new_inp[0], new_param, new_inp[1], reduce_opr.config());
            return new_matmul_opr.node()->owner_opr();
        }
    };

M
Megvii Engine Team 已提交
865
    auto replace_cvt_opr = [](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
866 867 868
        auto& cvt_opr = opr->cast_final_safe<opr::TypeCvt>();
        SymbolVar new_cvt;
        if (cvt_opr.output(0)->dtype() == dtype::Float32()) {
M
Megvii Engine Team 已提交
869 870
            new_cvt =
                    opr::TypeCvt::make(new_inp[0], dtype::Float16(), cvt_opr.config());
871 872 873 874 875 876 877
        } else {
            new_cvt = opr::TypeCvt::make(
                    new_inp[0], cvt_opr.output()[0]->dtype(), cvt_opr.config());
        }
        return new_cvt.node()->owner_opr();
    };

M
Megvii Engine Team 已提交
878 879 880 881
    auto replace_warp_opr = [](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
        mgb_assert(
                opr->input().size() == new_inp.size() &&
                (new_inp.size() == 3 || new_inp.size() == 4));
882 883 884 885 886 887 888 889
        auto& warp_opr = opr->cast_final<opr::WarpPerspective>();
        // mat tensor must be float32
        auto new_mat = new_inp[1];
        if (new_inp[1]->dtype() != dtype::Float32()) {
            if (try_cast_as_op<opr::TypeCvt>(new_mat->owner_opr()) &&
                new_mat->owner_opr()->input(0)->dtype() == dtype::Float32())
                new_mat = new_mat->owner_opr()->input(0);
            else
M
Megvii Engine Team 已提交
890
                new_mat = opr::TypeCvt::make(new_inp[1], dtype::Float32(), {}).node();
891 892 893
        }
        SymbolVar new_warp;
        if (new_inp.size() == 3) {
M
Megvii Engine Team 已提交
894 895 896
            new_warp = opr::WarpPerspective::make(
                    new_inp[0], new_mat, new_inp[2], warp_opr.param(),
                    warp_opr.config());
897 898 899
        } else {
            mgb_assert(new_inp.size() == 4);
            new_warp = opr::WarpPerspective::make(
M
Megvii Engine Team 已提交
900 901
                    new_inp[0], new_mat, new_inp[2], new_inp[3], warp_opr.param(),
                    warp_opr.config());
902 903 904 905
        }
        return new_warp.node()->owner_opr();
    };

M
Megvii Engine Team 已提交
906 907
    auto replace_remap_opr = [](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size() && (new_inp.size() == 2));
908 909 910 911 912 913 914 915
        auto& remap_opr = opr->cast_final<opr::Remap>();
        // map tensor must be float32
        auto new_map = new_inp[1];
        if (new_inp[1]->dtype() != dtype::Float32()) {
            if (try_cast_as_op<opr::TypeCvt>(new_map->owner_opr()) &&
                new_map->owner_opr()->input(0)->dtype() == dtype::Float32())
                new_map = new_map->owner_opr()->input(0);
            else
M
Megvii Engine Team 已提交
916
                new_map = opr::TypeCvt::make(new_inp[1], dtype::Float32(), {}).node();
917 918 919
        }
        SymbolVar new_remap;

M
Megvii Engine Team 已提交
920 921
        new_remap = opr::Remap::make(
                new_inp[0], new_map, remap_opr.param(), remap_opr.config());
922 923 924
        return new_remap.node()->owner_opr();
    };

925 926
    auto ret = std::make_unique<ConvertF32ToF16Pass>();
    // don't check dtype
M
Megvii Engine Team 已提交
927 928
    ret->set_var_replace_check_flag(
            VarReplaceCheckFlag::CHECK_ALL ^ VarReplaceCheckFlag::CHECK_DTYPE);
929
    auto&& replace_func = ret->m_opr_replace_func;
930
    replace_func[opr::Linspace::typeinfo()] = replace_lsp_opr;
931 932 933
    replace_func[opr::Host2DeviceCopy::typeinfo()] = replace_h2d_opr;
    replace_func[opr::SharedDeviceTensor::typeinfo()] = replace_sdt_opr;
    replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
934
    replace_func[opr::ConvolutionBackwardData::typeinfo()] = replace_deconv_opr;
935
    replace_func[opr::ConvBias::typeinfo()] = replace_convbias_opr;
936 937 938 939 940
    replace_func[opr::MatrixMul::typeinfo()] = replace_matmul_opr;
    replace_func[opr::Reduce::typeinfo()] = replace_reduce_opr;
    replace_func[opr::ImmutableTensor::typeinfo()] = replace_imt_opr;
    replace_func[opr::TypeCvt::typeinfo()] = replace_cvt_opr;
    replace_func[opr::WarpPerspective::typeinfo()] = replace_warp_opr;
941
    replace_func[opr::Remap::typeinfo()] = replace_remap_opr;
M
Megvii Engine Team 已提交
942
    replace_func[opr::BatchedMatrixMul::typeinfo()] = replace_batched_matmul_opr;
943 944 945 946 947 948 949
    return ret;
#endif
}

/* ================ ConvertFormatPass ================ */

void ConvertFormatPass::apply(OptState& state) const {
950
    MIDOUT_B("ConvertFormatPass::apply")
951 952 953
    state.set_var_replace_check_flag(m_var_replace_check_flag);
    auto rewriter = state.graph().make_rewriter();
    VarNodeArray new_inp_cache;
M
Megvii Engine Team 已提交
954
    auto on_opr = [this, &state, &rewriter, &new_inp_cache](OperatorNodeBase* opr) {
955 956 957 958 959 960 961 962 963 964
        auto it = m_opr_replace_func.find(opr->dyn_typeinfo());
        if (it != m_opr_replace_func.end()) {
            auto&& new_inp = new_inp_cache;
            new_inp.clear();
            new_inp.reserve(opr->input().size());
            for (auto i : opr->input()) {
                new_inp.push_back(rewriter.get_var(i));
            }
            auto new_opr = (it->second)(opr, new_inp);
            auto &&out0 = opr->output(), &&out1 = new_opr->output();
M
Megvii Engine Team 已提交
965 966 967 968 969 970
            mgb_assert(
                    out0.size() == out1.size(),
                    "bad opr replace: src=%s{%s} dst=%s{%s}, src.size=%zu "
                    "dst.size=%zu",
                    opr->cname(), opr->dyn_typeinfo()->name, new_opr->cname(),
                    new_opr->dyn_typeinfo()->name, out0.size(), out1.size());
971 972
            for (size_t i = 0; i < out0.size(); i++) {
                if (!out0[i]->contain_flag(VarNode::Flag::VOLATILE_CONTENT)) {
M
Megvii Engine Team 已提交
973
                    mgb_assert(!out1[i]->contain_flag(VarNode::Flag::VOLATILE_CONTENT));
974 975
                    auto src = out0[i];
                    auto dst = out1[i];
M
Megvii Engine Team 已提交
976 977
                    auto dst_is_image =
                            dst->format().type() == TensorFormat::Type::IMAGE2D_PACK4;
978 979 980 981 982 983 984 985 986 987 988 989
                    if (!dst_is_image &&
                        !src->owner_opr()->same_type<opr::ImmutableTensor>()) {
                        mgb_log_warn(
                                "convert NHWCD4 replaced to non-img format: "
                                "dst_opr=%s{%s} format=%s",
                                dst->owner_opr()->cname(),
                                dst->owner_opr()->dyn_typeinfo()->name,
                                dst->format().to_string().c_str());
                    }
                    if (state.graph().endpoint_contain(src) && dst_is_image) {
                        // relayout back to NCHW for output vars
                        dst = opr::RelayoutFormat::make(
M
Megvii Engine Team 已提交
990 991
                                      dst,
                                      {opr::RelayoutFormat::Param::Mode::NHWCD4I_NCHW})
992 993 994 995 996 997 998 999 1000 1001 1002
                                      .node();
                    }
                    rewriter.replace_var(src, dst, nullptr);
                }
            }
        } else {
            rewriter.auto_replace_outputs(opr);
        }
    };
    state.graph().iter(on_opr);
    rewriter.apply_inplace();
1003
    MIDOUT_E
1004 1005 1006
}

std::unique_ptr<ConvertFormatPass> ConvertFormatPass::make_nhwcd4_converter() {
1007
    MIDOUT_B("ConvertFormatPass::make")
1008 1009 1010 1011 1012 1013 1014 1015 1016
    auto filter_mode =
            [](const megdnn::param::Convolution::Sparse conv_mode,
               const VarNode* filter) -> megdnn::param::RelayoutFormat::Mode {
        bool use_dot = false;
        if (filter->dtype().enumv() == megdnn::DTypeEnum::QuantizedS8 ||
            filter->dtype().enumv() == megdnn::DTypeEnum::Quantized8Asymm)
            use_dot = true;
        if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
            if (use_dot)
M
Megvii Engine Team 已提交
1017
                return megdnn::param::RelayoutFormat::Mode::INTER_WEIGHT_DENSEI_DOT;
1018 1019
            return megdnn::param::RelayoutFormat::Mode::INTER_WEIGHT_DENSEI;
        } else {
M
Megvii Engine Team 已提交
1020 1021 1022
            mgb_throw_if(
                    conv_mode != megdnn::param::Convolution::Sparse::GROUP,
                    MegBrainError, "mode error");
1023 1024 1025 1026
            if (filter->shape()[1] == 1 && filter->shape()[2] == 1) {
                return megdnn::param::RelayoutFormat::Mode::INTER_WEIGHT_CHANI;
            } else {
                if (use_dot)
M
Megvii Engine Team 已提交
1027
                    return megdnn::param::RelayoutFormat::Mode::INTER_WEIGHT_GROUPI_DOT;
1028 1029 1030 1031 1032
                return megdnn::param::RelayoutFormat::Mode::INTER_WEIGHT_GROUPI;
            }
        }
    };

M
Megvii Engine Team 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    auto size_one_conv_to_dense_conv = [](VarNode* origin_filter_input,
                                          megdnn::param::Convolution::Sparse sparse) {
        VarNode* reshaped_filter = origin_filter_input;
        bool is_size_one_group_conv = false;
        if (sparse == megdnn::param::Convolution::Sparse::GROUP &&
            origin_filter_input->shape()[0] == 1) {
            is_size_one_group_conv = true;
            auto new_shape = origin_filter_input->shape();
            new_shape.ndim = 4;
            for (int i = 0; i < 4; i++) {
                new_shape[i] = origin_filter_input->shape()[i + 1];
            }
            SymbolVar new_var(origin_filter_input);
            reshaped_filter = new_var.reshape(new_shape).node();
        }
        return std::make_tuple(reshaped_filter, is_size_one_group_conv);
    };
1050

M
Megvii Engine Team 已提交
1051 1052 1053
    auto replace_conv_opr = [&filter_mode, &size_one_conv_to_dense_conv](
                                    OperatorNodeBase* opr,
                                    const VarNodeArray& new_inp) {
1054 1055
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
1056
        mgb_throw_if(
M
Megvii Engine Team 已提交
1057
                conv_opr.param().format != megdnn::param::Convolution::Format::NCHW,
1058 1059
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NHWCD4");
1060 1061 1062 1063
        VarNode *conv_src = nullptr, *conv_weights = nullptr;
        if (new_inp[0]->shape().ndim == 4) {
            // new input src is NCHW
            size_t group, icpg, ocpg;
M
Megvii Engine Team 已提交
1064
            if (conv_opr.param().sparse == megdnn::param::Convolution::Sparse::DENSE) {
1065 1066 1067 1068
                group = 1;
                icpg = new_inp[1]->shape()[1];
                ocpg = new_inp[1]->shape()[0];
            } else {
M
Megvii Engine Team 已提交
1069 1070 1071 1072
                mgb_throw_if(
                        conv_opr.param().sparse !=
                                megdnn::param::Convolution::Sparse::GROUP,
                        MegBrainError, "ERROR mode");
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
                group = new_inp[1]->shape()[0];
                icpg = new_inp[1]->shape()[2];
                ocpg = new_inp[1]->shape()[1];
            }
            if (ocpg % 4 == 0 && (icpg % 4 == 0 || group == 1)) {
                auto param = megdnn::param::RelayoutFormat();
                param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
                auto rf = opr::RelayoutFormat::make(new_inp[0], param);
                conv_src = rf.node();
            } else {
                // can not convert to hwcd4
M
Megvii Engine Team 已提交
1084
                return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
1085 1086 1087 1088
            }
        } else {
            size_t ocpg;
            bool is_channel_wise = false;
M
Megvii Engine Team 已提交
1089
            if (conv_opr.param().sparse == megdnn::param::Convolution::Sparse::DENSE) {
1090 1091
                ocpg = new_inp[1]->shape()[0];
            } else {
M
Megvii Engine Team 已提交
1092 1093 1094 1095
                mgb_throw_if(
                        conv_opr.param().sparse !=
                                megdnn::param::Convolution::Sparse::GROUP,
                        MegBrainError, "ERROR mode");
1096 1097 1098
                size_t icpg = new_inp[1]->shape()[2];
                ocpg = new_inp[1]->shape()[1];
                if (icpg == 1 && ocpg == 1) {
M
Megvii Engine Team 已提交
1099
                    is_channel_wise = true;
1100 1101 1102 1103 1104 1105 1106 1107
                }
            }
            if (ocpg % 4 != 0 && !is_channel_wise) {
                VarNodeArray t_inp = new_inp;
                auto param = megdnn::param::RelayoutFormat();
                param.mode = megdnn::param::RelayoutFormat::Mode::NHWCD4I_NCHW;
                auto rf = opr::RelayoutFormat::make(new_inp[0], param);
                t_inp[0] = rf.node();
M
Megvii Engine Team 已提交
1108 1109
                auto new_opr =
                        serialization::copy_opr_shallow(*opr, t_inp, opr->config());
1110 1111 1112
                return new_opr;
            }
            // new input src is NHWCD4
M
Megvii Engine Team 已提交
1113 1114
            auto&& fmt =
                    new_inp[0]->format().as_impl<megdnn::Image2DPack4TensorFormat>();
1115 1116 1117
            mgb_assert(new_inp[0]->shape().ndim == 5 && fmt.align_axis() == 2);
            conv_src = new_inp[0];
        }
1118 1119 1120
        VarNode* reshaped_filter;
        bool is_size_one_group_conv;
        std::tie(reshaped_filter, is_size_one_group_conv) =
M
Megvii Engine Team 已提交
1121
                size_one_conv_to_dense_conv(new_inp[1], conv_opr.param().sparse);
1122 1123 1124 1125
        auto new_conv_param = conv_opr.param();
        if (is_size_one_group_conv) {
            new_conv_param.sparse = megdnn::param::Convolution::Sparse::DENSE;
        }
M
Megvii Engine Team 已提交
1126
        mgb_assert(new_inp[1]->format().type() != TensorFormat::Type::IMAGE2D_PACK4);
1127
        auto param = megdnn::param::RelayoutFormat();
1128 1129
        param.mode = filter_mode(new_conv_param.sparse, reshaped_filter);
        auto relayout_weight = opr::RelayoutFormat::make(reshaped_filter, param);
1130
        conv_weights = relayout_weight.node();
1131
        new_conv_param.format = megdnn::param::Convolution::Format::NHWCD4;
M
Megvii Engine Team 已提交
1132 1133 1134
        mgb_assert(
                conv_src->shape().ndim == 5 &&
                conv_src->format().type() == TensorFormat::Type::IMAGE2D_PACK4);
1135
        auto new_conv_opr = opr::Convolution::make(
1136
                conv_src, conv_weights, new_conv_param, conv_opr.execution_policy(),
1137 1138
                conv_opr.config());
        OperatorNodeBase* ret = new_conv_opr.node()->owner_opr();
M
Megvii Engine Team 已提交
1139 1140 1141
        mgb_assert(
                new_conv_opr.shape().ndim == 5 &&
                new_conv_opr.format().type() == TensorFormat::Type::IMAGE2D_PACK4);
1142 1143 1144
        return ret;
    };

M
Megvii Engine Team 已提交
1145 1146 1147
    auto replace_conv_bias_opr = [&filter_mode, &size_one_conv_to_dense_conv](
                                         OperatorNodeBase* opr,
                                         const VarNodeArray& new_inp) {
1148 1149
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
1150
        mgb_throw_if(
M
Megvii Engine Team 已提交
1151
                conv_bias_opr.param().format != megdnn::param::ConvBias::Format::NCHW,
1152 1153
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NHWCD4");
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
        VarNode *conv_bias_src = nullptr, *conv_bias_weights = nullptr,
                *conv_bias_bias = nullptr;
        if (new_inp[0]->shape().ndim == 4) {
            // new input src is NCHW
            size_t group, icpg, ocpg;
            if (conv_bias_opr.param().sparse ==
                megdnn::param::ConvBias::Sparse::DENSE) {
                group = 1;
                icpg = new_inp[1]->shape()[1];
                ocpg = new_inp[1]->shape()[0];
            } else {
M
Megvii Engine Team 已提交
1165 1166 1167 1168
                mgb_throw_if(
                        conv_bias_opr.param().sparse !=
                                megdnn::param::ConvBias::Sparse::GROUP,
                        MegBrainError, "mode error");
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
                group = new_inp[1]->shape()[0];
                icpg = new_inp[1]->shape()[2];
                ocpg = new_inp[1]->shape()[1];
            }
            if (ocpg % 4 == 0 && (icpg % 4 == 0 || group == 1)) {
                auto param = megdnn::param::RelayoutFormat();
                param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
                auto rf = opr::RelayoutFormat::make(new_inp[0], param);
                conv_bias_src = rf.node();
            } else {
                // can not convert to hwcd4
M
Megvii Engine Team 已提交
1180
                return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
1181 1182 1183 1184 1185 1186 1187 1188
            }
        } else {
            size_t ocpg;
            bool is_channel_wise = false;
            if (conv_bias_opr.param().sparse ==
                megdnn::param::ConvBias::Sparse::DENSE) {
                ocpg = new_inp[1]->shape()[0];
            } else {
M
Megvii Engine Team 已提交
1189 1190 1191 1192
                mgb_throw_if(
                        conv_bias_opr.param().sparse !=
                                megdnn::param::ConvBias::Sparse::GROUP,
                        MegBrainError, "ERROR mode");
1193 1194 1195
                size_t icpg = new_inp[1]->shape()[2];
                ocpg = new_inp[1]->shape()[1];
                if (icpg == 1 && ocpg == 1) {
M
Megvii Engine Team 已提交
1196
                    is_channel_wise = true;
1197 1198 1199 1200 1201 1202 1203 1204
                }
            }
            if (ocpg % 4 != 0 && !is_channel_wise) {
                VarNodeArray t_inp = new_inp;
                auto param = megdnn::param::RelayoutFormat();
                param.mode = megdnn::param::RelayoutFormat::Mode::NHWCD4I_NCHW;
                auto rf = opr::RelayoutFormat::make(new_inp[0], param);
                t_inp[0] = rf.node();
M
Megvii Engine Team 已提交
1205 1206
                auto new_opr =
                        serialization::copy_opr_shallow(*opr, t_inp, opr->config());
1207 1208 1209
                return new_opr;
            }
            // new input src is NHWCD4
M
Megvii Engine Team 已提交
1210 1211
            auto&& fmt =
                    new_inp[0]->format().as_impl<megdnn::Image2DPack4TensorFormat>();
1212 1213 1214
            mgb_assert(new_inp[0]->shape().ndim == 5 && fmt.align_axis() == 2);
            conv_bias_src = new_inp[0];
        }
M
Megvii Engine Team 已提交
1215
        mgb_assert(new_inp[1]->format().type() != TensorFormat::Type::IMAGE2D_PACK4);
1216

1217 1218 1219
        VarNode* reshaped_filter;
        bool is_size_one_group_conv;
        std::tie(reshaped_filter, is_size_one_group_conv) =
M
Megvii Engine Team 已提交
1220
                size_one_conv_to_dense_conv(new_inp[1], conv_bias_opr.param().sparse);
1221 1222 1223 1224
        auto new_conv_param = conv_bias_opr.param();
        if (is_size_one_group_conv) {
            new_conv_param.sparse = megdnn::param::Convolution::Sparse::DENSE;
        }
1225
        auto param = megdnn::param::RelayoutFormat();
1226 1227
        param.mode = filter_mode(new_conv_param.sparse, reshaped_filter);
        auto relayout_weight = opr::RelayoutFormat::make(reshaped_filter, param);
1228 1229
        conv_bias_weights = relayout_weight.node();

M
Megvii Engine Team 已提交
1230
        mgb_assert(new_inp.size() < 4, "ConvertFormat pass does not support fuse Z");
1231
        bool has_bias = new_inp.size() > 2;
M
Megvii Engine Team 已提交
1232
        if (has_bias && new_inp[2]->format().type() == TensorFormat::Type::DEFAULT) {
1233 1234 1235 1236 1237 1238
            param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
            auto relayout_bias = opr::RelayoutFormat::make(new_inp[2], param);
            conv_bias_bias = relayout_bias.node();
        } else if (has_bias) {
            conv_bias_bias = new_inp[2];
        }
1239

1240
        new_conv_param.format = megdnn::param::ConvBias::Format::NHWCD4;
M
Megvii Engine Team 已提交
1241 1242 1243
        mgb_assert(
                conv_bias_src->shape().ndim == 5 &&
                conv_bias_src->format().type() == TensorFormat::Type::IMAGE2D_PACK4);
1244 1245 1246
        SymbolVar new_conv_bias_opr;
        if (has_bias) {
            new_conv_bias_opr = opr::ConvBias::make(
1247
                    conv_bias_src, conv_bias_weights, conv_bias_bias, new_conv_param,
1248 1249 1250
                    conv_bias_opr.execution_policy(), conv_bias_opr.config());
        } else {
            new_conv_bias_opr = opr::ConvBias::make(
1251
                    conv_bias_src, conv_bias_weights, new_conv_param,
1252 1253
                    conv_bias_opr.execution_policy(), conv_bias_opr.config());
        }
1254
        OperatorNodeBase* ret = new_conv_bias_opr.node()->owner_opr();
M
Megvii Engine Team 已提交
1255 1256 1257
        mgb_assert(
                new_conv_bias_opr.shape().ndim == 5 &&
                new_conv_bias_opr.format().type() == TensorFormat::Type::IMAGE2D_PACK4);
1258 1259 1260
        return ret;
    };

M
Megvii Engine Team 已提交
1261 1262 1263
    auto replace_deconv_opr = [&filter_mode](
                                      OperatorNodeBase* opr,
                                      const VarNodeArray& new_inp) {
1264 1265
        mgb_assert(opr->input().size() == new_inp.size());
        auto& deconv_opr = opr->cast_final_safe<opr::ConvolutionBackwardData>();
1266
        mgb_throw_if(
M
Megvii Engine Team 已提交
1267
                deconv_opr.param().format != megdnn::param::Convolution::Format::NCHW,
1268 1269
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NHWCD4");
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        VarNode *deconv_src = nullptr, *deconv_weights = nullptr;
        if (new_inp[1]->shape().ndim == 4) {
            // new input src is NCHW
            size_t group, icpg, ocpg;
            if (deconv_opr.param().sparse ==
                megdnn::param::Convolution::Sparse::DENSE) {
                group = 1;
                icpg = new_inp[0]->shape()[0];
                ocpg = new_inp[0]->shape()[1];
            } else {
M
Megvii Engine Team 已提交
1280 1281 1282 1283
                mgb_throw_if(
                        deconv_opr.param().sparse !=
                                megdnn::param::Convolution::Sparse::GROUP,
                        MegBrainError, "mode error");
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
                group = new_inp[0]->shape()[0];
                icpg = new_inp[0]->shape()[1];
                ocpg = new_inp[0]->shape()[2];
            }
            if (ocpg % 4 == 0 && (icpg % 4 == 0 || group == 1)) {
                auto param = megdnn::param::RelayoutFormat();
                param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
                auto rf = opr::RelayoutFormat::make(new_inp[1], param);
                deconv_src = rf.node();
            } else {
                // can not convert to hwcd4
M
Megvii Engine Team 已提交
1295
                return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
1296 1297 1298 1299 1300 1301 1302 1303
            }
        } else {
            //! XXXX, fix me, check filter size
            size_t ocpg;
            if (deconv_opr.param().sparse ==
                megdnn::param::Convolution::Sparse::DENSE) {
                ocpg = new_inp[0]->shape()[1];
            } else {
M
Megvii Engine Team 已提交
1304 1305 1306 1307
                mgb_throw_if(
                        deconv_opr.param().sparse !=
                                megdnn::param::Convolution::Sparse::GROUP,
                        MegBrainError, "mode error");
1308 1309 1310 1311 1312 1313 1314 1315 1316

                ocpg = new_inp[0]->shape()[2];
            }
            if (ocpg % 4 != 0) {
                VarNodeArray t_inp = new_inp;
                auto param = megdnn::param::RelayoutFormat();
                param.mode = megdnn::param::RelayoutFormat::Mode::NHWCD4I_NCHW;
                auto rf = opr::RelayoutFormat::make(new_inp[1], param);
                t_inp[1] = rf.node();
M
Megvii Engine Team 已提交
1317 1318
                auto new_opr =
                        serialization::copy_opr_shallow(*opr, t_inp, opr->config());
1319 1320 1321
                return new_opr;
            }
            // new input src is NHWCD4
M
Megvii Engine Team 已提交
1322 1323
            auto&& fmt =
                    new_inp[1]->format().as_impl<megdnn::Image2DPack4TensorFormat>();
1324 1325 1326
            mgb_assert(new_inp[1]->shape().ndim == 5 && fmt.align_axis() == 2);
            deconv_src = new_inp[1];
        }
M
Megvii Engine Team 已提交
1327
        mgb_assert(new_inp[0]->format().type() != TensorFormat::Type::IMAGE2D_PACK4);
1328 1329 1330 1331 1332 1333
        auto param = megdnn::param::RelayoutFormat();
        param.mode = filter_mode(deconv_opr.param().sparse, new_inp[0]);
        auto relayout_weight = opr::RelayoutFormat::make(new_inp[0], param);
        deconv_weights = relayout_weight.node();
        auto new_param = deconv_opr.param();
        new_param.format = megdnn::param::Convolution::Format::NHWCD4;
M
Megvii Engine Team 已提交
1334 1335 1336
        mgb_assert(
                deconv_src->shape().ndim == 5 &&
                deconv_src->format().type() == TensorFormat::Type::IMAGE2D_PACK4);
1337
        auto new_deconv_opr = opr::ConvolutionBackwardData::make(
M
Megvii Engine Team 已提交
1338 1339
                deconv_weights, deconv_src, new_param, deconv_opr.execution_policy(),
                deconv_opr.config());
1340
        OperatorNodeBase* ret = new_deconv_opr.node()->owner_opr();
M
Megvii Engine Team 已提交
1341 1342 1343
        mgb_assert(
                new_deconv_opr.shape().ndim == 5 &&
                new_deconv_opr.format().type() == TensorFormat::Type::IMAGE2D_PACK4);
1344 1345
        return ret;
    };
1346 1347 1348 1349 1350 1351 1352 1353
    /* This helper function guarantees the format convert pass won't change
     * output var's channel. Changing output's channel will cause channel
     * mismatch problem for replacing conv/conv_bias operator.
     */
    auto replace_helper = [](OperatorNodeBase* opr,
                             const VarNodeArray& new_inp) -> OperatorNodeBase* {
        auto&& new_shp = new_inp[0]->shape();
        size_t inp_channel = new_shp[1];
M
Megvii Engine Team 已提交
1354 1355 1356
        if (new_shp.eq_shape(opr->input(0)->shape()) && inp_channel % 4 != 0) {
            auto new_opr =
                    serialization::copy_opr_shallow(*opr, new_inp, opr->config());
1357 1358 1359 1360
            return new_opr;
        }
        return nullptr;
    };
M
Megvii Engine Team 已提交
1361 1362 1363
    auto replace_resize_opr = [replace_helper](
                                      OperatorNodeBase* opr,
                                      const VarNodeArray& new_inp) {
1364
        mgb_assert(opr->input().size() == new_inp.size());
1365 1366 1367
        if (auto opr_shallow_copy = replace_helper(opr, new_inp)) {
            return opr_shallow_copy;
        }
1368
        auto& resize_opr = opr->cast_final_safe<opr::ResizeForward>();
1369
        mgb_throw_if(
M
Megvii Engine Team 已提交
1370
                resize_opr.param().format != megdnn::param::Resize::Format::NCHW,
1371 1372
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NHWCD4");
1373 1374 1375 1376 1377 1378 1379 1380
        VarNode* inp = nullptr;
        if (new_inp[0]->shape().ndim == 4) {
            auto param = megdnn::param::RelayoutFormat();
            param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
            auto rf = opr::RelayoutFormat::make(new_inp[0], param);
            inp = rf.node();
        } else {
            // new input src is NHWCD
M
Megvii Engine Team 已提交
1381 1382
            auto&& fmt =
                    new_inp[0]->format().as_impl<megdnn::Image2DPack4TensorFormat>();
1383 1384 1385 1386 1387
            mgb_assert(new_inp[0]->shape().ndim == 5 && fmt.align_axis() == 2);
            inp = new_inp[0];
        }
        auto new_param = resize_opr.param();
        new_param.format = megdnn::param::Resize::Format::NHWCD4;
M
Megvii Engine Team 已提交
1388 1389
        auto new_resize_opr =
                opr::ResizeForward::make(inp, new_inp[1], new_param, opr->config());
1390 1391 1392
        return new_resize_opr.node()->owner_opr();
    };

1393 1394 1395
    auto replace_warp_perspective_opr = [replace_helper](
                                                OperatorNodeBase* opr,
                                                const VarNodeArray& new_inp) {
1396
        mgb_assert(opr->input().size() == new_inp.size());
1397 1398 1399
        if (auto opr_shallow_copy = replace_helper(opr, new_inp)) {
            return opr_shallow_copy;
        }
1400
        auto& warp_opr = opr->cast_final_safe<opr::WarpPerspectiveForward>();
1401
        mgb_throw_if(
M
Megvii Engine Team 已提交
1402
                warp_opr.param().format != megdnn::param::WarpPerspective::Format::NCHW,
1403 1404
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NHWCD4");
1405 1406 1407 1408 1409 1410 1411 1412 1413
        VarNode* inp = nullptr;
        if (new_inp[0]->shape().ndim == 4) {
            // new input src is NCHW
            auto param = megdnn::param::RelayoutFormat();
            param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
            auto rf = opr::RelayoutFormat::make(new_inp[0], param);
            inp = rf.node();
        } else {
            // new input src is NHWCD
M
Megvii Engine Team 已提交
1414 1415
            auto&& fmt =
                    new_inp[0]->format().as_impl<megdnn::Image2DPack4TensorFormat>();
1416 1417 1418 1419 1420 1421 1422 1423
            mgb_assert(new_inp[0]->shape().ndim == 5 && fmt.align_axis() == 2);
            inp = new_inp[0];
        }
        auto new_param = warp_opr.param();
        new_param.format = megdnn::param::WarpPerspective::Format::NHWCD4;
        SymbolVar new_warp_opr;
        if (new_inp.size() == 3) {
            new_warp_opr = opr::WarpPerspectiveForward::make(
M
Megvii Engine Team 已提交
1424
                    inp, new_inp[1], nullptr, new_inp[2], new_param, opr->config());
1425 1426 1427
        } else {
            mgb_assert(new_inp.size() == 4);
            new_warp_opr = opr::WarpPerspectiveForward::make(
M
Megvii Engine Team 已提交
1428
                    inp, new_inp[1], new_inp[2], new_inp[3], new_param, opr->config());
1429 1430 1431 1432
        }
        return new_warp_opr.node()->owner_opr();
    };

M
Megvii Engine Team 已提交
1433 1434 1435
    auto replace_warp_affine_opr = [replace_helper](
                                           OperatorNodeBase* opr,
                                           const VarNodeArray& new_inp) {
1436
        mgb_assert(opr->input().size() == new_inp.size());
1437 1438 1439
        if (auto opr_shallow_copy = replace_helper(opr, new_inp)) {
            return opr_shallow_copy;
        }
1440
        auto& warp_opr = opr->cast_final_safe<opr::WarpAffineForward>();
1441
        mgb_throw_if(
M
Megvii Engine Team 已提交
1442
                warp_opr.param().format != megdnn::param::WarpAffine::Format::NCHW,
1443 1444
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NHWCD4");
1445 1446 1447 1448 1449 1450 1451 1452 1453
        VarNode* inp = nullptr;
        if (new_inp[0]->shape().ndim == 4) {
            // new input src is NCHW
            auto param = megdnn::param::RelayoutFormat();
            param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
            auto rf = opr::RelayoutFormat::make(new_inp[0], param);
            inp = rf.node();
        } else {
            // new input src is NHWCD
M
Megvii Engine Team 已提交
1454 1455
            auto&& fmt =
                    new_inp[0]->format().as_impl<megdnn::Image2DPack4TensorFormat>();
1456 1457 1458 1459 1460 1461
            mgb_assert(new_inp[0]->shape().ndim == 5 && fmt.align_axis() == 2);
            inp = new_inp[0];
        }
        auto new_param = warp_opr.param();
        new_param.format = megdnn::param::WarpAffine::Format::NHWCD4;
        SymbolVar new_warp_opr;
M
Megvii Engine Team 已提交
1462 1463
        new_warp_opr = opr::WarpAffineForward::make(
                inp, new_inp[1], new_inp[2], new_param, opr->config());
1464 1465 1466
        return new_warp_opr.node()->owner_opr();
    };

M
Megvii Engine Team 已提交
1467 1468 1469
    auto replace_pooling_opr = [replace_helper](
                                       OperatorNodeBase* opr,
                                       const VarNodeArray& new_inp) {
1470
        mgb_assert(opr->input().size() == new_inp.size());
1471 1472 1473
        if (auto opr_shallow_copy = replace_helper(opr, new_inp)) {
            return opr_shallow_copy;
        }
1474
        auto& pooling_opr = opr->cast_final_safe<opr::PoolingForward>();
1475
        mgb_throw_if(
M
Megvii Engine Team 已提交
1476
                pooling_opr.param().format != megdnn::param::Pooling::Format::NCHW,
1477 1478
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NHWCD4");
1479 1480 1481 1482 1483 1484 1485 1486 1487
        VarNode* inp = nullptr;
        if (new_inp[0]->shape().ndim == 4) {
            // new input src is NCHW
            auto param = megdnn::param::RelayoutFormat();
            param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
            auto rf = opr::RelayoutFormat::make(new_inp[0], param);
            inp = rf.node();
        } else {
            // new input src is NHWCD
M
Megvii Engine Team 已提交
1488 1489
            auto&& fmt =
                    new_inp[0]->format().as_impl<megdnn::Image2DPack4TensorFormat>();
1490 1491 1492 1493 1494
            mgb_assert(new_inp[0]->shape().ndim == 5 && fmt.align_axis() == 2);
            inp = new_inp[0];
        }
        auto new_param = pooling_opr.param();
        new_param.format = megdnn::param::Pooling::Format::NHWCD4;
1495 1496
        auto new_pooling_opr = opr::PoolingForward::make(
                inp, new_param, pooling_opr.execution_policy(), opr->config());
1497 1498 1499
        return new_pooling_opr.node()->owner_opr();
    };

1500 1501
    auto var_to_chw = [](VarNode* inp, VarNode* new_inp) {
        if (!inp->shape().eq_shape(new_inp->shape())) {
M
Megvii Engine Team 已提交
1502 1503 1504 1505 1506 1507
            mgb_assert(
                    inp->shape().ndim == 4 &&
                    inp->format().type() != TensorFormat::Type::IMAGE2D_PACK4);
            mgb_assert(
                    new_inp->shape().ndim == 5 &&
                    new_inp->format().type() == TensorFormat::Type::IMAGE2D_PACK4);
1508 1509 1510 1511 1512 1513 1514 1515
            auto param = megdnn::param::RelayoutFormat();
            param.mode = megdnn::param::RelayoutFormat::Mode::NHWCD4I_NCHW;
            auto rf = opr::RelayoutFormat::make(new_inp, param);
            return rf.node();
        }
        return new_inp;
    };

M
Megvii Engine Team 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
    auto relayout_inp_to_chw =
            [var_to_chw](OperatorNodeBase* opr, const VarNodeArray& new_inp) {
                mgb_assert(opr->input().size() == new_inp.size());
                VarNodeArray t_inp = new_inp;
                for (size_t i = 0; i < opr->input().size(); i++) {
                    t_inp[i] = var_to_chw(opr->input(i), new_inp[i]);
                }
                auto new_opr =
                        serialization::copy_opr_shallow(*opr, t_inp, opr->config());
                return new_opr;
            };
1527

1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    auto replace_concat_opr = [&relayout_inp_to_chw](
                                      OperatorNodeBase* opr,
                                      const VarNodeArray& new_inp) {
        //! map nchw axis to CD4 axis(n h c/4 w 4)
        auto axis_nchw_to_cd4_map = [=](int32_t org_axis) -> int32_t {
            mgb_assert(org_axis >= 0 && org_axis <= 3);
            int32_t ret = 0;
            if (0 == org_axis) {
                ret = 0;
            } else if (1 == org_axis) {
                ret = 2;
            } else if (2 == org_axis) {
                ret = 1;
            } else if (3 == org_axis) {
M
Megvii Engine Team 已提交
1542 1543 1544
                mgb_throw(
                        InternalError,
                        "Do not support axis=3 for concat bypass for CD4!");
1545
            } else {
M
Megvii Engine Team 已提交
1546 1547 1548 1549
                mgb_throw(
                        InternalError,
                        "Do not support axis for concat pass, may input is "
                        "not NCHW format!");
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
            }

            return ret;
        };

        mgb_assert(opr->input().size() == new_inp.size());
        auto nchw_axis = opr->cast_final_safe<opr::Concat>().param().axis;
        if (nchw_axis < 0 || nchw_axis > 3) {
            mgb_log_warn("concat pass fallback to relayout chw\n");
            return relayout_inp_to_chw(opr, new_inp);
        }
        bool can_exec_cd4 = true;
        //! only consider OpenCL CD4, if other backend has relayout performance
        //! issue, may add other bypass format
        for (size_t i = 0; i < opr->input().size(); i++) {
            if (opr->input(i)->format().type() != TensorFormat::Type::DEFAULT ||
M
Megvii Engine Team 已提交
1566 1567
                opr->input(i)->shape()[1] % 4 != 0 || new_inp[i]->shape().ndim != 5 ||
                new_inp[i]->format().type() != TensorFormat::Type::IMAGE2D_PACK4 ||
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
                nchw_axis == 3) {
                can_exec_cd4 = false;
                break;
            }
        }

        if (!can_exec_cd4) {
            mgb_log_warn("concat pass fallback to relayout chw");
            return relayout_inp_to_chw(opr, new_inp);
        }

        megdnn::param::Axis param;
        //! now only support nchw bypass to CD4
        mgb_log_warn("concat pass bypass to CD4");
        param.axis = axis_nchw_to_cd4_map(nchw_axis);
M
Megvii Engine Team 已提交
1583
        return opr::Concat::make(VarNodeArrayView(new_inp), param, opr->config())
1584 1585 1586 1587
                .node()
                ->owner_opr();
    };

1588 1589 1590
    auto replace_elemwise_opr = [&relayout_inp_to_chw](
                                        OperatorNodeBase* opr,
                                        const VarNodeArray& new_inp) {
1591 1592
        mgb_assert(opr->input().size() == new_inp.size());
        bool has_inp_changed = false;
1593
        bool can_exec_cd4 = true;
1594 1595 1596
        for (size_t i = 0; i < opr->input().size(); i++) {
            if (!new_inp[i]->format().is_default()) {
                has_inp_changed = true;
1597 1598 1599 1600
            } else if (new_inp[i]->shape().ndim == 4) {
                if (new_inp[i]->shape()[1] % 4 != 0) {
                    can_exec_cd4 = false;
                }
1601
                //! cd4 elemwise with scaler is unsupported
1602 1603
            } else if (!new_inp[i]->shape().is_scalar()) {
                can_exec_cd4 = false;
1604 1605
            }
        }
1606 1607 1608
        if (!can_exec_cd4) {
            return relayout_inp_to_chw(opr, new_inp);
        }
1609 1610 1611 1612 1613 1614
        if (has_inp_changed) {
            // assumption: all inputs are changed from nchw to nhwcd4
            auto t_inp = new_inp;
            for (size_t i = 0; i < opr->input().size(); i++) {
                if (new_inp[i]->shape().ndim == 4) {
                    auto param = megdnn::param::RelayoutFormat();
M
Megvii Engine Team 已提交
1615
                    param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I;
1616 1617 1618
                    auto rf = opr::RelayoutFormat::make(new_inp[i], param);
                    t_inp[i] = rf.node();
                } else {
M
Megvii Engine Team 已提交
1619 1620 1621 1622 1623
                    mgb_assert(
                            (new_inp[i]->shape().ndim == 5 &&
                             new_inp[i]->format().type() ==
                                     TensorFormat::Type::IMAGE2D_PACK4) ||
                            new_inp[i]->shape().is_scalar());
1624 1625 1626 1627
                }
            }
            return serialization::copy_opr_shallow(*opr, t_inp, opr->config());
        } else {
M
Megvii Engine Team 已提交
1628
            return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
1629 1630 1631
        }
    };

1632 1633 1634 1635
    /* This helper function converts the first input to the NCHW format to
     * handle operations that do not support NHWCD4 format
     */
    auto relayout_first_inp_to_chw =
M
Megvii Engine Team 已提交
1636 1637 1638
            [var_to_chw](
                    OperatorNodeBase* opr,
                    const VarNodeArray& new_inp) -> OperatorNodeBase* {
1639 1640 1641 1642 1643 1644
        mgb_assert(opr->input().size() == new_inp.size());
        VarNodeArray t_inp = new_inp;
        t_inp[0] = var_to_chw(opr->input(0), new_inp[0]);
        return serialization::copy_opr_shallow(*opr, t_inp, opr->config());
    };

1645 1646 1647 1648 1649 1650 1651 1652
    auto ret = std::make_unique<ConvertFormatPass>();
    ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
    auto&& replace_func = ret->m_opr_replace_func;
    replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
    replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
    replace_func[opr::ConvolutionBackwardData::typeinfo()] = replace_deconv_opr;
    replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
    replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_opr;
1653
    replace_func[opr::Concat::typeinfo()] = replace_concat_opr;
1654 1655
    replace_func[opr::Reshape::typeinfo()] = relayout_inp_to_chw;
    replace_func[opr::GetVarShape::typeinfo()] = relayout_inp_to_chw;
1656
    replace_func[opr::Images2NeibsBackward::typeinfo()] = relayout_inp_to_chw;
1657 1658 1659 1660 1661 1662
    replace_func[opr::Dimshuffle::typeinfo()] = relayout_inp_to_chw;
    replace_func[opr::Reduce::typeinfo()] = relayout_inp_to_chw;
    replace_func[opr::AssertEqual::typeinfo()] = relayout_inp_to_chw;
    replace_func[opr::Subtensor::typeinfo()] = relayout_inp_to_chw;
    replace_func[opr::Broadcast::typeinfo()] = relayout_inp_to_chw;
    replace_func[opr::IncrSubtensor::typeinfo()] = relayout_inp_to_chw;
1663
    replace_func[opr::AxisAddRemove::typeinfo()] = relayout_inp_to_chw;
1664
    replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_opr;
1665 1666 1667 1668
    replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
    replace_func[opr::WarpPerspectiveForward::typeinfo()] =
            replace_warp_perspective_opr;
    replace_func[opr::WarpAffineForward::typeinfo()] = replace_warp_affine_opr;
1669
    replace_func[opr::LocalForward::typeinfo()] = relayout_first_inp_to_chw;
M
Megvii Engine Team 已提交
1670
    replace_func[opr::GroupLocalForward::typeinfo()] = relayout_first_inp_to_chw;
1671
    return ret;
1672
    MIDOUT_E
1673 1674 1675 1676 1677 1678 1679 1680
}

/* ================ ConvertBatchNormPass ================ */
const char* ConvertBatchNormToElemwisePass::name() const {
    return "convert_batch_norm";
}

void ConvertBatchNormToElemwisePass::apply(OptState& state) const {
1681
    MIDOUT_B("ConvertBatchNormToElemwisePass::apply")
1682 1683 1684 1685
    auto rewriter = state.graph().make_rewriter();
    auto on_opr = [&](OperatorNodeBase* opr) {
        if (auto bn = try_cast_as_op<opr::BatchNorm>(opr)) {
            if (bn->input().size() == 5) {
M
Megvii Engine Team 已提交
1686 1687 1688
                mgb_assert(
                        bn->param().fwd_mode ==
                        opr::BatchNorm::Param::FwdMode::INFERENCE);
1689 1690 1691 1692 1693
                SymbolVar x = {rewriter.get_var(bn->input(0))};
                SymbolVar scale = {rewriter.get_var(bn->input(1))};
                SymbolVar bias = {rewriter.get_var(bn->input(2))};
                SymbolVar mean = {rewriter.get_var(bn->input(3))};
                SymbolVar variance = {rewriter.get_var(bn->input(4))};
M
Megvii Engine Team 已提交
1694 1695 1696
                SymbolVar invsqrt_variance = opr::PowC::make(
                        variance + variance.make_scalar_dt(float(bn->param().epsilon)),
                        {-0.5});
1697
                auto res = scale * (x - mean) * invsqrt_variance + bias;
1698
                if (x.dtype() != res.dtype()) {
M
Megvii Engine Team 已提交
1699 1700 1701 1702 1703 1704
                    mgb_throw(
                            MegBrainError,
                            "BN's input dtype %s is not compatible with "
                            "param dtype %s when fusing BN. You may need to "
                            "dump FP32 model.",
                            x.dtype().name(), res.dtype().name());
1705
                }
1706
                rewriter.replace_var(
1707
                        opr->output(5), res.node(),
M
Megvii Engine Team 已提交
1708 1709 1710
                        mgb_cstr_log("replace batch_norm(x, scale, bias, mean, "
                                     "varience) "
                                     "-> (sclae * (x - mean) / sqrt(variance)) + b)"));
1711 1712 1713 1714 1715 1716 1717 1718
                return;
            }
        }
        rewriter.auto_replace_outputs(opr);
    };
    state.graph().iter(on_opr);

    rewriter.apply_inplace();
1719
    MIDOUT_E
1720 1721 1722 1723 1724 1725 1726 1727
}

/* ================ FuseConvBiasNonlinPass ================ */
const char* FuseConvBiasNonlinPass::name() const {
    return "combine_conv_bias_and_relu";
}

void FuseConvBiasNonlinPass::apply(OptState& state) const {
1728
    MIDOUT_B("FuseConvBiasNonlinPass::apply")
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
    std::unordered_map<VarNode*, std::vector<OperatorNodeBase*>> m_deps;
    state.graph().iter([&m_deps](OperatorNodeBase* opr) {
        for (auto& inp : opr->input()) {
            m_deps[inp].push_back(opr);
        }
    });

    auto rewriter = state.graph().make_rewriter();
    using Mode = opr::Elemwise::Param::Mode;
    using NonlineMode = opr::ConvBiasForward::Param::NonlineMode;

    auto get_nonlinearity_mode = [&](opr::Elemwise* elem) -> NonlineMode {
        if (elem->param().mode == Mode::FUSE_ADD_RELU ||
            elem->param().mode == Mode::RELU) {
            return NonlineMode::RELU;
M
Megvii Engine Team 已提交
1744 1745 1746
        } else if (
                elem->param().mode == Mode::FUSE_ADD_SIGMOID ||
                elem->param().mode == Mode::SIGMOID) {
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
            return NonlineMode::SIGMOID;
        } else {
            return NonlineMode::IDENTITY;
        }
    };

    auto try_fuse_bias_nonlinearity = [&](opr::Elemwise* elem) -> bool {
        bool can_be_fused = true;
        can_be_fused &= (elem->input().size() == 2);
        can_be_fused &= (elem->param().mode == Mode::FUSE_ADD_RELU) ||
                        (elem->param().mode == Mode::FUSE_ADD_TANH) ||
                        (elem->param().mode == Mode::FUSE_ADD_SIGMOID);

        return can_be_fused;
    };

    auto try_fuse_bias = [&](opr::Elemwise* elem) -> bool {
        bool can_be_fused = true;
        can_be_fused &= (elem->input().size() == 2);
        can_be_fused &= (elem->param().mode == Mode::ADD);
        return can_be_fused;
    };

    auto try_fuse_nonlinearity = [&](opr::Elemwise* elem) -> bool {
        bool can_be_fused = true;
        can_be_fused &= (elem->input().size() == 1);
        can_be_fused &= (elem->param().mode == Mode::RELU) ||
                        (elem->param().mode == Mode::TANH) ||
                        (elem->param().mode == Mode::SIGMOID);

        return can_be_fused;
    };

M
Megvii Engine Team 已提交
1780 1781
    auto convert_to_conv_bias_param =
            [&](const opr::Convolution::Param& param) -> opr::ConvBiasForward::Param {
1782
        using Param = opr::ConvBiasForward::Param;
M
Megvii Engine Team 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
        return opr::ConvBiasForward::Param{
                Param::NonlineMode::IDENTITY,
                param.mode,
                param.sparse,
                param.format,
                param.pad_h,
                param.pad_w,
                param.stride_h,
                param.stride_w,
                param.dilate_h,
                param.dilate_w,
                param.compute_mode};
1795 1796 1797 1798 1799 1800 1801 1802 1803
    };

    auto check_bias_shape = [&](opr::Convolution* conv, VarNode* bias) -> bool {
        bool valid_bias_shape = true;
        using Format = opr::Convolution::Param::Format;
        using Sparse = opr::Convolution::Param::Sparse;
        auto dst_shape = conv->output(0)->shape();
        auto filter_shape = conv->input(1)->shape();
        auto bias_shape = bias->shape();
1804 1805 1806 1807 1808 1809

        //! pay attention: make sure bias node is not const provider when
        //! batch > 1 cause shape assert problem in convbias
        //! if you resize the input shape, can not update the bias shape too.
        //! so do not fuse conv bias in this situation
        if (dst_shape.eq_shape(bias_shape) && !cg::is_const_var_shape(bias)) {
1810 1811
            return valid_bias_shape;
        }
1812

1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
        size_t OC = filter_shape[0];
        if (conv->param().sparse == Sparse::GROUP) {
            OC *= filter_shape[1];
        }
        if (conv->param().format == Format::NCHW) {
            valid_bias_shape &=
                    ((bias_shape.ndim == 4) && (bias_shape[0] == 1) &&
                     (bias_shape[1] == OC) && (bias_shape[2] == 1) &&
                     (bias_shape[3] == 1));
        } else if (conv->param().format == Format::NCHW4) {
            valid_bias_shape &=
                    ((bias_shape.ndim == 5) && (bias_shape[0] == 1) &&
                     (bias_shape[1] == OC / 4) && (bias_shape[2] == 1) &&
                     (bias_shape[3] == 1) && bias_shape[4] == 4);
        } else if (conv->param().format == Format::NHWC) {
M
Megvii Engine Team 已提交
1828 1829 1830 1831
            valid_bias_shape &=
                    ((bias_shape.ndim == 4) && (bias_shape[0] == 1) &&
                     (bias_shape[1] == 1) && (bias_shape[2] == 1) &&
                     (bias_shape[3] == OC));
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
        } else {
            valid_bias_shape &=
                    ((bias_shape.ndim == 5) && (bias_shape[0] == 1) &&
                     (bias_shape[1] == 1) && (bias_shape[2] == OC) &&
                     (bias_shape[3] == 1) && (bias_shape[4] == 4));
            mgb_assert(conv->param().format == Format::NHWCD4);
        }
        return valid_bias_shape;
    };

    auto try_fuse_typecvt = [&](opr::TypeCvt* typecvt) -> OperatorNodeBase* {
        mgb_assert(typecvt->input().size() == 1);
        auto conv_bias = try_cast_as_op<opr::ConvBias>(
                rewriter.get_var(typecvt->input(0))->owner_opr());
        if (!conv_bias || m_deps.count(typecvt->input(0)) != 1 ||
            typecvt->output(0)->dtype().enumv() !=
1848 1849 1850
                    DTypeTrait<dtype::QuantizedS8>::enumv ||
            typecvt->input(0)->dtype().enumv() !=
                    DTypeTrait<dtype::QuantizedS32>::enumv)
1851 1852 1853 1854 1855 1856
            return nullptr;

        auto config = conv_bias->config();
        config.output_dtype(typecvt->output(0)->dtype());
        if (conv_bias->input().size() == 3) {
            // conv + bias
M
Megvii Engine Team 已提交
1857 1858 1859 1860
            return opr::ConvBias::make(
                           conv_bias->input(0), conv_bias->input(1),
                           conv_bias->input(2), conv_bias->param(),
                           conv_bias->execution_policy(), config)
1861 1862 1863 1864
                    .node()
                    ->owner_opr();
        } else {
            // conv without bias
M
Megvii Engine Team 已提交
1865 1866 1867
            return opr::ConvBias::make(
                           conv_bias->input(0), conv_bias->input(1), conv_bias->param(),
                           conv_bias->execution_policy(), config)
1868 1869 1870 1871 1872 1873
                    .node()
                    ->owner_opr();
        }
    };
    auto on_opr = [&](OperatorNodeBase* opr) {
        auto check_conv = [](opr::Convolution* conv) -> bool {
M
Megvii Engine Team 已提交
1874 1875 1876 1877 1878
            return conv->param().format == megdnn::param::Convolution::Format::NHWCD4 ||
                   conv->param().format == megdnn::param::Convolution::Format::NHWC ||
                   conv->param().format == megdnn::param::Convolution::Format::NCHW ||
                   conv->param().format == megdnn::param::Convolution::Format::NCHW4
                    ;
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
        };
        if (auto elem = try_cast_as_op<opr::Elemwise>(opr)) {
            if (try_fuse_bias_nonlinearity(elem) || try_fuse_bias(elem)) {
                auto inp1 = rewriter.get_var(elem->input(0));
                auto inp2 = rewriter.get_var(elem->input(1));
                opr::Convolution* conv = nullptr;
                size_t bias_idx = 0;
                if (inp1->owner_opr()->same_type<opr::Convolution>() &&
                    m_deps[elem->input(0)].size() == 1) {
                    conv = try_cast_as_op<opr::Convolution>(inp1->owner_opr());
                    bias_idx = 1;
M
Megvii Engine Team 已提交
1890 1891 1892
                } else if (
                        inp2->owner_opr()->same_type<opr::Convolution>() &&
                        m_deps[elem->input(1)].size() == 1) {
1893 1894 1895 1896
                    conv = try_cast_as_op<opr::Convolution>(inp2->owner_opr());
                    bias_idx = 0;
                }
                auto bias_inp = rewriter.get_var(elem->input(bias_idx));
M
Megvii Engine Team 已提交
1897
                if (conv && check_conv(conv) && check_bias_shape(conv, bias_inp)) {
1898 1899 1900 1901 1902
                    opr::ConvBiasForward::Param param =
                            convert_to_conv_bias_param(conv->param());
                    param.nonlineMode = get_nonlinearity_mode(elem);
                    auto new_var =
                            opr::ConvBiasForward::make(
M
Megvii Engine Team 已提交
1903 1904
                                    conv->input(0), conv->input(1), bias_inp, param,
                                    conv->execution_policy(), conv->config())
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
                                    .node();
                    rewriter.replace_var(
                            opr->output(0), new_var,
                            mgb_cstr_log("replace nonlinearity(conv(x, w) + b) "
                                         "-> conv_bias(x, w, b)"));
                    return;
                }
            } else if (try_fuse_nonlinearity(elem)) {
                auto inp = rewriter.get_var(elem->input(0));
                {
M
Megvii Engine Team 已提交
1915
                    auto conv = try_cast_as_op<opr::Convolution>(inp->owner_opr());
1916 1917 1918 1919 1920 1921
                    if (conv && check_conv(conv) &&
                        m_deps[elem->input(0)].size() == 1) {
                        opr::ConvBiasForward::Param param =
                                convert_to_conv_bias_param(conv->param());
                        param.nonlineMode = get_nonlinearity_mode(elem);
                        auto new_var = opr::ConvBiasForward::make(
M
Megvii Engine Team 已提交
1922 1923
                                               conv->input(0), conv->input(1), param,
                                               conv->execution_policy(), conv->config())
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
                                               .node();
                        rewriter.replace_var(
                                opr->output(0), new_var,
                                mgb_cstr_log("replace nonlinearity(conv(x, w)) "
                                             "-> conv_bias(x, w)"));
                        return;
                    }
                }
                {
                    auto conv = try_cast_as_op<opr::ConvBias>(inp->owner_opr());
                    auto check_conv_bias = [&](opr::ConvBias* opr) {
                        return opr->param().format ==
                                       opr::ConvBias::Param::Format::NHWC ||
                               opr->param().format ==
                                       opr::ConvBias::Param::Format::NCHW ||
                               opr->param().format ==
                                       opr::ConvBias::Param::Format::NCHW4
M
Megvii Engine Team 已提交
1941
                                ;
1942 1943 1944 1945 1946
                    };
                    if (conv && check_conv_bias(conv) &&
                        m_deps[elem->input(0)].size() == 1) {
                        auto param = conv->param();
                        param.nonlineMode = get_nonlinearity_mode(elem);
M
Megvii Engine Team 已提交
1947 1948 1949 1950 1951
                        auto new_var =
                                opr::ConvBiasForward::make(
                                        conv->input(0), conv->input(1), conv->input(2),
                                        param, conv->execution_policy(), conv->config())
                                        .node();
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
                        rewriter.replace_var(
                                opr->output(0), new_var,
                                mgb_cstr_log("replace nonlinearity(conv(x, w)) "
                                             "-> conv_bias(x, w)"));
                        return;
                    }
                }
            }
        } else if (auto typecvt = try_cast_as_op<opr::TypeCvt>(opr)) {
            auto new_opr = try_fuse_typecvt(typecvt);
            if (new_opr) {
                rewriter.replace_var(
                        opr->output(0), new_opr->output(0),
                        mgb_cstr_log("replace typecvt(conv_bias(x, w, b)) -> "
                                     "conv_bias(x, w, b)"));
                return;
            }
        }
        rewriter.auto_replace_outputs(opr);
    };
    state.graph().iter(on_opr);

    rewriter.apply_inplace();
1975
    MIDOUT_E
1976 1977 1978 1979 1980 1981 1982 1983
}

/* ================ FuseConvBiasZPass ================ */
const char* FuseConvBiasZPass::name() const {
    return "combine_conv_bias_and_z";
}

void FuseConvBiasZPass::apply(OptState& state) const {
1984
    MIDOUT_B("FuseConvBiasZPass::apply")
1985 1986 1987 1988 1989 1990 1991 1992
    UniqReaderCheck uniq_reader_check{state.graph()};

    auto rewriter = state.graph().make_rewriter();
    using Mode = opr::Elemwise::Param::Mode;
    using MultiMode = opr::ElemwiseMultiType::Param::Mode;
    using NonlineMode = opr::ConvBiasForward::Param::NonlineMode;

    auto check_conv_bias = [](opr::ConvBias* conv_bias) -> bool {
M
Megvii Engine Team 已提交
1993 1994 1995 1996
        return conv_bias->param().format == megdnn::param::ConvBias::Format::NHWC ||
               conv_bias->param().format == megdnn::param::ConvBias::Format::NCHW ||
               conv_bias->param().format == megdnn::param::ConvBias::Format::NCHW4
                ;
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
    };
    auto check_fuse_shape = [&](opr::ConvBias* conv_bias, VarNode* z) -> bool {
        bool valid_fuse_shape = true;
        auto z_shape = z->shape();
        auto bias_shape = conv_bias->input(2)->shape();
        auto conv_bias_shape = conv_bias->output(0)->shape();

        valid_fuse_shape &= (!conv_bias_shape.eq_shape(bias_shape));
        valid_fuse_shape &= conv_bias_shape.eq_shape(z_shape);

        return valid_fuse_shape;
    };
    auto check_fuse_dtype = [&](opr::ConvBias* conv_bias, VarNode* z) -> bool {
        return conv_bias->output(0)->dtype().enumv() == z->dtype().enumv();
    };
2012 2013 2014 2015 2016
#if MGB_CUDA && (CUDNN_MAJOR == 8)
    auto check_fuse_param = [&](opr::ConvBias* conv_bias, VarNode* z) -> bool {
        return conv_bias->input(0) != z;
    };
#endif
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
    auto get_convbias_nonline_mode = [&](OperatorNodeBase* opr) -> NonlineMode {
        if (opr->same_type<opr::Elemwise>()) {
            auto elem = try_cast_as_op<opr::Elemwise>(opr);
            if (elem->param().mode == Mode::FUSE_ADD_RELU)
                return NonlineMode::RELU;
        }

        if (opr->same_type<opr::ElemwiseMultiType>()) {
            auto elem = try_cast_as_op<opr::ElemwiseMultiType>(opr);
            if (elem->param().mode == MultiMode::QFUSE_ADD_RELU)
                return NonlineMode::RELU;
2028 2029
            else if (elem->param().mode == MultiMode::QFUSE_ADD_H_SWISH)
                return NonlineMode::H_SWISH;
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
        }
        return NonlineMode::IDENTITY;
    };
    auto try_replace_var_node = [&](OperatorNodeBase* opr) {
        opr::ConvBias* conv_bias = nullptr;
        size_t z_idx = 0;
        size_t nr_inps = opr->input().size();
        for (size_t i = 0; i < nr_inps; i++) {
            auto inp = rewriter.get_var(opr->input(i));
            if (inp->owner_opr()->same_type<opr::ConvBias>()) {
                auto cb = try_cast_as_op<opr::ConvBias>(inp->owner_opr());
                if (cb->input().size() == 3 &&
                    cb->param().nonlineMode ==
                            opr::ConvBias::Param::NonlineMode::IDENTITY &&
                    uniq_reader_check(opr->input(i))) {
                    conv_bias = cb;
                    z_idx = nr_inps - i - 1;
                    break;
                }
            }
        }
        auto z_inp = rewriter.get_var(opr->input(z_idx));

        if (conv_bias && check_conv_bias(conv_bias) &&
            check_fuse_shape(conv_bias, z_inp) &&
2055 2056 2057
#if MGB_CUDA && (CUDNN_MAJOR == 8)
            check_fuse_param(conv_bias, z_inp) &&
#endif
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
            check_fuse_dtype(conv_bias, z_inp)) {
            auto param = conv_bias->param();
            param.nonlineMode = get_convbias_nonline_mode(opr);
            auto config = conv_bias->config();

            auto new_var = opr::ConvBiasForward::make(
                                   conv_bias->input(0), conv_bias->input(1),
                                   conv_bias->input(2), z_inp, param,
                                   conv_bias->execution_policy(),
                                   config.output_dtype(opr->output(0)->dtype()))
                                   .node();
            rewriter.replace_var(
                    opr->output(0), new_var,
                    mgb_cstr_log("replace "
                                 "nonlinearity(conv_bias(x,w,b) + z) "
                                 "-> conv_bias(x, w, b, z)"));
M
Megvii Engine Team 已提交
2074
            uniq_reader_check.update_on_opr_auto_replace(opr, new_var->owner_opr());
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
            return true;
        }
        return false;
    };
    auto try_fuse_elemwise = [&](OperatorNodeBase* opr) {
        if (!opr->same_type<opr::Elemwise>())
            return false;
        auto elem = try_cast_as_op<opr::Elemwise>(opr);
        if (elem->input().size() != 2)
            return false;
        if (elem->param().mode != Mode::ADD &&
            elem->param().mode != Mode::FUSE_ADD_RELU)
            return false;
        return try_replace_var_node(opr);
    };

    auto try_fuse_elemwise_multi_type = [&](OperatorNodeBase* opr) {
        if (!opr->same_type<opr::ElemwiseMultiType>())
            return false;
        auto elem = try_cast_as_op<opr::ElemwiseMultiType>(opr);
        if (elem->input().size() != 2)
            return false;
        if (elem->param().mode != MultiMode::QADD &&
2098 2099
            elem->param().mode != MultiMode::QFUSE_ADD_RELU &&
            elem->param().mode != MultiMode::QFUSE_ADD_H_SWISH)
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
            return false;
        return try_replace_var_node(opr);
    };

    auto on_opr = [&](OperatorNodeBase* opr) {
        if (try_fuse_elemwise(opr))
            return;
        if (try_fuse_elemwise_multi_type(opr))
            return;
        auto new_opr = rewriter.auto_replace_outputs(opr);
        uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
    };
    state.graph().iter(on_opr);

    rewriter.apply_inplace();
2115
    MIDOUT_E
2116 2117 2118 2119 2120 2121 2122 2123
}

/* ================ FuseDeconvCvtPass ================ */
const char* FuseDeconvCvtPass::name() const {
    return "combine_deconv_and_typecvt";
}

void FuseDeconvCvtPass::apply(OptState& state) const {
2124
    MIDOUT_B("FuseDeconvCvtPass::apply")
2125 2126 2127 2128 2129 2130 2131 2132 2133
    std::unordered_map<VarNode*, std::vector<OperatorNodeBase*>> m_deps;
    state.graph().iter([&m_deps](OperatorNodeBase* opr) {
        for (auto& inp : opr->input()) {
            m_deps[inp].push_back(opr);
        }
    });

    UniqReaderCheck uniq_reader_check{state.graph()};
    auto rewriter = state.graph().make_rewriter();
M
Megvii Engine Team 已提交
2134
    auto try_fuse_deconv_typecvt = [&](opr::TypeCvt* typecvt) -> OperatorNodeBase* {
2135 2136 2137 2138
        mgb_assert(typecvt->input().size() == 1);
        auto deconv = try_cast_as_op<opr::ConvolutionBackwardData>(
                rewriter.get_var(typecvt->input(0))->owner_opr());
        if (!deconv
M
Megvii Engine Team 已提交
2139
            || m_deps.count(typecvt->input(0)) != 1 ||
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
            typecvt->output(0)->dtype().enumv() !=
                    DTypeTrait<dtype::QuantizedS8>::enumv) {
            return nullptr;
        }
        if (!uniq_reader_check(deconv->output(0)))
            return nullptr;

        auto config = deconv->config();
        config.output_dtype(typecvt->output(0)->dtype());
        return opr::ConvolutionBackwardData::make(
                       deconv->input(0), deconv->input(1), deconv->param(),
                       deconv->execution_policy(), config)
                .node()
                ->owner_opr();
    };

    auto on_opr = [&](OperatorNodeBase* opr) {
        if (auto typecvt = try_cast_as_op<opr::TypeCvt>(opr)) {
            if (auto deconv_new = try_fuse_deconv_typecvt(typecvt)) {
                rewriter.replace_var(
                        opr->output(0), deconv_new->output(0),
                        mgb_cstr_log("replace typecvt(deconv(x, w)) -> "
                                     "deconv(x, w)"));
                uniq_reader_check.update_on_opr_auto_replace(opr, deconv_new);
                return;
            }
        }
        auto new_opr = rewriter.auto_replace_outputs(opr);
M
Megvii Engine Team 已提交
2168
        uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
2169 2170 2171 2172
    };
    state.graph().iter(on_opr);

    rewriter.apply_inplace();
2173
    MIDOUT_E
2174 2175 2176 2177 2178 2179 2180 2181
}

/* ================ ParamMergePass ================ */
const char* ParamMergePass::name() const {
    return mgb_cstr_log("param_merge");
}

void ParamMergePass::apply(OptState& opt_state) const {
2182
    MIDOUT_B("ParamMergePass::apply")
M
Megvii Engine Team 已提交
2183 2184 2185 2186
    param_merge<opr::SharedDeviceTensor, opr::MultipleDeviceTensorHolder>(opt_state);
    param_merge<
            opr::SharedDeviceTensorWithFormat,
            opr::MultipleDeviceTensorWithFormatHolder>(opt_state);
2187
    MIDOUT_E
2188 2189 2190
}

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