tensor_reformat.cpp 241.2 KB
Newer Older
1 2 3 4
/**
 * \file src/gopt/impl/tensor_reformat.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
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
9 10
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
11 12 13
 */

#include "megbrain/gopt/basic_arith.h"
M
Megvii Engine Team 已提交
14 15
#include "megbrain/gopt/gtrans.h"
#include "megbrain/gopt/inference.h"
16 17 18
#include "megbrain/graph/event.h"
#include "megbrain/opr/basic_arith.h"
#include "megbrain/opr/blas.h"
M
Megvii Engine Team 已提交
19 20 21
#include "megbrain/opr/dnn/batch_norm.h"
#include "megbrain/opr/dnn/convolution.h"
#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 28 29
#include "megbrain/opr/tensor_manip.h"
#include "megbrain/opr/utility.h"
#include "megbrain/serialization/opr_shallow_copy.h"
#include "megbrain/utils/shared_set.h"
30

31
#include "megdnn/opr_param_defs.h"
32 33
#include "megdnn/tensor_format.h"

34 35
#include "megbrain/opr/internal/megdnn_opr_wrapper.h"

36 37 38 39 40
#if MGB_ENABLE_TENSOR_RT
#include "megbrain/tensorrt/tensorrt_opr.h"
#endif

#include "megbrain/gopt/misc.h"
41 42 43 44 45 46 47 48 49 50
#include "megbrain/utils/hash_ct.h"

#include "midout.h"

MIDOUT_DECL(megbrain_tensor_reformat)
#define MIDOUT_B(tag) \
    MIDOUT_BEGIN(megbrain_tensor_reformat, midout_iv(MGB_HASH_STR(tag))) {
#define MIDOUT_E \
    }            \
    MIDOUT_END();
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

using namespace mgb;
using namespace gopt;

/* ================ TensorReformatPass =============== */
/*!
 * \brief relayout placeholder opr
 *
 * RelayoutPlaceholder oprs act as the placeholders of the ComputingGraph
 * during graph opt pass `TensorReformatPass`. These oprs are introduced
 * into a ComputingGraph for conveniently discovering further optimize
 * opportunities (such as fuse consecutive relayouts, translate into
 * optimized implementations). They are canonized to have a shape infer, so
 * the ouput's shape can be correctly deduced during the opt pass.
 *
 * Note that the oprs in the ComputingGraph are only used as intermediate
 * representations before being translated to MegBrain oprs, so the
 * oprs should not get involved in any actual computing.
 */
MGB_DEFINE_OPR_CLASS(TensorReformatPass::RelayoutPlaceholder,
71
                           cg::SingleCNOperatorNodeBase) // {
72
public:
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    //! relayout type of this opr
    enum class LayoutType {
        NCHW4_TO_NCHW32,              //!< from nchw4 layout to nchw32 layout
        NCHW32_TO_NCHW4,              //!< from nchw32 layout to nchw4 layout
        NCHW4_TO_CHWN4,               //!< from nchw4 layout to chwn4 layout
        CHWN4_TO_NCHW4,               //!< from chwn4 layout to nchw4 layout
        NCHW_TO_NCHW4,                //!< from nchw layout to nchw4 layout
        NCHW_TO_NCHW4_IC_SMALL_CONV,  ///< from nchw layout to nchw4 whose
                                      ///< channel size less than 4
        NCHW4_TO_NCHW,                //!< from nchw4 layout to nchw layout
        NCHW_TO_NCHW88,               //!< from nchw layout to nchw88 layout
        NCHW88_TO_NCHW,               //!< from nchw88 layout to nchw layout

        WEIGHT_NCHW_TO_NCHW4_DENSE,  //!< weight from nchw layout to nchw4
                                     //!< layout
        WEIGHT_NCHW_TO_NCHW4_GROUP,  //!< group weight from nchw layout to
                                     //!< nchw4 layout
        WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV,  //!< weight from nchw layout
                                                   //!< to nchw4 layout whose
                                                   //! channel size less than 4

        WEIGHT_NCHW_TO_NCHW88_DENSE,  //!< weight from nchw layout to nchw88
                                      //!< layout
        WEIGHT_NCHW_TO_NCHW88_GROUP,  //!< group weight from nchw layout to
                                      //!< nchw88 layout
        WEIGHT_NCHW_TO_NCHW88_CHAN,   //!< channel wise weight from nchw layout
                                      //!< to nchw88 layout
        //!< the weight layout of input is nchw output is nchw88, special for
        //!< shape weight in nchw like {64, 2, 3, 3} to {8, 3, 3, 2, 8}
        WEIGHT_HYBIRD_NCHW_NCHW88,

        WEIGHT_NCHW_TO_NCHW44_DENSE,  //!< weight from nchw layout to nchw44
                                      //!< layout
        WEIGHT_NCHW_TO_NCHW44_GROUP,  //!< group weight from nchw layout to
                                      //!< nchw44 layout
        WEIGHT_NCHW_TO_NCHW44_CHAN,   //!< channel wise weight from nchw layout
                                      //!< to nchw44 layout
        //!< the weight layout of input is nchw output is nchw44, special for
        //!< shape weight in nchw like {64, 2, 3, 3} to {16, 3, 3, 2, 4}
        WEIGHT_HYBIRD_NCHW_NCHW44,
        WEIGHT_NCHW_TO_NCHW44_DOT_DENSE,  //!< weight from NCHW44 layout to
                                          //!< NCHW44_DOT layout dense
        WEIGHT_NCHW_TO_NCHW44_DOT_GROUP,  //!< weight from NCHW44 layout to
                                          //!< NCHW44_DOT layout group
        NCHW32_TO_NCHW,                   //! <from nchw32 layout to nchw layout
        NCHW32_TO_NCHW64,  //! <from nchw32 layout to nchw64 layout
        NCHW64_TO_NCHW,    //! <from nchw64 layout to nchw layout
        NCHW64_TO_NCHW4,   //! <from nchw64 layout to nchw4 layout
        NCHW64_TO_NCHW32,  //! <from nchw64 layout to nchw32 layout
        NCHW_TO_NCHW64,    //! <from nchw layout to nchw64 layout
        NCHW_TO_NCHW32,    //! <from nchw layout to nchw64 layout
        NCHW4_TO_NCHW64,   //! <from nchw4 layout to nchw64 layout
125 126 127 128 129 130 131 132
        NCHW_TO_NHWC, //! <NHWC related layout transformation 
        NCHW4_TO_NHWC, 
        NCHW32_TO_NHWC,
        NCHW64_TO_NHWC, 
        NHWC_TO_NCHW, 
        NHWC_TO_NCHW4, 
        NHWC_TO_NCHW32, 
        NHWC_TO_NCHW64, 
133
    };
M
Megvii Engine Team 已提交
134

135
    RelayoutPlaceholder(VarNode* src_var, LayoutType layout_type);
M
Megvii Engine Team 已提交
136

137 138 139 140 141
    /*!
     * \param src_var the input var
     * \param layout_type tensor layout transform type of this relayout
     * placeholder as described in LayoutType
     */
142
    static SymbolVar make(VarNode* src_var, LayoutType layout_type);
M
Megvii Engine Team 已提交
143

144
    LayoutType layout_type() const { return m_layout_type; }
145 146

private:
147 148 149 150 151
    void init_output_static_infer_desc() override;
    void scn_do_execute() override;
    void init_output_comp_node() override;
    const LayoutType m_layout_type;
};
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
MGB_DYN_TYPE_OBJ_FINAL_IMPL(TensorReformatPass::RelayoutPlaceholder);

TensorReformatPass::RelayoutPlaceholder::RelayoutPlaceholder(
        VarNode* src_var, LayoutType layout_type)
        : Super(src_var->owner_graph(), {}, "RelayoutPlaceholder", {src_var}),
          m_layout_type{layout_type} {
    add_input({src_var});
    add_equivalence_component<ScalarHash<LayoutType>>(m_layout_type);
    add_output(None)->dtype(src_var->dtype());
}

void TensorReformatPass::RelayoutPlaceholder::scn_do_execute() {
    mgb_throw(InternalError, "RelayoutPlaceholder opr can not be executed");
}

void TensorReformatPass::RelayoutPlaceholder::init_output_comp_node() {
    output(0)->comp_node(input(0)->comp_node());
}

void TensorReformatPass::RelayoutPlaceholder::init_output_static_infer_desc() {
    using namespace cg::static_infer;
    auto&& mgr = owner_graph()->static_infer_manager();
    DepVal deps;
    for (auto i : input())
        deps.push_back({i, DepType::SHAPE});
    auto infer_shape = [this](TensorShape& dst, const InpVal& inp) {
        TensorShape inp_shape = inp.val[0].shape();
        dst = inp_shape;
        if (layout_type() == RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 8;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4] * 8;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 8;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4] / 8;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
            dst[0] = inp_shape[1];
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[0];
            dst[4] = inp_shape[4];
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
            dst[0] = inp_shape[3];
            dst[1] = inp_shape[0];
            dst[2] = inp_shape[1];
            dst[3] = inp_shape[2];
            dst[4] = inp_shape[4];
        } else if (layout_type() ==
212 213 214 215 216
                           RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4 ||
                   layout_type() == RelayoutPlaceholder::LayoutType::
                                            NCHW_TO_NCHW4_IC_SMALL_CONV) {
            if (layout_type() ==
                RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4) {
217 218
                mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 4 == 0,
                           "src shape %s", inp_shape.to_string().c_str());
219 220 221 222 223 224
            } else {
                mgb_assert(layout_type() ==
                           RelayoutPlaceholder::LayoutType::
                                   NCHW_TO_NCHW4_IC_SMALL_CONV);
                mgb_assert(inp_shape.ndim == 4 && inp_shape[1] < 4);
            }
225 226
            dst.ndim = 5;
            dst[0] = inp_shape[0];
227
            dst[1] = (inp_shape[1] + 4 - 1) / 4;
228 229 230 231
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 4;
        } else if (layout_type() ==
M
Megvii Engine Team 已提交
232
                   RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW) {
233 234 235 236 237 238 239
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 4;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
240 241 242 243 244 245 246 247 248 249 250 251 252 253
                                            WEIGHT_NCHW_TO_NCHW4_DENSE ||
                   layout_type() ==
                           RelayoutPlaceholder::LayoutType::
                                   WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV) {
            if (layout_type() ==
                RelayoutPlaceholder::LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE) {
                mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 4 == 0);
            } else {
                mgb_assert(layout_type() ==
                           RelayoutPlaceholder::LayoutType::
                                   WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV);
                mgb_assert(inp_shape.ndim == 4 && inp_shape[1] < 4);
            }

254 255
            dst.ndim = 5;
            dst[0] = inp_shape[0];
256
            dst[1] = (inp_shape[1] + 4 - 1) / 4;
257 258 259 260 261 262 263 264 265 266 267 268 269
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 4;
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
                                            WEIGHT_NCHW_TO_NCHW4_GROUP) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[2] % 4 == 0);
            dst.ndim = 6;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1];
            dst[2] = inp_shape[2] / 4;
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4];
            dst[5] = 4;
M
Megvii Engine Team 已提交
270
        } else if (layout_type() ==
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
                   RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW88) {
            mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 8 == 0);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 8;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 8;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW88_TO_NCHW) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 8);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 8;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
                                            WEIGHT_NCHW_TO_NCHW88_DENSE) {
            mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 8 == 0 &&
                       inp_shape[1] % 8 == 0);
            dst.ndim = 6;
            dst[0] = inp_shape[0] / 8;
            dst[1] = inp_shape[1] / 8;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 8;
            dst[5] = 8;
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
                                            WEIGHT_NCHW_TO_NCHW88_GROUP) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 8 == 0 &&
                       inp_shape[2] % 8 == 0);
            dst.ndim = 7;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 8;
            dst[2] = inp_shape[2] / 8;
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4];
            dst[5] = 8;
            dst[6] = 8;
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
                                            WEIGHT_NCHW_TO_NCHW88_CHAN) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[1] == 1 &&
                       inp_shape[2] == 1 && inp_shape[0] % 8 == 0);
            dst.ndim = 6;
            dst[0] = inp_shape[0] / 8;
            dst[1] = inp_shape[1];
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4];
            dst[5] = 8;
321 322
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::WEIGHT_HYBIRD_NCHW_NCHW88) {
323 324 325 326 327 328 329
            mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 8 == 0);
            dst.ndim = 5;
            dst[0] = inp_shape[0] / 8;
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[1];
            dst[4] = 8;
330
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
331 332 333
                                            WEIGHT_NCHW_TO_NCHW44_DENSE ||
                   layout_type() == RelayoutPlaceholder::LayoutType::
                                            WEIGHT_NCHW_TO_NCHW44_DOT_DENSE) {
334 335 336 337 338 339 340 341 342 343
            mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 4 == 0 &&
                       inp_shape[1] % 4 == 0);
            dst.ndim = 6;
            dst[0] = inp_shape[0] / 4;
            dst[1] = inp_shape[1] / 4;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 4;
            dst[5] = 4;
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
344 345 346
                                            WEIGHT_NCHW_TO_NCHW44_GROUP ||
                   layout_type() == RelayoutPlaceholder::LayoutType::
                                            WEIGHT_NCHW_TO_NCHW44_DOT_GROUP) {
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 4 == 0 &&
                       inp_shape[2] % 4 == 0);
            dst.ndim = 7;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 4;
            dst[2] = inp_shape[2] / 4;
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4];
            dst[5] = 4;
            dst[6] = 4;
        } else if (layout_type() == RelayoutPlaceholder::LayoutType::
                                            WEIGHT_NCHW_TO_NCHW44_CHAN) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[1] == 1 &&
                       inp_shape[2] == 1 && inp_shape[0] % 4 == 0);
            dst.ndim = 6;
            dst[0] = inp_shape[0] / 4;
            dst[1] = inp_shape[1];
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4];
            dst[5] = 4;
368 369
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::WEIGHT_HYBIRD_NCHW_NCHW44) {
370 371 372 373 374 375 376
            mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 4 == 0);
            dst.ndim = 5;
            dst[0] = inp_shape[0] / 4;
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[1];
            dst[4] = 4;
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 32;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW64) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 2 == 0 &&
                       inp_shape[4] == 32);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 2;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 64;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 64);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 64;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW4) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 64);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 16;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 4;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW32) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 64);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 2;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 32;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW64) {
423 424
            mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 64 == 0, "%s",
                       inp_shape.to_string().c_str());
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 64;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 64;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW32) {
            mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 32 == 0);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 32;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 32;
440 441
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW64) {
442 443 444 445 446 447 448
            mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 16 == 0);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 16;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 64;
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW_TO_NHWC) {
            mgb_assert(inp_shape.ndim == 4);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[1];
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW4_TO_NHWC) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[1] * 4;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW32_TO_NHWC) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[1] * 32;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NCHW64_TO_NHWC) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 64);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[1] * 64;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW) {
            mgb_assert(inp_shape.ndim == 4);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[3];
            dst[2] = inp_shape[1];
            dst[3] = inp_shape[2];
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW4) {
            mgb_assert(inp_shape.ndim == 4 && inp_shape[3] % 4 == 0);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[3] / 4;
            dst[2] = inp_shape[1];
            dst[3] = inp_shape[2];
            dst[4] = 4;
        } else if (layout_type() ==
                   RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW32) {
            mgb_assert(inp_shape.ndim == 4 && inp_shape[3] % 32 == 0);
501
            dst.ndim = 5;
502 503 504 505 506
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[3] / 32;
            dst[2] = inp_shape[1];
            dst[3] = inp_shape[2];
            dst[4] = 32;
507
        } else {
508 509 510
            mgb_assert(layout_type() ==
                       RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW64);
            mgb_assert(inp_shape.ndim == 4 && inp_shape[3] % 64 == 0);
511
            dst.ndim = 5;
512 513 514 515 516
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[3] / 64;
            dst[2] = inp_shape[1];
            dst[3] = inp_shape[2];
            dst[4] = 64;
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
        }
        return true;
    };
    mgr.register_shape_infer(output(0), {SourceType::DEP, deps, infer_shape});
}

SymbolVar TensorReformatPass::RelayoutPlaceholder::make(
        VarNode* src_var, LayoutType layout_type) {
    return src_var->owner_graph()
            ->insert_opr(
                    std::make_unique<RelayoutPlaceholder>(src_var, layout_type))
            ->output(0);
}

void TensorReformatPass::insert_pass(OptState& opt) const {
    opt.set_var_replace_check_flag(m_var_replace_check_flag);
    auto rewriter = opt.graph().make_rewriter();
    VarNodeArray new_inp_cache;
    auto on_opr = [this, &opt, &rewriter,
                   &new_inp_cache](OperatorNodeBase* opr) {
        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&& inp : opr->input()) {
                new_inp.push_back(rewriter.get_var(inp));
            }
            auto new_opr = (it->second)(opr, new_inp);
            auto &&out0 = opr->output(), &&out1 = new_opr->output();
            mgb_assert(out0.size() == out1.size(),
548 549
                       "bad opr replace: src=%s{%s} dst=%s{%s}, "
                       "src.size=%zu "
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
                       "dst.size=%zu",
                       opr->cname(), opr->dyn_typeinfo()->name,
                       new_opr->cname(), new_opr->dyn_typeinfo()->name,
                       out0.size(), out1.size());
            for (size_t i = 0; i < out0.size(); ++i) {
                if (!out0[i]->contain_flag(VarNode::Flag::VOLATILE_CONTENT)) {
                    mgb_assert(!out1[i]->contain_flag(
                            VarNode::Flag::VOLATILE_CONTENT));
                    auto src = out0[i];
                    auto dst = out1[i];
                    if (opt.graph().endpoint_contain(src)) {
                        // additional process on endpoint var node
                        dst = on_graph_endpoint_var(dst, src);
                    }
                    rewriter.replace_var(src, dst, nullptr);
                }
            }
        } else {
            rewriter.auto_replace_outputs(opr);
        }
    };
    opt.graph().iter(on_opr);
    rewriter.apply_inplace();
}

void TensorReformatPass::translate_pass(OptState& opt) const {
    ThinHashMap<RelayoutPlaceholder::LayoutType,
                thin_function<VarNode*(VarNode*)>>
            reformat;
    using LayoutType = RelayoutPlaceholder::LayoutType;
    reformat[LayoutType::NCHW4_TO_CHWN4] = [](VarNode* inp) -> VarNode* {
        megdnn::param::RelayoutFormat param;
        param.mode = megdnn::param::RelayoutFormat::Mode::NCHW4_CHWN4;
        auto reformat = opr::RelayoutFormat::make(inp, param);
        return reformat.node();
    };
    reformat[LayoutType::CHWN4_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
        megdnn::param::RelayoutFormat param;
        param.mode = megdnn::param::RelayoutFormat::Mode::CHWN4_NCHW4;
        auto reformat = opr::RelayoutFormat::make(inp, param);
        return reformat.node();
    };
    reformat[LayoutType::NCHW4_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::NCHW32_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640

    reformat[LayoutType::NCHW_TO_NCHW4_IC_SMALL_CONV] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto y = opr::RelayoutFormat::make(
                x, megdnn::param::RelayoutFormat::Mode::NCHW_NCHW4_IC_SMALL);
        return y.node();
    };
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto y = opr::RelayoutFormat::make(
                x, megdnn::param::RelayoutFormat::Mode::
                           NCHW_NCHW4_IC_SMALL_CONV_DENSE_WEIGHT);
        return y.node();
    };

641 642 643 644 645 646 647 648
    reformat[LayoutType::NCHW_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
M
Megvii Engine Team 已提交
649
                {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
650 651
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
652
        return y1.node();
653 654 655 656 657 658 659 660 661 662 663 664 665
    };
    reformat[LayoutType::NCHW4_TO_NCHW] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
        auto y1 = opr::Reshape::make(y0, tshp0);
        return y1.node();
    };
666 667
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE] =
            [](VarNode* inp) -> VarNode* {
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) / 4, sub(2), sub(3), cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
683 684
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_GROUP] =
            [](VarNode* inp) -> VarNode* {
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1), sub(2) / 4, cv(4), sub(3), sub(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1), sub(2) / 4, sub(3), sub(4), cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 2, 4, 5, 3});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    reformat[LayoutType::NCHW_TO_NCHW88] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1) / 8, cv(8), sub(2), sub(3)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) / 8, sub(2), sub(3), cv(8)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::NCHW88_TO_NCHW] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make({sub(0), sub(1) * 8, sub(2), sub(3)}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
        auto y1 = opr::Reshape::make(y0, tshp0);
        return y1.node();
    };
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_DENSE] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0) / 8, cv(8), sub(1) / 8, cv(8), sub(2), sub(3)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0) / 8, sub(1) / 8, sub(2), sub(3), cv(8), cv(8)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 3, 1});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_GROUP] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make({sub(0), sub(1) / 8, cv(8), sub(2) / 8,
                                        cv(8), sub(3), sub(4)},
                                       0),
             tshp1 = opr::Concat::make({sub(0), sub(1) / 8, sub(2) / 8, sub(3),
                                        sub(4), cv(8), cv(8)},
                                       0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 4, 2});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_CHAN] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0) / 8, cv(8), sub(1), sub(2), sub(3), sub(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0) / 8, sub(1), sub(2), sub(3), sub(4), cv(8)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 2, 3, 4, 5, 1});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::WEIGHT_HYBIRD_NCHW_NCHW88] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0) / 8, cv(8), sub(1), sub(2), sub(3)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0) / 8, sub(2), sub(3), sub(1), cv(8)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 3, 4, 2, 1});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DENSE] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0) / 4, cv(4), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0) / 4, sub(1) / 4, sub(2), sub(3), cv(4), cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 3, 1});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_GROUP] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2) / 4,
                                        cv(4), sub(3), sub(4)},
                                       0),
             tshp1 = opr::Concat::make({sub(0), sub(1) / 4, sub(2) / 4, sub(3),
                                        sub(4), cv(4), cv(4)},
                                       0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 4, 2});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_CHAN] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0) / 4, cv(4), sub(1), sub(2), sub(3), sub(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0) / 4, sub(1), sub(2), sub(3), sub(4), cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 2, 3, 4, 5, 1});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::WEIGHT_HYBIRD_NCHW_NCHW44] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0) / 4, cv(4), sub(1), sub(2), sub(3)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0) / 4, sub(2), sub(3), sub(1), cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 3, 4, 2, 1});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DOT_DENSE] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0) / 4, cv(4), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0) / 4, sub(1) / 4, sub(2), sub(3), cv(4), cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 1, 3});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DOT_GROUP] =
            [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2) / 4,
                                        cv(4), sub(3), sub(4)},
                                       0),
             tshp1 = opr::Concat::make({sub(0), sub(1) / 4, sub(2) / 4, sub(3),
                                        sub(4), cv(4), cv(4)},
                                       0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 2, 4});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    reformat[LayoutType::NCHW32_TO_NCHW] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 =
                opr::Concat::make({sub(0), sub(1) * 32, sub(2), sub(3)}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
        auto y1 = opr::Reshape::make(y0, tshp0);
        return y1.node();
    };
    reformat[LayoutType::NCHW32_TO_NCHW64] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1) / 2, cv(2), sub(2), sub(3), sub(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) / 2, sub(2), sub(3), sub(4) * 2}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::NCHW64_TO_NCHW] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 =
                opr::Concat::make({sub(0), sub(1) * 64, sub(2), sub(3)}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
        auto y1 = opr::Reshape::make(y0, tshp0);
        return y1.node();
    };
    reformat[LayoutType::NCHW64_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1), sub(2), sub(3), sub(4) / 4, cv(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) * 16, sub(2), sub(3), cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::NCHW64_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1), sub(2), sub(3), sub(4) / 32, cv(32)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) * 2, sub(2), sub(3), cv(32)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
    reformat[LayoutType::NCHW_TO_NCHW64] = [](VarNode* inp) -> VarNode* {
        megdnn::param::RelayoutFormat param;
        param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NCHW64;
        auto reformat = opr::RelayoutFormat::make(inp, param);
        return reformat.node();
    };
    reformat[LayoutType::NCHW_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                {sub(0), sub(1) / 32, cv(32), sub(2), sub(3)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
        return y1.node();
    };
    reformat[LayoutType::NCHW4_TO_NCHW64] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1) / 16, cv(16), sub(2), sub(3), sub(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) / 16, sub(2), sub(3), sub(4) * 16}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    reformat[LayoutType::NCHW_TO_NHWC] = [](VarNode* inp) -> VarNode* {
        megdnn::param::RelayoutFormat param;
        param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NHWC;
        auto reformat = opr::RelayoutFormat::make(inp, param);
        return reformat.node();
    };
    reformat[LayoutType::NCHW4_TO_NHWC] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 =
                opr::Concat::make({sub(0), sub(2), sub(3), sub(1) * 4}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 2, 3, 1, 4});
        auto y1 = opr::Reshape::make(y0, tshp0);
        return y1.node();
    };
    reformat[LayoutType::NCHW32_TO_NHWC] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make({sub(0), sub(2), sub(3), sub(1) * 32}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 2, 3, 1, 4});
        auto y1 = opr::Reshape::make(y0, tshp0);
        return y1.node();
    };
    reformat[LayoutType::NCHW64_TO_NHWC] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make({sub(0), sub(2), sub(3), sub(1) * 64}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 2, 3, 1, 4});
        auto y1 = opr::Reshape::make(y0, tshp0);
        return y1.node();
    };
    reformat[LayoutType::NHWC_TO_NCHW] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto y = opr::Dimshuffle::make(x, {0, 3, 1, 2});
        return y.node();
    };
    reformat[LayoutType::NHWC_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                {sub(0), sub(1), sub(2), sub(3) / 4, cv(4)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 3, 1, 2, 4});
        return y1.node();
    };
    reformat[LayoutType::NHWC_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                {sub(0), sub(1), sub(2), sub(3) / 32, cv(32)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 3, 1, 2, 4});
        return y1.node();
    };
    reformat[LayoutType::NHWC_TO_NCHW64] = [](VarNode* inp) -> VarNode* {
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                {sub(0), sub(1), sub(2), sub(3) / 64, cv(64)}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 3, 1, 2, 4});
        return y1.node();
    };
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

    auto rewriter = opt.graph().make_rewriter();
    auto on_opr = [&reformat, &rewriter](OperatorNodeBase* opr) {
        if (opr->same_type<RelayoutPlaceholder>()) {
            auto ph = try_cast_as_op<RelayoutPlaceholder>(opr);
            auto new_inp = rewriter.get_var(opr->input(0));
            mgb_assert(reformat.count(ph->layout_type()),
                       "no replace rule can be found for layout_type(%u)",
                       static_cast<uint32_t>(ph->layout_type()));
            auto new_var = reformat[ph->layout_type()](new_inp);
            rewriter.replace_var(opr->output(0), new_var,
                                 mgb_cstr_log("replace relayout placeholder"));
            return;
        }
        rewriter.auto_replace_outputs(opr);
    };
    opt.graph().iter(on_opr);
    rewriter.apply_inplace();
}

