inference.cpp 196.1 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
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 已提交
1285
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1286 1287 1288 1289 1290 1291 1292
    };

    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 已提交
1293
    auto w1 = mkcvar("w1", {8, 8, 3, 3}), conv = opr::Convolution::make(x, w1, param);
1294 1295

    auto b = mkvar("b", {1, 1, 1, 1}),
M
Megvii Engine Team 已提交
1296
         elem = opr::Elemwise::make({conv + b}, opr::Elemwise::Param::Mode::RELU);
1297 1298 1299 1300 1301 1302 1303
    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 已提交
1304
    auto w3 = mkcvar("w2", {8, 8, 3, 3}), y = opr::Convolution::make(elem2, w3, param);
1305 1306 1307 1308 1309 1310

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

M
Megvii Engine Team 已提交
1311 1312 1313
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1314 1315 1316

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1317 1318
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4Elemwise.json"));
1319 1320

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1321 1322
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1323 1324 1325 1326 1327 1328 1329 1330
    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);
}

1331 1332 1333 1334 1335 1336 1337 1338
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 已提交
1339
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1340 1341 1342 1343 1344 1345 1346
    };
    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 已提交
1347
    auto w1 = mkcvar("w1", {8, 8, 3, 3}), conv1 = opr::Convolution::make(x, w1, param),
1348
         tcvt1 = opr::TypeCvt::make(conv1, dtype::Float16());
M
Megvii Engine Team 已提交
1349
    auto w2 = mkcvar("w2", {8, 8, 3, 3}), conv2 = opr::Convolution::make(x, w2, param),
1350 1351 1352 1353 1354 1355 1356 1357
         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 已提交
1358 1359 1360
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1361 1362 1363

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1364 1365
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4TypeCvt.json"));
1366 1367

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1368 1369
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1370 1371 1372 1373 1374 1375 1376 1377
    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);
}

1378 1379 1380 1381 1382 1383 1384 1385 1386
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 已提交
1387
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1388 1389 1390 1391 1392 1393 1394
    };

    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 已提交
1395
    auto w1 = mkcvar("w1", {4, 8, 3, 3}), conv1 = opr::Convolution::make(x, w1, param);
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411

    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;
1412
    auto options = gopt::OptimizeForInferenceOptions{};
1413
    options.enable_nhwcd4();
1414
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1415

M
Megvii Engine Team 已提交
1416 1417 1418
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1419

M
Megvii Engine Team 已提交
1420 1421 1422
    ASSERT_EQ(
            opr::Local::Param::Format::NCHW,
            find_opr<opr::Local>(y_opt).param().format);
1423

M
Megvii Engine Team 已提交
1424 1425 1426
    ASSERT_EQ(
            opr::GroupLocal::Param::Format::NCHW,
            find_opr<opr::GroupLocal>(y_opt).param().format);
1427 1428 1429

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1430 1431
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4LOCAL.json"));
1432 1433

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1434 1435
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1436 1437 1438 1439
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
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 已提交
1450
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1451 1452 1453 1454 1455 1456 1457
    };

    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 已提交
1458
    auto w0 = mkcvar("w1", {4, 8, 2, 2}), conv = opr::Convolution::make(x, w0, param);
1459 1460 1461 1462 1463

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

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

M
Megvii Engine Team 已提交
1468 1469 1470 1471 1472 1473
    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);
1474 1475

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1476 1477
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    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 已提交
1490
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
1491
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1492
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
                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 已提交
1504 1505
         y = opr::ConvBias::make(
                 x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(0.2f)});
1506 1507

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

M
Megvii Engine Team 已提交
1512 1513 1514
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NHWCD4,
            find_opr<opr::ConvBias>(y_opt).param().format);
1515 1516 1517

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1518 1519
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNHWCD4Qint8.json"));
1520 1521 1522 1523
    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 已提交
1524 1525 1526
    auto func = graph->compile(
            {make_callback_copy(float_y, host_y),
             make_callback_copy(float_y_opt, host_y_opt)});
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    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 已提交
1539
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1540 1541
    };

M
Megvii Engine Team 已提交
1542
    auto host_inp1 = gen({1, 6, 128, 128}, cn), host_inp2 = gen({1, 6, 256, 256}, cn);
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
    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;
1560
    auto options = gopt::OptimizeForInferenceOptions{};
1561
    options.enable_nhwcd4();
1562
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1563 1564

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
1565 1566
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1567 1568
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
1569 1570
}

1571 1572 1573 1574 1575 1576 1577 1578 1579
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 已提交
1580
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1581 1582
    };

M
Megvii Engine Team 已提交
1583
    auto host_inp1 = gen({1, 6, 16, 16}, cn), host_inp2 = gen({1, 6, 32, 32}, cn);
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    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 已提交
1617 1618
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
    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 已提交
1635 1636 1637
    ASSERT_EQ(
            opr::Convolution::Param::Format::NHWCD4,
            find_opr<opr::Convolution>(y_opt).param().format);
1638 1639 1640
    ASSERT_EQ(1, relayout_format_nr);
}

1641 1642 1643
TEST(TestGoptInference, ConvertBatchNormPass) {
    auto cn = CompNode::load("cpu0");

1644
    std::vector<TensorShape> shps = {{1, 3, 1, 1}, {1, 1, 1, 3}},
M
Megvii Engine Team 已提交
1645
                             xshps = {{2, 3, 16, 24}, {2, 16, 24, 3}};
1646 1647 1648 1649 1650 1651 1652 1653
    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 已提交
1654
            return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1655 1656
        };
        using Param = opr::BatchNorm::Param;
M
Megvii Engine Team 已提交
1657 1658
        Param::ParamDim param_dim =
                t == 0 ? Param::ParamDim::DIM_1C11 : Param::ParamDim::DIM_111C;
1659 1660 1661 1662 1663 1664
        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 已提交
