inference.cpp 203.5 KB
Newer Older
1 2 3 4
/**
 * \file src/gopt/test/inference.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
M
Megvii Engine Team 已提交
9 10
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
11 12
 */

13
#include "megbrain/opr/dnn/local.h"
14 15 16 17
#include "megbrain/test/helper.h"

#include "megbrain/gopt/basic_arith.h"
#include "megbrain/gopt/gtrans.h"
M
Megvii Engine Team 已提交
18
#include "megbrain/gopt/inference.h"
19 20

#include "megbrain/opr/basic_arith_wrapper.h"
M
Megvii Engine Team 已提交
21
#include "megbrain/opr/blas.h"
22 23
#include "megbrain/opr/dnn/batch_norm.h"
#include "megbrain/opr/dnn/convolution.h"
M
Megvii Engine Team 已提交
24
#include "megbrain/opr/dnn/pooling.h"
25
#include "megbrain/opr/imgproc.h"
M
Megvii Engine Team 已提交
26
#include "megbrain/opr/io.h"
27
#include "megbrain/opr/nn_int.h"
28
#include "megbrain/opr/tensor_gen.h"
M
Megvii Engine Team 已提交
29 30
#include "megbrain/opr/tensor_manip.h"
#include "megbrain/opr/utility.h"
31 32

#include "./helper.h"
M
Megvii Engine Team 已提交
33
#include "megbrain/comp_node_env.h"
34 35 36 37

#include "megdnn/tensor_format.h"

#include <random>
38
#include <vector>
39

40 41 42 43
#if MGB_CUDA
#include <cudnn.h>
#endif

44 45 46 47 48 49 50 51 52 53 54 55 56
using namespace mgb;

namespace {
//! find first the operator of specific type; raise exception if not found
template <typename T>
T& find_opr(SymbolVar endpoint) {
    T* found = nullptr;
    auto cb = [&found](cg::OperatorNodeBase* opr) {
        if (!found && opr->same_type<T>()) {
            found = &opr->cast_final_safe<T>();
        }
    };
    cg::DepOprIter{cb}.add(endpoint.node()->owner_opr());
57 58 59 60 61 62 63 64 65 66 67 68 69
    mgb_assert(found, "not found opr from %s", endpoint.node()->name().c_str());
    return *found;
}

template <typename T>
T& find_opr(SymbolVar endpoint, const std::string& node_name) {
    T* found = nullptr;
    auto cb = [&found, &node_name](cg::OperatorNodeBase* opr) {
        if (!found && opr->same_type<T>() && opr->name() == node_name) {
            found = &opr->cast_final_safe<T>();
        }
    };
    cg::DepOprIter{cb}.add(endpoint.node()->owner_opr());
M
Megvii Engine Team 已提交
70 71 72
    mgb_assert(
            found, "not found opr %s from %s", node_name.c_str(),
            endpoint.node()->name().c_str());
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
    return *found;
}

template <typename T>
size_t find_opr_num(SymbolVar endpoint) {
    size_t opr_num = 0;
    auto cb = [&opr_num](cg::OperatorNodeBase* opr) {
        if (opr->same_type<T>()) {
            opr_num++;
        }
    };
    cg::DepOprIter{cb}.add(endpoint.node()->owner_opr());
    return opr_num;
}

class NaiveMegDNNHandleScope {
    int m_orig_level;

public:
    NaiveMegDNNHandleScope()
            : m_orig_level{MegDNNHandle::exchange_default_dbg_level(2)} {
        CompNode::finalize();
    }
    ~NaiveMegDNNHandleScope() {
        auto set = MegDNNHandle::exchange_default_dbg_level(m_orig_level);
        mgb_assert(set == 2);
        CompNode::finalize();
    }
};

#if MGB_CUDA
//! this function is only used in TestGoptInference.EnableCHWN4...
M
Megvii Engine Team 已提交
105
void warp_perspective_mat_gen(HostTensorND& mat, size_t N, size_t INP_H, size_t INP_W) {
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    static std::mt19937 rng(next_rand_seed());
    auto rand_real = [&](double lo, double hi) {
        return rng() / (std::mt19937::max() + 1.0) * (hi - lo) + lo;
    };
    auto rand_real2 = [&](double range) { return rand_real(-range, range); };
    auto ptr = mat.ptr<float>();
    for (size_t i = 0; i < N; ++i) {
        auto rot = rand_real(0, M_PI * 2), scale = rand_real(0.8, 1.2),
             sheer = rand_real(0.9, 1.1), dy = rand_real2(INP_H * 0.5),
             dx = rand_real2(INP_W * 0.5), ky = rand_real2(0.1 / INP_H),
             kx = rand_real2(0.1 / INP_W), kb = rand_real2(0.1) + 1;
        ptr[0] = ptr[4] = cos(rot) * scale;
        ptr[1] = -(ptr[3] = sin(rot) * scale);
        ptr[3] *= sheer;
        ptr[4] *= sheer;
        ptr[2] = dx;
        ptr[5] = dy;
        ptr[6] = kx;
        ptr[7] = ky;
        ptr[8] = kb;
        ptr += 9;
    }
    mgb_assert(ptr == mat.ptr<float>() + mat.shape().total_nr_elems());
}
#endif
}  // namespace

133 134 135 136 137 138 139 140 141
TEST(TestGoptInference, ParamFuseConstEndPoint) {
    constexpr size_t SIZE = 23;
    HostTensorGenerator<> gen;
    auto host_x = gen({SIZE}), host_y = gen({1}), host_p = gen({1});

    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto x = opr::SharedDeviceTensor::make(*graph, *host_x),
         y = opr::SharedDeviceTensor::make(*graph, *host_y),
M
Megvii Engine Team 已提交
142 143
         p = opr::Host2DeviceCopy::make(*graph, host_p), q = p + x, a = y + 3,
         z0 = a + q, z1 = a + 4;
144 145 146 147

    HostTensorND host_z0, host_z1;

    SymbolVar z0_1, z1_1;
M
Megvii Engine Team 已提交
148 149 150 151 152 153 154 155 156
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{z1, z0}})
                    .endpoint_vars(),
            z1_1, z0_1);

    auto func = graph->compile(
            {make_callback_copy(z0_1, host_z0), make_callback_copy(z1_1, host_z1)});
157 158 159 160 161
    func->to_json()->writeto_fpath(
            output_file("TestGoptInference.ParamFuseEndPoint.json"));
    func->execute();

    int nr_opr = 0;
M
Megvii Engine Team 已提交
162 163 164 165
    func->iter_opr_seq([&](cg::OperatorNodeBase*) {
        ++nr_opr;
        return true;
    });
166 167 168 169 170 171 172
    ASSERT_EQ(8, nr_opr);

    auto px = host_x->ptr<float>(), pz0 = host_z0.ptr<float>();

    auto yv = host_y->ptr<float>()[0], pv = host_p->ptr<float>()[0],
         pz1 = host_z1.ptr<float>()[0];

M
Megvii Engine Team 已提交
173
    for (size_t i = 0; i < SIZE; ++i) {
174 175 176 177 178
        MGB_ASSERT_FLOAT_EQ(px[i] + yv + 3 + pv, pz0[i]);
    }
    MGB_ASSERT_FLOAT_EQ(yv + 7, pz1);
}

179 180 181 182 183 184 185 186 187 188
TEST(TestGoptInference, ParamFuse) {
    constexpr size_t SIZE = 23;
    HostTensorGenerator<> gen;
    auto host_x = gen({SIZE}), host_y = gen({1}), host_p = gen({1});

    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto x = opr::SharedDeviceTensor::make(*graph, *host_x),
         y = opr::SharedDeviceTensor::make(*graph, *host_y),
         p = opr::Host2DeviceCopy::make(*graph, host_p),
M
Megvii Engine Team 已提交
189 190
         z = x + y,         // endpoint
            q = x * y + p;  // middle point
191 192

    SymbolVar z1, q1;
M
Megvii Engine Team 已提交
193 194 195 196 197 198
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{z, q}})
                    .endpoint_vars(),
            z1, q1);
199 200 201

    ASSERT_TRUE(z1.node()->owner_opr()->same_type<opr::SharedDeviceTensor>());
    ASSERT_NE(q1.node()->owner_opr(), q.node()->owner_opr());
M
Megvii Engine Team 已提交
202 203 204
    ASSERT_EQ(
            q1.node()->owner_opr()->dyn_typeinfo(),
            q.node()->owner_opr()->dyn_typeinfo());
205 206 207

    HostTensorND host_z, host_q;
    auto func = graph->compile(
M
Megvii Engine Team 已提交
208
            {make_callback_copy(z1, host_z), make_callback_copy(q1, host_q)});
209 210 211
    func->execute();

    int nr_opr = 0;
M
Megvii Engine Team 已提交
212 213 214 215
    func->iter_opr_seq([&](cg::OperatorNodeBase*) {
        ++nr_opr;
        return true;
    });
216 217
    ASSERT_EQ(6, nr_opr);

M
Megvii Engine Team 已提交
218
    auto px = host_x->ptr<float>(), pz = host_z.ptr<float>(), pq = host_q.ptr<float>();
219
    auto yv = host_y->ptr<float>()[0], pv = host_p->ptr<float>()[0];
M
Megvii Engine Team 已提交
220
    for (size_t i = 0; i < SIZE; ++i) {
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        MGB_ASSERT_FLOAT_EQ(px[i] + yv, pz[i]);
        MGB_ASSERT_FLOAT_EQ(px[i] * yv + pv, pq[i]);
    }
}

TEST(TestGoptInference, ParamFuseMultiDeviceTensorHolder) {
    constexpr size_t SIZE = 23;
    HostTensorGenerator<> gen;
    auto host_x = gen({SIZE}), host_y = gen({1}), host_p = gen({1});

    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto x = opr::SharedDeviceTensor::make(*graph, *host_x),
         y = opr::SharedDeviceTensor::make(*graph, *host_y),
         p = opr::Host2DeviceCopy::make(*graph, host_p),
M
Megvii Engine Team 已提交
236 237
         z = x + y,         //! endpoint
            q = x * y + p;  //! middle point
238 239

    SymbolVar z1, q1;
M
Megvii Engine Team 已提交
240 241 242 243 244 245
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .apply({{z}})
                    .endpoint_vars(),
            z1);
246 247

    ASSERT_TRUE(z1.node()
M
Megvii Engine Team 已提交
248 249 250
                        ->owner_opr()
                        ->input(0)
                        ->owner_opr()
251
                        ->same_type<opr::MultipleDeviceTensorHolder>());
M
Megvii Engine Team 已提交
252 253 254 255 256 257 258
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{z, q}})
                    .endpoint_vars(),
            z1, q1);
259 260 261

    ASSERT_TRUE(z1.node()->owner_opr()->same_type<opr::SharedDeviceTensor>());
    ASSERT_NE(q1.node()->owner_opr(), q.node()->owner_opr());
M
Megvii Engine Team 已提交
262 263 264
    ASSERT_EQ(
            q1.node()->owner_opr()->dyn_typeinfo(),
            q.node()->owner_opr()->dyn_typeinfo());
265 266 267

    HostTensorND host_z, host_q;
    auto func = graph->compile(
M
Megvii Engine Team 已提交
268
            {make_callback_copy(z1, host_z), make_callback_copy(q1, host_q)});
269 270 271
    func->execute();

    int nr_opr = 0;
M
Megvii Engine Team 已提交
272 273 274 275
    func->iter_opr_seq([&](cg::OperatorNodeBase* op) {
        ++nr_opr;
        return true;
    });
276 277
    ASSERT_EQ(6, nr_opr);

M
Megvii Engine Team 已提交
278
    auto px = host_x->ptr<float>(), pz = host_z.ptr<float>(), pq = host_q.ptr<float>();
279
    auto yv = host_y->ptr<float>()[0], pv = host_p->ptr<float>()[0];
M
Megvii Engine Team 已提交
280
    for (size_t i = 0; i < SIZE; ++i) {
281 282 283 284 285 286 287 288 289 290 291
        MGB_ASSERT_FLOAT_EQ(px[i] + yv, pz[i]);
        MGB_ASSERT_FLOAT_EQ(px[i] * yv + pv, pq[i]);
    }
}

TEST(TestGoptInference, ParamFuseMultiRead) {
    HostTensorGenerator<> gen;

    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

M
Megvii Engine Team 已提交
292
    auto mkvar = [&](const char* name, const TensorShape& shp) {
293 294
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
M
Megvii Engine Team 已提交
295
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
296 297 298
        return opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name);
    };

M
Megvii Engine Team 已提交
299
    auto x = mkvar("x", {23}), p0 = mkcvar("p0", {1}), p1 = mkcvar("p1", {1}),
300 301 302
         z0 = x * (p0 + p1) + x / (p0 + p1);

    SymbolVar z1;
M
Megvii Engine Team 已提交
303 304 305 306 307 308
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{z0}})
                    .endpoint_vars(),
            z1);
309 310

    ASSERT_NE(z0.node(), z1.node());
M
Megvii Engine Team 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324
    ASSERT_TRUE(z1.node()
                        ->owner_opr()
                        ->input(0)
                        ->owner_opr()
                        ->input(1)
                        ->owner_opr()
                        ->same_type<opr::SharedDeviceTensor>());
    ASSERT_TRUE(z1.node()
                        ->owner_opr()
                        ->input(1)
                        ->owner_opr()
                        ->input(1)
                        ->owner_opr()
                        ->same_type<opr::SharedDeviceTensor>());
325
    HostTensorND host_z0, host_z1;
M
Megvii Engine Team 已提交
326
    graph->compile({make_callback_copy(z0, host_z0), make_callback_copy(z1, host_z1)})
M
Megvii Engine Team 已提交
327
            ->execute();
328 329 330 331 332 333 334 335
    MGB_ASSERT_TENSOR_EQ(host_z0, host_z1);
}

TEST(TestGoptInference, ParamFuseStaticInfer) {
    HostTensorGenerator<> gen;

    auto graph = ComputingGraph::make();

M
Megvii Engine Team 已提交
336
    auto mkvar = [&](const char* name, const TensorShape& shp) {
337 338
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
M
Megvii Engine Team 已提交
339
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
340 341 342 343 344 345 346
        return opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name);
    };

    auto a = mkvar("x", {4}),
         b = a.reshape(opr::GetVarShape::make(mkcvar("tshp", {2, 2})));

    SymbolVar b1;
M
Megvii Engine Team 已提交
347 348 349 350 351 352
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{b}})
                    .endpoint_vars(),
            b1);
353 354 355 356 357 358 359 360 361 362 363 364 365 366

    ASSERT_EQ(b1, a.reshape({2, 2}));
}

TEST(TestGoptInference, ParamRedistributeConvMul) {
    constexpr size_t N = 4, IC = 3, IH = 5, IW = 4, OC = 4, KH = 3, KW = 2;

    HostTensorGenerator<> gen;
    auto host_x = gen({N, IC, IH, IW}), host_k = gen({IC}),
         host_w = gen({OC, IC, KH, KW});

    auto graph = ComputingGraph::make();
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         k = opr::Dimshuffle::make(
M
Megvii Engine Team 已提交
367
                 opr::SharedDeviceTensor::make(*graph, *host_k), {-1, 0, -1, -1}),
368 369 370 371
         w = opr::SharedDeviceTensor::make(*graph, *host_w),
         y0 = opr::Convolution::make(x * k, w);

    SymbolVar y1;
M
Megvii Engine Team 已提交
372 373 374 375 376 377
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .apply({{y0}})
                    .endpoint_vars(),
            y1);
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

    ASSERT_NE(y0.node(), y1.node());

    HostTensorND host_y0, host_y1;
    auto func = graph->compile(
            {make_callback_copy(y0, host_y0), make_callback_copy(y1, host_y1)});
    func->execute();

    MGB_ASSERT_TENSOR_EQ(host_y0, host_y1);
}

TEST(TestGoptInference, ParamRedistributeConvMulUniqReader) {
    constexpr size_t N = 4, C = 3, IH = 5, IW = 4, KH = 1, KW = 1;

    HostTensorGenerator<> gen;
M
Megvii Engine Team 已提交
393
    auto host_x = gen({N, C, IH, IW}), host_k = gen({C}), host_w = gen({C, C, KH, KW});
394 395 396 397 398

    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         k = opr::Dimshuffle::make(
M
Megvii Engine Team 已提交
399
                 opr::SharedDeviceTensor::make(*graph, *host_k) + 2, {-1, 0, -1, -1}),
400 401
         w = opr::SharedDeviceTensor::make(*graph, *host_w),
         // y0 should be replaced
M
Megvii Engine Team 已提交
402
            y0 = opr::powf(opr::Convolution::make(x * k, w).rename("y0") + 2, 2),
403 404
         y0k = (y0 * k).rename("y0k"),
         // y0k is accessed twice, so it should not be replaced
M
Megvii Engine Team 已提交
405
            y1 = opr::Convolution::make(y0k, w).rename("y1"), z0 = y1 / y0k;
406 407

    SymbolVar z1;
M
Megvii Engine Team 已提交
408 409 410 411 412 413
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .apply({{z0}})
                    .endpoint_vars(),
            z1);
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431

    ASSERT_NE(z0.node(), z1.node());
    auto y1_repl = z1.node()->owner_opr()->input(0)->owner_opr();
    ASSERT_TRUE(y1_repl->same_type<opr::Convolution>());
    ASSERT_EQ(y1_repl->input(0), z1.node()->owner_opr()->input(1));

    HostTensorND host_z0, host_z1;
    auto func = graph->compile(
            {make_callback_copy(z0, host_z0), make_callback_copy(z1, host_z1)});
    func->execute();

    MGB_ASSERT_TENSOR_NEAR(host_z0, host_z1, 5e-5);
}

TEST(TestGoptInference, ParamRedistributeMulConvMul) {
    constexpr size_t N = 4, IC = 3, IH = 5, IW = 4, OC = 4, KH = 3, KW = 2;

    HostTensorGenerator<> gen;
M
Megvii Engine Team 已提交
432 433
    auto host_x = gen({N, IC, IH, IW}), host_k1 = gen({IC}),
         host_k2 = gen({1, OC, 1, 1}), host_w = gen({OC, IC, KH, KW});
434 435 436 437

    auto graph = ComputingGraph::make();
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         k1 = opr::Dimshuffle::make(
M
Megvii Engine Team 已提交
438
                 opr::SharedDeviceTensor::make(*graph, *host_k1), {-1, 0, -1, -1}),
439 440 441 442 443
         k2 = opr::SharedDeviceTensor::make(*graph, *host_k2),
         w = opr::SharedDeviceTensor::make(*graph, *host_w),
         y0 = opr::Convolution::make(x * k1, w) * k2;

    SymbolVar y1;
M
Megvii Engine Team 已提交
444 445 446 447 448 449 450
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y0}})
                    .endpoint_vars(),
            y1);
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

    auto y1opr = y1.node()->owner_opr();
    ASSERT_TRUE(y1opr->same_type<opr::Convolution>());
    ASSERT_EQ(y1opr->input(0), x.node());

    HostTensorND host_y0, host_y1;
    auto func = graph->compile(
            {make_callback_copy(y0, host_y0), make_callback_copy(y1, host_y1)});
    func->execute();

    MGB_ASSERT_TENSOR_NEAR(host_y0, host_y1, 5e-6);
}

TEST(TestGoptInference, ParamRedistributeConvAdd) {
    constexpr size_t N = 4, IC = 3, IH = 5, IW = 4, OC = 4, KH = 3, KW = 2;

    HostTensorGenerator<> gen;
    auto host_x = gen({N, IC, IH, IW}), host_b = gen({IC}),
         host_w = gen({OC, IC, KH, KW});

    auto graph = ComputingGraph::make();
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         b = opr::Dimshuffle::make(
M
Megvii Engine Team 已提交
474
                 opr::SharedDeviceTensor::make(*graph, *host_b), {-1, 0, -1, -1}),
475 476 477 478
         w = opr::SharedDeviceTensor::make(*graph, *host_w),
         y0 = opr::Convolution::make(x + b, w);

    SymbolVar y1;
M
Megvii Engine Team 已提交
479 480 481 482 483 484 485
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y0}})
                    .endpoint_vars(),
            y1);
486 487 488 489 490 491 492 493 494 495 496 497

    ASSERT_NE(y0.node(), y1.node());

    HostTensorND host_y0, host_y1;
    auto func = graph->compile(
            {make_callback_copy(y0, host_y0), make_callback_copy(y1, host_y1)});
    func->execute();

    MGB_ASSERT_TENSOR_NEAR(host_y0, host_y1, 1e-5);
}

TEST(TestGoptInference, ParamRedistributeDistThenReasso) {
M
Megvii Engine Team 已提交
498
    constexpr size_t N = 4, IC0 = 3, IC1 = 6, IH = 5, IW = 4, OC = 4, KH = 3, KW = 2;
499 500 501

    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
M
Megvii Engine Team 已提交
502
    auto mkvar = [&](const char* name, const TensorShape& shp) {
503 504
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
M
Megvii Engine Team 已提交
505
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
506 507
        return opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name);
    };
M
Megvii Engine Team 已提交
508
    auto x0 = mkvar("x0", {N, IC0, IH, IW}), x1 = mkvar("x1", {N, IC1, IH, IW}),
M
Megvii Engine Team 已提交
509 510
         k0 = opr::Dimshuffle::make(mkcvar("x1_", {IC0}), {-1, 0, -1, -1}).rename("x1"),
         w0 = mkcvar("w0", {OC, IC0, KH, KW}), k1 = mkcvar("k1", {1, IC1, 1, 1}),
M
Megvii Engine Team 已提交
511 512 513 514 515
         w1 = mkcvar("w1", {OC, IC1, KH, KW}), b0 = mkvar("b0", {1, OC, 1, 1}),
         b1 = mkcvar("b1", {1}), k2 = mkcvar("k2", {1}),
         y0 = (opr::Convolution::make(x0 * k0, w0) +
               opr::Convolution::make(x1 + k1, w1) + b0 + b1) *
              k2;