void TensorReformatPass::apply(OptState& opt) const {
1121
    MIDOUT_B("TensorReformatPass::apply")
1122 1123
    insert_pass(opt);
    translate_pass(opt);
1124
    MIDOUT_E
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
}

/* ================ EnableTensorCorePass =============== */
VarNode* EnableTensorCorePass::on_graph_endpoint_var(VarNode* new_var,
                                                     VarNode* orig_var) const {
    if (!orig_var->shape().eq_shape(new_var->shape())) {
        return RelayoutPlaceholder::make(
                       new_var,
                       RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4)
                .node();
    }
    return new_var;
}

std::unique_ptr<EnableTensorCorePass>
EnableTensorCorePass::make_tensorcore_converter() {
1141
    MIDOUT_B("EnableTensorCorePass::make")
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    // replace rule for conv bias opr
    auto replace_conv_bias_opr = [](OperatorNodeBase* opr,
                                    const VarNodeArray& new_inp) {
        using Param = megdnn::param::ConvBias;
        using Format = Param::Format;
        using Sparse = Param::Sparse;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
        if (conv_bias.param().format != Format::NCHW4 ||
            conv_bias.output(0)->dtype().enumv() != DTypeEnum::QuantizedS8) {
            size_t nr_inps = opr->input().size();
            bool shape_has_changed = false;
            for (size_t i = 0; i < nr_inps; ++i) {
                if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                    shape_has_changed = true;
                }
            }
            MGB_MARK_USED_VAR(shape_has_changed);
            mgb_assert(
                    !shape_has_changed,
                    "EnableTensorCorePass assumes that the shape of inputs of"
                    "ConvBias operators whose output dtype is not QuantizedS8 "
                    "can not be changed in this opt pass");
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
        mgb_assert(opr->input(1)->shape().eq_shape(new_inp[1]->shape()),
                   "EnableTensorCorePass assumes that filter tensor of "
                   "conv_bias operator can not be changed by other operators");
        VarNode* orig_filter = opr->input(1);
        auto is_nchw4 = [](TensorShape shape) -> bool {
            return shape.ndim == 5 && shape[4] == 4;
        };
        auto is_nchw32 = [](TensorShape shape) -> bool {
            return shape.ndim == 5 && shape[4] == 32;
        };
        bool can_replace_nchw32 = false;
        VarNode *src = nullptr, *weight = nullptr, *bias = nullptr,
                *z_inp = nullptr;
        // process src tensor
        if (is_nchw4(new_inp[0]->shape())) {  // new input is NCHW4 layout
            size_t group = 1, icpg, ocpg;
            if (conv_bias.param().sparse == Sparse::DENSE) {
                icpg = orig_filter->shape()[1] * 4;
                ocpg = orig_filter->shape()[0];
            } else {
                mgb_assert(conv_bias.param().sparse == Sparse::GROUP);
                group = orig_filter->shape()[0];
                icpg = orig_filter->shape()[2];
                ocpg = orig_filter->shape()[1];
                if (icpg == 1 && ocpg == 1) {  // channel wise conv
                    group *= 4;
                } else {
                    icpg *= 4;
                }
            }
            // nchw32 layout need that input width and height are larger than 3
            size_t ih = new_inp[0]->shape()[2], iw = new_inp[0]->shape()[3];
            if (group == 1 && ocpg % 32 == 0 && icpg % 32 == 0 && ih >= 3 &&
                iw >= 3) {
                auto symvar = RelayoutPlaceholder::make(
                        new_inp[0],
                        RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
                src = symvar.node();
                can_replace_nchw32 = true;
            } else {
                src = new_inp[0];
            }
        } else {  // new input is NCHW32 layout
            mgb_assert(is_nchw32(new_inp[0]->shape()));
            size_t group = 1, ocpg;
            if (conv_bias.param().sparse == Sparse::DENSE) {
                ocpg = orig_filter->shape()[0];
            } else {
                mgb_assert(conv_bias.param().sparse == Sparse::GROUP);
                size_t icpg = orig_filter->shape()[2];
                ocpg = orig_filter->shape()[1];
                if (icpg == 1 && ocpg == 1) {
                    group *= 4;
                } else {
                    icpg *= 4;
                }
            }
            size_t ih = new_inp[0]->shape()[2], iw = new_inp[0]->shape()[3];
            if (group == 1 && ocpg % 32 == 0 && ih >= 3 && iw >= 3) {
                can_replace_nchw32 = true;
                src = new_inp[0];
            } else {
                auto symvar = RelayoutPlaceholder::make(
                        new_inp[0],
                        RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
                src = symvar.node();
            }
        }
        // process filter tensor
        if (can_replace_nchw32) {
            auto symvar = RelayoutPlaceholder::make(
                    new_inp[1],
                    RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
            weight = symvar.node();
        } else {
            weight = new_inp[1];
        }
        if (new_inp.size() == 2) {
            if (can_replace_nchw32) {
                auto param = conv_bias.param();
                param.format = Format::NCHW32;
                auto new_opr = opr::ConvBiasForward::make(
                        src, weight, param, conv_bias.execution_policy(),
                        conv_bias.config());
                return new_opr.node()->owner_opr();
            } else {
                VarNodeArray inps{src, weight};
                auto new_opr = serialization::copy_opr_shallow(*opr, inps,
                                                               opr->config());
                return new_opr;
            }
        }
        auto process_inp = [&](VarNode* inp) -> VarNode* {
            if (can_replace_nchw32) {
                if (is_nchw4(inp->shape())) {
                    auto symvar = RelayoutPlaceholder::make(
                            inp,
                            RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
                    return symvar.node();
                } else {
                    mgb_assert(is_nchw32(inp->shape()));
                    return inp;
                }
            } else {
                if (is_nchw4(inp->shape())) {
                    return inp;
                } else {
                    mgb_assert(is_nchw32(inp->shape()));
                    auto symvar = RelayoutPlaceholder::make(
                            inp,
                            RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
                    return symvar.node();
                }
            }
        };
        // process bias tensor
        bias = process_inp(new_inp[2]);
        if (new_inp.size() == 3) {
            if (can_replace_nchw32) {
                auto param = conv_bias.param();
                param.format = Format::NCHW32;
                auto new_opr = opr::ConvBiasForward::make(
                        src, weight, bias, param, conv_bias.execution_policy(),
                        conv_bias.config());
                return new_opr.node()->owner_opr();
            } else {
                VarNodeArray inps{src, weight, bias};
                auto new_opr = serialization::copy_opr_shallow(*opr, inps,
                                                               opr->config());
                return new_opr;
            }
        }
        // process z_inp tensor
        z_inp = process_inp(new_inp[3]);
        if (can_replace_nchw32) {
            auto param = conv_bias.param();
            param.format = Format::NCHW32;
            auto new_opr = opr::ConvBiasForward::make(
                    src, weight, bias, z_inp, param,
                    conv_bias.execution_policy(), conv_bias.config());
            return new_opr.node()->owner_opr();
        }
        VarNodeArray inps{src, weight, bias, z_inp};
        auto new_opr =
                serialization::copy_opr_shallow(*opr, inps, opr->config());
        return new_opr;
    };
    // replace rule for elemwise like opr
    // for oprs support NCHW4 and NCHW32 layout
    auto replace_elemwise_like_opr = [](OperatorNodeBase* opr,
                                        const VarNodeArray new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        size_t nr_inps = new_inp.size();
        size_t nr_shape_changed = 0;
        for (size_t i = 0; i < nr_inps; ++i) {
            if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                nr_shape_changed++;
            }
        }
        if (nr_shape_changed) {
            auto inps = new_inp;
            if (nr_shape_changed >=
                nr_inps / 2) {  // NCHW32 > NCHW4 -> use NCHW32
                for (size_t i = 0; i < nr_inps; ++i) {
                    if (opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                        auto symvar = RelayoutPlaceholder::make(
                                new_inp[i], RelayoutPlaceholder::LayoutType::
                                                    NCHW4_TO_NCHW32);
                        inps[i] = symvar.node();
                    }
                }
            } else {  // NCHW32 < NCHW4 -> use NCHW4
                for (size_t i = 0; i < nr_inps; ++i) {
                    if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                        auto symvar = RelayoutPlaceholder::make(
                                new_inp[i], RelayoutPlaceholder::LayoutType::
                                                    NCHW32_TO_NCHW4);
                        inps[i] = symvar.node();
                    }
                }
            }
            return serialization::copy_opr_shallow(*opr, inps, opr->config());
        }
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    // for oprs only supports NCHW4 layout
    auto replace_inps_to_nchw4 = [](OperatorNodeBase* opr,
                                    const VarNodeArray new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        VarNodeArray inps = new_inp;
        for (size_t i = 0; i < opr->input().size(); ++i) {
            if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                mgb_assert(opr->input(i)->shape().ndim == 5 &&
                           opr->input(i)->shape()[4] == 4);
                mgb_assert(new_inp[i]->shape().ndim == 5 &&
                           new_inp[i]->shape()[4] == 32);
                auto symvar = RelayoutPlaceholder::make(
                        new_inp[i],
                        RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
                inps[i] = symvar.node();
            }
        }
        auto new_opr =
                serialization::copy_opr_shallow(*opr, inps, opr->config());
        return new_opr;
    };
    auto replace_non_nchw4_opr = [](OperatorNodeBase* opr,
                                    const VarNodeArray new_inp) {
        size_t nr_inps = opr->input().size();
        bool shape_has_changed = false;
        for (size_t i = 0; i < nr_inps; ++i) {
            if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                shape_has_changed = true;
            }
        }
        mgb_assert(!shape_has_changed,
                   "EnableTensorCorePass assumes that inputs' shape of "
                   "non-nchw4 operators "
                   "can not be changed in this opt "
                   "pass");
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    auto replace_warp_affine_opr =
            [replace_inps_to_nchw4, replace_non_nchw4_opr](
                    OperatorNodeBase* opr, const VarNodeArray new_inp) {
                using Param = opr::WarpAffineForward::Param;
                using Format = Param::Format;
                mgb_assert(opr->input().size() == new_inp.size());
                auto& warp = opr->cast_final_safe<opr::WarpAffineForward>();
                if (warp.param().format != Format::NCHW4) {
                    return replace_non_nchw4_opr(opr, new_inp);
                }
                return replace_inps_to_nchw4(opr, new_inp);
            };
    auto replace_warp_perspective_opr =
            [replace_inps_to_nchw4, replace_non_nchw4_opr](
                    OperatorNodeBase* opr, const VarNodeArray new_inp) {
                using Param = opr::WarpPerspectiveForward::Param;
                using Format = Param::Format;
                mgb_assert(opr->input().size() == new_inp.size());
                auto& warp =
                        opr->cast_final_safe<opr::WarpPerspectiveForward>();
                if (warp.param().format != Format::NCHW4) {
                    return replace_non_nchw4_opr(opr, new_inp);
                }
                return replace_inps_to_nchw4(opr, new_inp);
            };
    auto replace_resize_opr = [replace_inps_to_nchw4, replace_non_nchw4_opr](
                                      OperatorNodeBase* opr,
                                      const VarNodeArray new_inp) {
        using Param = opr::ResizeForward::Param;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& resize = opr->cast_final_safe<opr::ResizeForward>();
        if (resize.param().format != Format::NCHW4) {
            return replace_non_nchw4_opr(opr, new_inp);
        }
        return replace_inps_to_nchw4(opr, new_inp);
    };
    auto replace_pooling_opr = [replace_non_nchw4_opr](
                                       OperatorNodeBase* opr,
                                       const VarNodeArray new_inp) {
        using Param = opr::PoolingForward::Param;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
        if (pooling.param().format != Format::NCHW4) {
            return replace_non_nchw4_opr(opr, new_inp);
        }
        size_t nr_inps = opr->input().size();
        MGB_MARK_USED_VAR(nr_inps);
        mgb_assert(nr_inps == 1);
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
        size_t nr_channels = opr->input(0)->shape()[1] * 4;
        if (nr_channels % 32 == 0) {  // use nchw32 format
            VarNode* new_inp_var = new_inp[0];
            if (opr->input(0)->shape().eq_shape(new_inp[0]->shape())) {
                new_inp_var =
                        RelayoutPlaceholder::make(
                                new_inp[0], RelayoutPlaceholder::LayoutType::
                                                    NCHW4_TO_NCHW32)
                                .node();
            } else {
                mgb_assert(opr->input(0)->shape().ndim == 5 &&
                           opr->input(0)->shape()[4] == 4);
                mgb_assert(new_inp[0]->shape().ndim == 5 &&
                           new_inp[0]->shape()[4] == 32);
            }
1455 1456
            auto new_param = pooling.param();
            new_param.format = Format::NCHW32;
1457
            auto new_pooling = opr::PoolingForward::make(new_inp_var, new_param,
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
                                                         opr->config());
            return new_pooling.node()->owner_opr();
        }
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    auto ret = std::make_unique<EnableTensorCorePass>();
    ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
    auto&& replace_func = ret->m_opr_replace_func;
    replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;

    // elemwise like
    replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
    replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
    replace_func[opr::ElemwiseMultiType::typeinfo()] =
            replace_elemwise_like_opr;
    replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;

    // format aware
    replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
    replace_func[opr::WarpAffineForward::typeinfo()] = replace_warp_affine_opr;
    replace_func[opr::WarpPerspectiveForward::typeinfo()] =
            replace_warp_perspective_opr;
    replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;

    // to nchw4
    replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw4;
    return ret;
1489
    MIDOUT_E
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
}

/* ================ EnableCHWN4Pass =============== */
VarNode* EnableCHWN4Pass::on_graph_endpoint_var(VarNode* new_var,
                                                VarNode* /* orig_var */) const {
    if (m_varshape_changed.count(new_var)) {
        return RelayoutPlaceholder::make(
                       new_var, RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4)
                .node();
    }
    return new_var;
}

std::unique_ptr<EnableCHWN4Pass> EnableCHWN4Pass::make_chwn4_converter() {
1504
    MIDOUT_B("EnableCHWN4Pass::make")
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    auto ret = std::make_unique<EnableCHWN4Pass>();
    ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
    auto&& replace_func = ret->m_opr_replace_func;
    auto&& varshape_changed = ret->m_varshape_changed;
    // replace rule for conv bias opr
    auto replace_conv_bias_opr = [&varshape_changed](
                                         OperatorNodeBase* opr,
                                         const VarNodeArray& new_inp) {
        using Param = megdnn::param::ConvBias;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
        if (conv_bias.param().format != Format::NCHW4 ||
            conv_bias.output(0)->dtype().enumv() != DTypeEnum::QuantizedS8) {
            size_t nr_inps = new_inp.size();
            bool shape_has_changed = false;
            for (size_t i = 0; i < nr_inps; ++i) {
                if (varshape_changed.count(new_inp[i])) {
                    shape_has_changed = true;
                    break;
                }
            }
            mgb_assert(
                    !shape_has_changed,
                    "EnableCHWN4Pass assumes that the shape of inputs of"
                    "ConvBias operators whose output dtype is not QuantizedS8 "
                    "can not be changed in this opt pass");
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
        mgb_assert(varshape_changed.count(new_inp[1]) == 0,
                   "EnableCHWN4Pass assumes that filter tensor of "
                   "conv_bias operator can not be changed by other operators");
        VarNode *src = nullptr, *weight = nullptr, *bias = nullptr,
                *z_inp = nullptr;
        // process src tensor
        if (varshape_changed.count(new_inp[0]) ==
            0) {  // new input is NCHW4 layout
            // currently not support group conv
            auto symvar = RelayoutPlaceholder::make(
                    new_inp[0],
                    RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
            src = symvar.node();
        } else {  // new input is NCHW32 layout
            src = new_inp[0];
        }
        // process weight tensor
        {
            auto symvar = RelayoutPlaceholder::make(
                    new_inp[1],
                    RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
            weight = symvar.node();
        }
        if (new_inp.size() == 2) {
            auto param = conv_bias.param();
            param.format = Format::CHWN4;
            auto new_opr = opr::ConvBiasForward::make(
                    src, weight, param, conv_bias.execution_policy(),
                    conv_bias.config());
            varshape_changed.insert(new_opr.node());
            return new_opr.node()->owner_opr();
        }
        auto process_inp = [&](VarNode* inp) -> VarNode* {
            if (varshape_changed.count(inp) == 0) {
                auto symvar = RelayoutPlaceholder::make(
                        inp, RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
                return symvar.node();
            } else {
                return inp;
            }
        };
        // process bias tensor
        bias = process_inp(new_inp[2]);
        if (new_inp.size() == 3) {
            auto param = conv_bias.param();
            param.format = Format::CHWN4;
            auto new_opr = opr::ConvBiasForward::make(
                    src, weight, bias, param, conv_bias.execution_policy(),
                    conv_bias.config());
            varshape_changed.insert(new_opr.node());
            return new_opr.node()->owner_opr();
        }
        // process z_inp tensor
        z_inp = process_inp(new_inp[3]);
        auto param = conv_bias.param();
        param.format = Format::CHWN4;
        auto new_opr = opr::ConvBiasForward::make(
                src, weight, bias, z_inp, param, conv_bias.execution_policy(),
                conv_bias.config());
        varshape_changed.insert(new_opr.node());
        return new_opr.node()->owner_opr();
    };
    // replace rule for elemwise like opr
    // for oprs support NCHW4 and CHWN4 layout
    auto replace_elemwise_like_opr = [&varshape_changed](
                                             OperatorNodeBase* opr,
                                             const VarNodeArray new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        size_t nr_inps = new_inp.size();
        size_t nr_shape_changed = 0;
        for (size_t i = 0; i < nr_inps; ++i) {
            if (varshape_changed.count(new_inp[i])) {
                nr_shape_changed++;
            }
        }
        if (nr_shape_changed) {
            auto inps = new_inp;
M
Megvii Engine Team 已提交
1612 1613
            if (nr_shape_changed >=
                nr_inps / 2) {  // CHWN4 > NCHW4 -> use CHWN4
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
                for (size_t i = 0; i < nr_inps; ++i) {
                    if (varshape_changed.count(new_inp[i]) == 0) {
                        auto symvar = RelayoutPlaceholder::make(
                                new_inp[i], RelayoutPlaceholder::LayoutType::
                                                    NCHW4_TO_CHWN4);
                        inps[i] = symvar.node();
                    }
                }
                auto new_opr = serialization::copy_opr_shallow(*opr, inps,
                                                               opr->config());
                varshape_changed.insert(new_opr->output(0));
                return new_opr;
            } else {  // CHWN4 < NCHW4 -> use NCHW4
                for (size_t i = 0; i < nr_inps; ++i) {
                    if (varshape_changed.count(new_inp[i])) {
                        auto symvar = RelayoutPlaceholder::make(
                                new_inp[i], RelayoutPlaceholder::LayoutType::
                                                    CHWN4_TO_NCHW4);
                        inps[i] = symvar.node();
                    }
                }
                return serialization::copy_opr_shallow(*opr, inps,
                                                       opr->config());
            }
        }
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    // for oprs only supports NCHW4 layout
    auto replace_inps_to_nchw4 = [&varshape_changed](
                                         OperatorNodeBase* opr,
                                         const VarNodeArray new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        VarNodeArray inps = new_inp;
        for (size_t i = 0; i < opr->input().size(); ++i) {
            if (varshape_changed.count(new_inp[i])) {
                auto symvar = RelayoutPlaceholder::make(
                        new_inp[i],
                        RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4);
                inps[i] = symvar.node();
            }
        }
        auto new_opr =
                serialization::copy_opr_shallow(*opr, inps, opr->config());
        return new_opr;
    };
    auto replace_non_nchw4_opr = [&varshape_changed](
                                         OperatorNodeBase* opr,
                                         const VarNodeArray new_inp) {
        size_t nr_inps = opr->input().size();
        bool shape_has_changed = false;
        for (size_t i = 0; i < nr_inps; ++i) {
            if (varshape_changed.count(new_inp[i])) {
                shape_has_changed = true;
            }
        }
        mgb_assert(!shape_has_changed,
                   "EnableCHWN4Pass assumes that inputs' shape of "
                   "non-nchw4 operators "
                   "can not be changed in this opt "
                   "pass");
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    // capture by copy to avoid use after return
    auto replace_warp_affine_opr =
            [replace_inps_to_nchw4, replace_non_nchw4_opr](
                    OperatorNodeBase* opr, const VarNodeArray new_inp) {
                using Param = opr::WarpAffineForward::Param;
                using Format = Param::Format;
                mgb_assert(opr->input().size() == new_inp.size());
                auto& warp = opr->cast_final_safe<opr::WarpAffineForward>();
                if (warp.param().format != Format::NCHW4) {
                    return replace_non_nchw4_opr(opr, new_inp);
                }
                return replace_inps_to_nchw4(opr, new_inp);
            };
    auto replace_warp_perspective_opr =
            [replace_inps_to_nchw4, replace_non_nchw4_opr](
                    OperatorNodeBase* opr, const VarNodeArray new_inp) {
                using Param = opr::WarpPerspectiveForward::Param;
                using Format = Param::Format;
                mgb_assert(opr->input().size() == new_inp.size());
                auto& warp =
                        opr->cast_final_safe<opr::WarpPerspectiveForward>();
                if (warp.param().format != Format::NCHW4) {
                    return replace_non_nchw4_opr(opr, new_inp);
                }
                return replace_inps_to_nchw4(opr, new_inp);
            };
    auto replace_resize_opr = [replace_inps_to_nchw4, replace_non_nchw4_opr](
                                      OperatorNodeBase* opr,
                                      const VarNodeArray new_inp) {
        using Param = opr::ResizeForward::Param;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& resize = opr->cast_final_safe<opr::ResizeForward>();
        if (resize.param().format != Format::NCHW4) {
            return replace_non_nchw4_opr(opr, new_inp);
        }
        return replace_inps_to_nchw4(opr, new_inp);
    };
    auto replace_pooling_opr = [&varshape_changed, replace_non_nchw4_opr](
                                       OperatorNodeBase* opr,
                                       const VarNodeArray new_inp) {
        using Param = opr::PoolingForward::Param;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
        if (pooling.param().format != Format::NCHW4) {
            return replace_non_nchw4_opr(opr, new_inp);
        }
        size_t nr_inps = opr->input().size();
        MGB_MARK_USED_VAR(nr_inps);
        mgb_assert(nr_inps == 1);
        if (varshape_changed.count(new_inp[0])) {
            auto new_param = pooling.param();
            new_param.format = Format::CHWN4;
            auto new_pooling = opr::PoolingForward::make(new_inp[0], new_param,
                                                         opr->config());
            varshape_changed.insert(new_pooling.node());
            return new_pooling.node()->owner_opr();
        }
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;

    // elemwise like
    replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
    replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
    replace_func[opr::ElemwiseMultiType::typeinfo()] =
            replace_elemwise_like_opr;
    replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;

    // format aware
    replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
    replace_func[opr::WarpAffineForward::typeinfo()] = replace_warp_affine_opr;
    replace_func[opr::WarpPerspectiveForward::typeinfo()] =
            replace_warp_perspective_opr;
    replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;

    // to nchw4
    replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw4;
    replace_func[opr::BatchConvBias::typeinfo()] = replace_inps_to_nchw4;
    return ret;
1761
    MIDOUT_E
1762 1763
}

1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
/* ================ EnableNCHW4Pass ================ */
VarNode* EnableNCHW4Pass::on_graph_endpoint_var(VarNode* new_var,
                                                VarNode* orig_var) const {
    if (!orig_var->shape().eq_shape(new_var->shape())) {
        return RelayoutPlaceholder::make(
                       new_var, RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
                .node();
    }
    return new_var;
}

1775
//! FIXME: All float oprs do not support NCHW4. Supports it in the future plz.
M
Megvii Engine Team 已提交
1776
std::unique_ptr<EnableNCHW4Pass> EnableNCHW4Pass::make_nchw4_converter() {
1777
    MIDOUT_B("EnableNCHW4Pass::make")
1778 1779 1780 1781 1782
    auto ret = std::make_unique<EnableNCHW4Pass>();
    ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
    using RelayoutMode = RelayoutPlaceholder::LayoutType;
    megdnn::param::Convolution::Format conv_format =
            megdnn::param::Convolution::Format::NCHW4;
1783
    megdnn::param::ConvBias::Format conv_bias_format =
1784
            megdnn::param::ConvBias::Format::NCHW4;
1785 1786
    megdnn::param::ConvBias::Format conv_bias_format_nchw4_nchw =
            megdnn::param::ConvBias::Format::NCHW4_NCHW;
1787 1788 1789 1790
    megdnn::param::BatchConvBias::Format batch_conv_bias_format =
            megdnn::param::BatchConvBias::Format::NCHW4;
    RelayoutMode src_to_nchw4_mode = RelayoutMode::NCHW_TO_NCHW4;
    RelayoutMode src_to_nchw_mode = RelayoutMode::NCHW4_TO_NCHW;
1791
    RelayoutMode weight_to_nchw4_mode_dense =
1792
            RelayoutMode::WEIGHT_NCHW_TO_NCHW4_DENSE;
1793
    RelayoutMode weight_to_nchw4_mode_group =
1794
            RelayoutMode::WEIGHT_NCHW_TO_NCHW4_GROUP;
1795

1796 1797 1798 1799 1800 1801 1802 1803
    struct ConvMode {
        RelayoutMode weight;
        RelayoutMode src;
    };

    auto trans_nchw4 =
            [weight_to_nchw4_mode_dense, weight_to_nchw4_mode_group,
             src_to_nchw4_mode](
1804
                    const megdnn::param::Convolution::Sparse conv_mode,
1805
                    const VarNode* filter) -> ConvMode {
1806 1807 1808 1809
        if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
            mgb_assert(filter->shape().ndim == 4,
                       "The origin filter is not NCHW mode");
            size_t IC = filter->shape()[1];
1810 1811 1812 1813 1814 1815
            if (IC < 4) {
                return {RelayoutMode::WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV,
                        RelayoutMode::NCHW_TO_NCHW4_IC_SMALL_CONV};
            } else {
                return {weight_to_nchw4_mode_dense, src_to_nchw4_mode};
            }
1816
        } else {
1817 1818
            mgb_throw_if(conv_mode != megdnn::param::Convolution::Sparse::GROUP,
                         MegBrainError, "mode error");
1819 1820 1821 1822
            mgb_assert(filter->shape().ndim == 5,
                       "The origin filter if not NCHW mode");
            size_t IC = filter->shape()[2];
            mgb_assert(IC % 4 == 0,
1823 1824 1825
                       "The input channel should be divisible by 4 for group "
                       "conv");
            return {weight_to_nchw4_mode_group, src_to_nchw4_mode};
1826 1827
        }
    };
1828 1829 1830
    auto replace_conv_opr = [trans_nchw4, conv_format](
                                    OperatorNodeBase* opr,
                                    const VarNodeArray& new_inp) {
1831 1832 1833 1834
        if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
1835 1836
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
1837 1838 1839 1840 1841
        if (conv_opr.param().format !=
            megdnn::param::Convolution::Format::NCHW) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
M
Megvii Engine Team 已提交
1842
        auto conv_mode = trans_nchw4(conv_opr.param().sparse, new_inp[1]);
1843 1844 1845 1846
        VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
        // src: NCHW --> NCWH4
        if (new_inp[0]->shape().ndim != 5) {
            mgb_assert(new_inp[0]->shape().ndim == 4);
M
Megvii Engine Team 已提交
1847
            auto new_src = RelayoutPlaceholder::make(new_inp[0], conv_mode.src);
1848 1849 1850
            conv_src = new_src.node();
        }
        // weight: NCHW --> NCHW4
1851 1852
        auto new_filter =
                RelayoutPlaceholder::make(new_inp[1], conv_mode.weight);
1853 1854 1855 1856 1857 1858
        conv_filter = new_filter.node();
        // format: NCHW --> NCHW4
        auto new_param = conv_opr.param();
        new_param.format = conv_format;
        // dst
        auto new_conv_opr = opr::Convolution::make(
M
Megvii Engine Team 已提交
1859 1860
                conv_src, conv_filter, new_param, conv_opr.execution_policy(),
                conv_opr.config());
1861 1862
        OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
        mgb_assert(new_conv_opr.shape().ndim == 5,
M
Megvii Engine Team 已提交
1863
                   "The conv dst dim is not trans to nchw4");
1864 1865 1866
        return new_opr;
    };

1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    auto replace_deconv_opr = [trans_nchw4, conv_format](
                                    OperatorNodeBase* opr,
                                    const VarNodeArray& new_inp) {
        if (new_inp[1]->dtype().enumv() == DTypeEnum::Float32) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
        mgb_assert(opr->input().size() == new_inp.size());
        auto& deconv_opr = opr->cast_final_safe<opr::ConvolutionBackwardData>();
        if ((deconv_opr.param().format !=
             megdnn::param::Convolution::Format::NCHW) ||
            (deconv_opr.param().sparse !=
             megdnn::param::Convolution::Sparse::DENSE)) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
        VarNode *deconv_src = new_inp[1], *deconv_filter = new_inp[0];
        auto deconv_mode = trans_nchw4(deconv_opr.param().sparse, deconv_filter);
        // src: NCHW --> NCWH4
        if (deconv_src->shape().ndim != 5) {
            mgb_assert(deconv_src->shape().ndim == 4);
            auto new_src =
                    RelayoutPlaceholder::make(deconv_src, deconv_mode.src);
            deconv_src = new_src.node();
        }
        // weight: NCHW --> NCHW4
        auto new_filter =
                RelayoutPlaceholder::make(deconv_filter, deconv_mode.weight);
        deconv_filter = new_filter.node();
        // format: NCHW --> NCHW4
        auto new_param = deconv_opr.param();
        new_param.format = conv_format;
        // dst
        auto new_deconv_opr = opr::ConvolutionBackwardData::make_deconv(
                deconv_src, deconv_filter, new_param,
                deconv_opr.execution_policy(), deconv_opr.config());
        OperatorNodeBase* new_opr = new_deconv_opr.node()->owner_opr();
        return new_opr;
    };

1907
    auto replace_batch_conv_bias_opr = [batch_conv_bias_format,
M
Megvii Engine Team 已提交
1908 1909 1910
                                        src_to_nchw4_mode](
                                               OperatorNodeBase* opr,
                                               const VarNodeArray& new_inp) {
1911 1912 1913 1914
        if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
1915 1916
        mgb_assert(opr->input().size() == new_inp.size());
        auto& batch_conv_bias_opr =
M
Megvii Engine Team 已提交
1917
                opr->cast_final_safe<opr::BatchConvBiasForward>();
1918 1919 1920 1921 1922 1923 1924
        if (batch_conv_bias_opr.param().format !=
            megdnn::param::BatchConvBias::Format::NCHW) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }

        mgb_assert(batch_conv_bias_opr.param().format ==
1925 1926 1927 1928 1929
                           megdnn::param::BatchConvBias::Format::NCHW,
                   "ConvertFormat Pass only support converting NCHW to NCHW4");
        // what should be converted: src, weight
        VarNode *src = new_inp[0], *filter = new_inp[1];
        // src: NCHW --> NCHW4
M
Megvii Engine Team 已提交
1930
        if (new_inp[0]->shape().ndim != 5) {
1931
            mgb_assert(new_inp[0]->shape().ndim == 4);
M
Megvii Engine Team 已提交
1932 1933
            auto new_src =
                    RelayoutPlaceholder::make(new_inp[0], src_to_nchw4_mode);
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
            src = new_src.node();
        }
        // weight: BNCHW --> BNCHW4
        // only support dense mode, which is similar with conv->group.
        auto weight_mode =
                RelayoutPlaceholder::LayoutType::WEIGHT_NCHW_TO_NCHW4_GROUP;
        auto new_filter = RelayoutPlaceholder::make(new_inp[1], weight_mode);
        filter = new_filter.node();
        // format: NCHW --> NCHW4
        auto new_param = batch_conv_bias_opr.param();
        new_param.format = batch_conv_bias_format;
        if (new_inp.size() == 2) {
M
Megvii Engine Team 已提交
1946 1947 1948 1949
            auto dst = opr::BatchConvBias::make(
                    src, filter, new_param,
                    batch_conv_bias_opr.execution_policy(),
                    batch_conv_bias_opr.config());
1950 1951 1952 1953 1954 1955 1956 1957
            OperatorNodeBase* new_opr = dst.node()->owner_opr();
            mgb_assert(dst.shape().ndim == 5,
                       "The conv_bias dst dim is not trans to nchw4");
            return new_opr;
        }
        // bias: NCHW --> NCHW4
        VarNode* bias = new_inp[2];
        if (new_inp[2]->shape().ndim == 4) {
M
Megvii Engine Team 已提交
1958 1959
            auto new_bias =
                    RelayoutPlaceholder::make(new_inp[2], src_to_nchw4_mode);
1960 1961 1962
            bias = new_bias.node();
        }
        if (new_inp.size() == 3) {
M
Megvii Engine Team 已提交
1963 1964 1965 1966
            auto dst = opr::BatchConvBias::make(
                    src, filter, bias, new_param,
                    batch_conv_bias_opr.execution_policy(),
                    batch_conv_bias_opr.config());
1967 1968 1969 1970 1971 1972 1973 1974
            OperatorNodeBase* new_opr = dst.node()->owner_opr();
            mgb_assert(dst.shape().ndim == 5,
                       "The conv_bias dst dim is not trans to nchw4");
            return new_opr;
        }
        // z_inp: NCHW --> NCHW4
        VarNode* z_inp = new_inp[3];
        if (new_inp[3]->shape().ndim == 4) {
M
Megvii Engine Team 已提交
1975 1976
            auto new_z =
                    RelayoutPlaceholder::make(new_inp[3], src_to_nchw4_mode);
1977 1978
            z_inp = new_z.node();
        }
M
Megvii Engine Team 已提交
1979 1980 1981 1982
        auto dst =
                opr::BatchConvBias::make(src, filter, bias, z_inp, new_param,
                                         batch_conv_bias_opr.execution_policy(),
                                         batch_conv_bias_opr.config());
1983 1984 1985 1986 1987 1988
        OperatorNodeBase* new_opr = dst.node()->owner_opr();
        mgb_assert(dst.shape().ndim == 5,
                   "The conv_bias dst dim is not trans to nchw4");
        return new_opr;
    };
    auto replace_conv_bias_opr = [trans_nchw4, conv_bias_format,
1989
                                  conv_bias_format_nchw4_nchw,
1990
                                  src_to_nchw4_mode](
1991 1992
                                         OperatorNodeBase* opr,
                                         const VarNodeArray& new_inp) {
1993 1994 1995 1996
        if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
1997 1998
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
1999 2000 2001 2002 2003 2004
        if (conv_bias_opr.param().format !=
            megdnn::param::Convolution::Format::NCHW) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }

2005 2006
        // what should be converted: src, weight
        VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1];
M
Megvii Engine Team 已提交
2007
        auto conv_mode = trans_nchw4(conv_bias_opr.param().sparse, new_inp[1]);
2008
        // src: NCHW --> NCHW4
2009
        if (new_inp[0]->shape().ndim != 5) {
2010
            mgb_assert(new_inp[0]->shape().ndim == 4);
M
Megvii Engine Team 已提交
2011
            auto new_src = RelayoutPlaceholder::make(new_inp[0], conv_mode.src);
2012 2013 2014
            conv_bias_src = new_src.node();
        }
        // weight: NCHW --> NCHW4 or GNCHW --> GNCHW4
2015 2016
        auto new_filter =
                RelayoutPlaceholder::make(new_inp[1], conv_mode.weight);
2017 2018 2019
        conv_bias_filter = new_filter.node();
        // format: NCHW --> NCHW4
        auto new_param = conv_bias_opr.param();
2020 2021 2022 2023 2024 2025
        if (conv_bias_opr.output().size() > 0 &&
            conv_bias_opr.output(0)->dtype().enumv() == DTypeEnum::Float32) {
            new_param.format = conv_bias_format_nchw4_nchw;
        } else {
            new_param.format = conv_bias_format;
        }
2026 2027
        if (new_inp.size() == 2) {
            auto new_conv_bias_opr = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2028 2029
                    conv_bias_src, conv_bias_filter, new_param,
                    conv_bias_opr.execution_policy(), conv_bias_opr.config());
2030
            OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
2031 2032 2033 2034
            mgb_assert(
                new_conv_bias_opr.node()->dtype().enumv() == DTypeEnum::Float32 ||
                new_conv_bias_opr.shape().ndim == 5,
                "The conv_bias dst dim is not trans to nchw4");
2035 2036
            return new_opr;
        }
2037
        // bias: NCHW --> NCHW4 when bias_dtype is not Float32
2038
        VarNode* conv_bias_bias = new_inp[2];
2039 2040
        if (new_inp[2]->dtype().enumv() != DTypeEnum::Float32 &&
            new_inp[2]->shape().ndim == 4) {
2041 2042
            auto new_bias =
                    RelayoutPlaceholder::make(new_inp[2], src_to_nchw4_mode);
2043 2044 2045 2046
            conv_bias_bias = new_bias.node();
        }
        if (new_inp.size() == 3) {
            auto new_conv_bias_opr = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2047 2048
                    conv_bias_src, conv_bias_filter, conv_bias_bias, new_param,
                    conv_bias_opr.execution_policy(), conv_bias_opr.config());
2049
            OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
2050 2051 2052 2053
            mgb_assert(
                new_conv_bias_opr.node()->dtype().enumv() == DTypeEnum::Float32 ||
                new_conv_bias_opr.shape().ndim == 5,
                "The conv_bias dst dim is not trans to nchw4");
2054 2055
            return new_opr;
        }
2056
        // z_inp: NCHW --> NCHW4 when bias_dtype is not Float32
2057
        VarNode* z_inp = new_inp[3];
2058 2059
        if (new_inp[3]->dtype().enumv() != DTypeEnum::Float32 &&
            new_inp[3]->shape().ndim == 4) {
2060 2061
            auto new_z =
                    RelayoutPlaceholder::make(new_inp[3], src_to_nchw4_mode);
2062 2063
            z_inp = new_z.node();
        }
M
Megvii Engine Team 已提交
2064 2065 2066 2067
        auto new_conv_bias_opr = opr::ConvBias::make(
                conv_bias_src, conv_bias_filter, conv_bias_bias, z_inp,
                new_param, conv_bias_opr.execution_policy(),
                conv_bias_opr.config());
2068
        OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
2069 2070 2071 2072
        mgb_assert(
            new_conv_bias_opr.node()->dtype().enumv() == DTypeEnum::Float32 ||
            new_conv_bias_opr.shape().ndim == 5,
            "The conv_bias dst dim is not trans to nchw4");
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
        return new_opr;
    };
    auto replace_elemwise_opr = [=](OperatorNodeBase* opr,
                                    const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        bool has_inp_changed = false;
        for (size_t i = 0; i < opr->input().size(); i++) {
            if (new_inp[i]->shape().ndim == 5) {
                has_inp_changed = true;
                break;
            }
        }
        if (has_inp_changed) {
            auto temp_inp = new_inp;
            for (size_t i = 0; i < opr->input().size(); i++) {
                if (new_inp[i]->shape().ndim == 4) {
M
Megvii Engine Team 已提交
2089 2090
                    auto new_var = RelayoutPlaceholder::make(new_inp[i],
                                                             src_to_nchw4_mode);
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
                    temp_inp[i] = new_var.node();
                } else {
                    mgb_assert((new_inp[i]->shape().ndim == 5) ||
                               new_inp[i]->shape().is_scalar());
                }
            }
            return serialization::copy_opr_shallow(*opr, temp_inp,
                                                   opr->config());
        } else {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
    };
    auto relayout_inp_to_nchw = [=](OperatorNodeBase* opr,
M
Megvii Engine Team 已提交
2105
                                    const VarNodeArray& new_inp) {
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
        mgb_assert(opr->input().size() == new_inp.size());
        VarNodeArray temp_inp = new_inp;
        for (size_t i = 0; i < opr->input().size(); i++) {
            if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                mgb_assert(opr->input(i)->shape().ndim == 4);
                mgb_assert(new_inp[i]->shape().ndim == 5);
                auto new_var =
                        RelayoutPlaceholder::make(new_inp[i], src_to_nchw_mode);
                temp_inp[i] = new_var.node();
            }
        }
        return serialization::copy_opr_shallow(*opr, temp_inp, opr->config());
    };
2119 2120
    auto replace_pooling_opr = [](OperatorNodeBase* opr,
                                  const VarNodeArray& new_inp) {
2121 2122 2123 2124
        if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
2125 2126 2127 2128
        using Param = opr::PoolingForward::Param;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
2129 2130 2131
        if (pooling.param().format != Format::NCHW) {
            return opr;
        }
2132 2133 2134 2135
        if (new_inp[0]->shape().ndim == 5) {
            mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
            auto new_param = pooling.param();
            new_param.format = Format::NCHW4;
M
Megvii Engine Team 已提交
2136 2137
            auto new_pooling = opr::PoolingForward::make(new_inp[0], new_param,
                                                         opr->config());
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
            mgb_assert(new_pooling.shape().ndim == 5,
                       "out var of Pooling opr after transform must be 5 (got: "
                       "%zu).",
                       new_pooling.shape().ndim);
            return new_pooling.node()->owner_opr();
        }
        auto new_opr =
                serialization::copy_opr_shallow(*opr, new_inp, opr->config());
        return new_opr;
    };
    auto replace_resize_opr = [](OperatorNodeBase* opr,
                                 const VarNodeArray& new_inp) {
2150 2151 2152 2153
        if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
        using Param = opr::ResizeForward::Param;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& resize = opr->cast_final_safe<opr::ResizeForward>();
        if (new_inp[0]->shape().ndim == 5) {
            mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
            auto new_param = resize.param();
            new_param.format = Format::NCHW4;
            auto new_resize = opr::ResizeForward::make(
                    new_inp[0], new_inp[1], new_param, opr->config());
            mgb_assert(new_resize.shape().ndim == 5,
                       "out var of Resize opr after transform must be 5 (got: "
                       "%zu).",
                       new_resize.shape().ndim);
            return new_resize.node()->owner_opr();
        }
        auto new_opr =
                serialization::copy_opr_shallow(*opr, new_inp, opr->config());
        return new_opr;
    };
    auto replace_warp_perspective_opr = [](OperatorNodeBase* opr,
                                           const VarNodeArray& new_inp) {
2176 2177 2178 2179
        if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
        using Param = opr::WarpPerspective::Param;
        using Format = Param::Format;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& warp = opr->cast_final_safe<opr::WarpPerspectiveForward>();
        if (new_inp[0]->shape().ndim == 5) {
            mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
            auto new_param = warp.param();
            new_param.format = Format::NCHW4;
            SymbolVar new_warp;
            if (new_inp.size() == 3) {
                new_warp = opr::WarpPerspectiveForward::make(
                        new_inp[0], new_inp[1], nullptr, new_inp[2], new_param,
                        opr->config());
            } else {
                mgb_assert(new_inp.size() == 4);
                new_warp = opr::WarpPerspectiveForward::make(
                        new_inp[0], new_inp[1], new_inp[2], new_inp[3],
                        new_param, opr->config());
            }
            mgb_assert(new_warp.shape().ndim == 5,
                       "out var of WarpPerspective opr after transform must be "
                       "5 (got: "
                       "%zu).",
                       new_warp.shape().ndim);
            return new_warp.node()->owner_opr();
        }
        auto new_opr =
                serialization::copy_opr_shallow(*opr, new_inp, opr->config());
        return new_opr;
    };
2210 2211 2212
    auto&& replace_func = ret->m_opr_replace_func;
    //! supportted nchw4
    replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
2213 2214
    replace_func[opr::ConvolutionBackwardData::typeinfo()] =
            replace_deconv_opr;
2215
    replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
M
Megvii Engine Team 已提交
2216
    replace_func[opr::BatchConvBias::typeinfo()] = replace_batch_conv_bias_opr;
2217 2218 2219 2220
    replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
    replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
    replace_func[opr::WarpPerspectiveForward::typeinfo()] =
            replace_warp_perspective_opr;
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
    replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_opr;
    replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_opr;
    replace_func[opr::ElemwiseMultiType::typeinfo()] = replace_elemwise_opr;
    replace_func[opr::PowC::typeinfo()] = replace_elemwise_opr;
    //! not supported nchw4
    replace_func[opr::Concat::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::Subtensor::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::GetVarShape::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::Dimshuffle::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::Reduce::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::AssertEqual::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::IncrSubtensor::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::WarpAffineForward::typeinfo()] = relayout_inp_to_nchw;
    return ret;
2235
    MIDOUT_E
2236 2237
}

2238 2239 2240 2241
/* ================ EnableNchwxxPass =============== */
VarNode* EnableNchwxxPass::on_graph_endpoint_var(VarNode* new_var,
                                                 VarNode* orig_var) const {
    if (!orig_var->shape().eq_shape(new_var->shape())) {
2242 2243 2244 2245 2246 2247 2248 2249
        if (m_pack_c_size == 8) {
            return RelayoutPlaceholder::make(
                           new_var,
                           RelayoutPlaceholder::LayoutType::NCHW88_TO_NCHW)
                    .node();
        } else if (m_pack_c_size == 4) {
            return RelayoutPlaceholder::make(
                           new_var,
2250
                           RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
2251 2252
                    .node();
        }
2253 2254 2255
    }
    return new_var;
}
2256

2257 2258 2259 2260 2261 2262 2263 2264 2265
static inline TensorShape nchwxx_shape_2_nchw_shape(
        const TensorShape& origin_shape) {
    mgb_assert(origin_shape.ndim == 5);
    TensorShape result = origin_shape;
    result[1] *= result[4];
    result.ndim = 4;
    return result;
}

2266
template <typename OprType>
2267 2268 2269 2270 2271 2272 2273 2274
static inline bool nchw_nchwxx_valid(
        const OprType& opr, const VarNodeArray& new_inp, const size_t pack_size,
        megdnn::param::ConvBias::NonlineMode nonline_mode =
                megdnn::param::ConvBias::NonlineMode::IDENTITY,
        bool is_dot = false) {
    auto& src_node = new_inp[0];
    auto& filter_node = new_inp[1];
    auto dst_node = opr.output(0);
2275 2276
    //! already transformed or have fuse Z
    if (filter_node->shape().ndim != 4 || new_inp.size() == 4) {
2277 2278
        return false;
    }
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
    megdnn::ConvolutionBase<megdnn::param::Convolution>::CanonizedFilterMeta fm;
    fm.format = megdnn::param::Convolution::Format::NCHW;
    fm.should_flip =
            opr.param().mode == megdnn::ConvBiasForward::Mode::CONVOLUTION;
    fm.group = 1;
    fm.spatial_ndim = 2;
    fm.ocpg = filter_node->shape()[0];
    fm.icpg = filter_node->shape()[1];
    fm.spatial[0] = filter_node->shape()[2];
    fm.spatial[1] = filter_node->shape()[3];
    fm.stride[0] = opr.param().stride_h;
    fm.stride[1] = opr.param().stride_w;
    fm.padding[0] = opr.param().pad_h;
    fm.padding[1] = opr.param().pad_w;
    fm.dilation[0] = opr.param().dilate_h;
    fm.dilation[1] = opr.param().dilate_w;

    megdnn::ConvBiasForward::BiasMode bias_mode =
            megdnn::ConvBiasForward::BiasMode::NO_BIAS;
2298 2299
    if (std::is_same<OprType, opr::ConvBiasForward>::value &&
        new_inp.size() > 2) {
2300 2301 2302 2303
        TensorShape bias_shape = new_inp[2]->shape();
        if (bias_shape.ndim == 5) {
            bias_shape = nchwxx_shape_2_nchw_shape(bias_shape);
        }
2304 2305 2306 2307 2308 2309 2310 2311 2312
        if (bias_shape.ndim == 0) {
            bias_mode = megdnn::ConvBiasForward::BiasMode::NO_BIAS;
        } else if (bias_shape.eq_shape(dst_node->shape())) {
            bias_mode = megdnn::ConvBiasForward::BiasMode::BIAS;
        } else {
            //! just check the ndim, the detail shape check is in check_exec
            mgb_assert(bias_shape.ndim == dst_node->shape().ndim);
            bias_mode =
                    megdnn::ConvBiasForward::BiasMode::BROADCAST_CHANNEL_BIAS;
2313 2314 2315
        }
    }

2316 2317 2318 2319 2320
    if (pack_size == 4) {
        if (is_dot && filter_node->dtype().enumv() == DTypeEnum::QuantizedS8) {
            fm.format = megdnn::param::Convolution::Format::NCHW44_DOT;
        } else {
            fm.format = megdnn::param::Convolution::Format::NCHW44;
2321
        }
2322 2323 2324 2325
    } else if (pack_size == 8) {
        fm.format = megdnn::param::Convolution::Format::NCHW88;
    } else {
        mgb_assert(0, "only support nchw44 nchw88");
2326 2327
    }

2328 2329 2330
    return megdnn::ConvBiasForward::is_nchw_nchwxx_optimized(
            src_node->dtype().enumv(), filter_node->dtype().enumv(),
            dst_node->dtype().enumv(), fm, bias_mode, nonline_mode);
2331
}
2332

M
Megvii Engine Team 已提交
2333
void EnableNchwxxPass::fill_opr_convert_fun(size_t pack_c_size) {
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
    using RelayoutMode = RelayoutPlaceholder::LayoutType;
    using TestFilterResult = std::pair<TransType, RelayoutMode>;
    RelayoutMode weight_to_nchwxx_mode_dense =
            RelayoutMode::WEIGHT_NCHW_TO_NCHW88_DENSE;
    RelayoutMode weight_to_nchwxx_mode_group =
            RelayoutMode::WEIGHT_NCHW_TO_NCHW88_GROUP;
    RelayoutMode weight_to_nchwxx_mode_chan =
            RelayoutMode::WEIGHT_NCHW_TO_NCHW88_CHAN;
    RelayoutMode hybrid_nchw_nchwxx = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW88;
    RelayoutMode src_to_nchwxx_mode = RelayoutMode::NCHW_TO_NCHW88;
    RelayoutMode src_to_nchw_mode = RelayoutMode::NCHW88_TO_NCHW;
    megdnn::param::ConvBias::Format conv_bias_format =
            megdnn::param::ConvBias::Format::NCHW88;
    megdnn::param::Convolution::Format conv_format =
2348
            megdnn::param::Convolution::Format::NCHW88;
2349 2350 2351
    megdnn::param::Pooling::Format pooling_format =
            megdnn::param::Pooling::Format::NCHW88;
    std::string convter_pass_name = "conv_format_nchw88";
2352

2353 2354 2355 2356 2357
    if (pack_c_size == 4) {
        weight_to_nchwxx_mode_dense = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DENSE;
        weight_to_nchwxx_mode_group = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_GROUP;
        weight_to_nchwxx_mode_chan = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_CHAN;
        hybrid_nchw_nchwxx = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW44;
2358 2359
        src_to_nchwxx_mode = RelayoutMode::NCHW_TO_NCHW4;
        src_to_nchw_mode = RelayoutMode::NCHW4_TO_NCHW;
2360
        conv_bias_format = megdnn::param::ConvBias::Format::NCHW44;
2361
        conv_format = megdnn::param::Convolution::Format::NCHW44;
2362 2363 2364
        pooling_format = megdnn::param::Pooling::Format::NCHW44;
        convter_pass_name = "conv_format_nchw44";
    }
2365 2366 2367 2368 2369
    auto test_trans_nchwxx =
            [pack_c_size, weight_to_nchwxx_mode_dense,
             weight_to_nchwxx_mode_group, weight_to_nchwxx_mode_chan,
             hybrid_nchw_nchwxx](
                    const megdnn::param::Convolution::Sparse conv_mode,
2370
                    const VarNode* filter, const size_t stride_h,
2371 2372
                    const size_t stride_w,
                    bool valid_nchw_nchw44) -> TestFilterResult {
2373 2374 2375
        TestFilterResult ret{TransType::TRANS_NONE, {}};
        if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
            size_t OC = filter->shape()[0];
2376
            size_t IC = filter->shape()[1];
2377 2378 2379
            if ((IC % pack_c_size == 0) && (OC % pack_c_size == 0)) {
                ret.first = TransType::TRANS_PURE_NCHWXX;
                ret.second = weight_to_nchwxx_mode_dense;
2380
            } else if (valid_nchw_nchw44) {
2381 2382 2383 2384
                ret.first = TransType::TRANS_HYBIRD_NCHWXX;
                ret.second = hybrid_nchw_nchwxx;
            }
        } else {
2385 2386
            mgb_throw_if(conv_mode != megdnn::param::Convolution::Sparse::GROUP,
                         MegBrainError, "mode error");
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
            size_t group = filter->shape()[0];
            size_t ocpg = filter->shape()[1];
            size_t icpg = filter->shape()[2];
            if (icpg == 1 && ocpg == 1 && (group % pack_c_size == 0)) {
                ret.first = TransType::TRANS_PURE_NCHWXX;
                ret.second = weight_to_nchwxx_mode_chan;
            } else if ((icpg % pack_c_size == 0) && (ocpg % pack_c_size == 0)) {
                ret.first = TransType::TRANS_PURE_NCHWXX;
                ret.second = weight_to_nchwxx_mode_group;
            }
        }
        return ret;
    };
    auto replace_conv_opr = [test_trans_nchwxx, conv_format, src_to_nchwxx_mode,
2401 2402 2403
                             src_to_nchw_mode,
                             pack_c_size](OperatorNodeBase* opr,
                                          const VarNodeArray& new_inp) {
2404 2405
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
2406 2407 2408 2409 2410
        mgb_throw_if(
                conv_opr.param().format !=
                        megdnn::param::Convolution::Format::NCHW,
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NCHWXX");
2411
        bool valid_nchw_nchw44 =
2412
                nchw_nchwxx_valid(conv_opr, new_inp, pack_c_size);
2413 2414 2415
        auto is_trans = test_trans_nchwxx(
                conv_opr.param().sparse, new_inp[1], conv_opr.param().stride_h,
                conv_opr.param().stride_w, valid_nchw_nchw44);
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
        //! can not trans to nchwxx
        if (is_trans.first == TransType::TRANS_NONE) {
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
            VarNodeArray temp_inp = new_inp;
            //! if src is nchwxx, should RelayoutPlaceholder to nchw
            if (temp_inp[0]->shape().ndim == 5) {
                auto new_src =
                        RelayoutPlaceholder::make(new_inp[0], src_to_nchw_mode);
                temp_inp[0] = new_src.node();
            }
            auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
                                                           opr->config());
            return new_opr;
        } else if (is_trans.first == TransType::TRANS_PURE_NCHWXX) {
            //! filter trans to nchwxx mode
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
            VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
            auto new_filter =
                    RelayoutPlaceholder::make(new_inp[1], is_trans.second);
            conv_filter = new_filter.node();
            //! src trans to nchwxx mode
            if (new_inp[0]->shape().ndim != 5) {
                mgb_assert(new_inp[0]->shape().ndim == 4);
                auto new_src = RelayoutPlaceholder::make(new_inp[0],
                                                         src_to_nchwxx_mode);
                conv_src = new_src.node();
            }
            auto new_param = conv_opr.param();
            new_param.format = conv_format;
            mgb_assert(conv_src->shape().ndim == 5 &&
                               conv_filter->shape().ndim >= 6,
                       "The conv src dim is not trans to nchwxx");
            auto new_conv_opr = opr::Convolution::make(
                    conv_src, conv_filter, new_param,
                    conv_opr.execution_policy(), conv_opr.config());
            OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
            mgb_assert(new_conv_opr.shape().ndim == 5,
                       "The conv dst dim is not trans to nchwxx");
            return new_opr;
        } else {
            mgb_assert(is_trans.first == TransType::TRANS_HYBIRD_NCHWXX);
            VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
            auto new_filter =
                    RelayoutPlaceholder::make(new_inp[1], is_trans.second);
            conv_filter = new_filter.node();
            mgb_assert(conv_src->shape().ndim == 4 &&
                               conv_filter->shape().ndim == 5,
                       "The src and filter is OK");
            auto new_param = conv_opr.param();
            new_param.format = conv_format;
            auto new_conv_opr = opr::Convolution::make(
                    conv_src, conv_filter, new_param,
                    conv_opr.execution_policy(), conv_opr.config());
            OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
            mgb_assert(new_conv_opr.shape().ndim == 5,
                       "The conv dst dim is not trans to nchwxx");
            return new_opr;
        }
    };

    auto replace_conv_bias_opr = [test_trans_nchwxx, conv_bias_format,
2481 2482 2483
                                  src_to_nchwxx_mode, src_to_nchw_mode,
                                  pack_c_size](OperatorNodeBase* opr,
                                               const VarNodeArray& new_inp) {
2484
        mgb_assert(opr->input().size() == new_inp.size());
2485 2486
        mgb_assert(opr->input().size() <= 3,
                   "nchwxx does not support conv_bias fuse Z right now");
2487
        auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
2488 2489 2490 2491 2492
        mgb_throw_if(
                conv_bias_opr.param().format !=
                        megdnn::param::ConvBias::Format::NCHW,
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NCHWXX");
2493 2494 2495
        bool valid_nchw_nchw44 =
                nchw_nchwxx_valid(conv_bias_opr, new_inp, pack_c_size,
                                  conv_bias_opr.param().nonlineMode);
2496 2497
        auto is_trans = test_trans_nchwxx(
                conv_bias_opr.param().sparse, new_inp[1],
2498 2499 2500
                conv_bias_opr.param().stride_h, conv_bias_opr.param().stride_w,
                valid_nchw_nchw44);

2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
        //! can not trans to nchwxx
        if (is_trans.first == TransType::TRANS_NONE) {
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
            VarNodeArray temp_inp = new_inp;
            //! if src is nchwxx, should RelayoutPlaceholder to nchw
            if (temp_inp[0]->shape().ndim == 5) {
                auto new_src =
                        RelayoutPlaceholder::make(new_inp[0], src_to_nchw_mode);
                temp_inp[0] = new_src.node();
            }
            //! the bias is nchwxx
2514
            if (new_inp.size() > 2 && temp_inp[2]->shape().ndim == 5) {
2515 2516 2517 2518 2519 2520 2521 2522 2523
                auto new_bias =
                        RelayoutPlaceholder::make(new_inp[2], src_to_nchw_mode);
                temp_inp[2] = new_bias.node();
            }
            auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
                                                           opr->config());
            return new_opr;
        } else if (is_trans.first == TransType::TRANS_PURE_NCHWXX) {
            VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
2524
                    *conv_bias_bias = nullptr;
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
            //! filter trans to nchwxx mode
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
            auto new_filter =
                    RelayoutPlaceholder::make(new_inp[1], is_trans.second);
            conv_bias_filter = new_filter.node();
            //! src trans to nchwxx mode
            if (new_inp[0]->shape().ndim != 5) {
                mgb_assert(new_inp[0]->shape().ndim == 4);
                auto new_src = RelayoutPlaceholder::make(new_inp[0],
                                                         src_to_nchwxx_mode);
                conv_bias_src = new_src.node();
            }
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
            //! bias trans to nchwxx mode
            if (new_inp.size() > 2) {
                if (new_inp[2]->shape().ndim == 4) {
                    auto new_bias = RelayoutPlaceholder::make(
                            new_inp[2], src_to_nchwxx_mode);
                    conv_bias_bias = new_bias.node();
                } else {
                    mgb_assert(new_inp[2]->shape().ndim == 5);
                    conv_bias_bias = new_inp[2];
                }
2549 2550 2551 2552 2553 2554
            }
            auto new_param = conv_bias_opr.param();
            new_param.format = conv_bias_format;
            mgb_assert(conv_bias_src->shape().ndim == 5 &&
                               conv_bias_filter->shape().ndim >= 6,
                       "The conv_bias src dim is not trans to nchwxx");
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
            SymbolVar new_conv_bias_opr;
            if (conv_bias_bias) {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, conv_bias_bias,
                        new_param, conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            } else {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, new_param,
                        conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            }
2567 2568 2569 2570 2571 2572 2573
            OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
            mgb_assert(new_conv_bias_opr.shape().ndim == 5,
                       "The conv_bias dst dim is not trans to nchwxx");
            return new_opr;
        } else {
            mgb_assert(is_trans.first == TransType::TRANS_HYBIRD_NCHWXX);
            VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
2574
                    *conv_bias_bias = nullptr;
2575 2576 2577 2578
            auto new_filter =
                    RelayoutPlaceholder::make(new_inp[1], is_trans.second);
            conv_bias_filter = new_filter.node();
            //! bias trans to nchwxx mode, bias may be scale
2579 2580 2581 2582 2583 2584 2585 2586 2587
            if (new_inp.size() > 2) {
                if (new_inp[2]->shape().ndim == 4) {
                    auto new_bias = RelayoutPlaceholder::make(
                            new_inp[2], src_to_nchwxx_mode);
                    conv_bias_bias = new_bias.node();
                } else {
                    mgb_assert(new_inp[2]->shape().ndim == 5);
                    conv_bias_bias = new_inp[2];
                }
2588 2589 2590 2591 2592
            }
            mgb_assert(conv_bias_src->shape().ndim == 4 &&
                       conv_bias_filter->shape().ndim == 5);
            auto new_param = conv_bias_opr.param();
            new_param.format = conv_bias_format;
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
            SymbolVar new_conv_bias_opr;
            if (conv_bias_bias) {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, conv_bias_bias,
                        new_param, conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            } else {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, new_param,
                        conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            }
2605 2606 2607 2608 2609 2610 2611 2612
            OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
            mgb_assert(new_conv_bias_opr.shape().ndim == 5,
                       "The conv dst dim is not trans to nchwxx");
            return new_opr;
        }
    };

    auto replace_pooling_opr = [=](OperatorNodeBase* opr,
M
Megvii Engine Team 已提交
2613
                                   const VarNodeArray& new_inp) {
2614 2615
        mgb_assert(opr->input().size() == new_inp.size());
        auto& pooling_opr = opr->cast_final_safe<opr::PoolingForward>();
2616 2617 2618 2619 2620
        mgb_throw_if(
                pooling_opr.param().format !=
                        megdnn::param::Pooling::Format::NCHW,
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NCHWxx");
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
        VarNode* inp = new_inp[0];
        //! if input is nchwxx
        if (inp->shape().ndim == 5) {
            auto new_param = pooling_opr.param();
            new_param.format = pooling_format;
            auto new_pooling_opr =
                    opr::PoolingForward::make(inp, new_param, opr->config());
            mgb_assert(new_pooling_opr.shape().ndim == 5,
                       "The pooling dst dim is not trans to nchwxx");
            return new_pooling_opr.node()->owner_opr();
        } else {
            auto new_opr = serialization::copy_opr_shallow(*opr, new_inp,
                                                           opr->config());
            return new_opr;
        }
    };
2637 2638 2639 2640 2641
    //! When input change and all input can convert to nchwxx, this opr will run
    //! in nchwxx mode, else it will run in nchw mode, for example concat and
    //! elemwise opr
    auto replace_multi_inp_opr = [=](OperatorNodeBase* opr,
                                     const VarNodeArray& new_inp) {
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
        mgb_assert(opr->input().size() == new_inp.size());
        bool has_inp_changed = false;
        bool can_exec_ncwxx = true;
        for (size_t i = 0; i < opr->input().size(); i++) {
            if (new_inp[i]->shape().ndim == 5) {
                has_inp_changed = true;
            } else if (new_inp[i]->shape().ndim == 4) {
                if (new_inp[i]->shape()[1] % pack_c_size != 0) {
                    can_exec_ncwxx = false;
                }
2652 2653
            } else if (!new_inp[i]->shape().is_scalar()) {
                can_exec_ncwxx = false;
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
            }
        }
        if (has_inp_changed) {
            auto temp_inp = new_inp;
            if (can_exec_ncwxx) {
                for (size_t i = 0; i < opr->input().size(); i++) {
                    if (new_inp[i]->shape().ndim == 4) {
                        auto new_var = RelayoutPlaceholder::make(
                                new_inp[i], src_to_nchwxx_mode);
                        temp_inp[i] = new_var.node();
                    } else {
                        mgb_assert((new_inp[i]->shape().ndim == 5) ||
                                   new_inp[i]->shape().is_scalar());
                    }
                }
            } else {
                for (size_t i = 0; i < opr->input().size(); i++) {
                    if (new_inp[i]->shape().ndim == 5) {
                        auto new_var = RelayoutPlaceholder::make(
                                new_inp[i], src_to_nchw_mode);
                        temp_inp[i] = new_var.node();
                    }
                }
            }
            return serialization::copy_opr_shallow(*opr, temp_inp,
                                                   opr->config());
        } else {
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
    };

2686
    auto relayout_inp_to_nchw = [=](OperatorNodeBase* opr,
M
Megvii Engine Team 已提交
2687
                                    const VarNodeArray& new_inp) {
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
        mgb_assert(opr->input().size() == new_inp.size());
        VarNodeArray temp_inp = new_inp;
        for (size_t i = 0; i < opr->input().size(); i++) {
            if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
                mgb_assert(opr->input(i)->shape().ndim == 4);
                mgb_assert(new_inp[i]->shape().ndim == 5);
                auto new_var =
                        RelayoutPlaceholder::make(new_inp[i], src_to_nchw_mode);
                temp_inp[i] = new_var.node();
            }
        }
        return serialization::copy_opr_shallow(*opr, temp_inp, opr->config());
    };

2702
    auto&& replace_func = m_opr_replace_func;
2703 2704 2705 2706
    //! supportted nchwxx
    replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
    replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
    replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
2707 2708 2709 2710 2711
    replace_func[opr::Concat::typeinfo()] = replace_multi_inp_opr;
    replace_func[opr::Elemwise::typeinfo()] = replace_multi_inp_opr;
    replace_func[opr::TypeCvt::typeinfo()] = replace_multi_inp_opr;
    replace_func[opr::ElemwiseMultiType::typeinfo()] = replace_multi_inp_opr;
    replace_func[opr::PowC::typeinfo()] = replace_multi_inp_opr;
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    //! not support yet
    replace_func[opr::ConvolutionBackwardData::typeinfo()] =
            relayout_inp_to_nchw;
    replace_func[opr::Subtensor::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::GetVarShape::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::Dimshuffle::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::Reduce::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::AssertEqual::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::IncrSubtensor::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::ResizeForward::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::WarpPerspectiveForward::typeinfo()] =
            relayout_inp_to_nchw;
    replace_func[opr::WarpAffineForward::typeinfo()] = relayout_inp_to_nchw;
2725
    replace_func[opr::Reshape::typeinfo()] = relayout_inp_to_nchw;
2726 2727 2728 2729
    replace_func[opr::AxisAddRemove::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::Argmax::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::Broadcast::typeinfo()] = relayout_inp_to_nchw;
    replace_func[opr::ImmutableTensor::typeinfo()] = relayout_inp_to_nchw;
2730 2731 2732 2733
}

std::unique_ptr<EnableNchwxxPass> EnableNchwxxPass::make_nchwxx_converter(
        size_t pack_c_size) {
2734
    MIDOUT_B("EnableNchwxxPass::make")
2735 2736 2737 2738 2739 2740 2741 2742 2743
    auto ret = std::make_unique<EnableNchwxxPass>(pack_c_size);
    ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
    std::string convter_pass_name = "conv_format_nchw88";
    if (pack_c_size == 4) {
        convter_pass_name = "conv_format_nchw44";
    }
    ret->fill_opr_convert_fun(pack_c_size);
    ret->set_name(convter_pass_name);
    return ret;
2744
    MIDOUT_E
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
}

/* ================ EnableNchw44DotPass =============== */
VarNode* EnableNchw44DotPass::on_graph_endpoint_var(VarNode* new_var,
                                                    VarNode* orig_var) const {
    if (!orig_var->shape().eq_shape(new_var->shape())) {
        return RelayoutPlaceholder::make(
                       new_var, RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
                .node();
    }
    return new_var;
}

std::unique_ptr<EnableNchw44DotPass>
EnableNchw44DotPass::make_nchw44_dot_converter() {
2760
    MIDOUT_B("EnableNchw44DotPass::make")
2761 2762
    auto ret = std::make_unique<EnableNchw44DotPass>();
    ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
2763 2764
    //! First is whether the conv can trans to nchwxx, second is the filter
    //! trans mode
2765

2766
    using RelayoutMode = RelayoutPlaceholder::LayoutType;
2767 2768 2769
    struct TestTransResult {
        TransType trans_type;
        RelayoutMode relayout_mod;
2770
        megdnn::param::Convolution::Format conv_format;
2771
    };
2772 2773 2774
    constexpr size_t pack_c_size = 4_z;
    auto test_trans_nchw44_dot =
            [](const megdnn::param::Convolution::Sparse conv_mode,
2775
               const VarNode* filter, const size_t stride_h,
2776 2777
               const size_t stride_w,
               const bool valid_nchw_nchw44) -> TestTransResult {
2778
        TestTransResult ret{TransType::TRANS_NONE, {}, {}};
2779 2780
        bool is_int8 = filter->dtype().enumv() == DTypeEnum::QuantizedS8 ||
                       filter->dtype().enumv() == DTypeEnum::Int8;
2781 2782
        if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
            size_t OC = filter->shape()[0];
2783
            size_t IC = filter->shape()[1];
2784
            if ((IC % pack_c_size == 0) && (OC % pack_c_size == 0)) {
2785
                ret.trans_type = TransType::TRANS_PURE_NCHWXX;
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
                if (is_int8) {
                    ret.relayout_mod =
                            RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DOT_DENSE;
                    ret.conv_format =
                            megdnn::param::ConvBias::Format::NCHW44_DOT;
                } else {
                    ret.relayout_mod =
                            RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DENSE;
                    ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
                }
            } else if (valid_nchw_nchw44) {
2797 2798
                ret.trans_type = TransType::TRANS_HYBIRD_NCHWXX;
                ret.relayout_mod = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW44;
2799 2800 2801 2802 2803 2804
                if (is_int8) {
                    ret.conv_format =
                            megdnn::param::ConvBias::Format::NCHW44_DOT;
                } else {
                    ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
                }
2805 2806
            }
        } else {
2807 2808
            mgb_throw_if(conv_mode != megdnn::param::Convolution::Sparse::GROUP,
                         MegBrainError, "mode error");
2809 2810 2811 2812
            size_t group = filter->shape()[0];
            size_t ocpg = filter->shape()[1];
            size_t icpg = filter->shape()[2];
            if (icpg == 1 && ocpg == 1 && (group % pack_c_size == 0)) {
2813 2814 2815
                ret.trans_type = TransType::TRANS_PURE_NCHWXX;
                ret.relayout_mod = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_CHAN;
                ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
2816
            } else if ((icpg % pack_c_size == 0) && (ocpg % pack_c_size == 0)) {
2817
                ret.trans_type = TransType::TRANS_PURE_NCHWXX;
2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
                if (is_int8) {
                    ret.relayout_mod =
                            RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DOT_GROUP;
                    ret.conv_format =
                            megdnn::param::ConvBias::Format::NCHW44_DOT;
                } else {
                    ret.relayout_mod =
                            RelayoutMode::WEIGHT_NCHW_TO_NCHW44_GROUP;
                    ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
                }
2828 2829 2830 2831
            }
        }
        return ret;
    };
2832
    auto replace_conv_opr = [test_trans_nchw44_dot](
2833 2834 2835 2836
                                    OperatorNodeBase* opr,
                                    const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
2837 2838 2839 2840 2841
        mgb_throw_if(conv_opr.param().format !=
                             megdnn::param::Convolution::Format::NCHW,
                     MegBrainError,
                     "ConvertFormat Pass only support converting NCHW to "
                     "NCHW44_DOT");
2842 2843 2844
        bool valid_nchw_nchw44 = nchw_nchwxx_valid(
                conv_opr, new_inp, pack_c_size,
                megdnn::param::ConvBias::NonlineMode::IDENTITY, true);
2845 2846
        auto is_trans = test_trans_nchw44_dot(
                conv_opr.param().sparse, new_inp[1], conv_opr.param().stride_h,
2847
                conv_opr.param().stride_w, valid_nchw_nchw44);
2848
        //! can not trans to nchwxx
2849
        if (is_trans.trans_type == TransType::TRANS_NONE) {
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
            VarNodeArray temp_inp = new_inp;
            //! if src is nchwxx, should RelayoutPlaceholder to nchw
            if (temp_inp[0]->shape().ndim == 5) {
                auto new_src = RelayoutPlaceholder::make(
                        new_inp[0], RelayoutMode::NCHW4_TO_NCHW);
                temp_inp[0] = new_src.node();
            }
            auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
                                                           opr->config());
            return new_opr;
2863
        } else if (is_trans.trans_type == TransType::TRANS_PURE_NCHWXX) {
2864 2865 2866 2867 2868
            //! filter trans to nchwxx mode
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
            VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
2869 2870
            auto new_filter = RelayoutPlaceholder::make(new_inp[1],
                                                        is_trans.relayout_mod);
2871 2872 2873 2874 2875 2876 2877 2878 2879
            conv_filter = new_filter.node();
            //! src trans to nchwxx mode
            if (new_inp[0]->shape().ndim != 5) {
                mgb_assert(new_inp[0]->shape().ndim == 4);
                auto new_src = RelayoutPlaceholder::make(
                        new_inp[0], RelayoutMode::NCHW_TO_NCHW4);
                conv_src = new_src.node();
            }
            auto new_param = conv_opr.param();
2880
            new_param.format = is_trans.conv_format;
2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
            mgb_assert(conv_src->shape().ndim == 5 &&
                               conv_filter->shape().ndim >= 6,
                       "The conv src dim is not trans to nchwxx");
            auto new_conv_opr = opr::Convolution::make(
                    conv_src, conv_filter, new_param,
                    conv_opr.execution_policy(), conv_opr.config());
            OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
            mgb_assert(new_conv_opr.shape().ndim == 5,
                       "The conv dst dim is not trans to nchwxx");
            return new_opr;
        } else {
2892
            mgb_assert(is_trans.trans_type == TransType::TRANS_HYBIRD_NCHWXX);
2893
            VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
2894 2895
            auto new_filter = RelayoutPlaceholder::make(new_inp[1],
                                                        is_trans.relayout_mod);
2896 2897 2898 2899 2900
            conv_filter = new_filter.node();
            mgb_assert(conv_src->shape().ndim == 4 &&
                               conv_filter->shape().ndim == 5,
                       "The src and filter is OK");
            auto new_param = conv_opr.param();
2901
            new_param.format = is_trans.conv_format;
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
            auto new_conv_opr = opr::Convolution::make(
                    conv_src, conv_filter, new_param,
                    conv_opr.execution_policy(), conv_opr.config());
            OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
            mgb_assert(new_conv_opr.shape().ndim == 5,
                       "The conv dst dim is not trans to nchwxx");
            return new_opr;
        }
    };

2912
    auto replace_conv_bias_opr = [test_trans_nchw44_dot](
2913 2914 2915
                                         OperatorNodeBase* opr,
                                         const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
2916 2917
        mgb_assert(opr->input().size() <= 3,
                   "nchwxx-dot does not support conv_bias fuse Z right now");
2918
        auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
2919 2920 2921 2922 2923
        mgb_throw_if(
                conv_bias_opr.param().format !=
                        megdnn::param::ConvBias::Format::NCHW,
                MegBrainError,
                "ConvertFormat Pass only support converting NCHW to NCHWXX");
2924 2925 2926
        bool valid_nchw_nchw44 =
                nchw_nchwxx_valid(conv_bias_opr, new_inp, pack_c_size,
                                  conv_bias_opr.param().nonlineMode, true);
2927 2928
        auto is_trans = test_trans_nchw44_dot(
                conv_bias_opr.param().sparse, new_inp[1],
2929 2930 2931 2932 2933 2934 2935
                conv_bias_opr.param().stride_h, conv_bias_opr.param().stride_w,
                valid_nchw_nchw44);
        auto megdnn_conv =
                opr::intl::get_megdnn_handle(conv_bias_opr.comp_node())
                        ->create_operator<megdnn::ConvBiasForward>();
        SmallVector<TensorLayout> layouts;

2936
        //! can not trans to nchwxx
2937
        if (is_trans.trans_type == TransType::TRANS_NONE) {
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
            VarNodeArray temp_inp = new_inp;
            //! if src is nchwxx, should RelayoutPlaceholder to nchw
            if (temp_inp[0]->shape().ndim == 5) {
                auto new_src = RelayoutPlaceholder::make(
                        new_inp[0], RelayoutMode::NCHW4_TO_NCHW);
                temp_inp[0] = new_src.node();
            }
2948

2949
            //! the bias is nchwxx
2950
            if (new_inp.size() > 2 && temp_inp[2]->shape().ndim == 5) {
2951 2952 2953 2954 2955 2956 2957
                auto new_bias = RelayoutPlaceholder::make(
                        new_inp[2], RelayoutMode::NCHW4_TO_NCHW);
                temp_inp[2] = new_bias.node();
            }
            auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
                                                           opr->config());
            return new_opr;
2958
        } else if (is_trans.trans_type == TransType::TRANS_PURE_NCHWXX) {
2959
            VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
2960
                    *conv_bias_bias = nullptr;
2961 2962 2963 2964
            //! filter trans to nchwxx mode
            mgb_assert(new_inp[1]->shape().ndim == 4 ||
                               new_inp[1]->shape().ndim == 5,
                       "The origin filter is not NCHW mode");
2965 2966
            auto new_filter = RelayoutPlaceholder::make(new_inp[1],
                                                        is_trans.relayout_mod);
2967 2968 2969 2970 2971 2972 2973 2974
            conv_bias_filter = new_filter.node();
            //! src trans to nchwxx mode
            if (new_inp[0]->shape().ndim != 5) {
                mgb_assert(new_inp[0]->shape().ndim == 4);
                auto new_src = RelayoutPlaceholder::make(
                        new_inp[0], RelayoutMode::NCHW_TO_NCHW4);
                conv_bias_src = new_src.node();
            }
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
            //! bias trans to nchwxx mode
            if (new_inp.size() > 2) {
                if (new_inp[2]->shape().ndim == 4) {
                    auto new_bias = RelayoutPlaceholder::make(
                            new_inp[2], RelayoutMode::NCHW_TO_NCHW4);
                    conv_bias_bias = new_bias.node();
                } else {
                    mgb_assert(new_inp[2]->shape().ndim == 5);
                    conv_bias_bias = new_inp[2];
                }
2985 2986
            }
            auto new_param = conv_bias_opr.param();
2987
            new_param.format = is_trans.conv_format;
2988 2989 2990
            mgb_assert(conv_bias_src->shape().ndim == 5 &&
                               conv_bias_filter->shape().ndim >= 6,
                       "The conv_bias src dim is not trans to nchwxx");
2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
            SymbolVar new_conv_bias_opr;
            if (conv_bias_bias) {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, conv_bias_bias,
                        new_param, conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            } else {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, new_param,
                        conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            }
3003 3004 3005 3006 3007
            OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
            mgb_assert(new_conv_bias_opr.shape().ndim == 5,
                       "The conv_bias dst dim is not trans to nchwxx");
            return new_opr;
        } else {
3008
            mgb_assert(is_trans.trans_type == TransType::TRANS_HYBIRD_NCHWXX);
3009
            VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
3010
                    *conv_bias_bias = nullptr;
3011 3012
            auto new_filter = RelayoutPlaceholder::make(new_inp[1],
                                                        is_trans.relayout_mod);
3013 3014
            conv_bias_filter = new_filter.node();
            //! bias trans to nchwxx mode, bias may be scale
3015 3016 3017 3018 3019 3020 3021 3022 3023
            if (new_inp.size() > 2) {
                if (new_inp[2]->shape().ndim == 4) {
                    auto new_bias = RelayoutPlaceholder::make(
                            new_inp[2], RelayoutMode::NCHW_TO_NCHW4);
                    conv_bias_bias = new_bias.node();
                } else {
                    mgb_assert(new_inp[2]->shape().ndim == 5);
                    conv_bias_bias = new_inp[2];
                }
3024 3025 3026 3027
            }
            mgb_assert(conv_bias_src->shape().ndim == 4 &&
                       conv_bias_filter->shape().ndim == 5);
            auto new_param = conv_bias_opr.param();
3028
            new_param.format = is_trans.conv_format;
3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040
            SymbolVar new_conv_bias_opr;
            if (conv_bias_bias) {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, conv_bias_bias,
                        new_param, conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            } else {
                new_conv_bias_opr = opr::ConvBias::make(
                        conv_bias_src, conv_bias_filter, new_param,
                        conv_bias_opr.execution_policy(),
                        conv_bias_opr.config());
            }
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
            OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
            mgb_assert(new_conv_bias_opr.shape().ndim == 5,
                       "The conv dst dim is not trans to nchwxx");
            return new_opr;
        }
    };
    ret->fill_opr_convert_fun(4);
    auto&& replace_func = ret->m_opr_replace_func;
    //! supportted nchwxx
    replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
    replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
3052
    return ret;
3053
    MIDOUT_E
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
}

/* ==================== ShuffleShuffleRemovePass ================= */
class ShuffleShuffleRemovePass::Impl {
    using TensorFormat = opr::ConvBias::Param::Format;

    OptState& m_opt_state;
    ThinHashMap<std::pair<TensorFormat, TensorFormat>,
                thin_function<VarNode*(VarNode*)>>
            m_reformat;

    class AbstractShuffleOpr;

    void detect_shuffle_operations();
    void do_replace();

public:
    Impl(OptState& opt_state) : m_opt_state{opt_state} {
        m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::NCHW4)] =
                [](VarNode* inp) -> VarNode* {
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp = opr::Concat::make(
                    {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
            auto y0 = opr::Reshape::make(x, tshp);
            auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
            return y1.node();
        };

        m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::NCHW32)] =
                [](VarNode* inp) -> VarNode* {
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp = opr::Concat::make(
                    {sub(0), sub(1) / 32, cv(32), sub(2), sub(3)}, 0);
            auto y0 = opr::Reshape::make(x, tshp);
            auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
            return y1.node();
        };

        m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::NCHW)] =
                [](VarNode* inp) -> VarNode* {
            mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp =
                    opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
            auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
            auto y1 = opr::Reshape::make(y0, tshp);
            return y1.node();
        };

        m_reformat[std::make_pair(TensorFormat::NCHW32, TensorFormat::NCHW)] =
                [](VarNode* inp) -> VarNode* {
            mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp =
                    opr::Concat::make({sub(0), sub(1) * 32, sub(2), sub(3)}, 0);
            auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
            auto y1 = opr::Reshape::make(y0, tshp);
            return y1.node();
        };

        m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::NCHW32)] =
                [](VarNode* inp) -> VarNode* {
            mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp0 = opr::Concat::make(
                         {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)},
                         0),
                 tshp1 = opr::Concat::make(
                         {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
            auto y0 = opr::Reshape::make(x, tshp0);
            auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
            auto y2 = opr::Reshape::make(y1, tshp1);
            return y2.node();
        };

        m_reformat[std::make_pair(TensorFormat::NCHW32, TensorFormat::NCHW4)] =
                [](VarNode* inp) -> VarNode* {
            mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp0 = opr::Concat::make(
                         {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8},
                         0),
                 tshp1 = opr::Concat::make(
                         {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
            auto y0 = opr::Reshape::make(x, tshp0);
            auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
            auto y2 = opr::Reshape::make(y1, tshp1);
            return y2.node();
        };

        m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::CHWN4)] =
                [](VarNode* inp) -> VarNode* {
            megdnn::param::RelayoutFormat param;
            param.mode = megdnn::param::RelayoutFormat::Mode::NCHW4_CHWN4;
            auto reformat = opr::RelayoutFormat::make(inp, param);
            return reformat.node();
        };
3187

3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
        m_reformat[std::make_pair(TensorFormat::CHWN4, TensorFormat::NCHW4)] =
                [](VarNode* inp) -> VarNode* {
            megdnn::param::RelayoutFormat param;
            param.mode = megdnn::param::RelayoutFormat::Mode::CHWN4_NCHW4;
            auto reformat = opr::RelayoutFormat::make(inp, param);
            return reformat.node();
        };

        m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::CHWN4)] =
                [](VarNode* inp) -> VarNode* {
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp = opr::Concat::make(
                    {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
            auto y0 = opr::Reshape::make(x, tshp);
            auto y1 = opr::Dimshuffle::make(y0, {1, 3, 4, 0, 2});
            return y1.node();
        };

        m_reformat[std::make_pair(TensorFormat::CHWN4, TensorFormat::NCHW)] =
                [](VarNode* inp) -> VarNode* {
            mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
            auto x = SymbolVar(inp);
            auto xshp = opr::GetVarShape::make(x);

            auto cv = [&x](int v) { return x.make_scalar(v); };
            auto sub = [&xshp, &cv](int idx) {
                return opr::IndexAt::make(xshp, {{0, cv(idx)}});
            };
            auto tshp =
                    opr::Concat::make({sub(3), sub(0) * 4, sub(1), sub(2)}, 0);
            auto y0 = opr::Dimshuffle::make(x, {3, 0, 4, 1, 2});
            auto y1 = opr::Reshape::make(y0, tshp);
            return y1.node();
        };
        detect_shuffle_operations();
        do_replace();
    }
};

/*!
 * \brief abstract operator representation of shuffle operation
 */
MGB_DEFINE_OPR_CLASS(ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr,
M
Megvii Engine Team 已提交
3237
                     cg::SingleCNOperatorNodeBase)  // {
3238
public:
3239 3240
    AbstractShuffleOpr(VarNode* inpvar, TensorFormat inp_format,
                       TensorFormat out_format);
3241

3242 3243
    static SymbolVar make(VarNode* inpvar, TensorFormat inp_format,
                          TensorFormat out_format);
3244

3245 3246 3247
    TensorFormat inp_format() const {
        return m_inp_format;
    }
3248

3249 3250 3251
    TensorFormat out_format() const {
        return m_out_format;
    }
3252

3253
private:
3254 3255 3256 3257 3258
    void init_output_static_infer_desc() override;
    void scn_do_execute() override;
    const TensorFormat m_inp_format;
    const TensorFormat m_out_format;
};
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517