1665
            host_variance->ptr<float>()[i] = std::abs(host_variance->ptr<float>()[i]);
1666 1667 1668 1669 1670
        }
        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 已提交
1671 1672 1673
        unpack_vector(
                gopt::optimize_for_inference({y}, gopt::OptimizeForInferenceOptions{}),
                y_opt);
1674 1675 1676 1677 1678 1679 1680
        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 已提交
1681 1682
        auto func = graph->compile(
                {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1683 1684
        func->execute();
        MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
    }
}

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 已提交
1701
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1702 1703 1704 1705 1706 1707
    };
    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 已提交
1708
         y1 = opr::Elemwise::make({y_cut + b1}, opr::Elemwise::Param::Mode::RELU);
1709
    param.pad_w = param.pad_h = 1;
M
Megvii Engine Team 已提交
1710 1711 1712
    auto y2 = opr::Elemwise::make(
            {opr::Convolution::make(y1, w2, param) + b2},
            opr::Elemwise::Param::Mode::SIGMOID);
1713 1714
    param.pad_w = param.pad_h = 0;
    auto y3 = opr::Convolution::make(y2, w3, param), y_tmp = y3 + x,
M
Megvii Engine Team 已提交
1715
         y_expand = opr::Elemwise::make({y_cut}, opr::Elemwise::Param::Mode::RELU),
1716 1717
         y_y = opr::Convolution::make(y_expand, w3, param), y = y_y + y_tmp;
    SymbolVar y_opt;
1718
    auto options = gopt::OptimizeForInferenceOptions{};
1719
    options.enable_nhwcd4().enable_fuse_conv_bias_nonlinearity();
1720
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
1721 1722 1723
    ASSERT_EQ(3u, find_opr<opr::ConvBias>(y_opt).input().size());
    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
1724 1725
            ->writeto_fpath(
                    output_file("TestGoptInference.FuseConvBiasNonlinPass.json"));
1726 1727

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

1734 1735 1736 1737 1738 1739 1740 1741
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 已提交
1742
            return opr::ImmutableTensor::make(*graph, *gen(shp, cn)).rename(name);
1743 1744 1745 1746
        };

        graph->options().graph_opt_level = 0;
        auto mkcvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
1747
            return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
1748 1749 1750 1751 1752 1753
        };
        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 已提交
1754
             b = i == 0 ? mkcvar("b", {1, 4, 16, 24}) : mkImvar("bias", {1, 4, 16, 24}),
1755 1756 1757
             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 已提交
1758 1759
        auto y1 = opr::Elemwise::make(
                {y_cut0 + y_cut1}, opr::Elemwise::Param::Mode::RELU);
1760 1761
        param.pad_w = param.pad_h = 0;
        auto y2 = opr::Convolution::make(y1, w3, param);
M
Megvii Engine Team 已提交
1762
        auto y = opr::Elemwise::make({y2 + b}, opr::Elemwise::Param::Mode::RELU);
1763 1764 1765 1766 1767 1768 1769
        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 已提交
1770 1771
                ->writeto_fpath(output_file("TestGoptInference.FuseConvBiasNonlinPass_"
                                            "FulBias.json"));
1772
        HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
1773 1774
        auto func = graph->compile(
                {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
1775 1776 1777 1778 1779 1780 1781 1782
        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);
    }
}

1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
#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

1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
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 已提交
1926 1927 1928 1929 1930 1931
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_opt);
1932 1933
    auto opr = y_opt.node()->owner_opr();
    ASSERT_EQ(2u, opr->input().size());
M
Megvii Engine Team 已提交
1934
    ASSERT_EQ(2u, find_opr<opr::MultipleDeviceTensorHolder>(y_opt).output().size());
1935 1936 1937 1938 1939 1940 1941 1942 1943
    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 已提交
1944 1945 1946
        TensorLayout layout{
                hv.layout(), hv.layout().dtype,
                megdnn::Image2DPack4TensorFormat::make_raw(1, 64)};
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
        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 已提交
1963 1964 1965 1966 1967 1968
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_opt);
1969 1970
    auto opr = y_opt.node()->owner_opr();
    ASSERT_EQ(2u, opr->input().size());
M
Megvii Engine Team 已提交
1971 1972 1973
    ASSERT_EQ(
            2u,
            find_opr<opr::MultipleDeviceTensorWithFormatHolder>(y_opt).output().size());
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    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});
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
    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 已提交
2019
    gopt::modify_opr_algo_strategy_inplace({z + 2.3f}, S::PROFILE | S::OPTIMIZED);
M
Megvii Engine Team 已提交
2020
    ASSERT_EQ(S::PROFILE | S::OPTIMIZED, conv.execution_policy().strategy);
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
}

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 已提交
2031 2032 2033
    ASSERT_EQ(
            std::numeric_limits<uint64_t>::max(),
            conv.execution_policy_transient().workspace_limit);
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
    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 已提交
2044
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2045
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2046
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2047
    };
M
Megvii Engine Team 已提交
2048
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2049
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2050
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2051 2052 2053
                dtype);
    };

M
Megvii Engine Team 已提交
2054 2055 2056
    for (auto format :
         {opr::Convolution::Param::Format::NCHW, opr::Convolution::Param::Format::NHWC,
          opr::Convolution::Param::Format::NCHW4}) {
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
        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
2090

2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
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 已提交
2107
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2108
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2109
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2110
    };
M
Megvii Engine Team 已提交
2111
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2112
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2113
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
                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 已提交
2127 2128 2129 2130
    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)});
2131 2132 2133 2134
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2135 2136
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2137
        options.enable_nchw32().enable_fuse_conv_bias_nonlinearity();
2138 2139 2140 2141 2142 2143 2144
        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);
    }
2145 2146 2147
    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 已提交
2148 2149 2150
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2151 2152 2153 2154
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
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 已提交
2171
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2172
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2173
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2174
    };
M
Megvii Engine Team 已提交
2175
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2176
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2177
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2178 2179 2180
                dtype);
    };