516 517

    SymbolVar y1;
M
Megvii Engine Team 已提交
518 519 520 521 522 523 524 525 526
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .add_pass<gopt::ReorderArithChainPass>(
                            gopt::ConstVarType::IMMUTABLE_AND_PARAM)
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y0}})
                    .endpoint_vars(),
            y1);
527 528 529 530 531 532 533 534 535

    ASSERT_NE(y0.node(), y1.node());
    HostTensorND host_y0, host_y1;
    auto func = graph->compile(
            {make_callback_copy(y0, host_y0), make_callback_copy(y1, host_y1)});
    func->execute();

    MGB_ASSERT_TENSOR_NEAR(host_y0, host_y1, 1e-5);

M
Megvii Engine Team 已提交
536 537 538
    auto chain = gopt::extract_opr_leaves(y1.node(), [](cg::OperatorNodeBase* opr) {
        return gopt::as_elem_opr(opr, opr::Elemwise::Mode::ADD);
    });
539
    size_t nr_conv = 0;
M
Megvii Engine Team 已提交
540
    for (auto i : chain) {
541 542
        auto opr = i->owner_opr();
        if (opr->same_type<opr::Convolution>()) {
M
Megvii Engine Team 已提交
543
            ++nr_conv;
M
Megvii Engine Team 已提交
544 545 546
            ASSERT_TRUE(opr->input(0)->owner_opr()->same_type<opr::Host2DeviceCopy>());
            ASSERT_TRUE(
                    opr->input(1)->owner_opr()->same_type<opr::SharedDeviceTensor>());
547 548 549 550 551 552 553 554 555 556 557 558
        }
    }
    ASSERT_EQ(2u, nr_conv);
    ASSERT_EQ(4u, chain.size());
}

TEST(TestGoptInference, ParamRedistributeMultiChange) {
    constexpr size_t N = 4, IC = 3, IH = 5, IW = 4, OC = 4, KH = 3, KW = 2;

    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
559
    auto mkvar = [&](const char* name, const TensorShape& shp) {
560 561
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
M
Megvii Engine Team 已提交
562
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
563 564
        return opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name);
    };
M
Megvii Engine Team 已提交
565 566 567
    auto x = mkvar("x", {N, IC, IH, IW}), k0 = mkcvar("k0", {1, IC, 1, 1}),
         b0 = mkcvar("b0", {1, IC, 1, 1}), k1 = mkcvar("k0", {1}),
         b1 = mkcvar("b0", {1}), w = mkcvar("w", {OC, IC, KH, KW}),
568 569 570
         y0 = (opr::Convolution::make(x * k0 + b0, w) + b1) * k1;

    SymbolVar y1;
M
Megvii Engine Team 已提交
571 572 573 574 575 576 577
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y0}})
                    .endpoint_vars(),
            y1);
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

    ASSERT_NE(y0.node(), y1.node());
    HostTensorND host_y0, host_y1;
    auto func = graph->compile(
            {make_callback_copy(y0, host_y0), make_callback_copy(y1, host_y1)});
    func->execute();

    MGB_ASSERT_TENSOR_NEAR(host_y0, host_y1, 1e-5);

    auto y1elem = gopt::as_elem_opr(y1.node(), opr::Elemwise::Mode::ADD);
    ASSERT_TRUE(y1elem);
    auto yconv = y1elem->input(0)->owner_opr();
    if (!yconv->same_type<opr::Convolution>())
        yconv = y1elem->input(1)->owner_opr();
    ASSERT_TRUE(yconv->same_type<opr::Convolution>());
    ASSERT_EQ(x.node(), yconv->input(0));
}

TEST(TestGoptInference, ParamRedistributeMultiReader) {
    constexpr size_t N = 4, IC = 3, IH = 5, IW = 4, OC = 4, KH = 3, KW = 2;

    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

M
Megvii Engine Team 已提交
603
    auto mkvar = [&](const char* name, const TensorShape& shp) {
604 605 606
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };

M
Megvii Engine Team 已提交
607
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
608 609 610
        return opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name);
    };

M
Megvii Engine Team 已提交
611
    auto x = mkvar("x", {N, IC, IH, IW}), k = mkcvar("k", {1, OC, 1, 1}),
612 613 614 615 616 617 618
         w = mkcvar("w", {OC, IC, KH, KW});

    auto conv = opr::Convolution::make(x, w);
    auto t = conv * k;
    auto y0 = t * 4.2f + t * 2.4f;

    SymbolVar y1;
M
Megvii Engine Team 已提交
619 620 621 622 623 624 625
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y0}})
                    .endpoint_vars(),
            y1);
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

    ASSERT_NE(y0.node(), y1.node());
    HostTensorND host_y0, host_y1;
    auto func = graph->compile(
            {make_callback_copy(y0, host_y0), make_callback_copy(y1, host_y1)});
    func->execute();

    MGB_ASSERT_TENSOR_NEAR(host_y0, host_y1, 1e-5);

    auto y1elem = gopt::as_elem_opr(y1.node(), opr::Elemwise::Mode::ADD);
    ASSERT_TRUE(y1elem);
    auto ymul0 = gopt::as_elem_opr(y1elem->input(0), opr::Elemwise::Mode::MUL),
         ymul1 = gopt::as_elem_opr(y1elem->input(1), opr::Elemwise::Mode::MUL);
    ASSERT_TRUE(ymul0);
    ASSERT_TRUE(ymul1);
    auto yconv = ymul0->input(0)->owner_opr();
M
Megvii Engine Team 已提交
642
    if (!yconv->same_type<opr::Convolution>()) {
643 644 645
        yconv = ymul0->input(1)->owner_opr();
    }
    ASSERT_TRUE(yconv->same_type<opr::Convolution>());
M
Megvii Engine Team 已提交
646
    if (ymul1->input(0) != yconv->output(0)) {
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
        ASSERT_EQ(yconv->output(0), ymul1->input(1));
    }
    ASSERT_EQ(x.node(), yconv->input(0));
}

TEST(TestGoptInference, ParamFuseBiasMerge) {
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
        return opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name);
    };
    auto x = mkvar("x", {6, 3, 8, 8}), w1 = mkcvar("w1", {4, 3, 3, 3}),
         w2 = mkcvar("w2", {4, 3, 3, 3}), b1 = mkcvar("b1", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
664
         b2 = mkcvar("b2", {1, 4, 1, 1}), y1 = opr::Convolution::make(x, w1) + b1,
665 666 667 668 669 670
         y2 = opr::Convolution::make(x, w2) + b2, y = y1 + y2;

    SymbolVar y_opt;
    unpack_vector(gopt::optimize_for_inference({y}), y_opt);

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
671 672
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
673 674 675 676 677
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
678
            ->writeto_fpath(output_file("TestGoptInference.ParamFuseConvMerge.json"));
679

M
Megvii Engine Team 已提交
680 681 682
    auto chain = gopt::extract_opr_leaves(y_opt.node(), [](cg::OperatorNodeBase* opr) {
        return gopt::as_elem_opr(opr, opr::Elemwise::Mode::ADD);
    });
683 684 685 686 687 688 689 690 691 692 693
    ASSERT_EQ(3u, chain.size());
}

TEST(TestGoptInference, Float16IOFloat32Compute) {
    constexpr size_t INP_H = 10, INP_W = 10;
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
694
    auto a = mkvar("a", {1, 4, INP_H, INP_W}), s0 = mkvar("s0", {20, 3, INP_H, INP_W}),
695 696 697 698 699 700
         s1 = mkvar("s1", {4, 3, 1, 1});
    auto b = opr::Convolution::make(s0, s1, {}, {});
    auto y = a + b;
    y = opr::Concat::make({y, -y}, 0);
    y = opr::Reduce::make(y, {}, y.make_scalar(1));
    SymbolVar y_opt;
701 702 703
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_f16_io_f32_comp();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
704 705 706
    ASSERT_EQ(y_opt.dtype(), dtype::Float32());

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
707 708
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
709 710 711 712
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

713 714 715 716 717 718 719 720 721
TEST(TestGoptInference, Float16IOFloat32ComputeDeConv) {
    constexpr size_t INP_H = 10, INP_W = 10;
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
    graph->options().graph_opt_level = 0;

722
    auto s0 = mkvar("s0", {5, 5, 3, 3}), s1 = mkvar("s1", {1, 5, INP_H, INP_W});
723 724 725 726 727
    auto y = opr::ConvolutionBackwardData::make(s0, s1, {}, {});
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_f16_io_f32_comp();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
728 729 730
    ASSERT_EQ(
            find_opr<opr::ConvolutionBackwardData>(y_opt).param().compute_mode,
            opr::ConvBias::Param::ConvBias::ComputeMode::FLOAT32);
731 732 733
    ASSERT_EQ(y_opt.dtype(), dtype::Float32());

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
734 735
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
736 737 738 739
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-2);
}

740 741 742 743 744 745 746 747 748 749 750 751 752
TEST(TestGoptInference, Float16IOFloat32ComputeWarpPerspective) {
    constexpr size_t INP_H = 10, INP_W = 10, N = 2;
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };
    graph->options().graph_opt_level = 0;
    auto a = mkvar("a", {N, 4, INP_H, INP_W});
    float value1 = M_PI, value2 = 0.6;
    auto gen_mat = [&](HostTensorND& mat) {
        auto ptr = mat.ptr<float>();
        for (size_t i = 0; i < N; ++i) {
M
Megvii Engine Team 已提交
753 754
            auto rot = value1, scale = value2, sheer = value1, dy = value2, dx = value2,
                 ky = value2, kx = value2, kb = value2;
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
            ptr[0] = ptr[4] = cos(rot) * scale;
            ptr[1] = -(ptr[3] = sin(rot) * scale);
            ptr[3] *= sheer;
            ptr[4] *= sheer;
            ptr[2] = dx;
            ptr[5] = dy;
            ptr[6] = kx;
            ptr[7] = ky;
            ptr[8] = kb;
            ptr += 9;
        }
        mgb_assert(ptr == mat.ptr<float>() + mat.shape().total_nr_elems());
    };
    auto mat_host = std::make_shared<HostTensorND>(
            a.node()->comp_node(), TensorShape{N, 3, 3}, dtype::Float32());
    gen_mat(*mat_host);
    auto mat = opr::Host2DeviceCopy::make(*graph, mat_host).rename("mat");
    TensorShape out_shp{20, 20};
    auto y = opr::WarpPerspective::make(a, mat, out_shp);
    SymbolVar y_opt;
775 776 777
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_f16_io_f32_comp();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
778 779
    ASSERT_EQ(y_opt.dtype(), dtype::Float32());
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
780 781
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
782 783 784 785
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

786 787 788 789 790 791 792 793 794 795 796 797
TEST(TestGoptInference, Float16IOFloat32ComputeRemap) {
    auto cn = CompNode::load("cpu1");
    constexpr size_t INP_H = 10, INP_W = 10, N = 2;
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    graph->options().graph_opt_level = 0;
    auto a = mkvar("a", {N, 4, INP_H, INP_W});
    auto gen_map = [&](HostTensorND& mat) {
        auto ptr = mat.ptr<float>();
M
Megvii Engine Team 已提交
798 799 800
        for (size_t n = 0; n < N; ++n) {
            for (int h = 0; h < 5; ++h) {
                for (int w = 0; w < 5; ++w) {
801 802 803 804 805 806 807 808 809 810 811 812 813
                    *ptr++ = (h * 5 * 2) + 5 * 2 + 0;
                    *ptr++ = (h * 5 * 2) + 5 * 2 + 1;
                }
            }
        }
        mgb_assert(ptr == mat.ptr<float>() + mat.shape().total_nr_elems());
    };
    auto map_host = std::make_shared<HostTensorND>(
            a.node()->comp_node(), TensorShape{N, 5, 5, 2}, dtype::Float32());
    gen_map(*map_host);
    auto map = opr::Host2DeviceCopy::make(*graph, map_host).rename("map");
    auto y = opr::Remap::make(a, map);
    SymbolVar y_opt;
814 815 816
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_f16_io_f32_comp();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
817 818
    ASSERT_EQ(y_opt.dtype(), dtype::Float32());
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
819 820
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
821 822 823 824
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

825 826 827 828 829 830 831 832 833 834 835 836 837
TEST(TestGoptInference, Uint8IOFloat16ComputeWarpPerspective) {
    constexpr size_t INP_H = 10, INP_W = 10, N = 2;
    HostTensorGenerator<dtype::Uint8> gen_uint8;
    auto graph = ComputingGraph::make();
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen_uint8(shp)).rename(name);
    };
    graph->options().graph_opt_level = 0;
    auto a = mkvar("a", {N, 4, INP_H, INP_W});
    float value1 = M_PI, value2 = 0.6;
    auto gen_mat = [&](HostTensorND& mat) {
        auto ptr = mat.ptr<float>();
        for (size_t i = 0; i < N; ++i) {
M
Megvii Engine Team 已提交
838 839
            auto rot = value1, scale = value2, sheer = value1, dy = value2, dx = value2,
                 ky = value2, kx = value2, kb = value2;
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
            ptr[0] = ptr[4] = cos(rot) * scale;
            ptr[1] = -(ptr[3] = sin(rot) * scale);
            ptr[3] *= sheer;
            ptr[4] *= sheer;
            ptr[2] = dx;
            ptr[5] = dy;
            ptr[6] = kx;
            ptr[7] = ky;
            ptr[8] = kb;
            ptr += 9;
        }
        mgb_assert(ptr == mat.ptr<float>() + mat.shape().total_nr_elems());
    };
    auto mat_host = std::make_shared<HostTensorND>(
            a.node()->comp_node(), TensorShape{N, 3, 3}, dtype::Float32());
    gen_mat(*mat_host);
    auto mat = opr::Host2DeviceCopy::make(*graph, mat_host).rename("mat");
    TensorShape out_shp{20, 20};
    auto y = opr::WarpPerspective::make(a, mat, out_shp);
    SymbolVar y_opt;
860 861 862
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_f16_io_comp();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
863 864
    ASSERT_EQ(y_opt.dtype(), dtype::Uint8());
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
865 866
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

TEST(TestGoptInference, Float32TOFloat16) {
    CompNode cn = CompNode::load("cpu0");
    HostTensorGenerator<> gen(0, 1, 0);
    auto host_x0 = gen({1, 4, 16, 8}, cn), host_x1 = gen({2, 3, 16, 8}, cn),
         host_x2 = gen({4, 3, 1, 1}, cn);
    auto graph = ComputingGraph::make();

    auto make_f32_to_f16_graph = [&]() {
        graph->options().graph_opt_level = 0;

        auto d0 = opr::Host2DeviceCopy::make(*graph, host_x0),
             d1 = opr::Host2DeviceCopy::make(*graph, host_x1),
             d2 = opr::SharedDeviceTensor::make(*graph, *host_x2);

        auto b = opr::Convolution::make(d1, d2, {}, {});
        auto y = d0 + b;
        y = opr::Reduce::make(y, {}, y.make_scalar(1));

        SymbolVar y_opt;
890 891 892
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_f16_io_comp();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
893 894 895 896 897
        return y_opt;
    };

    auto make_f16_graph = [&]() {
        auto d0 = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
898
                     opr::Host2DeviceCopy::make(*graph, host_x0), dtype::Float16{}),
899
             d1 = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
900
                     opr::Host2DeviceCopy::make(*graph, host_x1), dtype::Float16{}),
901
             d2 = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
902
                     opr::SharedDeviceTensor::make(*graph, *host_x2), dtype::Float16{});
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

        auto b = opr::Convolution::make(d1, d2, {}, {});
        SymbolVar y = d0 + b;
        y = opr::Reduce::make(y, {}, y.make_scalar(1));
        y = opr::TypeCvt::make(y, dtype::Float32{});

        return y;
    };

    auto y_opt = make_f32_to_f16_graph();
    auto y = make_f16_graph();
    ASSERT_EQ(y_opt.dtype(), dtype::Float32{});
    ASSERT_EQ(y.dtype(), dtype::Float32{});

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
918 919
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
920 921 922 923
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

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
TEST(TestGoptInference, Float32TOFloat16C32) {
    CompNode cn = CompNode::load("cpu0");
    HostTensorGenerator<> gen(0, 1, 0);
    auto host_x0 = gen({1, 4, 1, 1}, cn), host_x1 = gen({2, 3, 16, 8}, cn),
         host_x2 = gen({4, 3, 1, 1}, cn);
    auto graph = ComputingGraph::make();

    auto make_f32_to_f16_graph = [&]() {
        graph->options().graph_opt_level = 0;

        auto d0 = opr::Host2DeviceCopy::make(*graph, host_x0),
             d1 = opr::Host2DeviceCopy::make(*graph, host_x1),
             d2 = opr::SharedDeviceTensor::make(*graph, *host_x2);

        auto y = opr::ConvBias::make(d1, d2, d0);
        y = opr::Reduce::make(y, {}, y.make_scalar(1));

        SymbolVar y_opt;
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_f16_io_f32_comp();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
        return y_opt;
    };

    auto make_f16_graph = [&]() {
M
Megvii Engine Team 已提交
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
        auto d0 = opr::TypeCvt::make(
                     opr::TypeCvt::make(
                             opr::Host2DeviceCopy::make(*graph, host_x0),
                             dtype::Float16{}),
                     dtype::Float32{}),
             d1 = opr::TypeCvt::make(
                     opr::TypeCvt::make(
                             opr::Host2DeviceCopy::make(*graph, host_x1),
                             dtype::Float16{}),
                     dtype::Float32{}),
             d2 = opr::TypeCvt::make(
                     opr::TypeCvt::make(
                             opr::SharedDeviceTensor::make(*graph, *host_x2),
                             dtype::Float16{}),
                     dtype::Float32{});
964 965 966

        auto y = opr::ConvBias::make(d1, d2, d0);
        y = opr::Reduce::make(y, {}, y.make_scalar(1));
M
Megvii Engine Team 已提交
967 968
        y = opr::TypeCvt::make(
                opr::TypeCvt::make(y, dtype::Float16{}), dtype::Float32{});
969 970 971 972 973 974

        return y;
    };

    auto y_opt = make_f32_to_f16_graph();
    auto y = make_f16_graph();
M
Megvii Engine Team 已提交
975 976 977
    ASSERT_EQ(
            find_opr<opr::ConvBias>(y_opt).param().compute_mode,
            opr::ConvBias::Param::ConvBias::ComputeMode::FLOAT32);
978 979 980 981
    ASSERT_EQ(y_opt.dtype(), dtype::Float32{});
    ASSERT_EQ(y.dtype(), dtype::Float32{});

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
982 983
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
984 985 986 987
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
TEST(TestGoptInference, Float32TOFloat16EndpointElemwise) {
    CompNode cn = CompNode::load("cpu0");
    HostTensorGenerator<> gen(0, 1, 0);
    auto host_x0 = gen({1, 4, 16, 8}, cn), host_x1 = gen({2, 3, 16, 8}, cn),
         host_x2 = gen({4, 3, 1, 1}, cn);
    auto graph = ComputingGraph::make();

    auto make_f32_to_f16_graph = [&]() {
        graph->options().graph_opt_level = 0;

        auto d0 = opr::Host2DeviceCopy::make(*graph, host_x0),
             d1 = opr::Host2DeviceCopy::make(*graph, host_x1),
             d2 = opr::SharedDeviceTensor::make(*graph, *host_x2);

        auto b = opr::Convolution::make(d1, d2, {}, {});
        auto y = d0 + b;

        SymbolVar y_opt;
1006 1007 1008
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_f16_io_comp();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1009 1010 1011 1012 1013
        return y_opt;
    };

    auto make_f16_graph = [&]() {
        auto d0 = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1014
                     opr::Host2DeviceCopy::make(*graph, host_x0), dtype::Float16{}),
1015
             d1 = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1016
                     opr::Host2DeviceCopy::make(*graph, host_x1), dtype::Float16{}),
1017
             d2 = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1018
                     opr::SharedDeviceTensor::make(*graph, *host_x2), dtype::Float16{});
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

        auto b = opr::Convolution::make(d1, d2, {}, {});
        SymbolVar y = d0 + b;
        y = opr::TypeCvt::make(y, dtype::Float32{});

        return y;
    };

    auto y_opt = make_f32_to_f16_graph();
    auto y = make_f16_graph();
    ASSERT_EQ(y_opt.dtype(), dtype::Float32{});
    ASSERT_EQ(y.dtype(), dtype::Float32{});

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1033 1034
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1035 1036 1037 1038
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

1039 1040 1041
TEST(TestGoptInference, Float32TOFloat16Linspace) {
    CompNode cn = CompNode::load("cpu0");
    HostTensorGenerator<> gen(0, 1, 0);
1042
    auto host_x = gen({3, 1}, cn);
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    auto graph = ComputingGraph::make();

    auto make_f32_to_f16_graph = [&]() {
        graph->options().graph_opt_level = 0;

        auto x = opr::Host2DeviceCopy::make(*graph, host_x);
        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 lin = opr::Linspace::make(cv(0), sub(0) - 1, sub(0), {}, {});
        auto shp = opr::Concat::make({sub(1), sub(0)}, 0);
        auto y = opr::Reshape::make(lin, shp);
        auto mm = opr::MatrixMul::make(x, y);

        SymbolVar mm_opt;
1061 1062 1063
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_f16_io_comp();
        unpack_vector(gopt::optimize_for_inference({mm}, options), mm_opt);
1064 1065 1066 1067
        return mm_opt;
    };

    auto make_f16_graph = [&]() {
M
Megvii Engine Team 已提交
1068 1069
        auto x = opr::TypeCvt::make(
                opr::Host2DeviceCopy::make(*graph, host_x), dtype::Float16());
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        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 lin = opr::Linspace::make(cv(0), sub(0) - 1, sub(0), {}, {});
        lin = opr::TypeCvt::make(lin, dtype::Float16());
        auto shp = opr::Concat::make({sub(1), sub(0)}, 0);
        auto y = opr::Reshape::make(lin, shp);
        auto mm = opr::MatrixMul::make(x, y);

        mm = opr::TypeCvt::make(mm, dtype::Float32{});

        return mm;
    };

    auto y_opt = make_f32_to_f16_graph();
    auto y = make_f16_graph();
    ASSERT_EQ(y_opt.dtype(), dtype::Float32{});
    ASSERT_EQ(y.dtype(), dtype::Float32{});

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1093 1094
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1095 1096 1097 1098
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

1099 1100 1101 1102 1103 1104 1105 1106 1107
TEST(TestGoptInference, Float32TOFloat16Endpoints) {
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();

    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name);
    };

    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1108
        return opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name);