MGB_DYN_TYPE_OBJ_FINAL_IMPL(ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr);

void ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::scn_do_execute() {
    mgb_throw(InternalError, "AbstractShuffleOpr cannot be executed");
}

void ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::
        init_output_static_infer_desc() {
    using namespace cg::static_infer;
    auto&& mgr = owner_graph()->static_infer_manager();
    DepVal deps;
    for (auto i : input())
        deps.push_back({i, DepType::SHAPE});
    auto infer_shape = [this](TensorShape& dst, const InpVal& inp) {
        TensorShape inp_shape = inp.val[0].shape();
        if (m_inp_format == TensorFormat::NCHW4 &&
            m_out_format == TensorFormat::NCHW32) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
            dst = inp_shape;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 8;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4] * 8;
        } else if (m_inp_format == TensorFormat::NCHW32 &&
                   m_out_format == TensorFormat::NCHW4) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
            dst = inp_shape;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 8;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = inp_shape[4] / 8;
        } else if (m_inp_format == TensorFormat::NCHW &&
                   m_out_format == TensorFormat::NCHW4) {
            mgb_assert(inp_shape.ndim == 4);
            dst.ndim = 5;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] / 4;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
            dst[4] = 4;
        } else if (m_inp_format == TensorFormat::NCHW4 &&
                   m_out_format == TensorFormat::NCHW) {
            mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
            dst.ndim = 4;
            dst[0] = inp_shape[0];
            dst[1] = inp_shape[1] * 4;
            dst[2] = inp_shape[2];
            dst[3] = inp_shape[3];
        } else if (m_inp_format == TensorFormat::NCHW4 &&
                   m_out_format == TensorFormat::CHWN4) {
            dst.ndim = 5;
            dst[0] = inp_shape[1];
            dst[1] = inp_shape[2];
            dst[2] = inp_shape[3];
            dst[3] = inp_shape[0];
            dst[4] = inp_shape[4];
        } else if (m_inp_format == TensorFormat::CHWN4 &&
                   m_out_format == TensorFormat::NCHW4) {
            dst.ndim = 5;
            dst[0] = inp_shape[3];
            dst[1] = inp_shape[0];
            dst[2] = inp_shape[1];
            dst[3] = inp_shape[2];
            dst[4] = inp_shape[4];
        } else {
            mgb_throw(InternalError,
                      "Unsupported input format and output format.");
        }
        return true;
    };
    mgr.register_shape_infer(output(0), {SourceType::DEP, deps, infer_shape});
}

ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::AbstractShuffleOpr(
        VarNode* inpvar, TensorFormat inp_format, TensorFormat out_format)
        : Super(inpvar->owner_graph(), {}, "AbstractShuffleOpr", {inpvar}),
          m_inp_format{inp_format},
          m_out_format{out_format} {
    add_input({inpvar});
    add_equivalence_component<ScalarHash<TensorFormat>>(m_inp_format);
    add_equivalence_component<ScalarHash<TensorFormat>>(m_out_format);
    add_output(None)->dtype(inpvar->dtype());
}