M
Megvii Engine Team 已提交
2181 2182
    auto mkshape = [](opr::ConvBias::Param::Format format, size_t N, size_t C, size_t H,
                      size_t W) -> TensorShape {
2183 2184 2185 2186 2187 2188 2189 2190 2191
        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 已提交
2192 2193 2194 2195 2196 2197
    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));
2198 2199 2200 2201 2202 2203 2204
        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 已提交
2205 2206 2207
                x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
        y = opr::ConvBias::make(
                y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
        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);
2223 2224
        if (format == opr::ConvBias::Param::Format::NCHW4) {
#if CUDA_VERSION >= 10020
M
Megvii Engine Team 已提交
2225
            //! try_conv_reformat_nchw322nchw4 used when cuda_version >= 10020
2226 2227 2228 2229 2230 2231 2232
            ASSERT_EQ(1u, nr_dimshuffle);
#else
            ASSERT_EQ(2u, nr_dimshuffle);
#endif
        } else {
            ASSERT_EQ(2u, nr_dimshuffle);
        }
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
        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 已提交
2245 2246 2247
        auto func = graph->compile(
                {make_callback_copy(y_no_tc, host_y),
                 make_callback_copy(y_opt, host_y_opt)});
2248 2249 2250 2251 2252
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
    }
}

2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
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 已提交
2269
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2270
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2271
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2272
    };
M
Megvii Engine Team 已提交
2273
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2274
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2275
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
                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 已提交
2289 2290
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2291 2292 2293 2294
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2295 2296
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2297
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2298 2299 2300 2301 2302 2303 2304
        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);
    }
2305
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2306 2307 2308
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
    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 已提交
2329
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2330
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2331
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2332
    };
M
Megvii Engine Team 已提交
2333
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2334
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2335
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
                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 已提交
2349 2350
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
    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 已提交
2363 2364 2365
    ASSERT_EQ(
            opr::Pooling::Param::Format::NCHW32,
            find_opr<opr::Pooling>(y_opt).param().format);
2366 2367 2368 2369 2370 2371
    {
        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;
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
    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 已提交
2433 2434 2435
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
    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 已提交
2456
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2457
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2458
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2459
    };
M
Megvii Engine Team 已提交
2460
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2461
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2462
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
                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;
2487 2488
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2489
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2490 2491 2492 2493
        unpack_vector(gopt::optimize_for_inference({y4}, options), y_opt);
    }
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2494
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2495 2496
        unpack_vector(gopt::optimize_for_inference({y4}, options), y_no_tc);
    }
2497 2498 2499 2500
    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 已提交
2501
            ->writeto_fpath(output_file("TestGoptInference.EnableTensorCorePass.json"));
2502 2503

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2504 2505 2506
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
    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 已提交
2527
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2528
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2529
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2530
    };
M
Megvii Engine Team 已提交
2531
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2532
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2533
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2534 2535 2536
                dtype);
    };

2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
    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;
        }
2552

2553 2554 2555 2556 2557
        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;
2558

2559
        auto y1 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2560
                x, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2561 2562 2563 2564 2565
        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 已提交
2566
                     {y1, y2}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(1.2f)});
2567 2568 2569 2570 2571 2572 2573 2574 2575
        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());

2576 2577 2578
        SymbolVar z_fuse;
        {
            auto options = gopt::OptimizeForInferenceOptions{};
M
Megvii Engine Team 已提交
2579
            options.enable_fuse_conv_bias_nonlinearity().enable_fuse_conv_bias_with_z();
2580 2581 2582 2583
            unpack_vector(gopt::optimize_for_inference({z}, options), z_fuse);
        }
        graph->compile({{z_fuse, {}}})
                ->to_json()
M
Megvii Engine Team 已提交
2584
                ->writeto_fpath(output_file("FuseConvBiasZPass.BlockFuse_fuse.json"));
2585

M
Megvii Engine Team 已提交
2586
        auto nr_elem_multi_type = find_opr_num<mgb::opr::ElemwiseMultiType>(z_fuse);
2587 2588 2589 2590 2591
        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);
2592 2593
        //! fuse z mannually
        auto z0 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2594
                x, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
        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 已提交
2610
            unpack_vector(gopt::optimize_for_inference({z4}, options), z_nonfuse);
2611 2612 2613
        }
        graph->compile({{z_nonfuse, {}}})
                ->to_json()
M
Megvii Engine Team 已提交
2614 2615
                ->writeto_fpath(
                        output_file("FuseConvBiasZPass.BlockFuse_nonfuse.json"));
2616
        HostTensorND host_z_fuse, host_z_nonfuse;
M
Megvii Engine Team 已提交
2617 2618 2619
        auto func = graph->compile(
                {make_callback_copy(z_nonfuse, host_z_nonfuse),
                 make_callback_copy(z_fuse, host_z_fuse)});
2620 2621
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_z_fuse, host_z_nonfuse);
2622
#endif
2623
    }
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
}

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 已提交
2642
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2643
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2644
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2645
    };
M
Megvii Engine Team 已提交
2646
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2647
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2648
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
                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 已提交
2659
        auto tshp = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
        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 已提交
2682
    x = nchw2nchw4(x), w = nchw2nchw4(w), b = nchw2nchw4(b), z = nchw2nchw4(z);
2683 2684 2685 2686 2687 2688
    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 已提交
2689 2690
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2691 2692 2693 2694 2695
    y = nchw42nchw(y);
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2696 2697
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2698
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2699 2700 2701 2702 2703 2704 2705
        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);
    }
2706 2707 2708
    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 已提交
2709 2710 2711
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    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 已提交
2725
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2726
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2727
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2728
    };
M
Megvii Engine Team 已提交
2729
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2730
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2731
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
                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 已提交