1109 1110 1111 1112 1113 1114
    };

    graph->options().graph_opt_level = 0;
    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 0;

M
Megvii Engine Team 已提交
1115
    auto x = mkvar("x", {8, 8, 8, 8}), y = mkvar("y", {8, 8, 8, 8}),
M
Megvii Engine Team 已提交
1116
         w = mkcvar("w", {4, 8, 3, 3}), z = opr::Convolution::make(x + y, w, param);
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_f16_io_f32_comp();
    SymbolVarArray out = gopt::optimize_for_inference({x + y, z}, options);

    ASSERT_EQ(out[0].dtype(), dtype::Float32());
    ASSERT_EQ(out[1].dtype(), dtype::Float32());
    ASSERT_EQ(out[0].node()->owner_opr()->input(0)->dtype(), dtype::Float16());
    ASSERT_EQ(out[1].node()->owner_opr()->input(0)->dtype(), dtype::Float16());
}

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
TEST(TestGoptInference, ConvertFormatNHWCD4) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1140
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1141 1142 1143 1144 1145 1146 1147
    };

    auto host_x = gen({8, 8, 8, 8}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 0;
M
Megvii Engine Team 已提交
1148
    auto w1 = mkcvar("w1", {4, 8, 3, 3}), conv = opr::Convolution::make(x, w1, param);
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    auto shape_of = opr::GetVarShape::make(conv);
    auto subtensor = opr::Subtensor::make(
            shape_of, {opr::Subtensor::AxisIndexer::make_interval(
                              0, x.make_scalar(2), None, x.make_scalar(1))});

    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
    auto resize = opr::ResizeForward::make(conv, subtensor * 2, param_resize);
    auto mat = mkcvar("mat", {8, 3, 3}),
         warp = opr::WarpPerspectiveForward::make(
                 resize, mat, nullptr, cg::var_from_tensor_shape(x, {4, 4}));

    auto b = mkvar("b", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
1162
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
1163
    param.pad_h = param.pad_w = 1;
M
Megvii Engine Team 已提交
1164 1165
    auto w2 = mkcvar("w2", {4, 4, 3, 3}), y = opr::Convolution::make(elem, w2, param),
         z = opr::AxisAddRemove::make(y, {opr::AxisAddRemove::AxisDesc::make_add(0)});
1166

1167
    SymbolVar y_opt, z_opt;
1168
    auto options = gopt::OptimizeForInferenceOptions{};
1169
    options.enable_nhwcd4();
1170
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1171
    unpack_vector(gopt::optimize_for_inference({z}, options), z_opt);
1172

M
Megvii Engine Team 已提交
1173 1174 1175
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1176

M
Megvii Engine Team 已提交
1177 1178 1179
    ASSERT_EQ(
            TensorFormat::Type::DEFAULT,
            find_opr<opr::AxisAddRemove>(z_opt).input(0)->format().type());
1180 1181
    ASSERT_EQ(4, find_opr<opr::AxisAddRemove>(z_opt).input(0)->shape().ndim);

1182 1183
    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1184
            ->writeto_fpath(output_file("TestGoptInference.ConvertFormatNHWCD4.json"));
1185 1186

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1187 1188
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1189 1190 1191 1192 1193 1194 1195 1196
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);

    *host_x = *gen({8, 8, 16, 16}, cn);
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
#if MGB_OPENCL
#include "megcore_opencl.h"

#define REQUIRE_OPENCL()                                                 \
    do {                                                                 \
        if (!CompNode::get_device_count(CompNode::DeviceType::OPENCL)) { \
            return;                                                      \
        }                                                                \
    } while (0)

TEST(TestGoptInference, ConvertFormatNHWCD4OpenCL) {
    REQUIRE_OPENCL();

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("openclx");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1218
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1219 1220 1221 1222 1223 1224 1225
    };

    auto host_x = gen({8, 8, 8, 8}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 0;
M
Megvii Engine Team 已提交
1226
    auto w1 = mkcvar("w1", {4, 8, 3, 3}), conv = opr::Convolution::make(x, w1, param);
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    auto shape_of = opr::GetVarShape::make(conv);
    auto subtensor = opr::Subtensor::make(
            shape_of, {opr::Subtensor::AxisIndexer::make_interval(
                              0, x.make_scalar(2), None, x.make_scalar(1))});

    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
    auto resize = opr::ResizeForward::make(conv, subtensor * 2, param_resize);
    auto mat = mkcvar("mat", {8, 3, 3}),
         warp = opr::WarpPerspectiveForward::make(
                 resize, mat, nullptr, cg::var_from_tensor_shape(x, {4, 4}));

    auto b = mkvar("b", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
1240
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
1241
    param.pad_h = param.pad_w = 1;
M
Megvii Engine Team 已提交
1242 1243
    auto w2 = mkcvar("w2", {4, 4, 3, 3}), y = opr::Convolution::make(elem, w2, param),
         z = opr::AxisAddRemove::make(y, {opr::AxisAddRemove::AxisDesc::make_add(0)});
1244 1245 1246 1247 1248 1249 1250

    SymbolVar y_opt, z_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    unpack_vector(gopt::optimize_for_inference({z}, options), z_opt);

M
Megvii Engine Team 已提交
1251 1252 1253
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1254

M
Megvii Engine Team 已提交
1255 1256 1257
    ASSERT_EQ(
            TensorFormat::Type::DEFAULT,
            find_opr<opr::AxisAddRemove>(z_opt).input(0)->format().type());
1258 1259 1260
    ASSERT_EQ(4, find_opr<opr::AxisAddRemove>(z_opt).input(0)->shape().ndim);

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1261 1262
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);

    *host_x = *gen({8, 8, 16, 16}, cn);
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}
#undef REQUIRE_OPENCL
#endif

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
//! this is to test elemwise to cd4 only
TEST(TestGoptInference, ConvertFormatNHWCD4Elemwise0) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };

    auto host_x = gen({8, 8, 8, 8}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    auto a = mkvar("a", {1});
    auto b = mkvar("b", {1});
    auto y = x * a + b;

    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_EQ(
            opr::Elemwise::Mode::FUSE_MUL_ADD3,
            find_opr<opr::Elemwise>(y_opt).param().mode);
    ASSERT_EQ(
            TensorFormat::Type::IMAGE2D_PACK4,
            find_opr<opr::Elemwise>(y_opt).input(1)->format().type());

    graph->compile({{y_opt, {}}})
            ->to_json()
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4Elemwise0.json"));

    HostTensorND host_y_opt, host_y;
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
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

    *host_x = *gen({8, 8, 16, 16}, cn);
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

TEST(TestGoptInference, MergeDimShuffleAndRelayoutFormat) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };

    auto host_x = gen({8, 8, 8, 8}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
    auto d0 = opr::Dimshuffle::make(x, {0, 3, 1, 2});

    auto a = mkvar("a", {1});
    auto b = mkvar("b", {1});
    auto y = d0 * a + b;

    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_EQ(
            megdnn::param::RelayoutFormat::Mode::NHWC_NHWCD4I,
            find_opr<opr::RelayoutFormat>(y_opt).param().mode);

    ASSERT_EQ(0, find_opr_num<opr::Dimshuffle>(y_opt));

    graph->compile({{y_opt, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.MergeDimShuffleAndRelayoutFormat.json"));

    HostTensorND host_y_opt, host_y;
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
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

    *host_x = *gen({8, 8, 16, 16}, cn);
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

TEST(TestGoptInference, MergeRelayoutFormatAndDimShuffle) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };

    auto host_x = gen({2, 8, 16, 32}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    auto a = mkvar("a", {1});
    auto b = mkvar("b", {1});
    auto z = x * a + b;

    //! to NHWC
    auto y = opr::Dimshuffle::make(z, {0, 2, 3, 1});

    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_EQ(0, find_opr_num<opr::Dimshuffle>(y_opt));
    auto check = [](SymbolVar endpoint) -> bool {
        bool valid = true;
        auto cb = [&](cg::OperatorNodeBase* opr) {
            if (opr->same_type<opr::RelayoutFormat>()) {
                auto mode = opr->try_cast_final<opr::RelayoutFormat>()->param().mode;
                //! The first relayout_format opr's mode is NCHW_NHWCD4I. The second is
                //! NHWCD4I_NHWC
                if (mode == megdnn::param::RelayoutFormat::Mode::NCHW_NHWCD4I ||
                    mode == megdnn::param::RelayoutFormat::Mode::NHWCD4I_NHWC) {
                    valid &= true;
                } else {
                    valid &= false;
                }
            }
        };
        cg::DepOprIter{cb}.add(endpoint.node()->owner_opr());
        return valid;
    };
    ASSERT_EQ(true, check(y_opt));

    graph->compile({{y_opt, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.MergeRelayoutFormatAndDimShuffle.json"));

    HostTensorND host_y;
    HostTensorND host_y_opt;
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
1427 1428 1429 1430 1431 1432

    *host_x = *gen({8, 8, 16, 16}, cn);
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
TEST(TestGoptInference, ConvertFormatNHWCD4Elemwise) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1445
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1446 1447 1448 1449 1450 1451 1452
    };

    auto host_x = gen({8, 8, 8, 8}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 0;
M
Megvii Engine Team 已提交
1453
    auto w1 = mkcvar("w1", {8, 8, 3, 3}), conv = opr::Convolution::make(x, w1, param);
1454 1455

    auto b = mkvar("b", {1, 1, 1, 1}),
M
Megvii Engine Team 已提交
1456
         elem = opr::Elemwise::make({conv + b}, opr::Elemwise::Param::Mode::RELU);
1457 1458 1459 1460 1461 1462 1463
    param.pad_h = param.pad_w = 1;
    auto w2 = mkcvar("w2", {8, 8, 3, 3}),
         conv2 = opr::Convolution::make(elem, w2, param);

    auto b_scaler = mkvar("b", {1}), elem2 = conv2 + b_scaler;

    param.pad_h = param.pad_w = 1;
M
Megvii Engine Team 已提交
1464
    auto w3 = mkcvar("w2", {8, 8, 3, 3}), y = opr::Convolution::make(elem2, w3, param);
1465 1466 1467 1468 1469 1470

    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

M
Megvii Engine Team 已提交
1471 1472 1473
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1474 1475 1476

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1477 1478
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4Elemwise.json"));
1479 1480

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1481 1482
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1483 1484 1485 1486 1487 1488 1489 1490
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);

    *host_x = *gen({8, 8, 16, 16}, cn);
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

1491 1492 1493 1494 1495 1496 1497 1498
TEST(TestGoptInference, ConvertFormatNHWCD4TypeCvt) {
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1499
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1500 1501 1502 1503 1504 1505 1506
    };
    auto host_x = gen({8, 8, 8, 8}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    opr::Convolution::Param param;

    param.pad_h = param.pad_w = 0;
M
Megvii Engine Team 已提交
1507
    auto w1 = mkcvar("w1", {8, 8, 3, 3}), conv1 = opr::Convolution::make(x, w1, param),
1508
         tcvt1 = opr::TypeCvt::make(conv1, dtype::Float16());
M
Megvii Engine Team 已提交
1509
    auto w2 = mkcvar("w2", {8, 8, 3, 3}), conv2 = opr::Convolution::make(x, w2, param),
1510 1511 1512 1513 1514 1515 1516 1517
         tcvt2 = opr::TypeCvt::make(conv2, dtype::Float16());
    auto y = opr::Elemwise::make({tcvt1, tcvt2}, opr::Elemwise::Param::Mode::ADD);

    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

M
Megvii Engine Team 已提交
1518 1519 1520
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1521 1522 1523

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1524 1525
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4TypeCvt.json"));
1526 1527

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1528 1529
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1530 1531 1532 1533 1534 1535 1536 1537
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);

    *host_x = *gen({8, 8, 16, 16}, cn);
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

1538 1539 1540 1541 1542 1543 1544 1545 1546
TEST(TestGoptInference, ConvertFormatNHWCD4LOCAL) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1547
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1548 1549 1550 1551 1552 1553 1554
    };

    auto host_x = gen({2, 8, 8, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 1;
M
Megvii Engine Team 已提交
1555
    auto w1 = mkcvar("w1", {4, 8, 3, 3}), conv1 = opr::Convolution::make(x, w1, param);
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

    auto w2 = mkcvar("w2", {8, 16, 4, 3, 3, 4}),
         local = opr::Local::make(conv1, w2, param);

    auto w3 = mkcvar("w3", {4, 4, 3, 3}),
         conv2 = opr::Convolution::make(local, w3, param);

    opr::GroupLocal::Param param_group_local;
    param_group_local.pad_h = param_group_local.pad_w = 1;
    auto w4 = mkcvar("w4", {2, 8, 16, 2, 3, 3, 2}),
         group_local = opr::GroupLocal::make(conv2, w4, param_group_local);

    auto w5 = mkcvar("w5", {4, 4, 3, 3}),
         y = opr::Convolution::make(group_local, w5, param);

    SymbolVar y_opt;
1572
    auto options = gopt::OptimizeForInferenceOptions{};
1573
    options.enable_nhwcd4();
1574
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1575

M
Megvii Engine Team 已提交
1576 1577 1578
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1579

M
Megvii Engine Team 已提交
1580 1581 1582
    ASSERT_EQ(
            opr::Local::Param::Format::NCHW,
            find_opr<opr::Local>(y_opt).param().format);
1583

M
Megvii Engine Team 已提交
1584 1585 1586
    ASSERT_EQ(
            opr::GroupLocal::Param::Format::NCHW,
            find_opr<opr::GroupLocal>(y_opt).param().format);
1587 1588 1589

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1590 1591
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4LOCAL.json"));
1592 1593

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1594 1595
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1596 1597 1598 1599
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
TEST(TestGoptInference, ConvertFormatNHWCD4Deconv) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1610
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1611 1612 1613 1614 1615 1616 1617
    };

    auto host_x = gen({8, 8, 8, 8}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);

    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 0;
M
Megvii Engine Team 已提交
1618
    auto w0 = mkcvar("w1", {4, 8, 2, 2}), conv = opr::Convolution::make(x, w0, param);
1619 1620 1621 1622 1623

    auto w1 = mkcvar("w1", {4, 1, 2, 2}),
         y = opr::ConvolutionBackwardData::make(w1, conv, param, {}, {});

    SymbolVar y_opt;
1624
    auto options = gopt::OptimizeForInferenceOptions{};
1625
    options.enable_nhwcd4();
1626
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1627

M
Megvii Engine Team 已提交
1628 1629 1630 1631 1632 1633
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW,
            find_opr<opr::ConvolutionBackwardData>(y_opt).param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1634 1635

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1636 1637
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}
TEST(TestGoptInference, ConvertFormatNHWCD4Qint8) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

M
Megvii Engine Team 已提交
1650
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
1651
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1652
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
                dtype);
    };

    auto host_x = gen({8, 8, 8, 8}, cn);
    auto _x = opr::Host2DeviceCopy::make(*graph, host_x),
         x = opr::TypeCvt::make(_x, dtype::QuantizedS8(0.2f));

    opr::ConvBias::Param param;
    param.pad_h = param.pad_w = 0;
    auto w = mkcvar("w", {4, 8, 3, 3}, dtype::QuantizedS8(0.1f)),
         b = mkcvar("b", {1, 4, 1, 1}, dtype::QuantizedS32(0.02f)),
M
Megvii Engine Team 已提交
1664 1665
         y = opr::ConvBias::make(
                 x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(0.2f)});
1666 1667

    SymbolVar y_opt;
1668
    auto options = gopt::OptimizeForInferenceOptions{};
1669
    options.enable_nhwcd4();
1670
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1671

M
Megvii Engine Team 已提交
1672 1673 1674
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NHWCD4,
            find_opr<opr::ConvBias>(y_opt).param().format);
1675 1676 1677

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1678 1679
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4Qint8.json"));
1680 1681 1682 1683
    auto float_y = opr::TypeCvt::make(y, dtype::Float32()),
         float_y_opt = opr::TypeCvt::make(y_opt, dtype::Float32());

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1684 1685 1686
    auto func = graph->compile(
            {make_callback_copy(float_y, host_y),
             make_callback_copy(float_y_opt, host_y_opt)});
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}
TEST(TestGoptInference, ConvertFormatPadIC) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1699
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1700 1701
    };

M
Megvii Engine Team 已提交
1702
    auto host_inp1 = gen({1, 6, 128, 128}, cn), host_inp2 = gen({1, 6, 256, 256}, cn);
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    auto inp1 = opr::Host2DeviceCopy::make(*graph, host_inp1),
         inp2 = opr::Host2DeviceCopy::make(*graph, host_inp2);

    auto shape_tmp = mkcvar("tmp", {256, 256});
    auto shape_of = opr::GetVarShape::make(shape_tmp);
    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
    auto resize = opr::ResizeForward::make(inp1, shape_of, param_resize);

    auto concat = opr::Concat::make({inp2, resize}, 1);

    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 1;
    param.sparse = opr::Convolution::Param::Sparse::DENSE;
    auto w1 = mkcvar("w1", {12, 12, 3, 3});
    auto y = opr::Convolution::make(concat, w1, param);
    SymbolVar y_opt;
1720
    auto options = gopt::OptimizeForInferenceOptions{};
1721
    options.enable_nhwcd4();
1722
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1723 1724

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1725 1726
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1727 1728
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
1729 1730
}

1731 1732 1733 1734 1735 1736 1737 1738 1739
TEST(TestGoptInference, concatbypass) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1740
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1741 1742
    };

M
Megvii Engine Team 已提交
1743
    auto host_inp1 = gen({1, 6, 16, 16}, cn), host_inp2 = gen({1, 6, 32, 32}, cn);
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
    auto inp1 = opr::Host2DeviceCopy::make(*graph, host_inp1),
         inp2 = opr::Host2DeviceCopy::make(*graph, host_inp2);

    auto shape_tmp = mkcvar("tmp", {32, 32});
    auto shape_of = opr::GetVarShape::make(shape_tmp);
    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
    auto resize = opr::ResizeForward::make(inp1, shape_of, param_resize);

    //! this concat should forward to chw
    auto concat = opr::Concat::make({inp2, resize}, 1);

    opr::Convolution::Param param;
    param.pad_h = param.pad_w = 1;
    param.sparse = opr::Convolution::Param::Sparse::DENSE;
    auto w1 = mkcvar("w1", {12, 12, 3, 3});
    auto w2 = mkcvar("w1", {12, 24, 3, 3});
    auto y = opr::Convolution::make(concat, w1, param);
    //! this concat should bypass CD4
    y = opr::Concat::make({y, y}, 0);
    y = opr::Convolution::make(y, w1, param);
    //! this concat should bypass CD4
    y = opr::Concat::make({y, y}, 1);
    y = opr::Convolution::make(y, w2, param);
    //! this concat should bypass CD4
    y = opr::Concat::make({y, y}, 2);
    y = opr::Convolution::make(y, w1, param);
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1777 1778
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
    size_t relayout_format_nr = 0;
    auto cb = [&](cg::OperatorNodeBase* opr) {
        if (opr->try_cast_final<opr::Convolution>()) {
            auto conv_inputs = opr->input();
            for (auto& input : conv_inputs) {
                if (std::string::npos !=
                    std::string(input->cname()).find("relayout_format")) {
                    relayout_format_nr++;
                }
            }
        }
        return true;
    };
    func->iter_opr_seq(cb);
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
M
Megvii Engine Team 已提交
1795 1796 1797
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1798 1799 1800
    ASSERT_EQ(1, relayout_format_nr);
}

1801 1802 1803
TEST(TestGoptInference, ConvertBatchNormPass) {
    auto cn = CompNode::load("cpu0");

1804
    std::vector<TensorShape> shps = {{1, 3, 1, 1}, {1, 1, 1, 3}},
M
Megvii Engine Team 已提交
1805
                             xshps = {{2, 3, 16, 24}, {2, 16, 24, 3}};
1806 1807 1808 1809 1810 1811 1812 1813
    for (int t = 0; t < 2; t++) {
        HostTensorGenerator<> gen(0, 1, 0);
        auto graph = ComputingGraph::make();
        graph->options().graph_opt_level = 0;
        auto mkvar = [&](const char* name, const TensorShape& shp) {
            return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
        };
        auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1814
            return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1815 1816
        };
        using Param = opr::BatchNorm::Param;
M
Megvii Engine Team 已提交
1817 1818
        Param::ParamDim param_dim =
                t == 0 ? Param::ParamDim::DIM_1C11 : Param::ParamDim::DIM_111C;
1819 1820 1821 1822 1823 1824
        Param param(param_dim, Param::FwdMode::INFERENCE);
        TensorShape shp = shps[t], xshp = xshps[t];
        auto x = mkvar("x", xshp), scale = mkcvar("scale", shp),
             bias = mkcvar("bias", shp), mean = mkcvar("mean", shp);
        auto host_variance = gen(shp, cn);
        for (size_t i = 0; i < shp.total_nr_elems(); ++i) {
M
Megvii Engine Team 已提交
1825
            host_variance->ptr<float>()[i] = std::abs(host_variance->ptr<float>()[i]);
1826 1827 1828 1829 1830
        }
        auto variance = opr::SharedDeviceTensor::make(*graph, *host_variance)
                                .rename("variance");
        auto y = opr::BatchNorm::make(x, scale, bias, mean, variance, param)[5];
        SymbolVar y_opt;
M
Megvii Engine Team 已提交
1831 1832 1833
        unpack_vector(
                gopt::optimize_for_inference({y}, gopt::OptimizeForInferenceOptions{}),
                y_opt);
1834 1835 1836 1837 1838 1839 1840
        ASSERT_EQ(0u, find_opr_num<opr::BatchNorm>(y_opt));
        graph->compile({{y_opt, {}}})
                ->to_json()
                ->writeto_fpath(
                        output_file("TestGoptInference.ConvertBatchNormPass.json"));

        HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
1841 1842
        auto func = graph->compile(
                {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1843 1844
        func->execute();
        MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
    }
}

TEST(TestGoptInference, ConvBiasNonlinearityFusePass) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    auto cn = CompNode::load("cpu0");

    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1861
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1862 1863 1864 1865 1866 1867
    };
    opr::Convolution::Param param;
    auto x = mkvar("x", {5, 8, 16, 24}), w1 = mkcvar("w1", {4, 8, 1, 1}),
         w2 = mkcvar("w2", {4, 4, 3, 3}), b1 = mkcvar("b1", {1, 4, 1, 1}),
         b2 = mkcvar("b2", {1, 4, 1, 1}), w3 = mkcvar("w3", {8, 4, 1, 1}),
         y_cut = opr::Convolution::make(x, w1, param),