SymbolVar ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::make(
        VarNode* inpvar, TensorFormat inp_format, TensorFormat out_format) {
    return inpvar->owner_graph()
            ->insert_opr(std::make_unique<AbstractShuffleOpr>(
                    inpvar, inp_format, out_format))
            ->output(0);
}

void ShuffleShuffleRemovePass::Impl::detect_shuffle_operations() {
    auto rewriter = m_opt_state.graph().make_rewriter();
    auto uniq_reader_check = UniqReaderCheck{m_opt_state.graph()};
    auto try_reshape_shuffle = [&rewriter,
                                &uniq_reader_check](OperatorNodeBase* opr) {
        // check shuffle
        auto shuffle = try_cast_as_op<opr::Dimshuffle>(opr);
        if (shuffle == nullptr)
            return false;
        auto&& param = shuffle->param();
        if (param.pattern_len != 5)
            return false;
        bool is_nchw2nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
                             param.pattern[2] == 3 && param.pattern[3] == 4 &&
                             param.pattern[4] == 2 &&
                             opr->output(0)->shape()[4] == 4;
        if (!is_nchw2nchw4)
            return false;
        if (!uniq_reader_check(shuffle->input(0)))
            return false;

        // check reshape
        auto reshape = try_cast_as_op<opr::Reshape>(opr->input(0)->owner_opr());
        if (reshape == nullptr)
            return false;
        auto inp_var = rewriter.get_var(reshape->input(0));
        auto abstract_shuffle = AbstractShuffleOpr::make(
                inp_var, TensorFormat::NCHW, TensorFormat::NCHW4);
        rewriter.replace_var(
                opr->output(0), abstract_shuffle.node(),
                mgb_cstr_log("replace reformat(nchw -> nchw4) to "
                             "AbstractShuffleOpr(nchw -> nchw4)."));
        return true;
    };

    auto try_reshape_shuffle_reshape = [&rewriter, &uniq_reader_check](
                                               OperatorNodeBase* opr) {
        // check reshape
        auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
        if (reshape1 == nullptr)
            return false;
        if (!uniq_reader_check(reshape1->input(0)))
            return false;

        // check shuffle
        auto shuffle =
                try_cast_as_op<opr::Dimshuffle>(opr->input(0)->owner_opr());
        if (shuffle == nullptr)
            return false;
        auto&& param = shuffle->param();
        if (param.pattern_len != 6)
            return false;
        bool is_nchw42nchw32 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
                               param.pattern[2] == 3 && param.pattern[3] == 4 &&
                               param.pattern[4] == 2 && param.pattern[5] == 5 &&
                               shuffle->input(0)->shape()[5] == 4 &&
                               shuffle->input(0)->shape()[2] == 8;
        bool is_nchw322nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
                               param.pattern[2] == 4 && param.pattern[3] == 2 &&
                               param.pattern[4] == 3 && param.pattern[5] == 5 &&
                               shuffle->input(0)->shape()[4] == 8 &&
                               shuffle->input(0)->shape()[5] == 4;
        if (!is_nchw42nchw32 && !is_nchw322nchw4)
            return false;
        if (!uniq_reader_check(shuffle->input(0)))
            return false;

        // check reshape
        auto reshape2 =
                try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
        if (reshape2 == nullptr)
            return false;
        auto inp_var = rewriter.get_var(reshape2->input(0));
        TensorFormat inp_format = is_nchw42nchw32 ? TensorFormat::NCHW4
                                                  : TensorFormat::NCHW32,
                     out_format = is_nchw42nchw32 ? TensorFormat::NCHW32
                                                  : TensorFormat::NCHW4;
        auto abstract_shuffle =
                AbstractShuffleOpr::make(inp_var, inp_format, out_format);
        std::string reformat_type =
                is_nchw42nchw32 ? "nchw4 -> nchw32" : "nchw32 -> nchw4";
        rewriter.replace_var(opr->output(0), abstract_shuffle.node(),
                             mgb_cstr_log(ssprintf("replace reformat(%s) to "
                                                   "AbstractShuffleOpr(%s).",
                                                   reformat_type.c_str(),
                                                   reformat_type.c_str())
                                                  .c_str()));
        return true;
    };

    auto try_shuffle_reshape = [&rewriter,
                                &uniq_reader_check](OperatorNodeBase* opr) {
        // check reshape
        auto reshape = try_cast_as_op<opr::Reshape>(opr);
        if (reshape == nullptr)
            return false;
        if (!uniq_reader_check(reshape->input(0)))
            return false;

        // check shuffle
        auto shuffle =
                try_cast_as_op<opr::Dimshuffle>(opr->input(0)->owner_opr());
        if (shuffle == nullptr)
            return false;
        auto&& param = shuffle->param();
        if (param.pattern_len != 5)
            return false;
        bool is_nchw42nchw = param.pattern[0] == 0 && param.pattern[1] == 1 &&
                             param.pattern[2] == 4 && param.pattern[3] == 2 &&
                             param.pattern[4] == 3 &&
                             shuffle->input(0)->shape()[4] == 4;
        if (!is_nchw42nchw)
            return false;
        auto inp_var = rewriter.get_var(shuffle->input(0));
        auto abstract_shuffle = AbstractShuffleOpr::make(
                inp_var, TensorFormat::NCHW4, TensorFormat::NCHW);
        rewriter.replace_var(
                opr->output(0), abstract_shuffle.node(),
                mgb_cstr_log("replace reformat(nchw4 -> nchw) to "
                             "AbstractShuffleOpr(nchw4 -> nchw)."));
        return true;
    };

    auto try_relayout_format = [&rewriter](OperatorNodeBase* opr) {
        // check relayout format
        auto reformat = try_cast_as_op<opr::RelayoutFormat>(opr);
        if (reformat == nullptr)
            return false;
        auto&& param = reformat->param();
        if (param.mode != opr::RelayoutFormat::Param::Mode::CHWN4_NCHW4 &&
            param.mode != opr::RelayoutFormat::Param::Mode::NCHW4_CHWN4)
            return false;
        auto inp_var = rewriter.get_var(reformat->input(0));
        cg::SymbolVar abstract_shuffle;
        if (param.mode == opr::RelayoutFormat::Param::Mode::NCHW4_CHWN4) {
            abstract_shuffle = AbstractShuffleOpr::make(
                    inp_var, TensorFormat::NCHW4, TensorFormat::CHWN4);
        } else {
            abstract_shuffle = AbstractShuffleOpr::make(
                    inp_var, TensorFormat::CHWN4, TensorFormat::NCHW4);
        }
        rewriter.replace_var(
                opr->output(0), abstract_shuffle.node(),
                mgb_cstr_log("replace reformat(nchw4 -> nchw) to "
                             "AbstractShuffleOpr(nchw4 -> nchw)."));
        return true;
    };

    auto on_opr = [&try_reshape_shuffle, &try_shuffle_reshape,
                   &try_reshape_shuffle_reshape, &try_relayout_format,
                   &rewriter, &uniq_reader_check](OperatorNodeBase* opr) {
        if (!try_reshape_shuffle_reshape(opr) && !try_reshape_shuffle(opr) &&
            !try_shuffle_reshape(opr) && !try_relayout_format(opr)) {
            auto new_opr = rewriter.auto_replace_outputs(opr);
            uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
        }
    };
    m_opt_state.graph().iter(on_opr);
    rewriter.apply_inplace();
}