2748 2749
    auto y = opr::ConvBias::make(
            x, w, b, conv_bias_param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2750 2751 2752 2753

    SymbolVar y_opt;

    // check fuse mode
M
Megvii Engine Team 已提交
2754 2755 2756 2757
    for (auto mode :
         {opr::ElemwiseMultiType::Param::Mode::QADD,
          opr::ElemwiseMultiType::Param::Mode::QMUL,
          opr::ElemwiseMultiType::Param::Mode::QFUSE_ADD_RELU}) {
2758 2759
        auto y1 = opr::ElemwiseMultiType::make(
                {y, b1}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2760 2761 2762 2763
        {
            auto options = gopt::OptimizeForInferenceOptions{};
            options.enable_fuse_conv_bias_nonlinearity()
                    .enable_fuse_conv_bias_with_z()
2764
                    .enable_nchw32();
2765 2766
            unpack_vector(gopt::optimize_for_inference({y1}, options), y_opt);
        }
2767 2768 2769 2770 2771 2772 2773 2774
        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 已提交
2775
                    {y1, b2}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2776 2777 2778 2779
            {
                auto options = gopt::OptimizeForInferenceOptions{};
                options.enable_fuse_conv_bias_nonlinearity()
                        .enable_fuse_conv_bias_with_z()
2780
                        .enable_nchw32();
M
Megvii Engine Team 已提交
2781
                unpack_vector(gopt::optimize_for_inference({y2}, options), y_opt);
2782
            }
M
Megvii Engine Team 已提交
2783
            auto nr_elemwisemultitype = find_opr_num<opr::ElemwiseMultiType>(y_opt);
2784 2785 2786 2787 2788 2789
            ASSERT_NE(0u, nr_elemwisemultitype);
        }
    }
}

#if MGB_CUDA
2790
//! close for cu111 ci, reopen it when bug fixed
2791
#if CUDA_VERSION < 11000
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807
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 已提交
2808
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2809
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2810
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2811
    };
M
Megvii Engine Team 已提交
2812
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2813
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2814
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2815 2816
                dtype);
    };
M
Megvii Engine Team 已提交
2817 2818
    auto mkshape = [](opr::ConvBias::Param::Format format, size_t N, size_t C, size_t H,
                      size_t W) -> TensorShape {
2819 2820 2821 2822 2823 2824 2825 2826
        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};
        }
    };
2827

M
Megvii Engine Team 已提交
2828 2829 2830 2831 2832 2833 2834
    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));
2835 2836 2837 2838 2839
        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;
2840

2841
        auto y = opr::ConvBiasForward::make(
M
Megvii Engine Team 已提交
2842
                x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
2843 2844 2845 2846
        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 已提交
2847
                y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
        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 已提交
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
        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);
2876
        HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2877 2878 2879
        auto func = graph->compile(
                {make_callback_copy(y_cudnn, host_y),
                 make_callback_copy(y_opt, host_y_opt)});
2880 2881
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
2882
    }
2883
}
2884
#endif
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901

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 已提交
2902
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2903
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2904
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2905
    };
M
Megvii Engine Team 已提交
2906
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2907
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2908
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2909 2910
                dtype);
    };
M
Megvii Engine Team 已提交
2911 2912
    std::shared_ptr<HostTensorND> mat =
            std::make_shared<HostTensorND>(cn, TensorShape{32, 3, 3}, dtype::Float32());
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
    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}});
2927

2928 2929
    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NCHW4;
M
Megvii Engine Team 已提交
2930
    auto y1 = opr::WarpPerspective::make(y, mat_var, TensorShape{16, 16}, warp_param);
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945
    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 已提交
2946
    auto y2 = opr::WarpPerspective::make(y1, mat_var, TensorShape{16, 16}, warp_param);
2947 2948
    SymbolVar y_opt;
    SymbolVar y_cudnn;
2949 2950
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2951
        options.enable_chwn4();
2952 2953
        unpack_vector(gopt::optimize_for_inference({y2}, options), y_opt);
    }
M
Megvii Engine Team 已提交
2954 2955 2956 2957 2958 2959 2960
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y2}})
                    .endpoint_vars(),
            y_cudnn);
2961 2962

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2963 2964 2965
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
    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 已提交
2986
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2987
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2988
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2989 2990
    };

M
Megvii Engine Team 已提交
2991
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2992
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2993
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
                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 已提交
3040 3041 3042 3043 3044 3045 3046
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y_cudnn);
3047 3048

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3049 3050 3051
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
    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 已提交
3072
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3073
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3074
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3075
    };
M
Megvii Engine Team 已提交
3076
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3077
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3078
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
                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 已提交
3089
        auto tshp = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
        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 已提交
3154 3155
            ->writeto_fpath(
                    output_file("TestGoptInference.EnableCHWN4ShuffleRemove.json"));
3156 3157 3158 3159
    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 已提交
3160 3161 3162 3163 3164 3165 3166
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y4}})
                    .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
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
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 已提交
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
    };
M
Megvii Engine Team 已提交
3196
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3197
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3198
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3199 3200
                dtype);
    };
3201

3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
    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(
3213 3214
            x, w1, b1, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3215

3216 3217 3218 3219 3220
    // 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));
3221 3222 3223
    auto conv2 = opr::ConvBiasForward::make(
            conv1, w2, b2, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3224

3225 3226 3227 3228 3229 3230 3231 3232
    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 已提交
3233
            conv2, w3, param_deconv, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3234 3235 3236

    auto deconv1_fp32 = opr::TypeCvt::make(deconv1, dtype::Float32());
    auto y = deconv1_fp32 + opr::TypeCvt::make(b2, dtype::Float32());
3237 3238 3239 3240 3241 3242 3243 3244

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

M
Megvii Engine Team 已提交
3245 3246 3247 3248 3249 3250
    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);
3251 3252
    auto nr_reshape = find_opr_num<mgb::opr::Reshape>(y_opt);
    ASSERT_EQ(2u, nr_reshape);
3253 3254 3255

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3256 3257
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW4GPU.json"));
3258 3259

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3260 3261
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3262 3263 3264 3265
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
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 已提交
3276
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3277
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3278
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3279 3280
    };