M
Megvii Engine Team 已提交
1868
         y1 = opr::Elemwise::make({y_cut + b1}, opr::Elemwise::Param::Mode::RELU);
1869
    param.pad_w = param.pad_h = 1;
M
Megvii Engine Team 已提交
1870 1871 1872
    auto y2 = opr::Elemwise::make(
            {opr::Convolution::make(y1, w2, param) + b2},
            opr::Elemwise::Param::Mode::SIGMOID);
1873 1874
    param.pad_w = param.pad_h = 0;
    auto y3 = opr::Convolution::make(y2, w3, param), y_tmp = y3 + x,
M
Megvii Engine Team 已提交
1875
         y_expand = opr::Elemwise::make({y_cut}, opr::Elemwise::Param::Mode::RELU),
1876 1877
         y_y = opr::Convolution::make(y_expand, w3, param), y = y_y + y_tmp;
    SymbolVar y_opt;
1878
    auto options = gopt::OptimizeForInferenceOptions{};
1879
    options.enable_nhwcd4().enable_fuse_conv_bias_nonlinearity();
1880
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1881 1882 1883
    ASSERT_EQ(3u, find_opr<opr::ConvBias>(y_opt).input().size());
    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1884 1885
            ->writeto_fpath(
                    output_file("TestGoptInference.FuseConvBiasNonlinPass.json"));
1886 1887

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
1888 1889
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1890 1891 1892 1893
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-4);
}

1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
TEST(TestGoptInference, ConvBiasNonlinearityFusePass2) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    auto cn = CompNode::load("cpu0");

    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
    };
    opr::Convolution::Param param;
    auto x = mkvar("x", {5, 8, 16, 24}), w1 = mkcvar("w1", {4, 8, 1, 1}),
         w2 = mkcvar("w2", {4, 8, 1, 1});

    auto b1 = mkcvar("b1", {1, 4, 1, 1});
    auto y_cut = opr::Convolution::make(x, w1, param);
    auto y = opr::Elemwise::make({y_cut + b1}, opr::Elemwise::Param::Mode::SIGMOID);
    y = opr::Elemwise::make({y}, opr::Elemwise::Param::Mode::RELU);
    auto y_cut2 = opr::Convolution::make(x, w2, param);
    y_cut2 = opr::Elemwise::make({y_cut2}, opr::Elemwise::Param::Mode::SIGMOID);
    y_cut2 = opr::Elemwise::make({y_cut2}, opr::Elemwise::Param::Mode::RELU);
    y = y + y_cut2;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nhwcd4().enable_fuse_conv_bias_nonlinearity();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    ASSERT_EQ(
            opr::ConvBias::Param::NonlineMode::SIGMOID,
            find_opr<opr::ConvBias>(y_opt).param().nonlineMode);
    graph->compile({{y_opt, {}}})
            ->to_json()
            ->writeto_fpath(
                    output_file("TestGoptInference.FuseConvBiasNonlinPass2.json"));

    HostTensorND host_y, host_y_opt;
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-4);
}

1940 1941 1942 1943 1944 1945 1946 1947
TEST(TestGoptInference, ConvBiasNonlinearityFusePass_FullBias) {
    NaiveMegDNNHandleScope naive_megdnn_handle;

    for (int i = 0; i < 2; i++) {
        auto graph = ComputingGraph::make();
        auto cn = CompNode::load("cpu0");
        HostTensorGenerator<> gen;
        auto mkImvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1948
            return opr::ImmutableTensor::make(*graph, *gen(shp, cn)).rename(name);
1949 1950 1951 1952
        };

        graph->options().graph_opt_level = 0;
        auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1953
            return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1954 1955 1956 1957 1958 1959
        };
        opr::Convolution::Param param;
        auto host_x = gen({1, 8, 16, 24}, cn);
        auto x = opr::Host2DeviceCopy::make(*graph, host_x),
             w1 = mkcvar("w1", {4, 8, 1, 1}), w2 = mkcvar("w2", {4, 8, 3, 3}),
             w3 = mkcvar("w3", {4, 4, 1, 1}),
M
Megvii Engine Team 已提交
1960
             b = i == 0 ? mkcvar("b", {1, 4, 16, 24}) : mkImvar("bias", {1, 4, 16, 24}),
1961 1962 1963
             y_cut0 = opr::Convolution::make(x, w1, param);
        param.pad_w = param.pad_h = 1;
        auto y_cut1 = opr::Convolution::make(x, w2, param);
M
Megvii Engine Team 已提交
1964 1965
        auto y1 = opr::Elemwise::make(
                {y_cut0 + y_cut1}, opr::Elemwise::Param::Mode::RELU);
1966 1967
        param.pad_w = param.pad_h = 0;
        auto y2 = opr::Convolution::make(y1, w3, param);
M
Megvii Engine Team 已提交
1968
        auto y = opr::Elemwise::make({y2 + b}, opr::Elemwise::Param::Mode::RELU);
1969 1970 1971 1972 1973 1974 1975
        SymbolVar y_opt;
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
        ASSERT_EQ(3u, find_opr<opr::ConvBias>(y_opt).input().size());
        graph->compile({{y_opt, {}}})
                ->to_json()
M
Megvii Engine Team 已提交
1976 1977
                ->writeto_fpath(output_file("TestGoptInference.FuseConvBiasNonlinPass_"
                                            "FulBias.json"));
1978
        HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
1979 1980
        auto func = graph->compile(
                {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1981 1982 1983 1984 1985 1986 1987 1988
        func->execute();
        MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-4);
        *host_x = *gen({4, 8, 16, 24}, cn);
        func->execute();
        MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-4);
    }
}

1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
#if (MEGDNN_AARCH64 || MEGDNN_ARMV7) && !MGB_OPENCL && !MGB_CUDA
TEST(TestGoptInference, FuseTypeCvtAndElemwiseCase0) {
    HostTensorGenerator<dtype::Int16, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    size_t n = 1;
    size_t c = 128;
    size_t h = 16;
    size_t w = 16;
    auto host_x1 = gen({n, h, w, c}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);

    auto x_nchw = opr::Dimshuffle::make(x, {0, 3, 1, 2}, 4, cn);
    auto x_f32 = opr::TypeCvt::make(x_nchw, dtype::Float32(), cn);
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
    };
    auto s = mkcvar("s", {1, c, 1, 1});
    auto b = mkcvar("b", {1, c, 1, 1});

    auto result = opr::Elemwise::make(
            {x_f32, s, b}, opr::Elemwise::Param::Mode::FUSE_MUL_ADD3);

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_TRUE(y_opt.node()->owner_opr()->same_type<opr::ElemwiseMultiType>());

    ASSERT_EQ(
            opr::ElemwiseMultiType::Param::Mode::FUSE_MUL_ADD3_INT16xF32xF32xF32,
            find_opr<opr::ElemwiseMultiType>(y_opt).param().mode);

    HostTensorND host_y_opt, host_y;
    auto func = graph->compile({make_callback_copy(y, host_y)});
    func->execute();
    graph->options().graph_opt_level = 2;
    auto func_opt = graph->compile({make_callback_copy(y, host_y_opt)});
    func_opt->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}

TEST(TestGoptInference, FuseTypeCvtAndElemwiseCase1) {
    HostTensorGenerator<dtype::Int16, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    size_t n = 1;
    size_t c = 128;
    size_t h = 16;
    size_t w = 16;
    auto host_x1 = gen({n, h, w, c}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);

    auto x_nchw = opr::Dimshuffle::make(x, {0, 3, 1, 2}, 4, cn);
    auto x_f32 = opr::TypeCvt::make(x_nchw, dtype::Float32(), cn);
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
    };
    auto s = mkcvar("s", {1, c, 1, 1});

    auto result = opr::Elemwise::make({x_f32, s}, opr::Elemwise::Param::Mode::MUL);

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_TRUE(y_opt.node()->owner_opr()->same_type<opr::ElemwiseMultiType>());

    ASSERT_EQ(
            opr::ElemwiseMultiType::Param::Mode::MUL_INT16xF32xF32,
            find_opr<opr::ElemwiseMultiType>(y_opt).param().mode);

    HostTensorND host_y_opt, host_y;
    auto func = graph->compile({make_callback_copy(y, host_y)});
    func->execute();
    graph->options().graph_opt_level = 2;
    auto func_opt = graph->compile({make_callback_copy(y, host_y_opt)});
    func_opt->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}

TEST(TestGoptInference, FuseTypeCvtAndElemwiseCase2) {
    HostTensorGenerator<dtype::Uint8, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    size_t n = 1;
    size_t c = 128;
    size_t h = 16;
    size_t w = 16;
    auto host_x1 = gen({n, h, w, c}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);

    auto x_nchw = opr::Dimshuffle::make(x, {0, 3, 1, 2}, 4, cn);
    auto x_f32 = opr::TypeCvt::make(x_nchw, dtype::Float32(), cn);
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
    };
    auto s = mkcvar("s", {1, c, 1, 1});
    auto b = mkcvar("b", {1, c, 1, 1});

    auto result = opr::Elemwise::make(
            {x_f32, s, b}, opr::Elemwise::Param::Mode::FUSE_MUL_ADD3);

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_TRUE(y_opt.node()->owner_opr()->same_type<opr::ElemwiseMultiType>());

    ASSERT_EQ(
            opr::ElemwiseMultiType::Param::Mode::FUSE_MUL_ADD3_UINT8xF32xF32xF32,
            find_opr<opr::ElemwiseMultiType>(y_opt).param().mode);

    HostTensorND host_y_opt, host_y;
    auto func = graph->compile({make_callback_copy(y, host_y)});
    func->execute();
    graph->options().graph_opt_level = 2;
    auto func_opt = graph->compile({make_callback_copy(y, host_y_opt)});
    func_opt->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}
#endif

2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
TEST(TestGoptInference, ParamMerge) {
    auto cns = load_multiple_xpus(2);
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto var0 = opr::SharedDeviceTensor::make(*graph, *gen({2, 3}, cns[0])),
         var1 = opr::SharedDeviceTensor::make(*graph, *gen({1, 3}, cns[1])),
         y = var0 + opr::Copy::make(var1, {cns[0]});
    HostTensorND y_expected_val;
    graph->compile({make_callback_copy(y, y_expected_val)})->execute();

    SymbolVar y_opt;
M
Megvii Engine Team 已提交
2132 2133 2134 2135 2136 2137
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_opt);
2138 2139
    auto opr = y_opt.node()->owner_opr();
    ASSERT_EQ(2u, opr->input().size());
M
Megvii Engine Team 已提交
2140
    ASSERT_EQ(2u, find_opr<opr::MultipleDeviceTensorHolder>(y_opt).output().size());
2141 2142 2143 2144 2145 2146 2147 2148 2149
    HostTensorND y_got_val;
    graph->compile({make_callback_copy(y_opt, y_got_val)})->execute();
    MGB_ASSERT_TENSOR_EQ(y_expected_val, y_got_val);
}

TEST(TestGoptInference, ParamMergeFormat) {
    auto cns = load_multiple_xpus(2);

    auto make_dv = [](const HostTensorND& hv) {
M
Megvii Engine Team 已提交
2150 2151 2152
        TensorLayout layout{
                hv.layout(), hv.layout().dtype,
                megdnn::Image2DPack4TensorFormat::make_raw(1, 64)};
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
        auto ret = std::make_shared<DeviceTensorND>(hv.comp_node(), layout);
        ret->copy_from_fixlayout(hv).sync();
        return ret;
    };

    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto var0 = opr::SharedDeviceTensorWithFormat::make(
                 *graph, make_dv(*gen({2, 32}, cns[0]))),
         var1 = opr::SharedDeviceTensorWithFormat::make(
                 *graph, make_dv(*gen({1, 32}, cns[1]))),
         y = var0 + opr::Copy::make(var1, {cns[0]});
    HostTensorND y_expected_val;
    graph->compile({make_callback_copy(y, y_expected_val)})->execute();

    SymbolVar y_opt;
M
Megvii Engine Team 已提交
2169 2170 2171 2172 2173 2174
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_opt);
2175 2176
    auto opr = y_opt.node()->owner_opr();
    ASSERT_EQ(2u, opr->input().size());
M
Megvii Engine Team 已提交
2177 2178 2179
    ASSERT_EQ(
            2u,
            find_opr<opr::MultipleDeviceTensorWithFormatHolder>(y_opt).output().size());
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 2210 2211
    HostTensorND y_got_val;
    graph->compile({make_callback_copy(y_opt, y_got_val)})->execute();
    MGB_ASSERT_TENSOR_EQ(y_expected_val, y_got_val);
}

#if MGB_ENABLE_FASTRUN
TEST(TestGoptInference, AlgoProfile) {
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto host_x = gen({4, 3, 8, 9}), host_y = gen({2, 3, 3, 3});
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y),
         z = opr::Convolution::make(x, y);
    auto&& conv = z.node()->owner_opr()->cast_final_safe<opr::Convolution>();
    using S = opr::Convolution::ExecutionPolicy::Strategy;
    ASSERT_EQ(S::HEURISTIC, conv.execution_policy_transient().strategy);
    gopt::enable_opr_algo_profiling_inplace({z + 2.3f});
    ASSERT_EQ(S::PROFILE, conv.execution_policy().strategy);
}
#endif

TEST(TestGoptInference, ProfileCache) {
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto host_x = gen({4, 3, 8, 9}), host_y = gen({2, 3, 3, 3});
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y),
         z = opr::Convolution::make(x, y);
    auto&& conv = z.node()->owner_opr()->cast_final_safe<opr::Convolution>();
    using S = opr::Convolution::ExecutionPolicy::Strategy;
    ASSERT_EQ(S::HEURISTIC, conv.execution_policy_transient().strategy);
    gopt::enable_opr_use_profiling_cache_inplace({z + 2.3f});
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
    ASSERT_EQ(S::PROFILE | S::HEURISTIC, conv.execution_policy().strategy);
}

TEST(TestGoptInference, FastProfileCache) {
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto host_x = gen({4, 3, 8, 9}), host_y = gen({2, 3, 3, 3});
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y),
         z = opr::Convolution::make(x, y);
    auto&& conv = z.node()->owner_opr()->cast_final_safe<opr::Convolution>();
    using S = opr::Convolution::ExecutionPolicy::Strategy;
    ASSERT_EQ(S::HEURISTIC, conv.execution_policy_transient().strategy);
M
Megvii Engine Team 已提交
2225
    gopt::modify_opr_algo_strategy_inplace({z + 2.3f}, S::PROFILE | S::OPTIMIZED);
M
Megvii Engine Team 已提交
2226
    ASSERT_EQ(S::PROFILE | S::OPTIMIZED, conv.execution_policy().strategy);
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
}

TEST(TestGoptInference, AlgoWorkspaceLimit) {
    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    auto host_x = gen({4, 3, 8, 9}), host_y = gen({2, 3, 3, 3});
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y),
         z = opr::Convolution::make(x, y);
    auto&& conv = z.node()->owner_opr()->cast_final_safe<opr::Convolution>();
M
Megvii Engine Team 已提交
2237 2238 2239
    ASSERT_EQ(
            std::numeric_limits<uint64_t>::max(),
            conv.execution_policy_transient().workspace_limit);
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
    gopt::set_opr_algo_workspace_limit_inplace({z + 2.3f}, 10000u);
    ASSERT_EQ(10000u, conv.execution_policy().workspace_limit);
}

TEST_PASS(FuseConvBiasNonlinPass, Basic) {
    auto cn = CompNode::load("xpux");

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2250
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2251
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2252
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2253
    };
M
Megvii Engine Team 已提交
2254
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2255
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2256
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2257 2258 2259
                dtype);
    };

M
Megvii Engine Team 已提交
2260 2261 2262
    for (auto format :
         {opr::Convolution::Param::Format::NCHW, opr::Convolution::Param::Format::NHWC,
          opr::Convolution::Param::Format::NCHW4}) {
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
        opr::Convolution::Param param;
        param.format = format;
        SymbolVar x, w, b;
        if (format == opr::Convolution::Param::Format::NHWC) {
            x = mkvar("x", {20, 20, 20, 4}, dtype::QuantizedS8(2.5f)),
            w = mkcvar("w1", {24, 1, 1, 4}, dtype::QuantizedS8(2.5f)),
            b = mkcvar("b", {1, 1, 1, 24}, dtype::QuantizedS32(6.25f));
        } else if (format == opr::Convolution::Param::Format::NCHW) {
            x = mkvar("x", {20, 4, 20, 20}, dtype::QuantizedS8(2.5f)),
            w = mkcvar("w1", {24, 4, 1, 1}, dtype::QuantizedS8(2.5f)),
            b = mkcvar("b", {1, 24, 1, 1}, dtype::QuantizedS32(6.25f));
        } else {
            mgb_assert(format == opr::Convolution::Param::Format::NCHW4);
            x = mkvar("x", {20, 1, 20, 20, 4}, dtype::QuantizedS8(2.5f)),
            w = mkcvar("w1", {24, 1, 1, 1, 4}, dtype::QuantizedS8(2.5f)),
            b = mkcvar("b", {1, 6, 1, 1, 4}, dtype::QuantizedS32(6.25f));
        }
        auto y = opr::Convolution::make(x, w, param);
        y = opr::Elemwise::make({y + b}, opr::Elemwise::Param::Mode::RELU);
        y = opr::TypeCvt::make(y, dtype::QuantizedS8(2.5f));

        opr::ConvBias::Param conv_bias_param;
        conv_bias_param.format = format;
        conv_bias_param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
        auto concret_y = opr::ConvBias::make(
                x, w, b, conv_bias_param, {},
                OperatorNodeConfig{dtype::QuantizedS8(2.5f)});

        check(concret_y, y);
    }
}

#if MGB_CUDA
2296

2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
TEST(TestEnableTensorCore, SmallInputShape) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2313
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2314
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2315
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2316
    };
M
Megvii Engine Team 已提交
2317
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2318
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2319
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
                dtype);
    };

    auto x = mkvar("x", {32, 16, 4, 8, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
         z = mkcvar("b1", {32, 16, 2, 4, 4}, dtype::QuantizedS8(2.5f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 2;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
2333 2334 2335 2336
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
    y = opr::ConvBias::make(
            y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2337 2338 2339 2340
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2341 2342
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2343
        options.enable_nchw32().enable_fuse_conv_bias_nonlinearity();
2344 2345 2346 2347 2348 2349 2350
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_no_tc);
    }
2351 2352 2353
    auto nr_dimshuffle = find_opr_num<mgb::opr::Dimshuffle>(y_opt);
    ASSERT_EQ(2u, nr_dimshuffle);
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2354 2355 2356
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2357 2358 2359 2360
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
TEST(TestEnableTensorCore, Nchw4Nchw) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2377
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2378
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2379
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2380
    };
M
Megvii Engine Team 已提交
2381
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2382
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2383
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2384 2385 2386
                dtype);
    };

M
Megvii Engine Team 已提交
2387 2388
    auto mkshape = [](opr::ConvBias::Param::Format format, size_t N, size_t C, size_t H,
                      size_t W) -> TensorShape {
2389 2390 2391 2392 2393 2394 2395 2396 2397
        mgb_assert(C % 4 == 0);
        if (format == opr::ConvBias::Param::Format::NCHW4) {
            return {N, C / 4, H, W, 4};
        } else {
            mgb_assert(format == opr::ConvBias::Param::Format::NCHW);
            return {N, C, H, W};
        }
    };