void ShuffleShuffleRemovePass::Impl::do_replace() {
    auto rewriter = m_opt_state.graph().make_rewriter();
    auto uniq_reader_check = UniqReaderCheck{m_opt_state.graph()};
3518 3519
    ThinHashSet<OperatorNodeBase*> writers;
    ThinHashSet<OperatorNodeBase*> root;
3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537
    ThinHashSet<VarNode*> trt_opr_inps;
    SmallVector<OperatorNodeBase*> topo_order;

    auto cb = [&topo_order, &trt_opr_inps](OperatorNodeBase* opr) {
        topo_order.push_back(opr);
        MGB_MARK_USED_VAR(trt_opr_inps);
#if MGB_ENABLE_TENSOR_RT
        if (opr->same_type<opr::TensorRTOpr>()) {
            for (auto&& inp : opr->input())
                trt_opr_inps.insert(inp);
        }
#endif
    };
    m_opt_state.graph().iter(cb);

    for (auto&& opr : reverse_adaptor(topo_order)) {
        if (opr->same_type<opr::TypeCvt>() ||
            opr->same_type<AbstractShuffleOpr>()) {
3538 3539 3540 3541
            writers.insert(opr->input(0)->owner_opr());
            if (writers.count(opr) > 0) {
                if (!uniq_reader_check(opr->output(0))) {
                    root.insert(opr);
3542 3543
                }
            } else {
3544
                root.insert(opr);
3545 3546 3547 3548 3549
            }
        }
    }

    auto on_opr = [this, &rewriter, &uniq_reader_check, &trt_opr_inps,
3550
                   &root](OperatorNodeBase* opr) {
3551 3552 3553 3554
        MGB_MARK_USED_VAR(trt_opr_inps);
        bool cond_opr = opr->same_type<opr::TypeCvt>() ||
                        opr->same_type<AbstractShuffleOpr>();
        if (cond_opr) {
3555 3556
            bool cond_endpoint = root.count(opr) > 0;
            if (!cond_endpoint) {
3557
                return;
3558
            }
3559 3560 3561 3562 3563
            auto cur = opr;
            auto var = opr->output(0), inp_var = opr->input(0);
            bool force_folding_typecvt = false;
            bool first_shuffle = false;
            // initialize inp_format and out_format
M
Megvii Engine Team 已提交
3564 3565
            TensorFormat out_format = TensorFormat::NCHW,
                         inp_format = out_format;
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
            megdnn::DType inp_dtype = cur->input(0)->dtype(),
                          out_dtype = cur->output(0)->dtype();
            SmallVector<megdnn::DType> out_dtype_vec;
            while (cond_opr) {
                if (cur->same_type<AbstractShuffleOpr>()) {
                    auto shuffle = try_cast_as_op<AbstractShuffleOpr>(cur);
                    inp_format = shuffle->inp_format();
                    if (!first_shuffle) {
                        out_format = shuffle->out_format();
                        first_shuffle = true;
                    }
                } else {
                    mgb_assert(cur->same_type<opr::TypeCvt>());
                    out_dtype_vec.push_back(cur->output(0)->dtype());
                }
                inp_var = cur->input(0);
                bool cond_reader = uniq_reader_check(inp_var);
                if (!cond_reader)
                    break;
                cur = cur->input(0)->owner_opr();
                cond_opr = cur->same_type<opr::TypeCvt>() ||
                           cur->same_type<AbstractShuffleOpr>();
            }
            std::reverse(out_dtype_vec.begin(), out_dtype_vec.end());
#if MGB_ENABLE_TENSOR_RT
            force_folding_typecvt =
                    inp_var->owner_opr()->same_type<opr::TensorRTOpr>() ||
                    trt_opr_inps.count(var);
#endif
            auto new_var = rewriter.get_var(inp_var);
            if (inp_format != out_format) {
3597 3598 3599
                mgb_assert(m_reformat.find(std::make_pair(
                                   inp_format, out_format)) != m_reformat.end(),
                           "Unsupported shuffle shuffle remove pass");
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
                new_var = m_reformat[std::make_pair(inp_format, out_format)](
                        new_var);
            }
            if (force_folding_typecvt) {
                inp_dtype = inp_var->dtype();
                if (inp_dtype != out_dtype) {
                    auto type_cvt = opr::TypeCvt::make(new_var, out_dtype);
                    new_var = type_cvt.node();
                }
            } else {
                if (out_dtype_vec.back() != var->dtype())
                    out_dtype_vec.push_back(var->dtype());
                for (auto&& dtype : out_dtype_vec) {
                    auto type_cvt = opr::TypeCvt::make(new_var, dtype);
                    new_var = type_cvt.node();
                }
            }
            rewriter.replace_var(
                    var, new_var,
                    mgb_cstr_log("replace Dimshuffle and TypeCvt chain"));
        } else {
            auto new_opr = rewriter.auto_replace_outputs(opr);
            uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
        }
    };
    m_opt_state.graph().iter(on_opr);
    rewriter.apply_inplace();
}