M
Megvii Engine Team 已提交
3281
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3282
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3283
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
                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 已提交
3295 3296
    auto conv1 = opr::ConvBias::make(
            x, w1, b1, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3297 3298 3299 3300 3301

    // 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 已提交
3302 3303
    auto conv2 = opr::ConvBias::make(
            x, w2, b2, z2, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3304 3305 3306 3307 3308 3309

    // 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 已提交
3310 3311
    auto conv3 = opr::ConvBias::make(
            x, w3, b3, z3, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325

    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 已提交
3326
            if (conv_bias.param().format != opr::ConvBias::Param::Format::NCHW4_NCHW) {
3327 3328 3329 3330 3331 3332 3333 3334 3335
                succ = false;
            }
        }
    };

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

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3336 3337
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3338 3339 3340 3341 3342
    func->execute();

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

3343 3344
#endif

3345 3346 3347 3348 3349
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 已提交
3350
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3351
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3352
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3353
    };
M
Megvii Engine Team 已提交
3354
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3355
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3356
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3357 3358 3359
                dtype);
    };
    auto mkcvarf32 = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
3360
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
    };

    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 已提交
3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425
    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);
3426 3427
}

3428 3429 3430 3431 3432 3433 3434 3435 3436
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 已提交
3437
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3438 3439 3440
    };

    auto x = mkvar("x", {2, 4, 16, 16});
3441
    // ConvBias test dense
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
    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 已提交
3464 3465 3466
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW,
            find_opr<opr::ConvBias>(y_opt).param().format);
3467 3468 3469

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

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3473 3474
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3475 3476 3477 3478
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

3479 3480
TEST(TestGoptInference, ConvertFormatNCHW4Ic3) {
    REQUIRE_GPU(1);
3481 3482 3483
    auto cn = CompNode::load("gpu0");
    cn.activate();
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
3484 3485 3486 3487
    HostTensorGenerator<dtype::Float32, RandomDistribution::UNIFORM> gen{
            1.2f, 127 * 127};
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3488
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3489
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3490
                opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name), dtype);
3491
    };
M
Megvii Engine Team 已提交
3492
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3493
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3494
                opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name), dtype);
3495 3496 3497 3498 3499 3500 3501 3502 3503
    };

    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 已提交
3504 3505 3506
    auto conv1 = opr::ConvBias::make(
            x, w1, b1, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3507 3508 3509
    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 已提交
3510 3511 3512
    auto conv2 = opr::ConvBias::make(
            conv1, w2, b2, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3513 3514 3515 3516 3517 3518 3519 3520 3521
    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 已提交
3522 3523 3524
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4,
            find_opr<opr::ConvBias>(y_opt).param().format);
3525 3526 3527

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3528 3529
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW4Ic3.json"));
3530 3531

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3532 3533
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3534 3535 3536 3537
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

3538 3539 3540 3541 3542 3543 3544 3545 3546
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 已提交
3547
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3548 3549 3550 3551
    };

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
M
Megvii Engine Team 已提交
3552
    //! Hybrid nchw88 mode
3553 3554 3555
    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 已提交
3556 3557
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
M
Megvii Engine Team 已提交
3558
    //! channel wise
3559 3560 3561 3562 3563 3564 3565 3566
    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);
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
    //! 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);
3578 3579 3580 3581 3582
    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 已提交
3583
    auto resize = opr::ResizeForward::make(reduce1, subtensor * 2, param_resize);
3584 3585 3586 3587 3588
    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 已提交
3589
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600
    //! 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;
3601 3602
    {
        auto options = gopt::OptimizeForInferenceOptions{};
3603
        options.enable_nchw88();
3604 3605
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
M
Megvii Engine Team 已提交
3606 3607 3608 3609 3610 3611
    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);
3612 3613 3614

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

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3618 3619
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
    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);
}

3630 3631 3632 3633 3634 3635 3636 3637 3638
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 已提交
3639
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3640
    };
3641 3642 3643
    auto mkcvar_dtype = [&](const char* name, const TensorShape& shp,
                            const DType& dtype) {
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3644
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3645 3646
                dtype);
    };
3647 3648 3649

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
3650
    //! Hybrid nchw44 mode
3651 3652 3653
    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 已提交
3654 3655
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
3656 3657 3658 3659 3660

    //! 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 已提交
3661 3662
    auto conv1_f1 = opr::ConvBias::make(
            x, w1_f1, param_conv_bias_pad0, {}, OperatorNodeConfig("conv1_f1"));
3663 3664 3665 3666 3667

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

    //! s8 dense conv
3668 3669
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
3670 3671 3672 3673 3674 3675 3676 3677
    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
3678 3679
    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}),
3680
         conv2 = opr::ConvBias::make(conv_1_2_fp32, w2, b2, param_conv_bias);
3681 3682 3683
    //! 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);
3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694
    //! 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);
3695 3696 3697 3698 3699
    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 已提交
3700
    auto resize = opr::ResizeForward::make(reduce1, subtensor * 2, param_resize);
3701 3702 3703 3704 3705
    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 已提交
3706
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3707 3708 3709
    //! 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 已提交
3710 3711 3712
    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"));
3713 3714 3715 3716 3717 3718 3719
    //! 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 已提交
3720
                 OperatorNodeConfig{"conv_3_3_q", cn, dtype::QuantizedS8{6.25f}});
3721 3722 3723 3724
    auto conv3_3 = opr::TypeCvt::make(conv3_3_q, dtype::Float32());

    //! Dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
3725
    auto w4 = mkcvar("w4", {16, 32, 3, 3}), b4 = mkcvar("b4", {1, 16, 1, 1}),
M
Megvii Engine Team 已提交
3726 3727 3728 3729 3730 3731
         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"));