M
Megvii Engine Team 已提交
2398 2399 2400 2401 2402 2403
    for (auto format :
         {opr::ConvBias::Param::Format::NCHW, opr::ConvBias::Param::Format::NCHW4}) {
        auto x = mkvar("x", mkshape(format, 32, 64, 16, 16), dtype::QuantizedS8(2.5f)),
             w = mkcvar("w1", mkshape(format, 64, 64, 3, 3), dtype::QuantizedS8(2.5f)),
             b = mkcvar("b", mkshape(format, 1, 64, 1, 1), dtype::QuantizedS32(6.25f)),
             z = mkcvar("b1", mkshape(format, 32, 64, 8, 8), dtype::QuantizedS8(2.5f));
2404 2405 2406 2407 2408 2409 2410
        opr::ConvBias::Param param;
        param.format = format;
        param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
        param.stride_h = param.stride_w = 2;
        param.pad_h = param.pad_w = 1;

        auto y = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2411 2412 2413
                x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
        y = opr::ConvBias::make(
                y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
        y = opr::TypeCvt::make(y, dtype::Float32());

        SymbolVar y_opt;
        SymbolVar y_no_tc;
        {
            auto options = gopt::OptimizeForInferenceOptions{};
            options.enable_nchw32().enable_fuse_conv_bias_nonlinearity();
            unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
        }
        {
            auto options = gopt::OptimizeForInferenceOptions{};
            options.enable_fuse_conv_bias_nonlinearity();
            unpack_vector(gopt::optimize_for_inference({y}, options), y_no_tc);
        }
        auto nr_dimshuffle = find_opr_num<mgb::opr::Dimshuffle>(y_opt);
2429 2430
        if (format == opr::ConvBias::Param::Format::NCHW4) {
#if CUDA_VERSION >= 10020
M
Megvii Engine Team 已提交
2431
            //! try_conv_reformat_nchw322nchw4 used when cuda_version >= 10020
2432 2433 2434 2435 2436 2437 2438
            ASSERT_EQ(1u, nr_dimshuffle);
#else
            ASSERT_EQ(2u, nr_dimshuffle);
#endif
        } else {
            ASSERT_EQ(2u, nr_dimshuffle);
        }
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
        std::string json_name;
        if (format == opr::ConvBias::Param::Format::NCHW4) {
            json_name = "TestGoptInference.Nchw4Nchw.NCHW4.json";
        } else {
            mgb_assert(format == opr::ConvBias::Param::Format::NCHW);
            json_name = "TestGoptInference.Nchw4Nchw.NCHW.json";
        }

        graph->compile({{y_opt, {}}})
                ->to_json()
                ->writeto_fpath(output_file(json_name.c_str()));
        HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2451 2452 2453
        auto func = graph->compile(
                {make_callback_copy(y_no_tc, host_y),
                 make_callback_copy(y_opt, host_y_opt)});
2454 2455 2456 2457 2458
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
    }
}

2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
TEST(TestEnableTensorCore, ConvBiasWithZ) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2475
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2476
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2477
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2478
    };
M
Megvii Engine Team 已提交
2479
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2480
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2481
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
                dtype);
    };

    auto x = mkvar("x", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
         z = mkvar("b1", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
2495 2496
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2497 2498 2499 2500
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2501 2502
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2503
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2504 2505 2506 2507 2508 2509 2510
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_no_tc);
    }
2511
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2512 2513 2514
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

TEST(TestEnableTensorCore, Pooling) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2535
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2536
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2537
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2538
    };
M
Megvii Engine Team 已提交
2539
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2540
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2541
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
                dtype);
    };

    auto x = mkvar("x", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
         z = mkvar("b1", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
2555 2556
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568
    opr::Pooling::Param pool_param;
    pool_param.format = opr::Pooling::Param::Format::NCHW4;
    y = opr::Pooling::make(y, pool_param);
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
M
Megvii Engine Team 已提交
2569 2570 2571
    ASSERT_EQ(
            opr::Pooling::Param::Format::NCHW32,
            find_opr<opr::Pooling>(y_opt).param().format);
2572 2573 2574 2575 2576 2577
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_no_tc);
    }
    HostTensorND host_y, host_y_opt;
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

TEST(TestEnableTensorCore, BatchConvBias) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
        return opr::TypeCvt::make(
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
        return opr::TypeCvt::make(
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
                dtype);
    };

    auto inp = mkvar("inp", {32, 24, 24, 24, 4}, dtype::QuantizedS8(1.1f)),
         flt = mkcvar("flt", {32, 96, 24, 1, 1, 4}, dtype::QuantizedS8(1.2f)),
         bias = mkcvar("bias", {1, 24, 1, 1, 4}, dtype::QuantizedS32{1.1f * 1.2f});
    opr::BatchConvBias::Param param;
    param.format = opr::BatchConvBias::Param::Format::NCHW4;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 0;

    auto y = opr::BatchConvBias::make(
            inp, flt, bias, param, {}, OperatorNodeConfig{dtype::QuantizedS8{1.3f}});
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
    ASSERT_EQ(
            opr::BatchConvBias::Param::Format::NCHW4,
            find_opr<opr::BatchConvBias>(y_opt).param().format);
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_no_tc);
    }
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2639 2640 2641
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

TEST(TestGoptInference, EnableTensorCore) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2662
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2663
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2664
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2665
    };
M
Megvii Engine Team 已提交
2666
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2667
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2668
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
                dtype);
    };

    auto x = mkvar("x", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
         b1 = mkvar("b1", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f));
    opr::Convolution::Param param;
    param.format = opr::Convolution::Param::Format::NCHW4;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

    auto y = opr::Convolution::make(x, w, param);
    y = opr::Elemwise::make({y + b}, opr::Elemwise::Param::Mode::RELU);
    y = opr::TypeCvt::make(y, dtype::QuantizedS8(2.5f));

    auto y1 = y + b1, y2 = opr::Convolution::make(y, w, param),
         y3 = opr::Elemwise::make({y - b1}, opr::Elemwise::Param::Mode::RELU);
    y2 = opr::Elemwise::make({y2 + b}, opr::Elemwise::Param::Mode::RELU),
    y2 = opr::TypeCvt::make(y2, dtype::QuantizedS8(2.5f));
    auto y4 = y1 + y2 + y3;
    y4 = opr::TypeCvt::make(y4, dtype::Float32());
    SymbolVar y_opt;
    SymbolVar y_no_tc;
2693 2694
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2695
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2696 2697 2698 2699
        unpack_vector(gopt::optimize_for_inference({y4}, options), y_opt);
    }
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2700
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2701 2702
        unpack_vector(gopt::optimize_for_inference({y4}, options), y_no_tc);
    }
2703 2704 2705 2706
    auto nr_dimshuffle = find_opr_num<mgb::opr::Dimshuffle>(y_opt);
    ASSERT_EQ(3u, nr_dimshuffle);
    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
2707
            ->writeto_fpath(output_file("TestGoptInference.EnableTensorCorePass.json"));
2708 2709

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2710 2711 2712
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

TEST(FuseConvBiasZPass, BlockFuse) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 61) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 61);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2733
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2734
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2735
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2736
    };
M
Megvii Engine Team 已提交
2737
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2738
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2739
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2740 2741 2742
                dtype);
    };

2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
    using ElemMultiMode = opr::ElemwiseMultiType::Param::Mode;
    using NonlineMode = opr::ConvBias::Param::NonlineMode;
    for (auto mode :
         {ElemMultiMode::QFUSE_ADD_RELU, ElemMultiMode::QFUSE_ADD_H_SWISH}) {
        auto x = mkvar("x", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
             w1 = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
             b1 = mkcvar("b1", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
             w2 = mkcvar("w2", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
             b2 = mkcvar("b2", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
             w3 = mkcvar("w3", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
             b3 = mkcvar("b3", {1, 16, 1, 1, 4}, dtype::QuantizedS32(3.0f));
        NonlineMode nonline_mode = NonlineMode::RELU;
        if (mode == ElemMultiMode::QFUSE_ADD_H_SWISH) {
            nonline_mode = NonlineMode::H_SWISH;
        }
2758

2759 2760 2761 2762 2763
        opr::ConvBias::Param param;
        param.format = opr::Convolution::Param::Format::NCHW4;
        param.nonlineMode = nonline_mode;
        param.stride_h = param.stride_w = 1;
        param.pad_h = param.pad_w = 1;
2764

2765
        auto y1 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2766
                x, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2767 2768 2769 2770 2771
        param.nonlineMode = opr::ConvBias::Param::NonlineMode::IDENTITY;
        auto y2 = opr::ConvBias::make(
                     y1, w2, b2, param, {},
                     OperatorNodeConfig{dtype::QuantizedS8(2.5f)}),
             y3 = opr::ElemwiseMultiType::make(
M
Megvii Engine Team 已提交
2772
                     {y1, y2}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(1.2f)});
2773 2774 2775 2776 2777 2778 2779 2780 2781
        param.nonlineMode = nonline_mode;
        auto y4 = opr::ConvBias::make(
                     y3, w3, b3, param, {},
                     OperatorNodeConfig{dtype::QuantizedS8(2.5f)}),
             z = opr::ElemwiseMultiType::make(
                     {y3, y4}, {opr::ElemwiseMultiType::Param::Mode::QADD},
                     OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
        z = opr::TypeCvt::make(z, dtype::Float32());

2782 2783 2784
        SymbolVar z_fuse;
        {
            auto options = gopt::OptimizeForInferenceOptions{};
M
Megvii Engine Team 已提交
2785
            options.enable_fuse_conv_bias_nonlinearity().enable_fuse_conv_bias_with_z();
2786 2787 2788 2789
            unpack_vector(gopt::optimize_for_inference({z}, options), z_fuse);
        }
        graph->compile({{z_fuse, {}}})
                ->to_json()
M
Megvii Engine Team 已提交
2790
                ->writeto_fpath(output_file("FuseConvBiasZPass.BlockFuse_fuse.json"));
2791

M
Megvii Engine Team 已提交
2792
        auto nr_elem_multi_type = find_opr_num<mgb::opr::ElemwiseMultiType>(z_fuse);
2793 2794 2795 2796 2797
        MGB_MARK_USED_VAR(nr_elem_multi_type);
#if MGB_CUDA && (CUDNN_MAJOR == 8)
        ASSERT_EQ(2u, nr_elem_multi_type);
#else
        ASSERT_EQ(1u, nr_elem_multi_type);
2798 2799
        //! fuse z mannually
        auto z0 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2800
                x, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
        auto z1 = opr::ConvBias::make(
                     z0, w2, b2, z0, param, {},
                     OperatorNodeConfig{dtype::QuantizedS8(1.2f)}),
             z2 = opr::ConvBias::make(
                     z1, w3, b3, param, {},
                     OperatorNodeConfig{dtype::QuantizedS8(2.5f)}),
             z4 = opr::ElemwiseMultiType::make(
                     {z1, z2}, {opr::ElemwiseMultiType::Mode::QADD},
                     OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
        z4 = opr::TypeCvt::make(z4, dtype::Float32());

        SymbolVar z_nonfuse;
        {
            auto options = gopt::OptimizeForInferenceOptions{};
            options.enable_fuse_conv_bias_nonlinearity();
M
Megvii Engine Team 已提交
2816
            unpack_vector(gopt::optimize_for_inference({z4}, options), z_nonfuse);
2817 2818 2819
        }
        graph->compile({{z_nonfuse, {}}})
                ->to_json()
M
Megvii Engine Team 已提交
2820 2821
                ->writeto_fpath(
                        output_file("FuseConvBiasZPass.BlockFuse_nonfuse.json"));
2822
        HostTensorND host_z_fuse, host_z_nonfuse;
M
Megvii Engine Team 已提交
2823 2824 2825
        auto func = graph->compile(
                {make_callback_copy(z_nonfuse, host_z_nonfuse),
                 make_callback_copy(z_fuse, host_z_fuse)});
2826 2827
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_z_fuse, host_z_nonfuse);
2828
#endif
2829
    }
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
}

TEST(TestEnableTensorCore, ShuffleMerge) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2848
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2849
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2850
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2851
    };
M
Megvii Engine Team 已提交
2852
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2853
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2854
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
                dtype);
    };

    auto nchw2nchw4 = [](SymbolVar x) {
        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)}});
        };
M
Megvii Engine Team 已提交
2865
        auto tshp = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
        auto y0 = opr::Reshape::make(x, tshp);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
        return y1;
    };

    auto nchw42nchw = [](SymbolVar x) {
        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;
    };

    auto x = mkvar("x", {32, 64, 16, 16}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 64, 3, 3}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 64, 1, 1}, dtype::QuantizedS32(6.25f)),
         z = mkvar("b1", {32, 64, 16, 16}, dtype::QuantizedS8(2.5f));
M
Megvii Engine Team 已提交
2888
    x = nchw2nchw4(x), w = nchw2nchw4(w), b = nchw2nchw4(b), z = nchw2nchw4(z);
2889 2890 2891 2892 2893 2894
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
2895 2896
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2897 2898 2899 2900 2901
    y = nchw42nchw(y);
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2902 2903
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2904
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2905 2906 2907 2908 2909 2910 2911
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_fuse_conv_bias_nonlinearity();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_no_tc);
    }
2912 2913 2914
    auto nr_dimshuffle = find_opr_num<mgb::opr::Dimshuffle>(y_opt);
    ASSERT_EQ(3u, nr_dimshuffle);
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2915 2916 2917
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

#endif

TEST(FuseConvBiasZPass, Basic) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
2931
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2932
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2933
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2934
    };
M
Megvii Engine Team 已提交
2935
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2936
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2937
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
                dtype);
    };

    auto format = opr::Convolution::Param::Format::NCHW4;

    auto x = mkvar("x", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
         b1 = mkvar("b1", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
         b2 = mkvar("b2", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f));

    opr::ConvBias::Param conv_bias_param;
    conv_bias_param.format = format;
    conv_bias_param.stride_h = conv_bias_param.stride_w = 1;
    conv_bias_param.pad_h = conv_bias_param.pad_w = 1;

M
Megvii Engine Team 已提交
2954 2955
    auto y = opr::ConvBias::make(
            x, w, b, conv_bias_param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2956 2957 2958 2959

    SymbolVar y_opt;

    // check fuse mode
M
Megvii Engine Team 已提交
2960 2961 2962 2963
    for (auto mode :
         {opr::ElemwiseMultiType::Param::Mode::QADD,
          opr::ElemwiseMultiType::Param::Mode::QMUL,
          opr::ElemwiseMultiType::Param::Mode::QFUSE_ADD_RELU}) {
2964 2965
        auto y1 = opr::ElemwiseMultiType::make(
                {y, b1}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2966 2967 2968 2969
        {
            auto options = gopt::OptimizeForInferenceOptions{};
            options.enable_fuse_conv_bias_nonlinearity()
                    .enable_fuse_conv_bias_with_z()
2970
                    .enable_nchw32();
2971 2972
            unpack_vector(gopt::optimize_for_inference({y1}, options), y_opt);
        }
2973 2974 2975 2976 2977 2978 2979 2980
        auto nr_elemwisemultitype = find_opr_num<opr::ElemwiseMultiType>(y_opt);
        if (mode == opr::ElemwiseMultiType::Param::Mode::QMUL) {
            ASSERT_NE(0u, nr_elemwisemultitype);
        } else
            ASSERT_EQ(0u, nr_elemwisemultitype);
        // fuse convbiasz and z
        if (mode == opr::ElemwiseMultiType::Param::Mode::QADD) {
            auto y2 = opr::ElemwiseMultiType::make(
M
Megvii Engine Team 已提交
2981
                    {y1, b2}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2982 2983 2984 2985
            {
                auto options = gopt::OptimizeForInferenceOptions{};
                options.enable_fuse_conv_bias_nonlinearity()
                        .enable_fuse_conv_bias_with_z()
2986
                        .enable_nchw32();
M
Megvii Engine Team 已提交
2987
                unpack_vector(gopt::optimize_for_inference({y2}, options), y_opt);
2988
            }
M
Megvii Engine Team 已提交
2989
            auto nr_elemwisemultitype = find_opr_num<opr::ElemwiseMultiType>(y_opt);
2990 2991 2992 2993 2994 2995
            ASSERT_NE(0u, nr_elemwisemultitype);
        }
    }
}

#if MGB_CUDA
2996
//! close for cu111 ci, reopen it when bug fixed
2997
#if CUDA_VERSION < 11000
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
TEST(TestGoptInference, EnableCHWN4) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 61) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 61);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3014
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3015
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3016
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3017
    };
M
Megvii Engine Team 已提交
3018
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3019
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3020
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3021 3022
                dtype);
    };
M
Megvii Engine Team 已提交
3023 3024
    auto mkshape = [](opr::ConvBias::Param::Format format, size_t N, size_t C, size_t H,
                      size_t W) -> TensorShape {
3025 3026 3027 3028 3029 3030 3031 3032
        mgb_assert(C % 4 == 0);
        if (format == opr::ConvBias::Param::Format::NCHW4) {
            return {N, C / 4, H, W, 4};
        } else {
            mgb_assert(format == opr::ConvBias::Param::Format::NCHW);
            return {N, C, H, W};
        }
    };
3033

M
Megvii Engine Team 已提交
3034 3035 3036 3037 3038 3039 3040
    for (auto format :
         {opr::ConvBias::Param::Format::NCHW, opr::ConvBias::Param::Format::NCHW4}) {
        auto x = mkvar("x", mkshape(format, 32, 64, 16, 16), dtype::QuantizedS8(2.5f)),
             w = mkcvar("w1", mkshape(format, 64, 64, 3, 3), dtype::QuantizedS8(2.5f)),
             b = mkcvar("b", mkshape(format, 1, 64, 1, 1), dtype::QuantizedS32(6.25f)),
             b1 = mkvar(
                     "b1", mkshape(format, 32, 64, 16, 16), dtype::QuantizedS8(2.5f));
3041 3042 3043 3044 3045
        opr::ConvBias::Param param;
        param.format = format;
        param.stride_h = param.stride_w = 1;
        param.pad_h = param.pad_w = 1;
        param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
3046

3047
        auto y = opr::ConvBiasForward::make(
M
Megvii Engine Team 已提交
3048
                x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3049 3050 3051 3052
        auto y1 = opr::ElemwiseMultiType::make(
                {y, b1}, opr::ElemwiseMultiType::Mode::QFUSE_ADD_RELU,
                OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
        auto y2 = opr::ConvBiasForward::make(
M
Megvii Engine Team 已提交
3053
                y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
        auto y3 = opr::ElemwiseMultiType::make(
                {y, b1}, opr::ElemwiseMultiType::Param::Mode::QSUB,
                OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
        auto y4 = opr::ElemwiseMultiType::make(
                {y1, y2}, opr::ElemwiseMultiType::Param::Mode::QADD,
                OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
        y4 = opr::ElemwiseMultiType::make(
                {y3, y4}, opr::ElemwiseMultiType::Param::Mode::QADD,
                OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
        y4 = opr::TypeCvt::make(y4, dtype::Float32());
        SymbolVar y_opt;
        SymbolVar y_cudnn;
        {
            auto options = gopt::OptimizeForInferenceOptions{};
            options.enable_chwn4();
            unpack_vector(gopt::optimize_for_inference({y4}, options), y_opt);
        }
M
Megvii Engine Team 已提交
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
        unpack_vector(
                gopt::GraphOptimizer{}
                        .add_pass<gopt::FuseConvBiasNonlinPass>()
                        .add_pass<gopt::FuseConvBiasZPass>()
                        .apply({{y4}})
                        .endpoint_vars(),
                y_cudnn);

        ASSERT_EQ(
                opr::ConvBias::Param::Format::CHWN4,
                find_opr<opr::ConvBias>(y_opt).param().format);
3082
        HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3083 3084 3085
        auto func = graph->compile(
                {make_callback_copy(y_cudnn, host_y),
                 make_callback_copy(y_opt, host_y_opt)});
3086 3087
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
3088
    }
3089
}
3090
#endif
3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107

TEST(TestGoptInference, EnableCHWN4WarpPespective) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 61) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 61);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3108
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3109
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3110
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3111
    };
M
Megvii Engine Team 已提交
3112
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3113
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3114
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3115 3116
                dtype);
    };
M
Megvii Engine Team 已提交
3117 3118
    std::shared_ptr<HostTensorND> mat =
            std::make_shared<HostTensorND>(cn, TensorShape{32, 3, 3}, dtype::Float32());
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
    warp_perspective_mat_gen(*mat, 32, 16, 16);
    auto mat_var = opr::Host2DeviceCopy::make(*graph, mat).rename("mat");

    auto x = mkvar("x", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;

    auto y = opr::ConvBiasForward::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3133

3134 3135
    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NCHW4;
M
Megvii Engine Team 已提交
3136
    auto y1 = opr::WarpPerspective::make(y, mat_var, TensorShape{16, 16}, warp_param);
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
    y1 = opr::TypeCvt::make(y1, dtype::Float32());
    auto nchw42nchw = [](SymbolVar x) {
        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;
    };
    y1 = nchw42nchw(y1);
    warp_param.format = opr::WarpPerspective::Param::Format::NCHW;
M
Megvii Engine Team 已提交
3152
    auto y2 = opr::WarpPerspective::make(y1, mat_var, TensorShape{16, 16}, warp_param);
3153 3154
    SymbolVar y_opt;
    SymbolVar y_cudnn;
3155 3156
    {
        auto options = gopt::OptimizeForInferenceOptions{};
3157
        options.enable_chwn4();
3158 3159
        unpack_vector(gopt::optimize_for_inference({y2}, options), y_opt);
    }
M
Megvii Engine Team 已提交
3160 3161 3162 3163 3164 3165 3166
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y2}})
                    .endpoint_vars(),
            y_cudnn);
3167 3168

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3169 3170 3171
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

TEST(TestGoptInference, EnableCHWN4Pooling) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 61) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 61);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3192
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3193
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3194
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3195 3196
    };

M
Megvii Engine Team 已提交
3197
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3198
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3199
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
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 3237 3238 3239 3240 3241 3242 3243 3244 3245
                dtype);
    };

    auto x = mkvar("x", {32, 16, 16, 16, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;

    auto y = opr::ConvBiasForward::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});

    opr::Pooling::Param pool_param;
    pool_param.format = opr::Pooling::Param::Format::NCHW4;
    y = opr::Pooling::make(y, pool_param);
    y = opr::TypeCvt::make(y, dtype::Float32());

    auto nchw42nchw = [](SymbolVar x) {
        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;
    };
    y = nchw42nchw(y);
    pool_param.format = opr::Pooling::Param::Format::NCHW;
    auto y1 = opr::Pooling::make(y, pool_param);

    SymbolVar y_opt;
    SymbolVar y_cudnn;
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass(gopt::EnableCHWN4Pass::make_chwn4_converter())
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y_opt);
M
Megvii Engine Team 已提交
3246 3247 3248 3249 3250 3251 3252
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y_cudnn);
3253 3254

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3255 3256 3257
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