const char* ShuffleShuffleRemovePass::name() const {
    return mgb_cstr_log("shuffle shuffle remove pass");
}

void ShuffleShuffleRemovePass::apply(OptState& opt) const {
3634
    MIDOUT_B("ShuffleShuffleRemovePass::apply")
3635 3636 3637
    opt.set_var_replace_check_flag(VarReplaceCheckFlag::CHECK_SHAPE |
                                   VarReplaceCheckFlag::CHECK_DTYPE);
    Impl{opt};
3638
    MIDOUT_E
3639 3640
}

3641
#if CUDA_VERSION >= 10020
3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
/* ==================== FoldingConvBiasDimshufflePass ================= */
const char* FoldingConvBiasDimshufflePass::name() const {
    return mgb_cstr_log("folding conv bias dimshuffle pass");
}

void FoldingConvBiasDimshufflePass::apply(OptState& opt) const {
    MIDOUT_B("FoldingConvBiasDimshufflePass::apply");
    using DepType = cg::OperatorNodeProp::DepType;
    ThinHashMap<OperatorNodeBase*,
                SmallVector<std::pair<OperatorNodeBase*, DepType>>>
            readers;
    static const ThinHashSet<Typeinfo*> opr_type_list = {
            opr::TypeCvt::typeinfo(), opr::Dimshuffle::typeinfo(),
            opr::Reshape::typeinfo(), opr::ConvBias::typeinfo()};
    opt.graph().iter([&readers](OperatorNodeBase* opr) {
        for (auto&& i : opr->node_prop().dep_map()) {
            if (opr_type_list.count(i.first->owner_opr()->dyn_typeinfo())) {
                readers[i.first->owner_opr()].emplace_back(opr, i.second);
            }
        }
    });

    auto rewriter = opt.graph().make_rewriter();
    auto nchw42nchw = [](VarNode* inp) -> VarNode* {
        mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);

        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp = opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
        auto y1 = opr::Reshape::make(y0, tshp);
3677
        auto y2 = opr::TypeCvt::make(y1, dtype::Float32());
3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
        return y2.node();
    };

    auto nchw42nchw32 = [](VarNode* inp) -> VarNode* {
        mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };

    auto nchw322nchw4 = [](VarNode* inp) -> VarNode* {
        mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp0 = opr::Concat::make(
                     {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8}, 0),
             tshp1 = opr::Concat::make(
                     {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
        auto y0 = opr::Reshape::make(x, tshp0);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
        auto y2 = opr::Reshape::make(y1, tshp1);
        return y2.node();
    };

3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
    auto nchw42nhwc = [](VarNode* inp) -> VarNode* {
        mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
        auto x = SymbolVar(inp);
        auto xshp = opr::GetVarShape::make(x);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        auto sub = [&xshp, &cv](int idx) {
            return opr::IndexAt::make(xshp, {{0, cv(idx)}});
        };
        auto tshp = opr::Concat::make({sub(0), sub(2), sub(3), sub(1) * 4}, 0);
        auto y0 = opr::Dimshuffle::make(x, {0, 2, 3, 1, 4});
        auto y1 = opr::Reshape::make(y0, tshp);
        return y1.node();
    };

3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
    auto try_conv_dimshuffle_reshape_typecvt = [&rewriter, &readers,
                                                &nchw42nchw](
                                                       OperatorNodeBase* opr) {
        ThinHashSet<OperatorNodeBase*> opr_set;
        ThinHashSet<OperatorNodeBase*> reader_set;
        // check typecvt
        auto typecvt = try_cast_as_op<opr::TypeCvt>(opr);
        if (typecvt == nullptr)
            return false;
        auto inp_dtype = typecvt->input(0)->dtype(),
             out_dtype = typecvt->output(0)->dtype();
        bool is_s82f32 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
                         out_dtype.enumv() == DTypeEnum::Float32;
        if (!is_s82f32)
            return false;
        opr_set.insert(opr);

        // check reshape
        auto reshape =
                try_cast_as_op<opr::Reshape>(typecvt->input(0)->owner_opr());
        if (reshape == nullptr)
            return false;
        opr_set.insert(reshape);
        for (auto&& i : readers[reshape]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }

        // check shuffle
        auto shuffle =
                try_cast_as_op<opr::Dimshuffle>(reshape->input(0)->owner_opr());
        if (shuffle == nullptr)
            return false;
        auto&& param = shuffle->param();
        if (param.pattern_len != 5)
            return false;
        bool is_nchw42nchw = param.pattern[0] == 0 && param.pattern[1] == 1 &&
                             param.pattern[2] == 4 && param.pattern[3] == 2 &&
                             param.pattern[4] == 3 &&
                             shuffle->input(0)->shape()[4] == 4;
        if (!is_nchw42nchw)
            return false;
        opr_set.insert(shuffle);
        for (auto&& i : readers[shuffle]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }

        // check conv bias
        auto conv_bias =
                try_cast_as_op<opr::ConvBias>(shuffle->input(0)->owner_opr());
        if (conv_bias == nullptr)
            return false;
        inp_dtype = conv_bias->input(0)->dtype();
        bool is_s8nchw4 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
                          conv_bias->param().format ==
                                  megdnn::param::ConvBias::Format::NCHW4;
        if (!is_s8nchw4)
            return false;
        if (conv_bias->input().size() != 3)
            return false;
        opr_set.insert(conv_bias);
        for (auto&& i : readers[conv_bias]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        for (auto reader : reader_set) {
            if (opr_set.count(reader) <= 0) {
                return false;
            }
        }
        auto src = rewriter.get_var(conv_bias->input(0)),
             filter = rewriter.get_var(conv_bias->input(1)),
             bias = rewriter.get_var(conv_bias->input(2));
        auto new_bias = nchw42nchw(bias);
        auto new_param = conv_bias->param();
        new_param.format = megdnn::param::ConvBias::Format::NCHW4_NCHW;
        auto conv_bias_shuffle = opr::ConvBias::make(
                src, filter, new_bias, new_param, conv_bias->execution_policy(),
                OperatorNodeConfig{dtype::Float32()});
        rewriter.replace_var(opr->output(0), conv_bias_shuffle.node(),
                             mgb_cstr_log("replace conv_bias + typecvt + "
                                          "dimshuffle + "
                                          "reshape to conv_bias(NCHW4_NCHW)"));
        return true;
    };

    auto try_conv_reformat_nchw42nchw32 = [&rewriter, &nchw42nchw32,
                                           &readers](OperatorNodeBase* opr) {
        ThinHashSet<OperatorNodeBase*> opr_set;
        ThinHashSet<OperatorNodeBase*> reader_set;
        // check reshape
        auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
        if (reshape1 == nullptr)
            return false;
        opr_set.insert(opr);
        // check dimshuffle
        auto shuffle = try_cast_as_op<opr::Dimshuffle>(
                reshape1->input(0)->owner_opr());
        if (shuffle == nullptr)
            return false;
        auto&& param = shuffle->param();
        if (param.pattern_len != 6)
            return false;
        bool is_nchw42nchw32 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
                               param.pattern[2] == 3 && param.pattern[3] == 4 &&
                               param.pattern[4] == 2 && param.pattern[5] == 5 &&
                               shuffle->output(0)->shape()[5] == 4 &&
                               shuffle->output(0)->shape()[4] == 8;
        if (!is_nchw42nchw32)
            return false;
        opr_set.insert(shuffle);
        for (auto&& i : readers[shuffle]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        // check reshape
        auto reshape2 =
                try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
        if (reshape2 == nullptr)
            return false;
        opr_set.insert(reshape2);
        for (auto&& i : readers[reshape2]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        // check conv bias
        auto conv_bias =
                try_cast_as_op<opr::ConvBias>(reshape2->input(0)->owner_opr());
        if (conv_bias == nullptr)
            return false;
        auto inp_dtype = conv_bias->input(0)->dtype();
        bool is_s8nchw4 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
                          conv_bias->param().format ==
                                  megdnn::param::ConvBias::Format::NCHW4;
        if (!is_s8nchw4)
            return false;
        if (conv_bias->input().size() != 3)
            return false;
        opr_set.insert(conv_bias);
        for (auto&& i : readers[conv_bias]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        for (auto reader : reader_set) {
            if (opr_set.count(reader) <= 0) {
                return false;
            }
        }
        auto src = rewriter.get_var(conv_bias->input(0)),
             filter = rewriter.get_var(conv_bias->input(1)),
             bias = rewriter.get_var(conv_bias->input(2));
        auto new_bias = nchw42nchw32(bias);
        auto new_param = conv_bias->param();
        new_param.format = megdnn::param::ConvBias::Format::NCHW4_NCHW32;
        auto conv_bias_shuffle = opr::ConvBias::make(
                src, filter, new_bias, new_param, conv_bias->execution_policy(),
                conv_bias->config());
        rewriter.replace_var(
                opr->output(0), conv_bias_shuffle.node(),
                mgb_cstr_log("replace conv_bias + "
                             "reformat to conv_bias(NCHW4_NCHW32)"));
        return true;
    };

3902 3903
    auto try_conv_reformat_nchw42nhwc = [&rewriter, &nchw42nhwc,
                                         &readers](OperatorNodeBase* opr) {
3904 3905 3906
        ThinHashSet<OperatorNodeBase*> opr_set;
        ThinHashSet<OperatorNodeBase*> reader_set;
        // check reshape
3907 3908
        auto reshape = try_cast_as_op<opr::Reshape>(opr);
        if (reshape == nullptr)
3909 3910 3911 3912 3913
            return false;
        opr_set.insert(opr);

        // check dimshuffle
        auto shuffle = try_cast_as_op<opr::Dimshuffle>(
3914
                reshape->input(0)->owner_opr());
3915 3916 3917
        if (shuffle == nullptr)
            return false;
        auto&& param = shuffle->param();
3918
        if (param.pattern_len != 5)
3919
            return false;
3920 3921 3922 3923 3924
        bool is_nchw42nhwc = param.pattern[0] == 0 && param.pattern[1] == 2 &&
                             param.pattern[2] == 3 && param.pattern[3] == 1 &&
                             param.pattern[4] == 4 &&
                             shuffle->output(0)->shape()[4] == 4;
        if (!is_nchw42nhwc)
3925 3926 3927 3928 3929 3930 3931 3932 3933
            return false;
        opr_set.insert(shuffle);
        for (auto&& i : readers[shuffle]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }

        auto typecvt =
3934
                try_cast_as_op<opr::TypeCvt>(shuffle->input(0)->owner_opr());
3935 3936 3937 3938 3939 3940 3941 3942 3943 3944
        if (typecvt == nullptr)
            return false;
        auto in_dtype = typecvt->input(0)->dtype(),
             out_dtype = typecvt->output(0)->dtype();
        bool is_s82s4 = in_dtype.enumv() == DTypeEnum::QuantizedS8 &&
                        (out_dtype.enumv() == DTypeEnum::QuantizedS4 ||
                         out_dtype.enumv() == DTypeEnum::Quantized4Asymm);
        if (!is_s82s4)
            return false;
        opr_set.insert(typecvt);
3945 3946 3947 3948 3949
        for (auto&& i : readers[typecvt]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984

        // check conv bias
        auto conv_bias =
                try_cast_as_op<opr::ConvBias>(typecvt->input(0)->owner_opr());
        if (conv_bias == nullptr)
            return false;
        auto inp_dtype = conv_bias->input(0)->dtype();
        bool is_s8nchw4 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
                          conv_bias->param().format ==
                                  megdnn::param::ConvBias::Format::NCHW4;
        if (!is_s8nchw4)
            return false;
        if (conv_bias->input().size() != 3)
            return false;
        opr_set.insert(conv_bias);
        for (auto&& i : readers[conv_bias]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        for (auto reader : reader_set) {
            if (opr_set.count(reader) <= 0) {
                return false;
            }
        }
        auto src = rewriter.get_var(conv_bias->input(0)),
             filter = rewriter.get_var(conv_bias->input(1)),
             bias = rewriter.get_var(conv_bias->input(2));
        auto new_bias = nchw42nhwc(bias);
        auto new_param = conv_bias->param();
        new_param.format = megdnn::param::ConvBias::Format::NCHW4_NHWC;
        auto conv_bias_shuffle = opr::ConvBias::make(
                src, filter, new_bias, new_param, conv_bias->execution_policy(),
                OperatorNodeConfig{out_dtype});
        rewriter.replace_var(
3985
                opr->output(0), conv_bias_shuffle.node(),
3986
                mgb_cstr_log("replace conv_bias + "
3987
                             "reformat to conv_bias(NCHW4_NHWC)"));
3988 3989 3990
        return true;
    };

3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071
    auto try_conv_reformat_nchw322nchw4 = [&rewriter, &readers, &nchw322nchw4](
                                                  OperatorNodeBase* opr) {
        ThinHashSet<OperatorNodeBase*> opr_set;
        ThinHashSet<OperatorNodeBase*> reader_set;
        // check reshape
        auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
        if (reshape1 == nullptr)
            return false;
        opr_set.insert(opr);
        // check dimshuffle
        auto shuffle = try_cast_as_op<opr::Dimshuffle>(
                reshape1->input(0)->owner_opr());
        if (shuffle == nullptr)
            return false;
        auto&& param = shuffle->param();
        if (param.pattern_len != 6)
            return false;
        bool is_nchw322nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
                               param.pattern[2] == 4 && param.pattern[3] == 2 &&
                               param.pattern[4] == 3 && param.pattern[5] == 5 &&
                               shuffle->input(0)->shape()[5] == 4 &&
                               shuffle->input(0)->shape()[4] == 8;
        if (!is_nchw322nchw4)
            return false;
        opr_set.insert(shuffle);
        for (auto&& i : readers[shuffle]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        // check reshape
        auto reshape2 =
                try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
        if (reshape2 == nullptr)
            return false;
        opr_set.insert(reshape2);
        for (auto&& i : readers[reshape2]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        // check conv bias
        auto conv_bias =
                try_cast_as_op<opr::ConvBias>(reshape2->input(0)->owner_opr());
        if (conv_bias == nullptr)
            return false;
        auto inp_dtype = conv_bias->input(0)->dtype();
        bool is_s8nchw32 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
                          conv_bias->param().format ==
                                  megdnn::param::ConvBias::Format::NCHW32;
        if (!is_s8nchw32)
            return false;
        if (conv_bias->input().size() != 3)
            return false;
        opr_set.insert(conv_bias);
        for (auto&& i : readers[conv_bias]) {
            if (i.second & DepType::DEV_VALUE) {
                reader_set.insert(i.first);
            }
        }
        for (auto reader : reader_set) {
            if (opr_set.count(reader) <= 0) {
                return false;
            }
        }
        auto src = rewriter.get_var(conv_bias->input(0)),
             filter = rewriter.get_var(conv_bias->input(1)),
             bias = rewriter.get_var(conv_bias->input(2));
        auto new_bias = nchw322nchw4(bias);
        auto new_param = conv_bias->param();
        new_param.format = megdnn::param::ConvBias::Format::NCHW32_NCHW4;
        auto conv_bias_shuffle = opr::ConvBias::make(
                src, filter, new_bias, new_param, conv_bias->execution_policy(),
                conv_bias->config());
        rewriter.replace_var(
                opr->output(0), conv_bias_shuffle.node(),
                mgb_cstr_log("replace conv_bias + "
                             "reformat to conv_bias(NCHW32_NCHW4)"));
        return true;
    };
    MGB_MARK_USED_VAR(try_conv_reformat_nchw322nchw4);
4072
    MGB_MARK_USED_VAR(try_conv_reformat_nchw42nchw32);
4073 4074 4075

    auto on_opr = [&try_conv_dimshuffle_reshape_typecvt,
                   &try_conv_reformat_nchw42nchw32,
4076
                   &try_conv_reformat_nchw42nhwc,
4077 4078 4079
                   &try_conv_reformat_nchw322nchw4,
                   &rewriter](OperatorNodeBase* opr) {
        if (!try_conv_dimshuffle_reshape_typecvt(opr) &&
4080 4081
            !try_conv_reformat_nchw42nchw32(opr) &&
            !try_conv_reformat_nchw42nhwc(opr)
4082 4083 4084 4085 4086 4087 4088 4089 4090 4091
            && !try_conv_reformat_nchw322nchw4(opr)
        ) {
            rewriter.auto_replace_outputs(opr);
        }
    };
    opt.graph().iter(on_opr);
    rewriter.apply_inplace();

    MIDOUT_E
}
4092
#endif
4093

4094
/* ==================== PaddingChannelPass ================= */
4095 4096 4097 4098 4099
const char* PaddingChannelPass::name() const {
    return mgb_cstr_log("padding output channel to multiple of 4/32");
}

void PaddingChannelPass::apply(OptState& opt) const {
4100
    MIDOUT_B("PaddingChannelPass::apply");
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
    // do not check shape
    opt.set_var_replace_check_flag(VarReplaceCheckFlag::CHECK_ALL ^
                                   VarReplaceCheckFlag::CHECK_SHAPE);

    ThinHashSet<OperatorNodeBase*> padding_oprs;
    ThinHashMap<Typeinfo*, thin_function<OperatorNodeBase*(
                                   OperatorNodeBase*, const VarNodeArray&)>>
            opr_replace_funcs;

    auto rewriter = opt.graph().make_rewriter();
    auto pad_in_channels = [](VarNode* inp, size_t pad_channels) -> VarNode* {
        mgb_assert(inp->shape().ndim == 4);
4113 4114 4115
        mgb_assert(inp->dtype().enumv() == DTypeEnum::QuantizedS4 ||
                   inp->dtype().enumv() == DTypeEnum::Quantized4Asymm ||
                   inp->dtype().enumv() == DTypeEnum::QuantizedS8 ||
4116 4117 4118
                   inp->dtype().enumv() == DTypeEnum::QuantizedS32);
        TensorShape shape{inp->shape()[0], pad_channels, inp->shape()[2],
                          inp->shape()[3]};
4119 4120 4121
        std::shared_ptr<HostTensorND> host_val =
                std::make_shared<HostTensorND>(inp->comp_node(), inp->dtype());
        host_val->resize(shape);
4122
        auto ptr = host_val->raw_ptr();
4123 4124 4125
        size_t size_bytes =
                TensorLayout{shape, inp->dtype()}.span().dist_byte();
        std::memset(ptr, 0, size_bytes);
4126 4127 4128 4129 4130 4131 4132 4133
        auto padding =
                opr::ImmutableTensor::make(*inp->owner_graph(), *host_val);
        auto out = opr::Concat::make({inp, padding}, 1);
        return out.node();
    };

    auto pad_out_channels = [](VarNode* inp, size_t pad_channels) -> VarNode* {
        mgb_assert(inp->shape().ndim == 4);
4134 4135 4136
        mgb_assert(inp->dtype().enumv() == DTypeEnum::QuantizedS4 ||
                   inp->dtype().enumv() == DTypeEnum::Quantized4Asymm ||
                   inp->dtype().enumv() == DTypeEnum::QuantizedS8 ||
4137 4138 4139
                   inp->dtype().enumv() == DTypeEnum::QuantizedS32);
        TensorShape shape{pad_channels, inp->shape()[1], inp->shape()[2],
                          inp->shape()[3]};
4140 4141 4142
        std::shared_ptr<HostTensorND> host_val =
                std::make_shared<HostTensorND>(inp->comp_node(), inp->dtype());
        host_val->resize(shape);
4143
        auto ptr = host_val->raw_ptr();
4144 4145 4146
        size_t size_bytes =
                TensorLayout{shape, inp->dtype()}.span().dist_byte();
        std::memset(ptr, 0, size_bytes);
4147 4148 4149 4150 4151 4152 4153
        auto padding =
                opr::ImmutableTensor::make(*inp->owner_graph(), *host_val);
        auto out = opr::Concat::make({inp, padding}, 0);
        return out.node();
    };

    auto extract_subtensor = [](VarNode* inp,
4154
                                const TensorShape& orig_shape) -> VarNode* {
4155
        mgb_assert(inp->shape().ndim == 4);
4156 4157 4158 4159
        mgb_assert(inp->shape()[0] == orig_shape[0]);
        mgb_assert(inp->shape()[2] == orig_shape[2]);
        mgb_assert(inp->shape()[3] == orig_shape[3]);
        size_t orig_channels = orig_shape[1];
4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205
        auto x = SymbolVar(inp);
        auto cv = [&x](int v) { return x.make_scalar(v); };
        using AIdx = opr::Subtensor::AxisIndexer;
        auto sub = opr::Subtensor::make(
                x, {AIdx::make_interval(0, None, None, cv(1)),
                    AIdx::make_interval(1, None, cv(orig_channels), None),
                    AIdx::make_interval(2, None, None, cv(1)),
                    AIdx::make_interval(3, None, None, cv(1))});
        return sub.node();
    };

    // padding policy for conv bias with data type qint8
    auto padding_policy_qint8 = [&padding_oprs, &pad_in_channels,
                                 &pad_out_channels](
                                        OperatorNodeBase* opr,
                                        const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        mgb_assert(new_inp.size() == 3);
        mgb_assert(opr->input(1)->shape().eq_shape(new_inp[1]->shape()));
        auto inps = new_inp;
        size_t out_channels = opr->input(1)->shape()[0];
        size_t in_channels = opr->input(1)->shape()[1];
        size_t new_in_channels = new_inp[0]->shape()[1];
        // pad input channels
        if (padding_oprs.count(opr->input(0)->owner_opr())) {
            size_t pad_channels = new_in_channels - in_channels;
            inps[1] = pad_in_channels(new_inp[1], pad_channels);
        } else {
            size_t pad_channels = 0;
            mgb_assert(new_in_channels == in_channels);
            if (in_channels <= 16) {
                if (in_channels % 4)
                    pad_channels = 4 - (in_channels % 4);  // pad to use dp4a
            } else {
                if (in_channels % 32)
                    pad_channels =
                            32 - (in_channels % 32);  // pad to use tensorcore
            }
            if (pad_channels > 0) {
                inps[0] = pad_in_channels(new_inp[0], pad_channels);
                inps[1] = pad_in_channels(new_inp[1], pad_channels);
            }
        }
        out_channels = inps[1]->shape()[0];
        in_channels = inps[1]->shape()[1];
        size_t pad_channels = 0;
4206
        if (out_channels <= 16) {
4207 4208 4209
            if (out_channels % 4)
                pad_channels = 4 - (out_channels % 4);
        } else {
4210 4211
            if (out_channels % 32)
                pad_channels = 32 - (out_channels % 32);
4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229
        }
        if (pad_channels > 0) {
            inps[1] = pad_out_channels(inps[1], pad_channels);
            inps[2] = pad_in_channels(inps[2], pad_channels);
            padding_oprs.insert(opr);
        }
        return serialization::copy_opr_shallow(*opr, inps, opr->config());
    };

    // padding policy for conv bias with data type qint4 and quint4
    auto padding_policy_int4 = [&padding_oprs, &pad_in_channels,
                                &pad_out_channels](
                                       OperatorNodeBase* opr,
                                       const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        mgb_assert(new_inp.size() == 3);
        mgb_assert(opr->input(1)->shape().eq_shape(new_inp[1]->shape()));
        auto inps = new_inp;
4230 4231 4232 4233 4234
        size_t out_channels = opr->input(1)->shape()[0];
        size_t in_channels = opr->input(1)->shape()[1];
        size_t new_in_channels = new_inp[0]->shape()[1];
        // pad input channels
        if (padding_oprs.count(opr->input(0)->owner_opr())) {
4235 4236 4237 4238 4239 4240 4241 4242 4243 4244
            if (new_in_channels <= 32) {
                if (new_in_channels % 8 == 0) {
                    size_t pad_channels = new_in_channels - in_channels;
                    inps[1] = pad_in_channels(new_inp[1], pad_channels);
                } else {
                    size_t pad_channels_0 = 8 - (new_in_channels % 8);
                    size_t pad_channels_1 = 8 - (in_channels % 8);
                    inps[0] = pad_in_channels(new_inp[0], pad_channels_0);
                    inps[1] = pad_in_channels(new_inp[1], pad_channels_1);
                }
4245
            } else {
4246 4247 4248 4249 4250 4251 4252 4253 4254
                if (new_in_channels % 64 == 0) {
                    size_t pad_channels = new_in_channels - in_channels;
                    inps[1] = pad_in_channels(new_inp[1], pad_channels);
                } else {
                    size_t pad_channels_0 = 64 - (new_in_channels % 64);
                    size_t pad_channels_1 = 64 - (in_channels % 64);
                    inps[0] = pad_in_channels(new_inp[0], pad_channels_0);
                    inps[1] = pad_in_channels(new_inp[1], pad_channels_1);
                }
4255 4256 4257 4258
            }
        } else {
            size_t pad_channels = 0;
            mgb_assert(new_in_channels == in_channels);
4259 4260 4261 4262 4263 4264 4265
            if (in_channels <= 32) {
                if (in_channels % 8)
                    pad_channels = 8 - (in_channels % 8);
            } else {
                if (in_channels % 64)
                    pad_channels = 64 - (in_channels % 64);
            }
4266 4267 4268 4269 4270 4271 4272 4273
            if (pad_channels > 0) {
                inps[0] = pad_in_channels(new_inp[0], pad_channels);
                inps[1] = pad_in_channels(new_inp[1], pad_channels);
            }
        }
        out_channels = inps[1]->shape()[0];
        in_channels = inps[1]->shape()[1];
        size_t pad_channels = 0;
4274 4275 4276 4277 4278 4279 4280
        if (out_channels <= 32) {
            if (out_channels % 8)
                pad_channels = 8 - (out_channels % 8);
        } else {
            if (out_channels % 64)
                pad_channels = 64 - (out_channels % 64);
        }
4281 4282 4283 4284 4285
        if (pad_channels > 0) {
            inps[1] = pad_out_channels(inps[1], pad_channels);
            inps[2] = pad_in_channels(inps[2], pad_channels);
            padding_oprs.insert(opr);
        }
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
        return serialization::copy_opr_shallow(*opr, inps, opr->config());
    };

    opr_replace_funcs[opr::ConvBiasForward::typeinfo()] =
            [&padding_oprs, &padding_policy_qint8, &padding_policy_int4](
                    OperatorNodeBase* opr, const VarNodeArray& new_inp) {
                if (opr->input(0)->dtype().enumv() == DTypeEnum::QuantizedS8) {
                    return padding_policy_qint8(opr, new_inp);
                } else if (opr->input(0)->dtype().enumv() ==
                                   DTypeEnum::QuantizedS4 ||
                           opr->input(0)->dtype().enumv() ==
                                   DTypeEnum::Quantized4Asymm) {
                    return padding_policy_int4(opr, new_inp);
                } else {
                    mgb_assert(
                            padding_oprs.count(opr->input(0)->owner_opr()) == 0,
                            "conv bias operator for data type(%s) cannot be "
                            "padded channel. "
                            "consumer(%s), producer(%s)",
                            opr->input(0)->dtype().name(), opr->cname(),
                            opr->input(0)->owner_opr()->cname());
                    return serialization::copy_opr_shallow(*opr, new_inp,
                                                           opr->config());
                }
            };
    opr_replace_funcs[opr::ConvolutionBackwardData::typeinfo()] =
            [&padding_oprs, &pad_in_channels, &pad_out_channels](
                    OperatorNodeBase* opr, const VarNodeArray& new_inp) {
                if (opr->input(1)->dtype().enumv() != DTypeEnum::QuantizedS8) {
                    mgb_assert(
                            padding_oprs.count(opr->input(0)->owner_opr()) == 0,
                            "conv bwd data operator for data type(%s) cannot "
                            "be "
                            "padded channel. "
                            "consumer(%s), producer(%s)",
                            opr->input(0)->dtype().name(), opr->cname(),
                            opr->input(0)->owner_opr()->cname());
                    return serialization::copy_opr_shallow(*opr, new_inp,
                                                           opr->config());
                }
                mgb_assert(opr->input().size() == new_inp.size());
                mgb_assert(new_inp.size() == 2,
                           "deconv (conv bwd data) operator for inference can "
                           "only have 2 input vars(got:%zu)",
                           new_inp.size());
                mgb_assert(
                        opr->input(0)->shape().eq_shape(new_inp[0]->shape()));
                auto inps = new_inp;
                size_t out_channels = opr->input(0)->shape()[0];
                size_t in_channels = opr->input(0)->shape()[1];
                size_t new_out_channels = new_inp[1]->shape()[1];
                // pad output channels
                if (padding_oprs.count(opr->input(1)->owner_opr())) {
                    size_t pad_channels = new_out_channels - out_channels;
                    inps[0] = pad_out_channels(new_inp[0], pad_channels);
                } else {
                    size_t pad_channels = 0;
                    if (out_channels % 4)
                        pad_channels = 4 - (out_channels % 4);
                    if (pad_channels > 0) {
                        inps[0] = pad_out_channels(new_inp[0], pad_channels);
                        inps[1] = pad_in_channels(new_inp[1], pad_channels);
                    }
                }
                out_channels = inps[0]->shape()[0];
                in_channels = inps[0]->shape()[1];
                // pad input channels
                size_t pad_channels = 0;
                if (in_channels % 4)
                    pad_channels = 4 - (in_channels % 4);
                if (pad_channels > 0) {
                    inps[0] = pad_in_channels(inps[0], pad_channels);
                    padding_oprs.insert(opr);
                }
                return serialization::copy_opr_shallow(*opr, inps,
                                                       opr->config());
            };
    auto replace_format_aware_opr = [&padding_oprs](
                                            OperatorNodeBase* opr,
                                            const VarNodeArray& new_inp) {
        if (opr->input(0)->dtype().enumv() != DTypeEnum::QuantizedS8 &&
            opr->input(0)->dtype().enumv() != DTypeEnum::QuantizedS4 &&
            opr->input(0)->dtype().enumv() != DTypeEnum::Quantized4Asymm) {
            mgb_assert(padding_oprs.count(opr->input(0)->owner_opr()) == 0,
                       "operator(type:%s,name:%s) for data type(%s) cannot be "
                       "padded channel. extra info:"
                       "consumer(%s), producer(%s)",
                       opr->dyn_typeinfo()->name, opr->cname(),
                       opr->input(0)->dtype().name(), opr->cname(),
                       opr->input(0)->owner_opr()->cname());
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
        mgb_assert(opr->input().size() == new_inp.size());
        if (padding_oprs.count(opr->input(0)->owner_opr())) {
            padding_oprs.insert(opr);
        }
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    opr_replace_funcs[opr::PoolingForward::typeinfo()] =
            replace_format_aware_opr;
    opr_replace_funcs[opr::WarpPerspectiveForward::typeinfo()] =
            replace_format_aware_opr;

    auto replace_elemwise_like_opr = [&padding_oprs, &extract_subtensor](
                                             OperatorNodeBase* opr,
                                             const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        bool have_padding_inp = false;
        bool padding_all_inps = true;
        bool same_padding = true;
        size_t channels_after_padding = 0;
4398
        size_t i = 0;
4399 4400 4401 4402 4403 4404
        for (auto&& cur_inp : opr->input()) {
            bool padding_cur_inp = padding_oprs.count(cur_inp->owner_opr()) > 0;
            if (padding_cur_inp) {
                if (!have_padding_inp)
                    have_padding_inp = true;
                if (channels_after_padding == 0) {
4405
                    channels_after_padding = new_inp[i]->shape()[1];
4406 4407
                } else {
                    same_padding =
4408
                            channels_after_padding == new_inp[i]->shape()[1];
4409 4410 4411 4412
                }
            }
            if (padding_all_inps && (!padding_cur_inp || !same_padding))
                padding_all_inps = false;
4413
            ++i;
4414 4415 4416 4417 4418 4419 4420 4421
        }
        if (have_padding_inp && !padding_all_inps) {
            auto inps = new_inp;
            for (size_t i = 0; i < new_inp.size(); ++i) {
                auto cur_inp = opr->input(i);
                bool padding_cur_inp =
                        padding_oprs.count(cur_inp->owner_opr()) > 0;
                if (padding_cur_inp) {
4422
                    inps[i] = extract_subtensor(inps[i], cur_inp->shape());
4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445
                }
            }
            return serialization::copy_opr_shallow(*opr, inps, opr->config());
        }
        if (padding_all_inps) {
            padding_oprs.insert(opr);
        }
        return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
    };
    opr_replace_funcs[opr::ElemwiseMultiType::typeinfo()] =
            replace_elemwise_like_opr;
    opr_replace_funcs[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
    opr_replace_funcs[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;

    auto replace_nonpadding_oprs = [&padding_oprs, &extract_subtensor](
                                           OperatorNodeBase* opr,
                                           const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        auto inps = new_inp;
        for (size_t i = 0; i < new_inp.size(); ++i) {
            auto cur_inp = opr->input(i);
            bool padding_cur_inp = padding_oprs.count(cur_inp->owner_opr()) > 0;
            if (padding_cur_inp) {
4446
                inps[i] = extract_subtensor(inps[i], cur_inp->shape());
4447 4448 4449 4450 4451 4452 4453
            }
        }
        return serialization::copy_opr_shallow(*opr, inps, opr->config());
    };
    opr_replace_funcs[opr::Reshape::typeinfo()] = replace_nonpadding_oprs;
    opr_replace_funcs[opr::GetVarShape::typeinfo()] = replace_nonpadding_oprs;
    opr_replace_funcs[opr::Concat::typeinfo()] = replace_nonpadding_oprs;
4454 4455
    opr_replace_funcs[opr::Reduce::typeinfo()] = replace_nonpadding_oprs;
    opr_replace_funcs[opr::Subtensor::typeinfo()] = replace_nonpadding_oprs;
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482

    auto on_opr = [&opt, &rewriter, &opr_replace_funcs,
                   &extract_subtensor](OperatorNodeBase* opr) {
        auto it = opr_replace_funcs.find(opr->dyn_typeinfo());
        if (it != opr_replace_funcs.end()) {
            VarNodeArray new_inp;
            new_inp.reserve(opr->input().size());
            for (auto&& inp : opr->input()) {
                new_inp.push_back(rewriter.get_var(inp));
            }
            auto new_opr = (it->second)(opr, new_inp);
            auto &&out0 = opr->output(), &&out1 = new_opr->output();
            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());
            for (size_t i = 0; i < out0.size(); ++i) {
                if (!out0[i]->contain_flag(VarNode::Flag::VOLATILE_CONTENT)) {
                    mgb_assert(!out1[i]->contain_flag(
                            VarNode::Flag::VOLATILE_CONTENT));
                    auto src = out0[i];
                    auto dst = out1[i];
                    if (opt.graph().endpoint_contain(src) &&
                        !src->shape().eq_shape(dst->shape())) {
4483
                        dst = extract_subtensor(dst, src->shape());
4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496
                    }
                    rewriter.replace_var(src, dst, nullptr);
                }
            }
        } else {
            rewriter.auto_replace_outputs(opr);
        }
    };
    opt.graph().iter(on_opr);
    rewriter.apply_inplace();

    MIDOUT_E
}
4497 4498 4499 4500 4501

/* ================ EnableNCHW64Pass =============== */
VarNode* EnableNCHW64Pass::on_graph_endpoint_var(VarNode* new_var,
                                               VarNode* orig_var) const {
    if (!orig_var->shape().eq_shape(new_var->shape())) {
4502
        auto iter = m_opr_format_map.find(new_var->owner_opr());
4503 4504 4505
        mgb_assert(iter != m_opr_format_map.end(),
                   "cannot find opr(type:%s,name:%s) information, related "
                   "output var node(name:%s)",
4506 4507
                   new_var->owner_opr()->dyn_typeinfo()->name,
                   new_var->owner_opr()->cname(), new_var->cname());
4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520
        const auto& fmt = iter->second;
        using LayoutType = RelayoutPlaceholder::LayoutType;
        LayoutType type;
        switch (fmt) {
            case Format::NCHW4:
                type = LayoutType::NCHW4_TO_NCHW;
                break;
            case Format::NCHW32:
                type = LayoutType::NCHW32_TO_NCHW;
                break;
            case Format::NCHW64:
                type = LayoutType::NCHW64_TO_NCHW;
                break;
4521 4522 4523
            case Format::NHWC:
                type = LayoutType::NHWC_TO_NCHW;
                break;
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566
            default:
                mgb_throw(AssertionError,
                          "format(%d) is not supported, related var "
                          "node(name:%s)",
                          static_cast<int>(fmt), orig_var->cname());
        };
        return RelayoutPlaceholder::make(new_var, type).node();
    }
    return new_var;
}

std::unique_ptr<EnableNCHW64Pass>
EnableNCHW64Pass::make_nchw64_converter() {
    MIDOUT_B("EnableNCHW64Pass::make")
    auto ret = std::make_unique<EnableNCHW64Pass>();
    ret->set_var_replace_check_flag(VarReplaceCheckFlag::CHECK_ALL ^
                                    VarReplaceCheckFlag::CHECK_SHAPE);
    auto& replace_func = ret->m_opr_replace_func;
    auto& format_map = ret->m_opr_format_map;
    auto make_new_conv = [](const VarNodeArray& inps,
                            const opr::ConvBiasForward* orig_conv,
                            Format format) {
        auto param = orig_conv->param();
        // change format
        param.format = format;
        if (inps.size() == 2) {
            auto new_conv = opr::ConvBiasForward::make(
                    inps[0], inps[1], param, orig_conv->execution_policy(),
                    orig_conv->config());
            return new_conv.node();
        } else if (inps.size() == 3) {
            auto new_conv = opr::ConvBiasForward::make(
                    inps[0], inps[1], inps[2], param,
                    orig_conv->execution_policy(), orig_conv->config());
            return new_conv.node();
        } else {
            mgb_assert(inps.size() == 4);
            auto new_conv = opr::ConvBiasForward::make(
                    inps[0], inps[1], inps[2], inps[3], param,
                    orig_conv->execution_policy(), orig_conv->config());
            return new_conv.node();
        }
    };
4567 4568 4569 4570 4571 4572
    auto try_transform_to_nchw =
            [&format_map](OperatorNodeBase* opr,
                          const VarNodeArray& new_inp) -> VarNode* {
        mgb_assert(opr->input().size() == new_inp.size());
        bool check_dtype = new_inp[0]->dtype().enumv() == DTypeEnum::Float32 &&
                           new_inp[1]->dtype().enumv() == DTypeEnum::Float32;
4573
        if (opr->input().size() >= 3)
4574
            check_dtype &= new_inp[2]->dtype().enumv() == DTypeEnum::Float32;
4575
        if (opr->input().size() >= 4)
4576
            check_dtype &= new_inp[3]->dtype().enumv() == DTypeEnum::Float32;
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595
        if (!check_dtype)
            return nullptr;
        auto inps = new_inp;
        auto process = [&](size_t i) -> VarNode* {
            auto iter = format_map.find(new_inp[i]->owner_opr());
            if (iter == format_map.end()) {
                return inps[i];
            } else {
                const auto& fmt = iter->second;
                if (fmt == Format::NCHW32) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW);
                    return ovar.node();
                } else if (fmt == Format::NCHW4) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW);
                    return ovar.node();
4596 4597 4598 4599 4600
                } else if (fmt == Format::NHWC) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW);
                    return ovar.node();
4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616
                } else {
                    mgb_assert(fmt == Format::NCHW64);
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW);
                    return ovar.node();
                }
            }
        };
        for (size_t i = 0; i < inps.size(); ++i) {
            inps[i] = process(i);
        }
        auto ret = serialization::copy_opr_shallow(*opr, inps, opr->config());
        return ret->output()[0];
    };

4617 4618 4619 4620
    auto try_transform_to_nchw4 =
            [make_new_conv, &format_map](
                    OperatorNodeBase* opr,
                    const VarNodeArray& new_inp) -> VarNode* {
4621
                        mgb_assert(opr->input().size()==new_inp.size());
4622
        bool check_dtype =
4623 4624
                new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8 &&
                new_inp[1]->dtype().enumv() == DTypeEnum::QuantizedS8;
4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635
        mgb_assert(opr->output().size() > 0);
        bool dst_float = opr->output(0)->dtype().enumv() == DTypeEnum::Float32;
        if (opr->input().size() >= 3) {
            auto dtype_expect = dst_float ? DTypeEnum::Float32
                                          : DTypeEnum::QuantizedS32;
            check_dtype &= new_inp[2]->dtype().enumv() == dtype_expect;
        }
        if (opr->input().size() >= 4) {
            check_dtype &= new_inp[3]->dtype().enumv() ==
                           opr->output(0)->dtype().enumv();
        }
4636 4637
        if (!check_dtype)
            return nullptr;
4638

4639 4640 4641 4642 4643 4644 4645 4646
        size_t out_channels = opr->input(1)->shape()[0];
        size_t in_channels = opr->input(1)->shape()[1];
        bool check_channels = out_channels % 4 == 0 && in_channels % 4 == 0;
        mgb_assert(check_channels,
                   "invalid quantize conv bias opr(name:%s,oc:%zu,ic:%zu)",
                   opr->cname(), out_channels, in_channels);
        auto inps = new_inp;
        auto process = [&](size_t i) -> VarNode* {
4647
            auto iter = format_map.find(new_inp[i]->owner_opr());
4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661
            if (iter == format_map.end()) {
                auto ovar = RelayoutPlaceholder::make(
                        inps[i],
                        RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4);
                return ovar.node();
            } else {
                const auto& fmt = iter->second;
                if (fmt == Format::NCHW4) {
                    return inps[i];
                } else if (fmt == Format::NCHW32) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
                    return ovar.node();
4662 4663 4664 4665 4666
                } else if (fmt == Format::NHWC) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW4);
                    return ovar.node();
4667 4668 4669 4670 4671 4672 4673 4674 4675
                } else {
                    mgb_assert(fmt == Format::NCHW64);
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW4);
                    return ovar.node();
                }
            }
        };
4676

4677
        for (size_t i = 0; i < inps.size(); ++i) {
4678 4679 4680
            // do not format bias and z when dst_float is true
            bool skip = dst_float && i >= 2;
            if (!skip) inps[i] = process(i);
4681 4682
        }
        auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
4683 4684 4685 4686 4687
        auto ret = make_new_conv(
                inps, &conv_bias,
                dst_float ? Format::NCHW4_NCHW : Format::NCHW4);
        if (!dst_float)
            format_map.insert(std::make_pair(ret->owner_opr(), Format::NCHW4));
4688
        return ret;
4689 4690 4691 4692 4693 4694
    };

    auto try_transform_to_nchw32 =
            [make_new_conv, &format_map](
                    OperatorNodeBase* opr,
                    const VarNodeArray& new_inp) -> VarNode* {
4695
        mgb_assert(opr->input().size()==new_inp.size());
4696
        bool check_dtype =
4697 4698
                new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8 &&
                new_inp[1]->dtype().enumv() == DTypeEnum::QuantizedS8;
4699 4700
        if (opr->input().size() >= 3)
            check_dtype &=
4701
                    new_inp[2]->dtype().enumv() == DTypeEnum::QuantizedS32;
4702 4703
        if (opr->input().size() >= 4)
            check_dtype &=
4704
                    new_inp[3]->dtype().enumv() == DTypeEnum::QuantizedS8;
4705 4706 4707 4708 4709 4710 4711 4712 4713
        if (!check_dtype)
            return nullptr;
        size_t out_channels = opr->input(1)->shape()[0];
        size_t in_channels = opr->input(1)->shape()[1];
        bool check_channels = out_channels % 32 == 0 && in_channels % 32 == 0;
        if (!check_channels)
            return nullptr;
        auto inps = new_inp;
        auto process = [&](size_t i) -> VarNode* {
4714
            auto iter = format_map.find(new_inp[i]->owner_opr());
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728
            if (iter == format_map.end()) {
                auto ovar = RelayoutPlaceholder::make(
                        inps[i],
                        RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW32);
                return ovar.node();
            } else {
                const auto& fmt = iter->second;
                if (fmt == Format::NCHW32) {
                    return inps[i];
                } else if (fmt == Format::NCHW4) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
                    return ovar.node();
4729 4730 4731 4732 4733
                } else if (fmt == Format::NHWC) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW32);
                    return ovar.node();
4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746
                } else {
                    mgb_assert(fmt == Format::NCHW64);
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW32);
                    return ovar.node();
                }
            }
        };
        for (size_t i = 0; i < inps.size(); ++i) {
            inps[i] = process(i);
        }
        auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