3732 3733 3734
    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 已提交
3735 3736
         conv5 = opr::ConvBias::make(
                 conv4_add, w5, b5, param_conv_bias, {}, OperatorNodeConfig("conv5"));
3737
    auto w6 = mkcvar("w6", {4, 6, 3, 3}), b6 = mkcvar("b6", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
3738 3739
         y = opr::ConvBias::make(
                 conv5, w6, b6, param_conv_bias, {}, OperatorNodeConfig("conv6"));
3740

3741
    SymbolVar y_opt;
3742
    auto options = gopt::OptimizeForInferenceOptions{};
3743
    options.enable_fuse_conv_bias_nonlinearity();
3744
    options.enable_nchw44();
3745
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
3746

M
Megvii Engine Team 已提交
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
    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);
3768 3769

    graph->compile({{y_opt, {}}})
3770
            ->to_json()
M
Megvii Engine Team 已提交
3771
            ->writeto_fpath(output_file("TestGoptInference.ConvertFormatNCHW44.json"));
3772 3773

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3774 3775
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3776 3777 3778 3779 3780 3781 3782 3783 3784
    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);
}
3785

3786 3787 3788 3789 3790 3791 3792 3793 3794
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 已提交
3795
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806
    };

    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 已提交
3807
         elem0 = opr::Elemwise::make({conv1 + b + b}, opr::Elemwise::Param::Mode::RELU);
3808 3809 3810 3811 3812

    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 已提交
3813
         y = opr::Elemwise::make({conv2 + b1 + b}, opr::Elemwise::Param::Mode::RELU);
3814 3815 3816 3817 3818 3819

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

M
Megvii Engine Team 已提交
3820 3821 3822
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt).param().format);
3823 3824 3825 3826 3827 3828 3829

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

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3830 3831
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
    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 已提交
3843
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858
    };

    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 已提交
3859 3860 3861
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt).param().format);
3862 3863 3864

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3865 3866
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW44Reshape.json"));
3867 3868

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3869 3870
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3871 3872 3873 3874 3875
    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);
}

3876 3877 3878 3879 3880 3881 3882 3883 3884
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 已提交
3885
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3886
    };
3887 3888 3889
    auto mkcvar_dtype = [&](const char* name, const TensorShape& shp,
                            const DType& dtype) {
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3890
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3891 3892
                dtype);
    };
3893 3894 3895

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
3896
    //! Hybrid nchw44 mode
3897 3898 3899
    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 已提交
3900 3901 3902
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
    printf("create conv1 %s\n", conv1.node()->owner_opr()->dyn_typeinfo()->name);
3903 3904 3905 3906 3907 3908
    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 已提交
3909 3910
    auto conv1_f1 = opr::ConvBias::make(
            x, w1_f1, b1, param_conv_bias_pad0, {}, OperatorNodeConfig("conv1_f1"));
3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923

    //! 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
3924 3925
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
3926 3927
    auto w1_2 = mkcvar_dtype("w1_2", {8, 8, 3, 3}, dtype::QuantizedS8(2.5f));
    auto conv_1_2 = opr::ConvBias::make(
3928
            conv_1_q8, w1_2, param_conv_bias, {},
3929 3930 3931 3932
            OperatorNodeConfig{"conv_1_2", cn, dtype::QuantizedS8{6.25f}});
    auto conv_1_2_fp32 = opr::TypeCvt::make(conv_1_2, dtype::Float32());

    //! channel wise
3933 3934
    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}),
3935
         conv2 = opr::ConvBias::make(conv_1_2_fp32, w2, b2, param_conv_bias);
3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
    //! 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 已提交
3952
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3953 3954 3955
    //! 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 已提交
3956 3957 3958
    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"));
3959 3960 3961 3962 3963 3964 3965
    //! 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 已提交
3966
                 OperatorNodeConfig{"conv_3_3_q", cn, dtype::QuantizedS8{6.25f}});
3967 3968 3969 3970 3971
    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 已提交
3972 3973
         conv4 = opr::ConvBias::make(
                 conv3_3, w4, b4, param_conv_bias, {}, OperatorNodeConfig("conv4"));
3974

3975
    auto w5 = mkcvar("w5", {6, 4, 3, 3}), b5 = mkcvar("b5", {1, 6, 1, 1}),
M
Megvii Engine Team 已提交
3976 3977
         conv5 = opr::ConvBias::make(
                 conv4, w5, b5, param_conv_bias, {}, OperatorNodeConfig("conv5"));
3978
    auto w6 = mkcvar("w6", {4, 6, 3, 3}), b6 = mkcvar("b6", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
3979 3980
         y = opr::ConvBias::make(
                 conv5, w6, b6, param_conv_bias, {}, OperatorNodeConfig("conv6"));
3981

3982
    SymbolVar y_opt;
3983
    auto options = gopt::OptimizeForInferenceOptions{};
3984
    options.enable_fuse_conv_bias_nonlinearity();
3985
    options.enable_nchw44_dot();
3986 3987
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

M
Megvii Engine Team 已提交
3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011
    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);
4012 4013 4014

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4015 4016
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW44_DOT.json"));
4017 4018

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4019 4020
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4021 4022 4023 4024 4025 4026 4027 4028 4029 4030
    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);
}

4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042
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 已提交
4043
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068
    };

    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 已提交
4069 4070
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4071 4072 4073 4074
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

4075 4076 4077
#if MGB_CUDA
TEST(TestGoptInference, PreProcessCase0) {
    REQUIRE_GPU(1);
M
Megvii Engine Team 已提交
4078 4079
    HostTensorGenerator<dtype::Quantized8Asymm, RandomDistribution::UNIFORM> gen(
            dt_quint8(0), dt_quint8(50), 1, 128, 1234);
4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093
    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 已提交
4094
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107
    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 已提交
4108
            ->writeto_fpath(output_file("TestGoptInference.PreProcessCase0.json"));
4109 4110

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4111 4112
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136
    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 已提交
4137
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151
    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 已提交
4152
            ->writeto_fpath(output_file("TestGoptInference.PreProcessCase1.json"));
4153 4154

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4155 4156
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4157 4158 4159 4160 4161
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);

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