TEST(TestGoptInference, EnableCHWN4ShuffleRemove) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 61) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 61);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3278
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3279
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3280
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3281
    };
M
Megvii Engine Team 已提交
3282
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3283
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3284
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
                dtype);
    };

    auto nchw2nchw4 = [](SymbolVar x) {
        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)}});
        };
M
Megvii Engine Team 已提交
3295
        auto tshp = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
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
        auto y0 = opr::Reshape::make(x, tshp);
        auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
        return y1;
    };

    auto nchw42nchw = [](SymbolVar x) {
        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;
    };

    auto x = mkvar("x", {32, 64, 16, 16}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w1", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
         b1 = mkcvar("b1", {32, 16, 16, 16, 4}, dtype::QuantizedS8{2.5f});
    x = nchw2nchw4(x);
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;

    auto y = opr::ConvBiasForward::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
    auto y1 = opr::ElemwiseMultiType::make(
            {y, b1}, opr::ElemwiseMultiType::Mode::QFUSE_ADD_RELU,
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
    auto y2 = opr::ConvBiasForward::make(
            y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
    auto y3 = opr::ElemwiseMultiType::make(
            {y, b1}, opr::ElemwiseMultiType::Param::Mode::QSUB,
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
    auto y4 = opr::ElemwiseMultiType::make(
            {y1, y2}, opr::ElemwiseMultiType::Param::Mode::QADD,
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
    y4 = opr::ElemwiseMultiType::make(
            {y3, y4}, opr::ElemwiseMultiType::Param::Mode::QADD,
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
    y4 = opr::TypeCvt::make(y4, dtype::Float32());
    y4 = nchw42nchw(y4);

    SymbolVar y_opt;
    SymbolVar y_cudnn;
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamRedistributePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .add_pass(gopt::EnableCHWN4Pass::make_chwn4_converter())
                    .add_pass<gopt::ShuffleShuffleRemovePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y4}})
                    .endpoint_vars(),
            y_opt);
    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3360 3361
            ->writeto_fpath(
                    output_file("TestGoptInference.EnableCHWN4ShuffleRemove.json"));
3362 3363 3364 3365
    auto nr_dimshuffle = find_opr_num<mgb::opr::Dimshuffle>(y_opt);
    ASSERT_EQ(2u, nr_dimshuffle);
    auto nr_reformat = find_opr_num<mgb::opr::RelayoutFormat>(y_opt);
    ASSERT_EQ(0u, nr_reformat);
M
Megvii Engine Team 已提交
3366 3367 3368 3369 3370 3371 3372
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y4}})
                    .endpoint_vars(),
            y_cudnn);
3373 3374

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3375 3376 3377
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
3378 3379 3380 3381
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
TEST(TestGoptInference, ConvertFormatNCHW4GPU) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 61) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 61);
        return;
    }

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3398
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3399
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3400
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3401
    };
M
Megvii Engine Team 已提交
3402
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3403
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3404
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3405 3406
                dtype);
    };
3407

3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
    auto x = mkvar("x", {2, 4, 16, 16}, dtype::QuantizedS8(2.5f));
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.format = opr::ConvBias::Param::Format::NCHW;
    param_conv_bias.stride_h = param_conv_bias.stride_w = 1;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    param_conv_bias.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    // dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    auto w1 = mkcvar("w1", {8, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 8, 1, 1}, dtype::QuantizedS32(6.25f));
    auto conv1 = opr::ConvBiasForward::make(
3419 3420
            x, w1, b1, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3421

3422 3423 3424 3425 3426
    // group
    // icpg != 1 && ocpg != 1
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w2 = mkcvar("w2", {2, 4, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b2 = mkcvar("b2", {1, 8, 1, 1}, dtype::QuantizedS32(6.25f));
3427 3428 3429
    auto conv2 = opr::ConvBiasForward::make(
            conv1, w2, b2, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3430

3431 3432 3433 3434 3435 3436 3437 3438
    opr::Convolution::Param param_deconv;
    param_deconv.format = opr::Convolution::Param::Format::NCHW;
    param_deconv.stride_h = param_deconv.stride_w = 2;
    param_deconv.pad_h = param_deconv.pad_w = 2;
    // dense
    param_deconv.sparse = opr::Convolution::Param::Sparse::DENSE;
    auto w3 = mkcvar("w3", {8, 8, 4, 4}, dtype::QuantizedS8(2.5f));
    auto deconv1 = opr::ConvolutionBackwardData::make_deconv(
M
Megvii Engine Team 已提交
3439
            conv2, w3, param_deconv, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3440 3441 3442

    auto deconv1_fp32 = opr::TypeCvt::make(deconv1, dtype::Float32());
    auto y = deconv1_fp32 + opr::TypeCvt::make(b2, dtype::Float32());
3443 3444 3445 3446 3447 3448 3449 3450

    SymbolVar y_opt;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nchw4();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }

M
Megvii Engine Team 已提交
3451 3452 3453 3454 3455 3456
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4,
            find_opr<opr::ConvBias>(y_opt).param().format);
    ASSERT_EQ(
            opr::ConvolutionBackwardData::Param::Format::NCHW4,
            find_opr<opr::ConvolutionBackwardData>(y_opt).param().format);
3457 3458
    auto nr_reshape = find_opr_num<mgb::opr::Reshape>(y_opt);
    ASSERT_EQ(2u, nr_reshape);
3459 3460 3461

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3462 3463
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW4GPU.json"));
3464 3465

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3466 3467
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3468 3469 3470 3471
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

3472 3473 3474 3475 3476 3477 3478 3479 3480 3481
TEST(TestGoptInference, ConvertFormatNCHW4FloatGPU) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
    REQUIRE_CUDA_COMPUTE_CAPABILITY_EQ(6, 1);

    HostTensorGenerator<> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

M
Megvii Engine Team 已提交
3482
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3483
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3484
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3485 3486
    };

M
Megvii Engine Team 已提交
3487
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3488
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3489
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500
                dtype);
    };

    auto x = mkvar("x", {2, 4, 16, 16}, dtype::QuantizedS8(1.2f));
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;

    // conv1, with bias
    auto w1 = mkcvar("w1", {8, 4, 3, 3}, dtype::QuantizedS8(1.3f)),
         b1 = mkcvar("b1", {1, 8, 1, 1}, dtype::Float32());
M
Megvii Engine Team 已提交
3501 3502
    auto conv1 = opr::ConvBias::make(
            x, w1, b1, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3503 3504 3505 3506 3507

    // conv2, with bias and z
    auto w2 = mkcvar("w2", {8, 4, 3, 3}, dtype::QuantizedS8(1.3f)),
         b2 = mkcvar("b2", {1, 8, 1, 1}, dtype::Float32()),
         z2 = mkcvar("z2", {2, 8, 16, 16}, dtype::Float32());
M
Megvii Engine Team 已提交
3508 3509
    auto conv2 = opr::ConvBias::make(
            x, w2, b2, z2, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3510 3511 3512 3513 3514 3515

    // conv3, relu
    param_conv_bias.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    auto w3 = mkcvar("w3", {8, 4, 3, 3}, dtype::QuantizedS8(1.3f)),
         b3 = mkcvar("b3", {1, 8, 1, 1}, dtype::Float32()),
         z3 = mkcvar("z3", {2, 8, 16, 16}, dtype::Float32());
M
Megvii Engine Team 已提交
3516 3517
    auto conv3 = opr::ConvBias::make(
            x, w3, b3, z3, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531

    auto y = conv1 + conv2 + conv3;

    SymbolVar y_opt;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nchw4();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }

    bool succ = true;
    auto cb = [&succ](cg::OperatorNodeBase* opr) {
        if (opr->same_type<opr::ConvBias>()) {
            auto& conv_bias = opr->cast_final_safe<opr::ConvBias>();
M
Megvii Engine Team 已提交
3532
            if (conv_bias.param().format != opr::ConvBias::Param::Format::NCHW4_NCHW) {
3533 3534 3535 3536 3537 3538 3539 3540 3541
                succ = false;
            }
        }
    };

    cg::DepOprIter{cb}.add(y_opt);
    ASSERT_TRUE(succ);

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3542 3543
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3544 3545 3546 3547 3548
    func->execute();

    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}

3549 3550
#endif

3551 3552 3553 3554 3555
TEST(TestGoptInference, ConvertFormatNCHW4NonConvOpr) {
    auto cn = CompNode::load("xpu0");
    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3556
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3557
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3558
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3559
    };
M
Megvii Engine Team 已提交
3560
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3561
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3562
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3563 3564 3565
                dtype);
    };
    auto mkcvarf32 = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
3566
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
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 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619
    };

    auto x = mkvar("x", {2, 4, 16, 16}, dtype::QuantizedS8(2.5f));
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.format = opr::ConvBias::Param::Format::NCHW;
    param_conv_bias.stride_h = param_conv_bias.stride_w = 1;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    param_conv_bias.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    // dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    auto w1 = mkcvar("w1", {8, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 8, 1, 1}, dtype::QuantizedS32(6.25f));
    auto conv1 = opr::ConvBiasForward::make(
            x, w1, b1, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
    // test Resize
    auto shape_of = opr::GetVarShape::make(x);
    auto subtensor = opr::Subtensor::make(
            shape_of, {opr::Subtensor::AxisIndexer::make_interval(
                              0, x.make_scalar(2), None, x.make_scalar(1))});
    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
    auto resize = opr::ResizeForward::make(conv1, subtensor * 2, param_resize);
    // test WarpPerspective
    auto mat = mkcvarf32("mat", {2, 3, 3}),
         warp = opr::WarpPerspectiveForward::make(
                 resize, mat, nullptr, cg::var_from_tensor_shape(x, {32, 32}));
    opr::Pooling::Param pool_param;
    pool_param.format = opr::Pooling::Param::Format::NCHW;
    // test Pooling
    auto pool = opr::Pooling::make(warp, pool_param);
    // group
    // icpg != 1 && ocpg != 1
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w2 = mkcvar("w2", {2, 4, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b2 = mkcvar("b2", {1, 8, 1, 1}, dtype::QuantizedS32(6.25f));
    auto conv2 = opr::ConvBiasForward::make(
            pool, w2, b2, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});

    auto add = opr::ElemwiseMultiType::make(
            {conv1, conv2}, {opr::ElemwiseMultiType::Param::Mode::QADD},
            OperatorNodeConfig{dtype::QuantizedS8{1.2f}});
    auto y = opr::TypeCvt::make(add, dtype::Float32());

    SymbolVar y_opt;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nchw4();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
    auto nr_dimshuffle = find_opr_num<mgb::opr::Dimshuffle>(y_opt);
    ASSERT_EQ(2u, nr_dimshuffle);
M
Megvii Engine Team 已提交
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4,
            find_opr<opr::ConvBias>(y_opt).param().format);
    ASSERT_EQ(
            opr::ResizeForward::Param::Format::NCHW4,
            find_opr<opr::ResizeForward>(y_opt).param().format);
    ASSERT_EQ(
            opr::WarpPerspectiveForward::Param::Format::NCHW4,
            find_opr<opr::WarpPerspectiveForward>(y_opt).param().format);
    ASSERT_EQ(
            opr::PoolingForward::Param::Format::NCHW4,
            find_opr<opr::PoolingForward>(y_opt).param().format);
3632 3633
}

3634 3635 3636 3637 3638 3639 3640 3641 3642
TEST(TestGoptInference, ConvertFormatNCHW4) {
    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
3643
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3644 3645 3646
    };

    auto x = mkvar("x", {2, 4, 16, 16});
3647
    // ConvBias test dense
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    auto w1 = mkcvar("w1", {8, 4, 3, 3}), b1 = mkcvar("b1", {1, 8, 1, 1});
    auto conv1 = opr::ConvBias::make(x, w1, b1, param_conv_bias);
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w2 = mkcvar("w2", {2, 4, 4, 3, 3}), b2 = mkcvar("b2", {1, 8, 1, 1});
    auto conv2 = opr::ConvBias::make(conv1, w2, b2, param_conv_bias);
    // Convolution
    opr::Convolution::Param param_conv;
    param_conv.pad_h = param_conv.pad_w = 1;
    param_conv.sparse = opr::Convolution::Param::Sparse::DENSE;
    auto w3 = mkcvar("w3", {8, 8, 3, 3});
    auto y = opr::Convolution::make(conv2, w3, param_conv);

    SymbolVar y_opt;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nchw4();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }

M
Megvii Engine Team 已提交
3670 3671 3672
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW,
            find_opr<opr::ConvBias>(y_opt).param().format);
3673 3674 3675

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3676
            ->writeto_fpath(output_file("TestGoptInference.ConvertFormatNCHW4.json"));
3677 3678

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3679 3680
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3681 3682 3683 3684
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

3685 3686
TEST(TestGoptInference, ConvertFormatNCHW4Ic3) {
    REQUIRE_GPU(1);
3687 3688 3689
    auto cn = CompNode::load("gpu0");
    cn.activate();
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
3690 3691 3692 3693
    HostTensorGenerator<dtype::Float32, RandomDistribution::UNIFORM> gen{
            1.2f, 127 * 127};
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3694
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3695
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3696
                opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name), dtype);
3697
    };
M
Megvii Engine Team 已提交
3698
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3699
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3700
                opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name), dtype);
3701 3702 3703 3704 3705 3706 3707 3708 3709
    };

    auto x = mkvar("x", {2, 3, 16, 16}, dtype::QuantizedS8(2.5f));
    // ConvBias test dense
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    auto w1 = mkcvar("w1", {8, 3, 3, 3}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 8, 1, 1}, dtype::QuantizedS32(6.25f));
M
Megvii Engine Team 已提交
3710 3711 3712
    auto conv1 = opr::ConvBias::make(
            x, w1, b1, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3713 3714 3715
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w2 = mkcvar("w2", {2, 4, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b2 = mkcvar("b2", {1, 8, 1, 1}, dtype::QuantizedS32(6.25f));
M
Megvii Engine Team 已提交
3716 3717 3718
    auto conv2 = opr::ConvBias::make(
            conv1, w2, b2, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3719 3720 3721 3722 3723 3724 3725 3726 3727
    auto y = opr::TypeCvt::make(conv2, dtype::Float32());

    SymbolVar y_opt;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nchw4();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }

M
Megvii Engine Team 已提交
3728 3729 3730
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4,
            find_opr<opr::ConvBias>(y_opt).param().format);
3731 3732 3733

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3734 3735
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW4Ic3.json"));
3736 3737

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3738 3739
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3740 3741 3742 3743
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

3744 3745 3746 3747 3748 3749 3750 3751 3752
TEST(TestGoptInference, ConvertFormatNCHW88) {
    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
3753
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3754 3755 3756 3757
    };

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
M
Megvii Engine Team 已提交
3758
    //! Hybrid nchw88 mode
3759 3760 3761
    opr::Convolution::Param param_conv;
    param_conv.pad_h = param_conv.pad_w = 1;
    auto w1 = mkcvar("w1", {8, 3, 3, 3}),
M
Megvii Engine Team 已提交
3762 3763
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
M
Megvii Engine Team 已提交
3764
    //! channel wise
3765 3766 3767 3768 3769 3770 3771 3772
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w2 = mkcvar("w2", {8, 1, 1, 3, 3}), b2 = mkcvar("b2", {1, 8, 1, 1}),
         conv2 = opr::ConvBias::make(conv1, w2, b2, param_conv_bias);
    //! group
    auto w3 = mkcvar("w3", {1, 8, 8, 3, 3}), b3 = mkcvar("b3", {1, 8, 1, 1}),
         conv3 = opr::ConvBias::make(conv2, w3, b3, param_conv_bias);
3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
    //! reduce
    opr::Reduce::Param param_reduce1;
    param_reduce1.axis = 2;
    param_reduce1.mode = opr::Reduce::Mode::SUM;
    opr::Reduce::Param param_reduce2;
    param_reduce2.axis = 0;
    param_reduce2.mode = opr::Reduce::Mode::MAX;
    auto reduce1 = conv3 + opr::Reduce::make(conv3, param_reduce1) +
                   opr::Reduce::make(conv3, param_reduce2);

    auto shape_of = opr::GetVarShape::make(reduce1);
3784 3785 3786 3787 3788
    auto subtensor = opr::Subtensor::make(
            shape_of, {opr::Subtensor::AxisIndexer::make_interval(
                              0, x.make_scalar(2), None, x.make_scalar(1))});
    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
M
Megvii Engine Team 已提交
3789
    auto resize = opr::ResizeForward::make(reduce1, subtensor * 2, param_resize);
3790 3791 3792 3793 3794
    auto mat = mkcvar("mat", {2, 3, 3}),
         warp = opr::WarpPerspectiveForward::make(
                 resize, mat, nullptr, cg::var_from_tensor_shape(x, {4, 4}));

    auto b = mkvar("b", {1, 8, 1, 1}),
M
Megvii Engine Team 已提交
3795
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806
    //! Dense
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    auto w4 = mkcvar("w4", {2, 6, 4, 3, 3}), b4 = mkcvar("b4", {1, 12, 1, 1}),
         conv4 = opr::ConvBias::make(elem, w4, b4, param_conv_bias);
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    auto w5 = mkcvar("w5", {8, 12, 3, 3}), b5 = mkcvar("b5", {1, 8, 1, 1}),
         conv5 = opr::ConvBias::make(conv4, w5, b5, param_conv_bias);
    auto w6 = mkcvar("w6", {8, 8, 3, 3}), b6 = mkcvar("b6", {1, 8, 1, 1}),
         y = opr::ConvBias::make(conv5, w6, b6, param_conv_bias);

    SymbolVar y_opt;
3807 3808
    {
        auto options = gopt::OptimizeForInferenceOptions{};
3809
        options.enable_nchw88();
3810 3811
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
M
Megvii Engine Team 已提交
3812 3813 3814 3815 3816 3817
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW88,
            find_opr<opr::Convolution>(y_opt, "conv1").param().format);
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW88,
            find_opr<opr::ConvBias>(y_opt).param().format);
3818 3819 3820

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3821
            ->writeto_fpath(output_file("TestGoptInference.ConvertFormatNCHW88.json"));
3822 3823

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3824 3825
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3826 3827 3828 3829 3830 3831 3832 3833 3834 3835
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);

    *host_x = *gen({2, 3, 32, 32}, cn);
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);
}

3836 3837 3838 3839 3840 3841 3842 3843 3844
TEST(TestGoptInference, ConvertFormatNCHW44) {
    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
3845
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3846
    };
3847 3848 3849
    auto mkcvar_dtype = [&](const char* name, const TensorShape& shp,
                            const DType& dtype) {
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3850
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3851 3852
                dtype);
    };
3853 3854 3855

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
3856
    //! Hybrid nchw44 mode
3857 3858 3859
    opr::Convolution::Param param_conv;
    param_conv.pad_h = param_conv.pad_w = 1;
    auto w1 = mkcvar("w1", {8, 3, 3, 3}),
M
Megvii Engine Team 已提交
3860 3861
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
3862 3863 3864 3865 3866

    //! no supported hybrid nchw44
    opr::ConvBias::Param param_conv_bias_pad0;
    param_conv_bias_pad0.pad_h = param_conv_bias_pad0.pad_w = 0;
    auto w1_f1 = mkcvar("w1_1", {8, 3, 1, 1});
M
Megvii Engine Team 已提交
3867 3868
    auto conv1_f1 = opr::ConvBias::make(
            x, w1_f1, param_conv_bias_pad0, {}, OperatorNodeConfig("conv1_f1"));
3869 3870 3871 3872 3873

    auto conv1_add = conv1_f1 * conv1;
    auto conv_1_q8 = opr::TypeCvt::make(conv1_add, dtype::QuantizedS8(2.5f));

    //! s8 dense conv
3874 3875
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
3876 3877 3878 3879 3880 3881 3882 3883
    auto w1_2 = mkcvar_dtype("w1_2", {8, 8, 3, 3}, dtype::QuantizedS8(2.5f));
    auto b1_2 = mkcvar_dtype("b1_2", {1, 8, 1, 1}, dtype::QuantizedS32(6.25f));
    auto conv_1_2 = opr::ConvBias::make(
            conv_1_q8, w1_2, b1_2, param_conv_bias, {},
            OperatorNodeConfig{"conv_1_2", cn, dtype::QuantizedS8{6.25f}});
    auto conv_1_2_fp32 = opr::TypeCvt::make(conv_1_2, dtype::Float32());

    //! channel wise
3884 3885
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w2 = mkcvar("w2", {8, 1, 1, 3, 3}), b2 = mkcvar("b2", {1, 8, 1, 1}),
3886
         conv2 = opr::ConvBias::make(conv_1_2_fp32, w2, b2, param_conv_bias);
3887 3888 3889
    //! group
    auto w3 = mkcvar("w3", {2, 4, 4, 3, 3}), b3 = mkcvar("b3", {1, 8, 1, 1}),
         conv3 = opr::ConvBias::make(conv2, w3, b3, param_conv_bias);
3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900
    //! reduce
    opr::Reduce::Param param_reduce1;
    param_reduce1.axis = 1;
    param_reduce1.mode = opr::Reduce::Mode::MIN;
    opr::Reduce::Param param_reduce2;
    param_reduce2.axis = 3;
    param_reduce2.mode = opr::Reduce::Mode::SUM_SQR;
    auto reduce1 = conv3 + opr::Reduce::make(conv3, param_reduce1) +
                   opr::Reduce::make(conv3, param_reduce2);

    auto shape_of = opr::GetVarShape::make(reduce1);
3901 3902 3903 3904 3905
    auto subtensor = opr::Subtensor::make(
            shape_of, {opr::Subtensor::AxisIndexer::make_interval(
                              0, x.make_scalar(2), None, x.make_scalar(1))});
    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