4747 4748 4749
        auto ret = make_new_conv(inps, &conv_bias, Format::NCHW32);
        format_map.insert(std::make_pair(ret->owner_opr(), Format::NCHW32));
        return ret;
4750 4751 4752 4753 4754 4755 4756
    };

    auto try_transform_to_nchw64 =
            [make_new_conv, &format_map](
                    OperatorNodeBase* opr,
                    const VarNodeArray& new_inp) -> VarNode* {
        // fint4XWint4 and fuint4XWint4
4757
        mgb_assert(opr->input().size()==new_inp.size());
4758
        bool check_dtype =
4759 4760
                (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS4 ||
                 new_inp[0]->dtype().enumv() ==
4761
                         DTypeEnum::Quantized4Asymm) &&
4762
                new_inp[1]->dtype().enumv() == DTypeEnum::QuantizedS4;
4763 4764
        if (opr->input().size() >= 3)
            check_dtype &=
4765
                    new_inp[2]->dtype().enumv() == DTypeEnum::QuantizedS32;
4766
        if (opr->input().size() >= 4)
4767 4768
            check_dtype &= new_inp[3]->dtype().enumv() ==
                           new_inp[0]->dtype().enumv();
4769 4770 4771 4772 4773 4774 4775 4776 4777
        if (!check_dtype)
            return nullptr;
        size_t out_channels = opr->input(1)->shape()[0];
        size_t in_channels = opr->input(1)->shape()[1];
        bool check_channels = out_channels % 64 == 0 && in_channels % 64 == 0;
        if (!check_channels)
            return nullptr;
        auto inps = new_inp;
        auto process = [&](size_t i) -> VarNode* {
4778
            auto iter = format_map.find(new_inp[i]->owner_opr());
4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792
            if (iter == format_map.end()) {
                auto ovar = RelayoutPlaceholder::make(
                        inps[i],
                        RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW64);
                return ovar.node();
            } else {
                const auto& fmt = iter->second;
                if (fmt == Format::NCHW64) {
                    return inps[i];
                } else if (fmt == Format::NCHW4) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW64);
                    return ovar.node();
4793 4794 4795 4796 4797
                } else if (fmt == Format::NHWC) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NHWC_TO_NCHW64);
                    return ovar.node();