4163
TEST(TestGoptInference, WarpAndPreProcessCase0) {
4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176
    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 已提交
4177 4178
    auto mat_host =
            std::make_shared<HostTensorND>(cn, TensorShape{n, 3, 3}, dtype::Float32());
4179 4180 4181 4182 4183
    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 已提交
4184
    auto x_warp = opr::WarpPerspective::make(x, mat, TensorShape{h, w}, warp_param);
4185 4186 4187 4188 4189 4190
    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 已提交
4191
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205
    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 已提交
4206 4207 4208
    ASSERT_EQ(
            opr::WarpPerspective::Param::Format::NHWC_NCHW4_IC_SMALL,
            find_opr<opr::WarpPerspective>(y_opt).param().format);
4209 4210 4211

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4212 4213
            ->writeto_fpath(
                    output_file("TestGoptInference.WarpAndPreProcessCase0.json"));
4214 4215

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4216 4217
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4218 4219 4220 4221
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}

4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235
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 已提交
4236
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4237
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4238
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
                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 已提交
4258 4259 4260
    auto result = opr::ConvBias::make(
            x_s8, weight, bias, param, {},
            OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4261 4262 4263 4264 4265 4266 4267 4268 4269

    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 已提交
4270 4271
            ->writeto_fpath(
                    output_file("TestGoptInference.PreProcessCaseAutopadNCHW64.json"));
4272 4273

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4274 4275
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4276 4277
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
M
Megvii Engine Team 已提交
4278 4279 4280
    ASSERT_TRUE(
            find_opr<opr::RelayoutFormat>(y_opt).param().mode ==
            opr::RelayoutFormat::Param::Mode::NCHW_NCHW4);
4281 4282
}

4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296
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 已提交
4297
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4298
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4299
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
                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 已提交
4312
    auto host_val = std::make_shared<HostTensorND>(cn, dtype::QuantizedS8(2.5f));
4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329
    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 已提交
4330 4331 4332
    auto result = opr::ConvBias::make(
            nhwc_x, weight, bias, param, {},
            OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4333 4334 4335 4336 4337 4338 4339 4340
    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 已提交
4341 4342
            ->writeto_fpath(
                    output_file("TestGoptInference.PreProcessCaseAutopadNHWC.json"));
4343 4344

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4345 4346
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4347 4348
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
M
Megvii Engine Team 已提交
4349 4350 4351
    ASSERT_TRUE(
            find_opr<opr::RelayoutFormat>(y_opt).param().mode ==
            opr::RelayoutFormat::Param::Mode::NCHW_NCHW4);
4352 4353
}

4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
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 已提交
4368 4369
    auto mat_host =
            std::make_shared<HostTensorND>(cn, TensorShape{n, 3, 3}, dtype::Float32());
4370 4371 4372 4373 4374
    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 已提交
4375
    auto x_warp = opr::WarpPerspective::make(x, mat, TensorShape{h, w}, warp_param);
4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387
    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 已提交
4388 4389 4390
    ASSERT_EQ(
            opr::WarpPerspective::Param::Format::NHWC_NCHW,
            find_opr<opr::WarpPerspective>(y_opt).param().format);
4391 4392 4393

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4394 4395
            ->writeto_fpath(
                    output_file("TestGoptInference.WarpAndPreProcessCase1.json"));
4396 4397

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4398 4399
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4400 4401 4402
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}
4403

4404
#if CUDA_VERSION >= 10020
4405 4406 4407 4408
TEST(TestGoptInference, FoldingConvDimshuffle) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4409
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4410 4411 4412 4413

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4414
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4415
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4416
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4417
    };
M
Megvii Engine Team 已提交
4418
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4419
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4420
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
                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 已提交
4444 4445
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4446 4447 4448
    y = opr::TypeCvt::make(y, dtype::Float32());
    y = nchw42nchw(y);
    SymbolVar y_fuse, y_non_fuse;
M
Megvii Engine Team 已提交
4449 4450 4451 4452 4453 4454 4455 4456
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ShuffleShuffleRemovePass>()
                    .add_pass<gopt::FoldingConvBiasDimshufflePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_fuse);
4457 4458 4459
    gopt::modify_opr_algo_strategy_inplace(
            {y_fuse},
            opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy::PROFILE);
4460 4461
    graph->compile({{y_fuse, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4462 4463 4464 4465 4466
            ->writeto_fpath(
                    output_file("TestGoptInference.FoldingConvDimshuffle.json"));
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4_NCHW,
            find_opr<opr::ConvBias>(y_fuse).param().format);
4467
    ASSERT_EQ(0u, find_opr_num<opr::Dimshuffle>(y_fuse));
M
Megvii Engine Team 已提交
4468
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4469
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4470 4471 4472
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4473 4474 4475 4476 4477 4478 4479
    func->execute();
}

TEST(TestGoptInference, FoldingConvDimshuffleNCHW4NCHW32) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4480
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4481 4482 4483 4484

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4485
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4486
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4487
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4488
    };
M
Megvii Engine Team 已提交
4489
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4490
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4491
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518
                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 已提交
4519 4520
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4521 4522 4523
    y = nchw42nchw32(y);
    y = opr::TypeCvt::make(y, dtype::Float32());
    SymbolVar y_fuse, y_non_fuse;
M
Megvii Engine Team 已提交
4524 4525 4526 4527 4528 4529 4530
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FoldingConvBiasDimshufflePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_fuse);
4531 4532 4533
    gopt::modify_opr_algo_strategy_inplace(
            {y_fuse},
            opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy::PROFILE);