M
Megvii Engine Team 已提交
3906
    auto resize = opr::ResizeForward::make(reduce1, subtensor * 2, param_resize);
3907 3908 3909 3910 3911
    auto mat = mkcvar("mat", {2, 3, 3}),
         warp = opr::WarpPerspectiveForward::make(
                 resize, mat, nullptr, cg::var_from_tensor_shape(x, {4, 4}));

    auto b = mkvar("b", {1, 8, 1, 1}),
M
Megvii Engine Team 已提交
3912
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3913 3914 3915
    //! Dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
M
Megvii Engine Team 已提交
3916 3917 3918
    auto w3_2 = mkcvar("w3_2", {16, 8, 3, 3}), b3_2 = mkcvar("b3_2", {1, 16, 1, 1}),
         conv3_2 = opr::ConvBias::make(
                 elem, w3_2, b3_2, param_conv_bias, {}, OperatorNodeConfig("conv3_2"));
3919 3920 3921 3922 3923 3924 3925
    //! s8 group conv
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto conv3_2_q8 = opr::TypeCvt::make(conv3_2, dtype::QuantizedS8(2.5f));
    auto w3_3 = mkcvar_dtype("w3_3", {4, 8, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b3_3 = mkcvar_dtype("b3_3", {1, 32, 1, 1}, dtype::QuantizedS32(6.25f)),
         conv3_3_q = opr::ConvBias::make(
                 conv3_2_q8, w3_3, b3_3, param_conv_bias, {},
M
Megvii Engine Team 已提交
3926
                 OperatorNodeConfig{"conv_3_3_q", cn, dtype::QuantizedS8{6.25f}});
3927 3928 3929 3930
    auto conv3_3 = opr::TypeCvt::make(conv3_3_q, dtype::Float32());

    //! Dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
3931
    auto w4 = mkcvar("w4", {16, 32, 3, 3}), b4 = mkcvar("b4", {1, 16, 1, 1}),
M
Megvii Engine Team 已提交
3932 3933 3934 3935 3936 3937
         conv4 = opr::ConvBias::make(
                 conv3_3, w4, b4, param_conv_bias, {}, OperatorNodeConfig("conv4"));
    auto w4_1 = mkcvar("w4_1", {16, 32, 1, 1}), b4_1 = mkcvar("b4_1", {2, 16, 4, 4}),
         conv4_1 = opr::ConvBias::make(
                 conv3_3, w4_1, b4_1, param_conv_bias_pad0, {},
                 OperatorNodeConfig("conv4_1"));
3938 3939 3940
    auto conv4_add = conv4 + conv4_1;

    auto w5 = mkcvar("w5", {6, 16, 3, 3}), b5 = mkcvar("b5", {1, 6, 1, 1}),
M
Megvii Engine Team 已提交
3941 3942
         conv5 = opr::ConvBias::make(
                 conv4_add, w5, b5, param_conv_bias, {}, OperatorNodeConfig("conv5"));
3943
    auto w6 = mkcvar("w6", {4, 6, 3, 3}), b6 = mkcvar("b6", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
3944 3945
         y = opr::ConvBias::make(
                 conv5, w6, b6, param_conv_bias, {}, OperatorNodeConfig("conv6"));
3946

3947
    SymbolVar y_opt;
3948
    auto options = gopt::OptimizeForInferenceOptions{};
3949
    options.enable_fuse_conv_bias_nonlinearity();
3950
    options.enable_nchw44();
3951
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
3952

M
Megvii Engine Team 已提交
3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt, "conv1").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW,
            find_opr<opr::ConvBias>(y_opt, "conv1_f1").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::ConvBias>(y_opt, "conv_1_2").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::ConvBias>(y_opt, "conv3_2").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::ConvBias>(y_opt, "conv_3_3_q").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::ConvBias>(y_opt, "conv4").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW,
            find_opr<opr::ConvBias>(y_opt, "conv5").param().format);
3974 3975

    graph->compile({{y_opt, {}}})
3976
            ->to_json()
M
Megvii Engine Team 已提交
3977
            ->writeto_fpath(output_file("TestGoptInference.ConvertFormatNCHW44.json"));
3978 3979

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3980 3981
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3982 3983 3984 3985 3986 3987 3988 3989 3990
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);

    *host_x = *gen({2, 3, 32, 32}, cn);
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);
}
3991

3992 3993 3994 3995 3996 3997 3998 3999 4000
TEST(TestGoptInference, ConvertFormatNCHW44MultiInput) {
    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
4001
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012
    };

    auto host_x1 = gen({1, 8, 16, 16}, cn);
    auto host_x2 = gen({1, 1, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);
    opr::Convolution::Param param_conv;
    param_conv.pad_h = param_conv.pad_w = 1;
    auto w1 = mkcvar("w1", {8, 8, 3, 3}),
         conv1 = opr::Convolution::make(x, w1, param_conv);

    auto b = mkvar("b", {1, 1, 16, 16}),
M
Megvii Engine Team 已提交
4013
         elem0 = opr::Elemwise::make({conv1 + b + b}, opr::Elemwise::Param::Mode::RELU);
4014 4015 4016 4017 4018

    auto w2 = mkcvar("w2", {8, 8, 3, 3}),
         conv2 = opr::Convolution::make(elem0, w2, param_conv);

    auto b1 = mkvar("b1", {1}),
M
Megvii Engine Team 已提交
4019
         y = opr::Elemwise::make({conv2 + b1 + b}, opr::Elemwise::Param::Mode::RELU);
4020 4021 4022 4023 4024 4025

    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nchw44();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

M
Megvii Engine Team 已提交
4026 4027 4028
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt).param().format);
4029 4030 4031 4032 4033 4034 4035

    graph->compile({{y_opt, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.ConvertFormatNCHW44MultiInput.json"));

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4036 4037
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);
}

TEST(TestGoptInference, ConvertFormatNCHW44Reshape) {
    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
4049
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064
    };

    auto host_x1 = gen({1, 8, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);
    opr::Convolution::Param param_conv;
    param_conv.pad_h = param_conv.pad_w = 1;
    auto w1 = mkcvar("w1", {8, 8, 3, 3}),
         conv1 = opr::Convolution::make(x, w1, param_conv);
    auto y = opr::Reshape::make(conv1, {8, 16 * 16});

    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nchw44();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

M
Megvii Engine Team 已提交
4065 4066 4067
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt).param().format);
4068 4069 4070

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4071 4072
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW44Reshape.json"));
4073 4074

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4075 4076
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4077 4078 4079 4080 4081
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);
}

4082 4083 4084 4085 4086 4087 4088 4089 4090
TEST(TestGoptInference, ConvertFormatNCHW44_DOT) {
    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
4091
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
4092
    };
4093 4094 4095
    auto mkcvar_dtype = [&](const char* name, const TensorShape& shp,
                            const DType& dtype) {
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4096
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4097 4098
                dtype);
    };
4099 4100 4101

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
4102
    //! Hybrid nchw44 mode
4103 4104 4105
    opr::Convolution::Param param_conv;
    param_conv.pad_h = param_conv.pad_w = 1;
    auto w1 = mkcvar("w1", {8, 3, 3, 3}),
M
Megvii Engine Team 已提交
4106 4107 4108
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
    printf("create conv1 %s\n", conv1.node()->owner_opr()->dyn_typeinfo()->name);
4109 4110 4111 4112 4113 4114
    param_conv.pad_h = param_conv.pad_w = 1;
    //! no supported hybrid nchw44
    opr::ConvBias::Param param_conv_bias_pad0;
    param_conv_bias_pad0.pad_h = param_conv_bias_pad0.pad_w = 0;
    auto b1 = mkcvar("b1", {1, 8, 1, 1});
    auto w1_f1 = mkcvar("w1_1", {8, 3, 1, 1});
M
Megvii Engine Team 已提交
4115 4116
    auto conv1_f1 = opr::ConvBias::make(
            x, w1_f1, b1, param_conv_bias_pad0, {}, OperatorNodeConfig("conv1_f1"));
4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129

    //! hybrid dot
    auto x_s = opr::TypeCvt::make(x, dtype::QuantizedS8(2.5f));
    auto w1_3 = mkcvar_dtype("w1_3", {8, 3, 3, 3}, dtype::QuantizedS8(2.5f));
    auto conv1_3_q = opr::Convolution::make(
            x_s, w1_3, param_conv, {},
            OperatorNodeConfig{"conv1_3_q", cn, dtype::QuantizedS8{6.25f}});
    auto conv1_3 = opr::TypeCvt::make(conv1_3_q, dtype::Float32());

    auto conv1_add = conv1_f1 * conv1 * conv1_3;
    auto conv_1_q8 = opr::TypeCvt::make(conv1_add, dtype::QuantizedS8(2.5f));

    //! s8 dense conv
4130 4131
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
4132 4133
    auto w1_2 = mkcvar_dtype("w1_2", {8, 8, 3, 3}, dtype::QuantizedS8(2.5f));
    auto conv_1_2 = opr::ConvBias::make(
4134
            conv_1_q8, w1_2, param_conv_bias, {},
4135 4136 4137 4138
            OperatorNodeConfig{"conv_1_2", cn, dtype::QuantizedS8{6.25f}});
    auto conv_1_2_fp32 = opr::TypeCvt::make(conv_1_2, dtype::Float32());

    //! channel wise
4139 4140
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w2 = mkcvar("w2", {8, 1, 1, 3, 3}), b2 = mkcvar("b2", {1, 8, 1, 1}),
4141
         conv2 = opr::ConvBias::make(conv_1_2_fp32, w2, b2, param_conv_bias);
4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
    //! group
    auto w3 = mkcvar("w3", {2, 4, 4, 3, 3}), b3 = mkcvar("b3", {1, 8, 1, 1}),
         conv3 = opr::ConvBias::make(conv2, w3, b3, param_conv_bias);

    auto shape_of = opr::GetVarShape::make(conv3);
    auto subtensor = opr::Subtensor::make(
            shape_of, {opr::Subtensor::AxisIndexer::make_interval(
                              0, x.make_scalar(2), None, x.make_scalar(1))});
    opr::Resize::Param param_resize;
    param_resize.format = opr::Resize::Param::Format::NCHW;
    auto resize = opr::ResizeForward::make(conv3, subtensor * 2, param_resize);
    auto mat = mkcvar("mat", {2, 3, 3}),
         warp = opr::WarpPerspectiveForward::make(
                 resize, mat, nullptr, cg::var_from_tensor_shape(x, {4, 4}));

    auto b = mkvar("b", {1, 8, 1, 1}),
M
Megvii Engine Team 已提交
4158
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
4159 4160 4161
    //! Dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
M
Megvii Engine Team 已提交
4162 4163 4164
    auto w3_2 = mkcvar("w3_2", {16, 8, 3, 3}), b3_2 = mkcvar("b3_2", {1, 16, 1, 1}),
         conv3_2 = opr::ConvBias::make(
                 elem, w3_2, b3_2, param_conv_bias, {}, OperatorNodeConfig("conv3_2"));
4165 4166 4167 4168 4169 4170 4171
    //! s8 group conv
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto conv3_2_q8 = opr::TypeCvt::make(conv3_2, dtype::QuantizedS8(2.5f));
    auto w3_3 = mkcvar_dtype("w3_3", {4, 8, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b3_3 = mkcvar_dtype("b3_3", {1, 32, 1, 1}, dtype::QuantizedS32(6.25f)),
         conv3_3_q = opr::ConvBias::make(
                 conv3_2_q8, w3_3, b3_3, param_conv_bias, {},
M
Megvii Engine Team 已提交
4172
                 OperatorNodeConfig{"conv_3_3_q", cn, dtype::QuantizedS8{6.25f}});
4173 4174 4175 4176 4177
    auto conv3_3 = opr::TypeCvt::make(conv3_3_q, dtype::Float32());

    //! Dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
    auto w4 = mkcvar("w4", {4, 32, 3, 3}), b4 = mkcvar("b4", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
4178 4179
         conv4 = opr::ConvBias::make(
                 conv3_3, w4, b4, param_conv_bias, {}, OperatorNodeConfig("conv4"));
4180

4181
    auto w5 = mkcvar("w5", {6, 4, 3, 3}), b5 = mkcvar("b5", {1, 6, 1, 1}),
M
Megvii Engine Team 已提交
4182 4183
         conv5 = opr::ConvBias::make(
                 conv4, w5, b5, param_conv_bias, {}, OperatorNodeConfig("conv5"));
4184
    auto w6 = mkcvar("w6", {4, 6, 3, 3}), b6 = mkcvar("b6", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
4185 4186
         y = opr::ConvBias::make(
                 conv5, w6, b6, param_conv_bias, {}, OperatorNodeConfig("conv6"));
4187

4188
    SymbolVar y_opt;
4189
    auto options = gopt::OptimizeForInferenceOptions{};
4190
    options.enable_fuse_conv_bias_nonlinearity();
4191
    options.enable_nchw44_dot();
4192 4193
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

M
Megvii Engine Team 已提交
4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt, "conv1").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44_DOT,
            find_opr<opr::Convolution>(y_opt, "conv1_3_q").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW,
            find_opr<opr::ConvBias>(y_opt, "conv1_f1").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44_DOT,
            find_opr<opr::ConvBias>(y_opt, "conv_1_2").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::ConvBias>(y_opt, "conv3_2").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44_DOT,
            find_opr<opr::ConvBias>(y_opt, "conv_3_3_q").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::ConvBias>(y_opt, "conv4").param().format);
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW,
            find_opr<opr::ConvBias>(y_opt, "conv5").param().format);
4218 4219 4220

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4221 4222
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW44_DOT.json"));
4223 4224

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4225 4226
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);

    *host_x = *gen({2, 3, 32, 32}, cn);
    func->execute();
    //! meybe go to winograd in x86-32, so set error 1e-1
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-1);
}

4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248
TEST(TestGoptInference, ConvertFormatCD4GroupOneConv) {
    // hwcd4 is only supported in naive handle
    NaiveMegDNNHandleScope naive_megdnn_handle;

    HostTensorGenerator<> gen;
    auto cn = CompNode::load("cpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
    auto mkvar = [&](const char* name, const TensorShape& shp) {
        return opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name);
    };
    auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
4249
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274
    };

    auto x = mkvar("x", {1, 3, 128, 128});
    // ConvBias
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    auto w1 = mkcvar("w1", {1, 16, 3, 3, 3}), b1 = mkcvar("b1", {1, 16, 1, 1});
    auto conv1 = opr::ConvBias::make(x, w1, b1, param_conv_bias);
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::GROUP;
    // Convolution
    opr::Convolution::Param param_conv;
    param_conv.pad_h = param_conv.pad_w = 1;
    param_conv.sparse = opr::Convolution::Param::Sparse::GROUP;
    auto w3 = mkcvar("w3", {1, 16, 16, 3, 3});
    auto y = opr::Convolution::make(conv1, w3, param_conv);

    SymbolVar y_opt;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nhwcd4();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4275 4276
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4277 4278 4279 4280
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

4281 4282 4283
#if MGB_CUDA
TEST(TestGoptInference, PreProcessCase0) {
    REQUIRE_GPU(1);
M
Megvii Engine Team 已提交
4284 4285
    HostTensorGenerator<dtype::Quantized8Asymm, RandomDistribution::UNIFORM> gen(
            dt_quint8(0), dt_quint8(50), 1, 128, 1234);
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299
    auto cn = CompNode::load("gpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    size_t n = 1;
    size_t c = 3;
    size_t h = 16;
    size_t w = 16;
    auto host_x1 = gen({n, c, h, w}, cn);

    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);
    auto x_q8 = opr::TypeCvt::make(x, dtype::QuantizedS8(1.f), cn);
    auto zero = DTypeScalar(dtype::QuantizedS8(1.f));
    auto zero_tensor = opr::ImmutableTensor::make(*graph, zero, cn);
M
Megvii Engine Team 已提交
4300
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313
    auto paded_x = opr::Concat::make({x_q8, pad_channel_tensor}, 1, cn)
                           .reshape({n, 1, 4, h, w});

    auto result = opr::Dimshuffle::make(paded_x, {0, 1, 3, 4, 2}, 5, cn);

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_fuse_preprocess();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4314
            ->writeto_fpath(output_file("TestGoptInference.PreProcessCase0.json"));
4315 4316

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4317 4318
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);

    ASSERT_TRUE(y_opt.node()->owner_opr()->same_type<opr::RelayoutFormat>());
}

TEST(TestGoptInference, PreProcessCase1) {
    REQUIRE_GPU(1);
    HostTensorGenerator<dtype::Uint8, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("gpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    size_t n = 1;
    size_t c = 3;
    size_t h = 16;
    size_t w = 16;
    auto host_x1 = gen({n, c, h, w}, cn);

    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);
    auto x_u8 = opr::TypeCvt::make(x, dtype::Float32(), cn);
    auto x_s8 = x_u8 - 128;
    auto zero = DTypeScalar(dtype::Float32());
    auto zero_tensor = opr::ImmutableTensor::make(*graph, zero, cn);
M
Megvii Engine Team 已提交
4343
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357
    auto paded_x = opr::Concat::make({x_s8, pad_channel_tensor}, 1, cn)
                           .reshape({n, 1, 4, h, w});

    auto nchw4_out = opr::Dimshuffle::make(paded_x, {0, 1, 3, 4, 2}, 5, cn);
    auto result = opr::TypeCvt::make(nchw4_out, dtype::QuantizedS8(1.f));

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_fuse_preprocess();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4358
            ->writeto_fpath(output_file("TestGoptInference.PreProcessCase1.json"));
4359 4360

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4361 4362
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4363 4364 4365 4366 4367
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);

    ASSERT_TRUE(y_opt.node()->owner_opr()->same_type<opr::RelayoutFormat>());
}
4368

4369
TEST(TestGoptInference, WarpAndPreProcessCase0) {
4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382
    REQUIRE_GPU(1);
    HostTensorGenerator<dtype::Uint8, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("gpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    size_t n = 1;
    size_t c = 3;
    size_t h = 16;
    size_t w = 16;
    auto host_x1 = gen({n, h, w, c}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);

M
Megvii Engine Team 已提交
4383 4384
    auto mat_host =
            std::make_shared<HostTensorND>(cn, TensorShape{n, 3, 3}, dtype::Float32());
4385 4386 4387 4388 4389
    warp_perspective_mat_gen(*mat_host, n, h, w);
    auto mat = opr::Host2DeviceCopy::make(*graph, mat_host).rename("mat");

    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NHWC;
M
Megvii Engine Team 已提交
4390
    auto x_warp = opr::WarpPerspective::make(x, mat, TensorShape{h, w}, warp_param);
4391 4392 4393 4394 4395 4396
    auto x_nchw = opr::Dimshuffle::make(x_warp, {0, 3, 1, 2}, 4, cn);

    auto x_u8 = opr::TypeCvt::make(x_nchw, dtype::Float32(), cn);
    auto x_s8 = x_u8 - 128;
    auto zero = DTypeScalar(dtype::Float32());
    auto zero_tensor = opr::ImmutableTensor::make(*graph, zero, cn);
M
Megvii Engine Team 已提交
4397
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411
    auto paded_x = opr::Concat::make({x_s8, pad_channel_tensor}, 1, cn)
                           .reshape({n, 1, 4, h, w});

    auto nchw4_out = opr::Dimshuffle::make(paded_x, {0, 1, 3, 4, 2}, 5, cn);
    auto result = opr::TypeCvt::make(nchw4_out, dtype::QuantizedS8(1.f));

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_fuse_preprocess();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_TRUE(y_opt.node()->owner_opr()->same_type<opr::WarpPerspective>());

M
Megvii Engine Team 已提交
4412 4413 4414
    ASSERT_EQ(
            opr::WarpPerspective::Param::Format::NHWC_NCHW4_IC_SMALL,
            find_opr<opr::WarpPerspective>(y_opt).param().format);
4415 4416 4417

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4418 4419
            ->writeto_fpath(
                    output_file("TestGoptInference.WarpAndPreProcessCase0.json"));
4420 4421

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4422 4423
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4424 4425 4426 4427
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}

4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441
TEST(TestGoptInference, PreProcessCaseAutopadNCHW64) {
    REQUIRE_GPU(1);
    HostTensorGenerator<dtype::Uint8, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("gpu0");
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4442
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4443
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4444
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463
                dtype);
    };
    size_t n = 2;
    size_t c = 3;
    size_t h = 32;
    size_t w = 32;
    auto host_x1 = gen({n, c, h, w}, cn);

    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);
    auto x_u8_fp32 = opr::TypeCvt::make(x, dtype::Float32(), cn);
    auto x_s8_fp32 = x_u8_fp32 - 128;
    auto x_s8 = opr::TypeCvt::make(x_s8_fp32, dtype::QuantizedS8(2.5f), cn);
    auto weight = mkcvar("weight", {16, 3, 3, 3}, dtype::QuantizedS8(2.5f)),
         bias = mkcvar("bias", {1, 16, 1, 1}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 2;
    param.pad_h = param.pad_w = 1;
M
Megvii Engine Team 已提交
4464 4465 4466
    auto result = opr::ConvBias::make(
            x_s8, weight, bias, param, {},
            OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4467 4468 4469 4470 4471 4472 4473 4474 4475

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_nchw64();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4476 4477
            ->writeto_fpath(
                    output_file("TestGoptInference.PreProcessCaseAutopadNCHW64.json"));
4478 4479

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4480 4481
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4482 4483
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
M
Megvii Engine Team 已提交
4484 4485 4486
    ASSERT_TRUE(
            find_opr<opr::RelayoutFormat>(y_opt).param().mode ==
            opr::RelayoutFormat::Param::Mode::NCHW_NCHW4);
4487 4488
}

4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502
TEST(TestGoptInference, PreProcessCaseAutopadNHWC) {
    REQUIRE_GPU(1);
    HostTensorGenerator<dtype::Uint8, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("gpu0");
    auto&& prop = CompNodeEnv::from_comp_node(cn).cuda_env().device_prop;
    auto sm_ver = prop.major * 10 + prop.minor;
    if (sm_ver < 75) {
        printf("This testcast ignored due to insufficient cuda cap(got: %d, "
               "expected: %d)\n",
               sm_ver, 75);
        return;
    }
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4503
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4504
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4505
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
                dtype);
    };
    size_t n = 2;
    size_t c = 3;
    size_t h = 32;
    size_t w = 32;
    auto host_x1 = gen({n, c, h, w}, cn);

    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);
    auto x_u8_fp32 = opr::TypeCvt::make(x, dtype::Float32(), cn);
    auto x_s8_fp32 = x_u8_fp32 - 128;
    auto x_s8 = opr::TypeCvt::make(x_s8_fp32, dtype::QuantizedS8(2.5f), cn);