4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810
                } else {
                    mgb_assert(fmt == Format::NCHW32);
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW64);
                    return ovar.node();
                }
            }
        };
        for (size_t i = 0; i < inps.size(); ++i) {
            inps[i] = process(i);
        }
        auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
4811 4812 4813
        auto ret = make_new_conv(inps, &conv_bias, Format::NCHW64);
        format_map.insert(std::make_pair(ret->owner_opr(), Format::NCHW64));
        return ret;
4814 4815
    };

4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879
    auto try_transform_to_nhwc =
            [make_new_conv, &format_map](
                    OperatorNodeBase* opr,
                    const VarNodeArray& new_inp) -> VarNode* {
        // fint4XWint4 and fuint4XWint4
        mgb_assert(opr->input().size()==new_inp.size());
        bool check_dtype =
                (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS4 ||
                 new_inp[0]->dtype().enumv() ==
                         DTypeEnum::Quantized4Asymm) &&
                new_inp[1]->dtype().enumv() == DTypeEnum::QuantizedS4;
        if (opr->input().size() >= 3)
            check_dtype &=
                    new_inp[2]->dtype().enumv() == DTypeEnum::QuantizedS32;
        if (opr->input().size() >= 4)
            check_dtype &= new_inp[3]->dtype().enumv() ==
                           new_inp[0]->dtype().enumv();
        if (!check_dtype)
            return nullptr;
        size_t out_channels = opr->input(1)->shape()[0];
        size_t in_channels = opr->input(1)->shape()[1];
        bool check_channels = out_channels % 8 == 0 && in_channels % 8 == 0;
        if (!check_channels)
            return nullptr;
        auto inps = new_inp;
        auto process = [&](size_t i) -> VarNode* {
            auto iter = format_map.find(new_inp[i]->owner_opr());
            if (iter == format_map.end()) {
                auto ovar = RelayoutPlaceholder::make(
                        inps[i],
                        RelayoutPlaceholder::LayoutType::NCHW_TO_NHWC);
                return ovar.node();
            } else {
                const auto& fmt = iter->second;
                if (fmt == Format::NHWC) {
                    return inps[i];
                } else if (fmt == Format::NCHW4) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW4_TO_NHWC);
                    return ovar.node();
                } else if (fmt == Format::NCHW32) {
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW32_TO_NHWC);
                    return ovar.node();
                } else {
                    mgb_assert(fmt == Format::NCHW64);
                    auto ovar = RelayoutPlaceholder::make(
                            inps[i],
                            RelayoutPlaceholder::LayoutType::NCHW64_TO_NHWC);
                    return ovar.node();
                }
            }
        };
        for (size_t i = 0; i < inps.size(); ++i) {
            inps[i] = process(i);
        }
        auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
        auto ret = make_new_conv(inps, &conv_bias, Format::NHWC);
        format_map.insert(std::make_pair(ret->owner_opr(), Format::NHWC));
        return ret;
    };

4880 4881 4882
    // replace rule for conv bias opr
    auto replace_conv_bias_opr = [&format_map, try_transform_to_nchw4,
                                  try_transform_to_nchw32,
4883 4884
                                  try_transform_to_nchw64,
                                  try_transform_to_nhwc, try_transform_to_nchw](
4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895
                                         OperatorNodeBase* opr,
                                         const VarNodeArray& new_inp) {
        using Param = megdnn::param::ConvBias;
        using Sparse = Param::Sparse;
        mgb_assert(opr->input().size() == new_inp.size());
        auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
        mgb_assert(conv_bias.param().sparse == Sparse::DENSE,
                   "only support dense conv now");
        VarNode* new_var = nullptr;
        if ((new_var = try_transform_to_nchw32(opr, new_inp)) ||
            (new_var = try_transform_to_nchw4(opr, new_inp)) ||
4896 4897
            (new_var = try_transform_to_nchw64(opr, new_inp)) ||
            (new_var = try_transform_to_nhwc(opr, new_inp)) ||
4898
            (new_var = try_transform_to_nchw(opr, new_inp))) {
4899 4900 4901
            return new_var->owner_opr();
        } else {
            mgb_assert(
4902 4903
                    new_inp[0]->dtype().enumv() != DTypeEnum::QuantizedS8 &&
                            new_inp[0]->dtype().enumv() !=
4904
                                    DTypeEnum::QuantizedS4 &&
4905 4906 4907 4908
                            new_inp[0]->dtype().enumv() !=
                                    DTypeEnum::Quantized4Asymm &&
                            new_inp[0]->dtype().enumv() != DTypeEnum::Float32,
                    "invalid data type(%s)", new_inp[0]->dtype().name());
4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934
            bool shape_changed = false;
            for (const auto& i : new_inp) {
                if (format_map.count(i->owner_opr()) > 0) {
                    shape_changed = true;
                    break;
                }
            }
            mgb_assert(!shape_changed,
                       "EnableNCHW64Pass won't change format of output tensor "
                       "of non quantized conv bias operator(name:%s)",
                       opr->cname());
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
    };
    replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;
    replace_func[opr::ConvolutionBackwardData::
                         typeinfo()] = [&format_map](OperatorNodeBase* opr,
                                                     const VarNodeArray&
                                                             new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        mgb_assert(new_inp.size() == 2,
                   "deconv (conv bwd data) operator for inference can "
                   "only have 2 input vars(got:%zu)",
                   new_inp.size());
        auto& deconv = opr->cast_final_safe<opr::ConvolutionBackwardData>();
4935
        if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8) {
4936
            Format cur;
4937
            auto iter = format_map.find(new_inp[1]->owner_opr());
4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954
            if (iter == format_map.end()) {
                cur = Format::NCHW;
            } else {
                cur = iter->second;
            }
            auto inps = new_inp;
            inps[0] = RelayoutPlaceholder::make(
                              inps[0],
                              RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4)
                              .node();
            switch (cur) {
                case Format::NCHW:
                    inps[1] = RelayoutPlaceholder::make(
                                      inps[1], RelayoutPlaceholder::LayoutType::
                                                       NCHW_TO_NCHW4)
                                      .node();
                    break;
4955 4956 4957
                case Format::NHWC:
                    inps[1] = RelayoutPlaceholder::make(
                                      inps[1], RelayoutPlaceholder::LayoutType::
4958
                                                       NHWC_TO_NCHW4)
4959 4960
                                      .node();
                    break;
4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
                case Format::NCHW32:
                    inps[1] = RelayoutPlaceholder::make(
                                      inps[1], RelayoutPlaceholder::LayoutType::
                                                       NCHW32_TO_NCHW4)
                                      .node();
                    break;
                case Format::NCHW64:
                    inps[1] = RelayoutPlaceholder::make(
                                      inps[1], RelayoutPlaceholder::LayoutType::
                                                       NCHW64_TO_NCHW4)
                                      .node();
                    break;
                default:
                    mgb_assert(cur == Format::NCHW4);
            }
4976
            
4977 4978 4979 4980 4981
            auto param = deconv.param();
            param.format = Format::NCHW4;
            auto new_deconv = opr::ConvolutionBackwardData::make(
                    inps[0], inps[1], param, deconv.execution_policy(),
                    deconv.config());
4982 4983 4984
            auto ret = new_deconv.node()->owner_opr();
            format_map.insert(std::make_pair(ret, Format::NCHW4));
            return ret;
4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008
        } else {
            bool shape_changed = false;
            for (const auto& i : new_inp) {
                if (format_map.count(i->owner_opr()) > 0) {
                    shape_changed = true;
                    break;
                }
            }
            mgb_assert(!shape_changed, 
                       "EnableNCHW64Pass won't change format of output tensor "
                       "of non quantized deconv operator(name:%s)",
                       opr->cname());
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
    };

    // replace rule for elemwise like opr
    auto replace_elemwise_like_opr = [&format_map](OperatorNodeBase* opr,
                                        const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        ThinHashMap<Format, size_t> format_size;
        bool same_format = true;
        bool first_touch = false;
5009
        Format format(Format::NCHW);
5010
        for (const auto& i : new_inp) {
5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028
            Format cur;
            auto iter = format_map.find(i->owner_opr());
            if (iter == format_map.end()) {
                cur = Format::NCHW;
            } else {
                cur = iter->second;
            }
            auto& size = format_size[cur];
            size += i->shape().total_nr_elems();
            if (!first_touch) {
                first_touch = true;
                format = cur;
            } else {
                if (format != cur)
                    same_format = false;
            }
        }
        if (same_format) {
5029 5030
            auto ret = serialization::copy_opr_shallow(*opr, new_inp,
                                                       opr->config());
5031
            if (format != Format::NCHW)
5032 5033
                format_map.insert(std::make_pair(ret, format));
            return ret;
5034 5035
        }

5036
        Format max_format(Format::NCHW);
5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060
        size_t max_size = std::numeric_limits<size_t>::min();
        for (const auto& item : format_size) {
            if (item.second > max_size) {
                max_format = item.first;
                max_size = item.second;
            }
        }
        static const ThinHashMap<std::pair<Format, Format>,
                                 thin_function<VarNode*(VarNode*)>>
                map = {
#define cb(_fmt1, _fmt2)                                                 \
    {                                                                    \
        std::make_pair(Format::_fmt1, Format::_fmt2),                    \
                [](VarNode* in) -> VarNode* {                            \
                    return RelayoutPlaceholder::make(                    \
                                   in, RelayoutPlaceholder::LayoutType:: \
                                               _fmt1##_TO_##_fmt2)       \
                            .node();                                     \
                }                                                        \
    }
                        cb(NCHW, NCHW4),  cb(NCHW, NCHW32),  cb(NCHW, NCHW64),
                        cb(NCHW4, NCHW),  cb(NCHW4, NCHW32), cb(NCHW4, NCHW64),
                        cb(NCHW32, NCHW), cb(NCHW32, NCHW4), cb(NCHW32, NCHW64),
                        cb(NCHW32, NCHW), cb(NCHW32, NCHW4), cb(NCHW32, NCHW64),
5061 5062 5063
                        cb(NCHW, NHWC),   cb(NCHW4, NHWC),   cb(NCHW32, NHWC),
                        cb(NCHW64, NHWC), cb(NHWC, NCHW),    cb(NHWC, NCHW4),
                        cb(NHWC, NCHW32), cb(NHWC, NCHW64),
5064 5065 5066 5067
#undef cb
                };
        auto inps = new_inp;
        for (size_t i = 0; i < opr->input().size(); ++i) {
5068
            auto iter = format_map.find(new_inp[i]->owner_opr());
5069 5070 5071 5072 5073 5074 5075 5076 5077 5078
            Format cur;
            if (iter != format_map.end()) {
                cur = iter->second;
            } else {
                cur = Format::NCHW;
            }
            if (cur != max_format) {
                inps[i] = map.at(std::make_pair(cur, max_format))(inps[i]); 
            }
        }
5079
        auto ret = serialization::copy_opr_shallow(*opr, inps, opr->config());
5080
        if (max_format != Format::NCHW)
5081 5082
            format_map.insert(std::make_pair(ret, max_format));
        return ret;
5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095
    };
    // elemwise like
    replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
    replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
    replace_func[opr::ElemwiseMultiType::typeinfo()] =
            replace_elemwise_like_opr;
    replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;

    auto replace_warp_perspective_opr = [&format_map](
                                                OperatorNodeBase* opr,
                                                const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        auto& warp = opr->cast_final_safe<opr::WarpPerspectiveForward>();
5096 5097
        if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS4 ||
            new_inp[0]->dtype().enumv() == DTypeEnum::Quantized4Asymm) {
5098
            Format cur;
5099
            auto iter = format_map.find(new_inp[0]->owner_opr());
5100 5101 5102 5103 5104 5105 5106 5107 5108 5109
            if (iter == format_map.end()) {
                cur = Format::NCHW;
            } else {
                cur = iter->second;
            }
            auto inps = new_inp;
            switch (cur) {
                case Format::NCHW:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
5110
                                                       NCHW_TO_NHWC)
5111 5112 5113 5114 5115
                                      .node();
                    break;
                case Format::NCHW4:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
5116
                                                       NCHW4_TO_NHWC)
5117 5118 5119 5120 5121
                                      .node();
                    break;
                case Format::NCHW32:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
5122
                                                       NCHW32_TO_NHWC)
5123 5124 5125
                                      .node();
                    break;
                default:
5126
                    mgb_assert(cur == Format::NCHW64 || cur == Format::NHWC);
5127
            }
5128
            auto target_format = cur == Format::NCHW64 ? cur : Format::NHWC;
5129
            auto param = warp.param();
5130
            param.format = target_format;
5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141
            SymbolVar new_warp;
            if (inps.size() == 3) {
                new_warp = opr::WarpPerspectiveForward::make(
                        inps[0], inps[1], inps[2], param,
                        warp.config());
            } else {
                mgb_assert(inps.size() == 4);
                new_warp = opr::WarpPerspectiveForward::make(
                        inps[0], inps[1], inps[2], inps[3], param,
                        warp.config());
            }
5142
            auto ret = new_warp.node()->owner_opr();
5143
            format_map.insert(std::make_pair(ret, target_format));
5144 5145
            return ret;
        } else if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8) {
5146
            Format cur;
5147
            auto iter = format_map.find(new_inp[0]->owner_opr());
5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160
            if (iter == format_map.end()) {
                cur = Format::NCHW;
            } else {
                cur = iter->second;
            }
            auto inps = new_inp;
            switch (cur) {
                case Format::NCHW:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
                                                       NCHW_TO_NCHW4)
                                      .node();
                    break;
5161 5162 5163 5164 5165 5166
                case Format::NHWC:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
                                                       NHWC_TO_NCHW4)
                                      .node();
                    break;
5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181
                case Format::NCHW32:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
                                                       NCHW32_TO_NCHW4)
                                      .node();
                    break;
                case Format::NCHW64:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
                                                       NCHW64_TO_NCHW4)
                                      .node();
                    break;
                default:
                    mgb_assert(cur == Format::NCHW4);
            }
5182
            
5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195
            auto param = warp.param();
            param.format = Format::NCHW4;
            SymbolVar new_warp;
            if (inps.size() == 3) {
                new_warp = opr::WarpPerspectiveForward::make(
                        inps[0], inps[1], inps[2], param,
                        warp.config());
            } else {
                mgb_assert(inps.size() == 4);
                new_warp = opr::WarpPerspectiveForward::make(
                        inps[0], inps[1], inps[2], inps[3], param,
                        warp.config());
            }
5196 5197 5198
            auto ret = new_warp.node()->owner_opr();
            format_map.insert(std::make_pair(ret, Format::NCHW4));
            return ret;
5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219
        } else {
            bool shape_changed = false;
            for (const auto& i : new_inp) {
                if (format_map.count(i->owner_opr()) > 0) {
                    shape_changed = true;
                    break;
                }
            }
            mgb_assert(!shape_changed, 
                       "EnableNCHW64Pass won't change format of output tensor "
                       "of non quantized warp perspective operator(name:%s)",
                       opr->cname());
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
    };
    auto replace_pooling_opr = [&format_map](
                                       OperatorNodeBase* opr,
                                       const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
5220 5221
        if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS4 ||
            new_inp[0]->dtype().enumv() == DTypeEnum::Quantized4Asymm) {
5222
            Format cur;
5223
            auto iter = format_map.find(new_inp[0]->owner_opr());
5224 5225 5226 5227 5228 5229 5230 5231 5232 5233
            if (iter == format_map.end()) {
                cur = Format::NCHW;
            } else {
                cur = iter->second;
            }
            auto inps = new_inp;
            switch (cur) {
                case Format::NCHW:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
5234
                                                       NCHW_TO_NHWC)
5235 5236 5237 5238 5239
                                      .node();
                    break;
                case Format::NCHW4:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
5240
                                                       NCHW4_TO_NHWC)
5241 5242 5243 5244 5245
                                      .node();
                    break;
                case Format::NCHW32:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
5246
                                                       NCHW32_TO_NHWC)
5247 5248 5249
                                      .node();
                    break;
                default:
5250
                    mgb_assert(cur == Format::NCHW64 || cur == Format::NHWC);
5251
            }
5252
            auto target_format = cur == Format::NCHW64 ? cur : Format::NHWC;
5253
            auto param = pooling.param();
5254
            param.format = target_format;
5255 5256
            auto new_pool =
                    opr::PoolingForward::make(inps[0], param, pooling.config());
5257
            auto ret = new_pool.node()->owner_opr();
5258
            format_map.insert(std::make_pair(ret, target_format));
5259 5260
            return ret;
        } else if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8) {
5261
            Format cur;
5262
            auto iter = format_map.find(new_inp[0]->owner_opr());
5263 5264 5265 5266 5267 5268 5269 5270 5271 5272
            if (iter == format_map.end()) {
                cur = Format::NCHW;
            } else {
                cur = iter->second;
            }
            bool use_nchw32 = false;
            auto inps = new_inp;
            using LayoutType = RelayoutPlaceholder::LayoutType;
            switch (cur) {
                case Format::NCHW: {
5273
                    size_t in_channels = new_inp[0]->shape()[1];
5274 5275 5276 5277 5278 5279 5280
                    use_nchw32 = in_channels % 32 == 0;
                    auto layout_type = use_nchw32 ? LayoutType::NCHW_TO_NCHW32
                                                  : LayoutType::NCHW_TO_NCHW4;
                    inps[0] = RelayoutPlaceholder::make(inps[0], layout_type)
                                      .node();
                    break;
                }
5281 5282 5283 5284 5285 5286 5287 5288 5289
                case Format::NHWC: {
                    size_t in_channels = new_inp[0]->shape()[3];
                    use_nchw32 = in_channels % 32 == 0;
                    auto layout_type = use_nchw32 ? LayoutType::NHWC_TO_NCHW32
                                                  : LayoutType::NHWC_TO_NCHW4;
                    inps[0] = RelayoutPlaceholder::make(inps[0], layout_type)
                                      .node();
                    break;
                }
5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302
                case Format::NCHW64:
                    inps[0] = RelayoutPlaceholder::make(
                                      inps[0], RelayoutPlaceholder::LayoutType::
                                                       NCHW64_TO_NCHW32)
                                      .node();
                    break;
                case Format::NCHW32:
                    use_nchw32 = true;
                    break;
                default:
                    mgb_assert(cur == Format::NCHW4);
            }
            Format out_format = use_nchw32 ? Format::NCHW32 : Format::NCHW4;
5303
            
5304 5305 5306 5307
            auto param = pooling.param();
            param.format = out_format;
            auto new_pool =
                    opr::PoolingForward::make(inps[0], param, pooling.config());
5308 5309 5310
            auto ret = new_pool.node()->owner_opr();
            format_map.insert(std::make_pair(ret, out_format));
            return ret;
5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337
        } else {
            bool shape_changed = false;
            for (const auto& i : new_inp) {
                if (format_map.count(i->owner_opr()) > 0) {
                    shape_changed = true;
                    break;
                }
            }
            mgb_assert(!shape_changed,
                       "EnableNCHW64Pass won't change format of output tensor "
                       "of non quantized pooling operator(name:%s)",
                       opr->cname());
            return serialization::copy_opr_shallow(*opr, new_inp,
                                                   opr->config());
        }
    };
    // format aware
    replace_func[opr::WarpPerspectiveForward::typeinfo()] =
            replace_warp_perspective_opr;
    replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;

    // to nchw
    auto replace_inps_to_nchw = [&format_map](OperatorNodeBase* opr,
                                              const VarNodeArray& new_inp) {
        mgb_assert(opr->input().size() == new_inp.size());
        auto inps = new_inp;
        for (size_t i = 0; i < opr->input().size(); ++i) {
5338 5339
            auto iter = format_map.find(new_inp[i]->owner_opr());
            auto fmt = iter != format_map.end()?iter->second:Format::NCHW;
5340 5341
            if (iter != format_map.end()) {
                switch (fmt) {
5342 5343 5344 5345 5346 5347 5348
                    case Format::NHWC:
                        inps[i] = RelayoutPlaceholder::make(
                                          inps[i],
                                          RelayoutPlaceholder::LayoutType::
                                                  NHWC_TO_NCHW)
                                          .node();
                        break;
5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373
                    case Format::NCHW4:
                        inps[i] = RelayoutPlaceholder::make(
                                          inps[i],
                                          RelayoutPlaceholder::LayoutType::
                                                  NCHW4_TO_NCHW)
                                          .node();
                        break;
                    case Format::NCHW32:
                        inps[i] = RelayoutPlaceholder::make(
                                          inps[i],
                                          RelayoutPlaceholder::LayoutType::
                                                  NCHW32_TO_NCHW)
                                          .node();
                        break;
                    default:
                        mgb_assert(fmt == Format::NCHW64);
                        inps[i] = RelayoutPlaceholder::make(
                                          inps[i],
                                          RelayoutPlaceholder::LayoutType::
                                                  NCHW64_TO_NCHW)
                                          .node();
                        break;
                }
            }
        }
5374 5375
        auto ret = serialization::copy_opr_shallow(*opr, inps, opr->config());
        return ret;
5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386
    };

    replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw;
    replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw;
    replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw;
    replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw;
    replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw;
    replace_func[opr::Subtensor::typeinfo()] = replace_inps_to_nchw;
    return ret;
    MIDOUT_E
}
5387
// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}