4534 4535 4536 4537
    graph->compile({{y_fuse, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.FoldingConvDimshuffleNCHW4NCHW32.json"));
M
Megvii Engine Team 已提交
4538 4539 4540
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4_NCHW32,
            find_opr<opr::ConvBias>(y_fuse).param().format);
4541
    ASSERT_EQ(0u, find_opr_num<opr::Dimshuffle>(y_fuse));
M
Megvii Engine Team 已提交
4542
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4543
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4544 4545 4546
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4547 4548 4549 4550 4551 4552 4553 4554
    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();
4555
    REQUIRE_CUDA_COMPUTE_CAPABILITY(7, 5);
4556 4557 4558 4559

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4560
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4561
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4562
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4563
    };
M
Megvii Engine Team 已提交
4564
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4565
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4566
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580
                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 已提交
4581 4582
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4583
    param.stride_h = param.stride_w = 1;
M
Megvii Engine Team 已提交
4584 4585
    y = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601
    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 已提交
4602
            if (cb->param().format == opr::ConvBias::Param::Format::NCHW32_NCHW4)
4603 4604
                found = true;
        }
M
Megvii Engine Team 已提交
4605
    }}.add(y_fuse.node()->owner_opr());
4606
    EXPECT_TRUE(found);
M
Megvii Engine Team 已提交
4607
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4608
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4609 4610 4611
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4612 4613 4614
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y_fuse, host_y_non_fuse);
}
4615 4616 4617 4618 4619

TEST(TestGoptInference, FoldingConvDimshuffleNCHW4NHWC) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4620
    REQUIRE_CUDA_COMPUTE_CAPABILITY(7, 5);
4621 4622 4623 4624

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4625
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4626
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4627
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4628
    };
M
Megvii Engine Team 已提交
4629
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4630
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4631
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4632 4633 4634 4635
                dtype);
    };

    auto x = mkvar("x", {32, 4, 23, 40}, dtype::QuantizedS8(2.5f)),
4636 4637 4638
         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 已提交
4639
         b1 = mkcvar("b1", {1, 32, 1, 1}, dtype::QuantizedS32(12.34567f * 1.234f));
4640 4641 4642 4643 4644 4645 4646
    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 已提交
4647
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(12.34567f)});
4648
    y = opr::TypeCvt::make(y, dtype::QuantizedS4(12.34567f));
M
Megvii Engine Team 已提交
4649 4650
    y = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS4(56.71234f)});
4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668
    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);
4669
    ASSERT_EQ(2u, nr_dimshuffle);
4670 4671 4672 4673 4674 4675 4676
    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 已提交
4677
    }}.add(y_fuse.node()->owner_opr());
4678
    EXPECT_TRUE(found);
M
Megvii Engine Team 已提交
4679
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4680 4681
    gopt::modify_opr_algo_strategy_inplace({y_non_fuse}, strategy);
    HostTensorND host_y_non_fuse;
M
Megvii Engine Team 已提交
4682
    auto func2 = graph->compile({make_callback_copy(y_non_fuse, host_y_non_fuse)});
4683 4684 4685
    func2->execute();
    MGB_ASSERT_TENSOR_EQ(host_y_fuse, host_y_non_fuse);
}
4686
#endif
4687 4688 4689 4690 4691

TEST(TestGoptInference, PaddingChannels) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4692
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4693 4694 4695 4696

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4697
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4698
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4699
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4700
    };
M
Megvii Engine Team 已提交
4701
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4702
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4703
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715
                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 已提交
4716 4717
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4718 4719
    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 已提交
4720 4721
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4722 4723
    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 已提交
4724 4725
    auto y2 = opr::ConvBias::make(
            y1, w2, b2, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4726 4727 4728 4729 4730 4731
    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 已提交
4732 4733 4734 4735 4736 4737
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y3}})
                    .endpoint_vars(),
            y3_pad);
4738 4739 4740 4741 4742 4743 4744 4745 4746
    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);
4747
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761
    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();
4762
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
M
Megvii Engine Team 已提交
4763

4764 4765 4766
    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4767
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4768
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4769
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4770
    };
M
Megvii Engine Team 已提交
4771
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4772
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4773
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785
                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 已提交
4786 4787
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4788 4789
    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 已提交
4790 4791
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4792 4793 4794 4795
    // 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 已提交
4796 4797 4798 4799 4800 4801
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y2}})
                    .endpoint_vars(),
            y2_pad);
4802 4803 4804 4805 4806 4807 4808 4809 4810
    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);
4811
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822
    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);
4823 4824
    auto cn = CompNode::load("gpu0");
    cn.activate();
4825
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4826 4827 4828 4829

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4830
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4831
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4832
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4833
    };
M
Megvii Engine Team 已提交
4834
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4835
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4836
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848
                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 已提交
4849 4850
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4851 4852
    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 已提交
4853 4854
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4855 4856 4857 4858 4859 4860

    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 已提交
4861 4862 4863 4864 4865 4866
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y1_pad);
4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890
    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 已提交
4891
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4892
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4893
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4894
    };
M
Megvii Engine Team 已提交
4895
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4896
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4897
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4898 4899 4900
                dtype);
    };

M
Megvii Engine Team 已提交
4901 4902
    std::shared_ptr<HostTensorND> mat =
            std::make_shared<HostTensorND>(cn, TensorShape{16, 3, 3}, dtype::Float32());
4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914
    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 已提交
4915 4916
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4917 4918
    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 已提交
4919 4920
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4921 4922 4923

    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NCHW;
M
Megvii Engine Team 已提交
4924
    y1 = opr::WarpPerspective::make(y1, mat_var, TensorShape{14, 14}, warp_param);
4925 4926
    y1 = opr::TypeCvt::make(y1, dtype::Float32());
    SymbolVar y1_pad;
M
Megvii Engine Team 已提交
4927 4928 4929 4930 4931 4932
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y1_pad);
4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948
    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);
}
4949

4950 4951
#endif

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