M
Megvii Engine Team 已提交
4518
    auto host_val = std::make_shared<HostTensorND>(cn, dtype::QuantizedS8(2.5f));
4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535
    TensorShape scalar{1, 1, 1, 1};
    host_val->resize(scalar);
    auto ptr = host_val->raw_ptr();
    size_t size_bytes =
            TensorLayout{scalar, dtype::QuantizedS8(2.5f)}.span().dist_byte();
    std::memset(ptr, 0, size_bytes);
    auto padding = opr::ImmutableTensor::make(*graph, *host_val);
    padding = opr::Broadcast::make(padding, {n, 1, h, w});
    auto padded_x = opr::Concat::make({x_s8, padding}, 1);
    auto nhwc_x = opr::Dimshuffle::make(padded_x, {0, 2, 3, 1});
    auto weight = mkcvar("weight", {16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         bias = mkcvar("bias", {1, 1, 1, 16}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NHWC;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 2;
    param.pad_h = param.pad_w = 1;
M
Megvii Engine Team 已提交
4536 4537 4538
    auto result = opr::ConvBias::make(
            nhwc_x, weight, bias, param, {},
            OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4539 4540 4541 4542 4543 4544 4545 4546
    auto y = opr::TypeCvt::make(result, dtype::Float32());
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_fuse_preprocess();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4547 4548
            ->writeto_fpath(
                    output_file("TestGoptInference.PreProcessCaseAutopadNHWC.json"));
4549 4550

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4551 4552
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4553 4554
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
M
Megvii Engine Team 已提交
4555 4556 4557
    ASSERT_TRUE(
            find_opr<opr::RelayoutFormat>(y_opt).param().mode ==
            opr::RelayoutFormat::Param::Mode::NCHW_NCHW4);
4558 4559
}

4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
TEST(TestGoptInference, WarpAndPreProcessCase1) {
    REQUIRE_GPU(1);
    HostTensorGenerator<dtype::Uint8, RandomDistribution::UNIFORM> gen(0, 255);
    auto cn = CompNode::load("gpu0");
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;

    size_t n = 1;
    size_t c = 3;
    size_t h = 16;
    size_t w = 16;
    auto host_x1 = gen({n, h, w, c}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x1);

M
Megvii Engine Team 已提交
4574 4575
    auto mat_host =
            std::make_shared<HostTensorND>(cn, TensorShape{n, 3, 3}, dtype::Float32());
4576 4577 4578 4579 4580
    warp_perspective_mat_gen(*mat_host, n, h, w);
    auto mat = opr::Host2DeviceCopy::make(*graph, mat_host).rename("mat");

    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NHWC;
M
Megvii Engine Team 已提交
4581
    auto x_warp = opr::WarpPerspective::make(x, mat, TensorShape{h, w}, warp_param);
4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593
    auto x_nchw = opr::Dimshuffle::make(x_warp, {0, 3, 1, 2}, 4, cn);

    auto result = opr::TypeCvt::make(x_nchw, dtype::Float32(), cn);

    auto y = result;
    SymbolVar y_opt;
    auto options = gopt::OptimizeForInferenceOptions{};
    options.enable_fuse_preprocess();
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

    ASSERT_TRUE(y_opt.node()->owner_opr()->same_type<opr::WarpPerspective>());

M
Megvii Engine Team 已提交
4594 4595 4596
    ASSERT_EQ(
            opr::WarpPerspective::Param::Format::NHWC_NCHW,
            find_opr<opr::WarpPerspective>(y_opt).param().format);
4597 4598 4599

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4600 4601
            ->writeto_fpath(
                    output_file("TestGoptInference.WarpAndPreProcessCase1.json"));
4602 4603

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4604 4605
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4606 4607 4608
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}
4609

4610
#if CUDA_VERSION >= 10020
4611 4612 4613 4614
TEST(TestGoptInference, FoldingConvDimshuffle) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4615
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4616 4617 4618 4619

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4620
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4621
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4622
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4623
    };
M
Megvii Engine Team 已提交
4624
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4625
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4626
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
                dtype);
    };
    auto nchw42nchw = [](SymbolVar x) {
        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;
    };

    auto x = mkvar("x", {32, 16, 4, 8, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 2;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
4650 4651
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4652 4653 4654
    y = opr::TypeCvt::make(y, dtype::Float32());
    y = nchw42nchw(y);
    SymbolVar y_fuse, y_non_fuse;
M
Megvii Engine Team 已提交
4655 4656 4657 4658 4659 4660 4661 4662
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ShuffleShuffleRemovePass>()
                    .add_pass<gopt::FoldingConvBiasDimshufflePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_fuse);
4663 4664 4665
    gopt::modify_opr_algo_strategy_inplace(
            {y_fuse},
            opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy::PROFILE);
4666 4667
    graph->compile({{y_fuse, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4668 4669 4670 4671 4672
            ->writeto_fpath(
                    output_file("TestGoptInference.FoldingConvDimshuffle.json"));
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4_NCHW,
            find_opr<opr::ConvBias>(y_fuse).param().format);
4673
    ASSERT_EQ(0u, find_opr_num<opr::Dimshuffle>(y_fuse));
M
Megvii Engine Team 已提交
4674
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4675
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4676 4677 4678
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4679 4680 4681 4682 4683 4684 4685
    func->execute();
}

TEST(TestGoptInference, FoldingConvDimshuffleNCHW4NCHW32) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4686
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4687 4688 4689 4690

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4691
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4692
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4693
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4694
    };
M
Megvii Engine Team 已提交
4695
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4696
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4697
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724
                dtype);
    };
    auto nchw42nchw32 = [](SymbolVar x) {
        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;
    };

    auto x = mkvar("x", {32, 16, 4, 8, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 2;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
4725 4726
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4727 4728 4729
    y = nchw42nchw32(y);
    y = opr::TypeCvt::make(y, dtype::Float32());
    SymbolVar y_fuse, y_non_fuse;
M
Megvii Engine Team 已提交
4730 4731 4732 4733 4734 4735 4736
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FoldingConvBiasDimshufflePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_fuse);
4737 4738 4739
    gopt::modify_opr_algo_strategy_inplace(
            {y_fuse},
            opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy::PROFILE);
4740 4741 4742 4743
    graph->compile({{y_fuse, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.FoldingConvDimshuffleNCHW4NCHW32.json"));
M
Megvii Engine Team 已提交
4744 4745 4746
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4_NCHW32,
            find_opr<opr::ConvBias>(y_fuse).param().format);
4747
    ASSERT_EQ(0u, find_opr_num<opr::Dimshuffle>(y_fuse));
M
Megvii Engine Team 已提交
4748
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4749
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4750 4751 4752
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4753 4754 4755 4756 4757 4758 4759 4760
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y_fuse, host_y_non_fuse);
}

TEST(TestGoptInference, FoldingConvDimshuffleNCHW32NCHW4) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4761
    REQUIRE_CUDA_COMPUTE_CAPABILITY(7, 5);
4762 4763 4764 4765

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4766
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4767
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4768
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4769
    };
M
Megvii Engine Team 已提交
4770
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4771
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4772
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786
                dtype);
    };

    auto x = mkvar("x", {32, 16, 4, 8, 4}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w", {64, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 16, 1, 1, 4}, dtype::QuantizedS32(6.25f)),
         w1 = mkcvar("w1", {16, 16, 3, 3, 4}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 4, 1, 1, 4}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW4;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 2;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
4787 4788
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4789
    param.stride_h = param.stride_w = 1;
M
Megvii Engine Team 已提交
4790 4791
    y = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807
    y = opr::TypeCvt::make(y, dtype::Float32());
    SymbolVar y_fuse, y_non_fuse;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nchw32().enable_fuse_conv_bias_nonlinearity();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_fuse);
    }
    graph->compile({{y_fuse, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.FoldingConvDimshuffleNCHW32NCHW4.json"));
    ASSERT_EQ(1u, find_opr_num<opr::Dimshuffle>(y_fuse));
    bool found = false;
    cg::DepOprIter{[&found](cg::OperatorNodeBase* opr) {
        if (!found && opr->same_type<opr::ConvBias>()) {
            opr::ConvBias* cb = &opr->cast_final_safe<opr::ConvBias>();
M
Megvii Engine Team 已提交
4808
            if (cb->param().format == opr::ConvBias::Param::Format::NCHW32_NCHW4)
4809 4810
                found = true;
        }
M
Megvii Engine Team 已提交
4811
    }}.add(y_fuse.node()->owner_opr());
4812
    EXPECT_TRUE(found);
M
Megvii Engine Team 已提交
4813
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4814
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4815 4816 4817
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4818 4819 4820
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y_fuse, host_y_non_fuse);
}
4821 4822 4823 4824 4825

TEST(TestGoptInference, FoldingConvDimshuffleNCHW4NHWC) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4826
    REQUIRE_CUDA_COMPUTE_CAPABILITY(7, 5);
4827 4828 4829 4830

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4831
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4832
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4833
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4834
    };
M
Megvii Engine Team 已提交
4835
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4836
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4837
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4838 4839 4840 4841
                dtype);
    };

    auto x = mkvar("x", {32, 4, 23, 40}, dtype::QuantizedS8(2.5f)),
4842 4843 4844
         w = mkcvar("w", {32, 4, 3, 3}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 32, 1, 1}, dtype::QuantizedS32(6.25f)),
         w1 = mkcvar("w1", {32, 32, 3, 3}, dtype::QuantizedS4(1.234f)),
M
Megvii Engine Team 已提交
4845
         b1 = mkcvar("b1", {1, 32, 1, 1}, dtype::QuantizedS32(12.34567f * 1.234f));
4846 4847 4848 4849 4850 4851 4852
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

    auto y = opr::ConvBias::make(
M
Megvii Engine Team 已提交
4853
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(12.34567f)});
4854
    y = opr::TypeCvt::make(y, dtype::QuantizedS4(12.34567f));
M
Megvii Engine Team 已提交
4855 4856
    y = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS4(56.71234f)});
4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
    y = opr::TypeCvt::make(y, dtype::Float32());
    SymbolVar y_fuse, y_non_fuse;
    {
        auto options = gopt::OptimizeForInferenceOptions{};
        options.enable_nchw64();
        unpack_vector(gopt::optimize_for_inference({y}, options), y_fuse);
    }
    using S = opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy;
    S strategy = S::PROFILE;
    gopt::modify_opr_algo_strategy_inplace({y_fuse}, strategy);
    HostTensorND host_y_fuse;
    auto func1 = graph->compile({make_callback_copy(y_fuse, host_y_fuse)});
    func1->execute();
    graph->compile({{y_fuse, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.FoldingConvDimshuffleNCHW4NHWC.json"));
    size_t nr_dimshuffle = find_opr_num<opr::TypeCvt>(y_fuse);
4875
    ASSERT_EQ(2u, nr_dimshuffle);
4876 4877 4878 4879 4880 4881 4882
    bool found = false;
    cg::DepOprIter{[&found](cg::OperatorNodeBase* opr) {
        if (!found && opr->same_type<opr::ConvBias>()) {
            opr::ConvBias* cb = &opr->cast_final_safe<opr::ConvBias>();
            if (cb->param().format == opr::ConvBias::Param::Format::NCHW4_NHWC)
                found = true;
        }
M
Megvii Engine Team 已提交
4883
    }}.add(y_fuse.node()->owner_opr());
4884
    EXPECT_TRUE(found);
M
Megvii Engine Team 已提交
4885
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4886 4887
    gopt::modify_opr_algo_strategy_inplace({y_non_fuse}, strategy);
    HostTensorND host_y_non_fuse;
M
Megvii Engine Team 已提交
4888
    auto func2 = graph->compile({make_callback_copy(y_non_fuse, host_y_non_fuse)});
4889 4890 4891
    func2->execute();
    MGB_ASSERT_TENSOR_EQ(host_y_fuse, host_y_non_fuse);
}
4892
#endif
4893 4894 4895 4896 4897

TEST(TestGoptInference, PaddingChannels) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4898
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4899 4900 4901 4902

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4903
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4904
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4905
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4906
    };
M
Megvii Engine Team 已提交
4907
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4908
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4909
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921
                dtype);
    };

    auto x = mkvar("x", {16, 3, 14, 14}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w", {20, 3, 3, 3}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 20, 1, 1}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
4922 4923
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4924 4925
    auto w1 = mkcvar("w1", {24, 20, 3, 3}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 24, 1, 1}, dtype::QuantizedS32(6.25f));
M
Megvii Engine Team 已提交
4926 4927
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4928 4929
    auto w2 = mkcvar("w2", {20, 24, 3, 3}, dtype::QuantizedS8(2.5f)),
         b2 = mkcvar("b2", {1, 20, 1, 1}, dtype::QuantizedS32(6.25f));
M
Megvii Engine Team 已提交
4930 4931
    auto y2 = opr::ConvBias::make(
            y1, w2, b2, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4932 4933 4934 4935 4936 4937
    using ElemMultiMode = opr::ElemwiseMultiType::Param::Mode;
    auto y3 = opr::ElemwiseMultiType::make(
            {y, y2}, {ElemMultiMode::QFUSE_ADD_RELU},
            OperatorNodeConfig{dtype::QuantizedS8{1.2f}});
    y3 = opr::TypeCvt::make(y3, dtype::Float32());
    SymbolVar y3_pad;
M
Megvii Engine Team 已提交
4938 4939 4940 4941 4942 4943
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y3}})
                    .endpoint_vars(),
            y3_pad);
4944 4945 4946 4947 4948 4949 4950 4951 4952
    ASSERT_EQ(y3_pad.node()->shape()[1], y3.node()->shape()[1]);
    SmallVector<cg::OperatorNodeBase*> oprs;
    auto cb = [&oprs](cg::OperatorNodeBase* opr) {
        if (opr->same_type<opr::ConvBias>()) {
            oprs.push_back(opr);
        }
    };
    cg::DepOprIter{cb}.add(y3_pad.node()->owner_opr());
    ASSERT_EQ(oprs.size(), 3);
4953
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967
    ASSERT_EQ(oprs[1]->output(0)->shape()[1], 32);
    ASSERT_EQ(oprs[2]->output(0)->shape()[1], 32);
    HostTensorND t1, t2;
    auto func1 = graph->compile({make_callback_copy(y3, t1)});
    func1->execute();
    auto func2 = graph->compile({make_callback_copy(y3_pad, t2)});
    func2->execute();
    MGB_ASSERT_TENSOR_EQ(t1, t2);
}

TEST(TestGoptInference, ConcatAfterPaddingChannels) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4968
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
M
Megvii Engine Team 已提交
4969

4970 4971 4972
    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4973
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4974
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4975
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4976
    };
M
Megvii Engine Team 已提交
4977
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4978
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4979
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991
                dtype);
    };

    auto x = mkvar("x", {16, 3, 14, 14}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w", {18, 3, 3, 3}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 18, 1, 1}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
4992 4993
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4994 4995
    auto w1 = mkcvar("w1", {18, 18, 3, 3}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 18, 1, 1}, dtype::QuantizedS32(6.25f));
M
Megvii Engine Team 已提交
4996 4997
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4998 4999 5000 5001
    // concat at batch dim
    auto y2 = opr::Concat::make({y, y1}, 0);
    y2 = opr::TypeCvt::make(y2, dtype::Float32());
    SymbolVar y2_pad;
M
Megvii Engine Team 已提交
5002 5003 5004 5005 5006 5007
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y2}})
                    .endpoint_vars(),
            y2_pad);
5008 5009 5010 5011 5012 5013 5014 5015 5016
    ASSERT_EQ(y2_pad.node()->shape()[1], y2.node()->shape()[1]);
    SmallVector<cg::OperatorNodeBase*> oprs;
    auto cb = [&oprs](cg::OperatorNodeBase* opr) {
        if (opr->same_type<opr::ConvBias>()) {
            oprs.push_back(opr);
        }
    };
    cg::DepOprIter{cb}.add(y2_pad.node()->owner_opr());
    ASSERT_EQ(oprs.size(), 2);
5017
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028
    ASSERT_EQ(oprs[1]->output(0)->shape()[1], 32);
    HostTensorND t1, t2;
    auto func1 = graph->compile({make_callback_copy(y2, t1)});
    func1->execute();
    auto func2 = graph->compile({make_callback_copy(y2_pad, t2)});
    func2->execute();
    MGB_ASSERT_TENSOR_EQ(t1, t2);
}

TEST(TestGoptInference, PaddingChannelsWithPooling) {
    REQUIRE_GPU(1);
5029 5030
    auto cn = CompNode::load("gpu0");
    cn.activate();
5031
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
5032 5033 5034 5035

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
5036
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
5037
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
5038
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
5039
    };
M
Megvii Engine Team 已提交
5040
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
5041
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
5042
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054
                dtype);
    };

    auto x = mkvar("x", {16, 3, 14, 14}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w", {20, 3, 3, 3}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 20, 1, 1}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
5055 5056
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
5057 5058
    auto w1 = mkcvar("w1", {24, 20, 3, 3}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 24, 1, 1}, dtype::QuantizedS32(6.25f));
M
Megvii Engine Team 已提交
5059 5060
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
5061 5062 5063 5064 5065 5066

    opr::Pooling::Param pool_param;
    pool_param.format = opr::Pooling::Param::Format::NCHW;
    y1 = opr::Pooling::make(y1, pool_param);
    y1 = opr::TypeCvt::make(y1, dtype::Float32());
    SymbolVar y1_pad;
M
Megvii Engine Team 已提交
5067 5068 5069 5070 5071 5072
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y1_pad);
5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096
    ASSERT_EQ(y1_pad.node()->shape()[1], y1.node()->shape()[1]);
    SmallVector<cg::OperatorNodeBase*> oprs;
    auto cb = [&oprs](cg::OperatorNodeBase* opr) {
        if (opr->same_type<opr::Pooling>()) {
            oprs.push_back(opr);
        }
    };
    cg::DepOprIter{cb}.add(y1_pad.node()->owner_opr());
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
    HostTensorND t1, t2;
    auto func1 = graph->compile({make_callback_copy(y1, t1)});
    func1->execute();
    auto func2 = graph->compile({make_callback_copy(y1_pad, t2)});
    func2->execute();
    MGB_ASSERT_TENSOR_EQ(t1, t2);
}

// FIXME replace cpu with gpu to enable gpu validation
TEST(TestGoptInference, PaddingChannelsWithWarpPerspective) {
    auto cn = CompNode::load("cpu0");

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
5097
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
5098
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
5099
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
5100
    };
M
Megvii Engine Team 已提交
5101
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
5102
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
5103
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
5104 5105 5106
                dtype);
    };

M
Megvii Engine Team 已提交
5107 5108
    std::shared_ptr<HostTensorND> mat =
            std::make_shared<HostTensorND>(cn, TensorShape{16, 3, 3}, dtype::Float32());
5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120
    warp_perspective_mat_gen(*mat, 16, 14, 14);
    auto mat_var = opr::Host2DeviceCopy::make(*graph, mat).rename("mat");

    auto x = mkvar("x", {16, 3, 14, 14}, dtype::QuantizedS8(2.5f)),
         w = mkcvar("w", {20, 3, 3, 3}, dtype::QuantizedS8(2.5f)),
         b = mkcvar("b", {1, 20, 1, 1}, dtype::QuantizedS32(6.25f));
    opr::ConvBias::Param param;
    param.format = opr::ConvBias::Param::Format::NCHW;
    param.nonlineMode = opr::ConvBias::Param::NonlineMode::RELU;
    param.stride_h = param.stride_w = 1;
    param.pad_h = param.pad_w = 1;

M
Megvii Engine Team 已提交
5121 5122
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
5123 5124
    auto w1 = mkcvar("w1", {24, 20, 3, 3}, dtype::QuantizedS8(2.5f)),
         b1 = mkcvar("b1", {1, 24, 1, 1}, dtype::QuantizedS32(6.25f));
M
Megvii Engine Team 已提交
5125 5126
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
5127 5128 5129

    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NCHW;
M
Megvii Engine Team 已提交
5130
    y1 = opr::WarpPerspective::make(y1, mat_var, TensorShape{14, 14}, warp_param);
5131 5132
    y1 = opr::TypeCvt::make(y1, dtype::Float32());
    SymbolVar y1_pad;
M
Megvii Engine Team 已提交
5133 5134 5135 5136 5137 5138
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y1_pad);
5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
    ASSERT_EQ(y1_pad.node()->shape()[1], y1.node()->shape()[1]);
    SmallVector<cg::OperatorNodeBase*> oprs;
    auto cb = [&oprs](cg::OperatorNodeBase* opr) {
        if (opr->same_type<opr::WarpPerspective>()) {
            oprs.push_back(opr);
        }
    };
    cg::DepOprIter{cb}.add(y1_pad.node()->owner_opr());
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
    HostTensorND t1, t2;
    auto func1 = graph->compile({make_callback_copy(y1, t1)});
    func1->execute();
    auto func2 = graph->compile({make_callback_copy(y1_pad, t2)});
    func2->execute();
    MGB_ASSERT_TENSOR_EQ(t1, t2);
}
5155

5156 5157
#endif

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