inference.cpp 191.3 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
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 已提交
1794 1795 1796 1797 1798 1799
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_opt);
1800 1801
    auto opr = y_opt.node()->owner_opr();
    ASSERT_EQ(2u, opr->input().size());
M
Megvii Engine Team 已提交
1802
    ASSERT_EQ(2u, find_opr<opr::MultipleDeviceTensorHolder>(y_opt).output().size());
1803 1804 1805 1806 1807 1808 1809 1810 1811
    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 已提交
1812 1813 1814
        TensorLayout layout{
                hv.layout(), hv.layout().dtype,
                megdnn::Image2DPack4TensorFormat::make_raw(1, 64)};
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
        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 已提交
1831 1832 1833 1834 1835 1836
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ParamMergePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_opt);
1837 1838
    auto opr = y_opt.node()->owner_opr();
    ASSERT_EQ(2u, opr->input().size());
M
Megvii Engine Team 已提交
1839 1840 1841
    ASSERT_EQ(
            2u,
            find_opr<opr::MultipleDeviceTensorWithFormatHolder>(y_opt).output().size());
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
    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});
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
    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 已提交
1887
    gopt::modify_opr_algo_strategy_inplace({z + 2.3f}, S::PROFILE | S::OPTIMIZED);
M
Megvii Engine Team 已提交
1888
    ASSERT_EQ(S::PROFILE | S::OPTIMIZED, conv.execution_policy().strategy);
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
}

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 已提交
1899 1900 1901
    ASSERT_EQ(
            std::numeric_limits<uint64_t>::max(),
            conv.execution_policy_transient().workspace_limit);
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
    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 已提交
1912
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
1913
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1914
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
1915
    };
M
Megvii Engine Team 已提交
1916
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
1917
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1918
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
1919 1920 1921
                dtype);
    };

M
Megvii Engine Team 已提交
1922 1923 1924
    for (auto format :
         {opr::Convolution::Param::Format::NCHW, opr::Convolution::Param::Format::NHWC,
          opr::Convolution::Param::Format::NCHW4}) {
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
        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
1958

1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
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 已提交
1975
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
1976
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1977
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
1978
    };
M
Megvii Engine Team 已提交
1979
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
1980
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
1981
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
                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 已提交
1995 1996 1997 1998
    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)});
1999 2000 2001 2002
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2003 2004
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2005
        options.enable_nchw32().enable_fuse_conv_bias_nonlinearity();
2006 2007 2008 2009 2010 2011 2012
        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);
    }
2013 2014 2015
    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 已提交
2016 2017 2018
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2019 2020 2021 2022
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
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 已提交
2039
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2040
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2041
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2042
    };
M
Megvii Engine Team 已提交
2043
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2044
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2045
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2046 2047 2048
                dtype);
    };

M
Megvii Engine Team 已提交
2049 2050
    auto mkshape = [](opr::ConvBias::Param::Format format, size_t N, size_t C, size_t H,
                      size_t W) -> TensorShape {
2051 2052 2053 2054 2055 2056 2057 2058 2059
        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 已提交
2060 2061 2062 2063 2064 2065
    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));
2066 2067 2068 2069 2070 2071 2072
        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 已提交
2073 2074 2075
                x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
        y = opr::ConvBias::make(
                y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
        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);
2091 2092
        if (format == opr::ConvBias::Param::Format::NCHW4) {
#if CUDA_VERSION >= 10020
M
Megvii Engine Team 已提交
2093
            //! try_conv_reformat_nchw322nchw4 used when cuda_version >= 10020
2094 2095 2096 2097 2098 2099 2100
            ASSERT_EQ(1u, nr_dimshuffle);
#else
            ASSERT_EQ(2u, nr_dimshuffle);
#endif
        } else {
            ASSERT_EQ(2u, nr_dimshuffle);
        }
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
        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 已提交
2113 2114 2115
        auto func = graph->compile(
                {make_callback_copy(y_no_tc, host_y),
                 make_callback_copy(y_opt, host_y_opt)});
2116 2117 2118 2119 2120
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
    }
}

2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
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 已提交
2137
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2138
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2139
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2140
    };
M
Megvii Engine Team 已提交
2141
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2142
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2143
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
                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 已提交
2157 2158
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2159 2160 2161 2162
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2163 2164
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2165
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2166 2167 2168 2169 2170 2171 2172
        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);
    }
2173
    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2174 2175 2176
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
    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 已提交
2197
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2198
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2199
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2200
    };
M
Megvii Engine Team 已提交
2201
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2202
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2203
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
                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 已提交
2217 2218
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
    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 已提交
2231 2232 2233
    ASSERT_EQ(
            opr::Pooling::Param::Format::NCHW32,
            find_opr<opr::Pooling>(y_opt).param().format);
2234 2235 2236 2237 2238 2239
    {
        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;
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
    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 已提交
2301 2302 2303
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
    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 已提交
2324
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2325
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2326
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2327
    };
M
Megvii Engine Team 已提交
2328
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2329
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2330
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
                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;
2355 2356
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2357
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2358 2359 2360 2361
        unpack_vector(gopt::optimize_for_inference({y4}, options), y_opt);
    }
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2362
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2363 2364
        unpack_vector(gopt::optimize_for_inference({y4}, options), y_no_tc);
    }
2365 2366 2367 2368
    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 已提交
2369
            ->writeto_fpath(output_file("TestGoptInference.EnableTensorCorePass.json"));
2370 2371

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2372 2373 2374
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
    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 已提交
2395
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2396
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2397
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2398
    };
M
Megvii Engine Team 已提交
2399
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2400
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2401
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2402 2403 2404
                dtype);
    };

2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
    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;
        }
2420

2421 2422 2423 2424 2425
        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;
2426

2427
        auto y1 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2428
                x, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2429 2430 2431 2432 2433
        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 已提交
2434
                     {y1, y2}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(1.2f)});
2435 2436 2437 2438 2439 2440 2441 2442 2443
        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());

2444 2445 2446
        SymbolVar z_fuse;
        {
            auto options = gopt::OptimizeForInferenceOptions{};
M
Megvii Engine Team 已提交
2447
            options.enable_fuse_conv_bias_nonlinearity().enable_fuse_conv_bias_with_z();
2448 2449 2450 2451
            unpack_vector(gopt::optimize_for_inference({z}, options), z_fuse);
        }
        graph->compile({{z_fuse, {}}})
                ->to_json()
M
Megvii Engine Team 已提交
2452
                ->writeto_fpath(output_file("FuseConvBiasZPass.BlockFuse_fuse.json"));
2453

M
Megvii Engine Team 已提交
2454
        auto nr_elem_multi_type = find_opr_num<mgb::opr::ElemwiseMultiType>(z_fuse);
2455 2456 2457 2458 2459
        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);
2460 2461
        //! fuse z mannually
        auto z0 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
2462
                x, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
        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 已提交
2478
            unpack_vector(gopt::optimize_for_inference({z4}, options), z_nonfuse);
2479 2480 2481
        }
        graph->compile({{z_nonfuse, {}}})
                ->to_json()
M
Megvii Engine Team 已提交
2482 2483
                ->writeto_fpath(
                        output_file("FuseConvBiasZPass.BlockFuse_nonfuse.json"));
2484
        HostTensorND host_z_fuse, host_z_nonfuse;
M
Megvii Engine Team 已提交
2485 2486 2487
        auto func = graph->compile(
                {make_callback_copy(z_nonfuse, host_z_nonfuse),
                 make_callback_copy(z_fuse, host_z_fuse)});
2488 2489
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_z_fuse, host_z_nonfuse);
2490
#endif
2491
    }
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
}

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 已提交
2510
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2511
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2512
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2513
    };
M
Megvii Engine Team 已提交
2514
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2515
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2516
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
                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 已提交
2527
        auto tshp = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
        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 已提交
2550
    x = nchw2nchw4(x), w = nchw2nchw4(w), b = nchw2nchw4(b), z = nchw2nchw4(z);
2551 2552 2553 2554 2555 2556
    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 已提交
2557 2558
    auto y = opr::ConvBias::make(
            x, w, b, z, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2559 2560 2561 2562 2563
    y = nchw42nchw(y);
    y = opr::TypeCvt::make(y, dtype::Float32());

    SymbolVar y_opt;
    SymbolVar y_no_tc;
2564 2565
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2566
        options.enable_fuse_conv_bias_nonlinearity().enable_nchw32();
2567 2568 2569 2570 2571 2572 2573
        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);
    }
2574 2575 2576
    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 已提交
2577 2578 2579
    auto func = graph->compile(
            {make_callback_copy(y_no_tc, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
    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 已提交
2593
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2594
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2595
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2596
    };
M
Megvii Engine Team 已提交
2597
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2598
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2599
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
                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 已提交
2616 2617
    auto y = opr::ConvBias::make(
            x, w, b, conv_bias_param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2618 2619 2620 2621

    SymbolVar y_opt;

    // check fuse mode
M
Megvii Engine Team 已提交
2622 2623 2624 2625
    for (auto mode :
         {opr::ElemwiseMultiType::Param::Mode::QADD,
          opr::ElemwiseMultiType::Param::Mode::QMUL,
          opr::ElemwiseMultiType::Param::Mode::QFUSE_ADD_RELU}) {
2626 2627
        auto y1 = opr::ElemwiseMultiType::make(
                {y, b1}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2628 2629 2630 2631
        {
            auto options = gopt::OptimizeForInferenceOptions{};
            options.enable_fuse_conv_bias_nonlinearity()
                    .enable_fuse_conv_bias_with_z()
2632
                    .enable_nchw32();
2633 2634
            unpack_vector(gopt::optimize_for_inference({y1}, options), y_opt);
        }
2635 2636 2637 2638 2639 2640 2641 2642
        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 已提交
2643
                    {y1, b2}, {mode}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
2644 2645 2646 2647
            {
                auto options = gopt::OptimizeForInferenceOptions{};
                options.enable_fuse_conv_bias_nonlinearity()
                        .enable_fuse_conv_bias_with_z()
2648
                        .enable_nchw32();
M
Megvii Engine Team 已提交
2649
                unpack_vector(gopt::optimize_for_inference({y2}, options), y_opt);
2650
            }
M
Megvii Engine Team 已提交
2651
            auto nr_elemwisemultitype = find_opr_num<opr::ElemwiseMultiType>(y_opt);
2652 2653 2654 2655 2656 2657
            ASSERT_NE(0u, nr_elemwisemultitype);
        }
    }
}

#if MGB_CUDA
2658
//! close for cu111 ci, reopen it when bug fixed
2659
#if CUDA_VERSION < 11000
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
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 已提交
2676
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2677
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2678
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2679
    };
M
Megvii Engine Team 已提交
2680
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2681
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2682
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2683 2684
                dtype);
    };
M
Megvii Engine Team 已提交
2685 2686
    auto mkshape = [](opr::ConvBias::Param::Format format, size_t N, size_t C, size_t H,
                      size_t W) -> TensorShape {
2687 2688 2689 2690 2691 2692 2693 2694
        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};
        }
    };
2695

M
Megvii Engine Team 已提交
2696 2697 2698 2699 2700 2701 2702
    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));
2703 2704 2705 2706 2707
        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;
2708

2709
        auto y = opr::ConvBiasForward::make(
M
Megvii Engine Team 已提交
2710
                x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
2711 2712 2713 2714
        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 已提交
2715
                y, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
        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 已提交
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
        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);
2744
        HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2745 2746 2747
        auto func = graph->compile(
                {make_callback_copy(y_cudnn, host_y),
                 make_callback_copy(y_opt, host_y_opt)});
2748 2749
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
2750
    }
2751
}
2752
#endif
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769

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 已提交
2770
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2771
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2772
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2773
    };
M
Megvii Engine Team 已提交
2774
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2775
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2776
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2777 2778
                dtype);
    };
M
Megvii Engine Team 已提交
2779 2780
    std::shared_ptr<HostTensorND> mat =
            std::make_shared<HostTensorND>(cn, TensorShape{32, 3, 3}, dtype::Float32());
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
    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}});
2795

2796 2797
    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NCHW4;
M
Megvii Engine Team 已提交
2798
    auto y1 = opr::WarpPerspective::make(y, mat_var, TensorShape{16, 16}, warp_param);
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
    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 已提交
2814
    auto y2 = opr::WarpPerspective::make(y1, mat_var, TensorShape{16, 16}, warp_param);
2815 2816
    SymbolVar y_opt;
    SymbolVar y_cudnn;
2817 2818
    {
        auto options = gopt::OptimizeForInferenceOptions{};
2819
        options.enable_chwn4();
2820 2821
        unpack_vector(gopt::optimize_for_inference({y2}, options), y_opt);
    }
M
Megvii Engine Team 已提交
2822 2823 2824 2825 2826 2827 2828
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y2}})
                    .endpoint_vars(),
            y_cudnn);
2829 2830

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2831 2832 2833
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
    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 已提交
2854
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2855
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2856
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2857 2858
    };

M
Megvii Engine Team 已提交
2859
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2860
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2861
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
                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 已提交
2908 2909 2910 2911 2912 2913 2914
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y_cudnn);
2915 2916

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
2917 2918 2919
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
    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 已提交
2940
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2941
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2942
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
2943
    };
M
Megvii Engine Team 已提交
2944
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
2945
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
2946
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956
                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 已提交
2957
        auto tshp = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 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
        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 已提交
3022 3023
            ->writeto_fpath(
                    output_file("TestGoptInference.EnableCHWN4ShuffleRemove.json"));
3024 3025 3026 3027
    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 已提交
3028 3029 3030 3031 3032 3033 3034
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FuseConvBiasNonlinPass>()
                    .add_pass<gopt::FuseConvBiasZPass>()
                    .apply({{y4}})
                    .endpoint_vars(),
            y_cudnn);
3035 3036

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3037 3038 3039
    auto func = graph->compile(
            {make_callback_copy(y_cudnn, host_y),
             make_callback_copy(y_opt, host_y_opt)});
3040 3041 3042 3043
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
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 已提交
3060
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3061
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3062
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3063
    };
M
Megvii Engine Team 已提交
3064
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3065
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3066
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3067 3068
                dtype);
    };
3069

3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
    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(
3081 3082
            x, w1, b1, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3083

3084 3085 3086 3087 3088
    // 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));
3089 3090 3091
    auto conv2 = opr::ConvBiasForward::make(
            conv1, w2, b2, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3092

3093 3094 3095 3096 3097 3098 3099 3100
    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 已提交
3101
            conv2, w3, param_deconv, {}, OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3102 3103 3104

    auto deconv1_fp32 = opr::TypeCvt::make(deconv1, dtype::Float32());
    auto y = deconv1_fp32 + opr::TypeCvt::make(b2, dtype::Float32());
3105 3106 3107 3108 3109 3110 3111 3112

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

M
Megvii Engine Team 已提交
3113 3114 3115 3116 3117 3118
    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);
3119 3120
    auto nr_reshape = find_opr_num<mgb::opr::Reshape>(y_opt);
    ASSERT_EQ(2u, nr_reshape);
3121 3122 3123

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3124 3125
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW4GPU.json"));
3126 3127

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3128 3129
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3130 3131 3132 3133
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y, host_y_opt);
}

3134 3135 3136 3137 3138 3139 3140 3141 3142 3143
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 已提交
3144
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3145
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3146
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3147 3148
    };

M
Megvii Engine Team 已提交
3149
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3150
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3151
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
                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 已提交
3163 3164
    auto conv1 = opr::ConvBias::make(
            x, w1, b1, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3165 3166 3167 3168 3169

    // 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 已提交
3170 3171
    auto conv2 = opr::ConvBias::make(
            x, w2, b2, z2, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3172 3173 3174 3175 3176 3177

    // 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 已提交
3178 3179
    auto conv3 = opr::ConvBias::make(
            x, w3, b3, z3, param_conv_bias, {}, OperatorNodeConfig{dtype::Float32()});
3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193

    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 已提交
3194
            if (conv_bias.param().format != opr::ConvBias::Param::Format::NCHW4_NCHW) {
3195 3196 3197 3198 3199 3200 3201 3202 3203
                succ = false;
            }
        }
    };

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

    HostTensorND host_y, host_y_opt;
M
Megvii Engine Team 已提交
3204 3205
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3206 3207 3208 3209 3210
    func->execute();

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

3211 3212
#endif

3213 3214 3215 3216 3217
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 已提交
3218
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3219
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3220
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
3221
    };
M
Megvii Engine Team 已提交
3222
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3223
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3224
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3225 3226 3227
                dtype);
    };
    auto mkcvarf32 = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
3228
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
    };

    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 已提交
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293
    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);
3294 3295
}

3296 3297 3298 3299 3300 3301 3302 3303 3304
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 已提交
3305
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3306 3307 3308
    };

    auto x = mkvar("x", {2, 4, 16, 16});
3309
    // ConvBias test dense
3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
    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 已提交
3332 3333 3334
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW,
            find_opr<opr::ConvBias>(y_opt).param().format);
3335 3336 3337

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

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3341 3342
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3343 3344 3345 3346
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

3347 3348
TEST(TestGoptInference, ConvertFormatNCHW4Ic3) {
    REQUIRE_GPU(1);
3349 3350 3351
    auto cn = CompNode::load("gpu0");
    cn.activate();
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
3352 3353 3354 3355
    HostTensorGenerator<dtype::Float32, RandomDistribution::UNIFORM> gen{
            1.2f, 127 * 127};
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
3356
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3357
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3358
                opr::Host2DeviceCopy::make(*graph, gen(shp)).rename(name), dtype);
3359
    };
M
Megvii Engine Team 已提交
3360
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
3361
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3362
                opr::SharedDeviceTensor::make(*graph, *gen(shp)).rename(name), dtype);
3363 3364 3365 3366 3367 3368 3369 3370 3371
    };

    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 已提交
3372 3373 3374
    auto conv1 = opr::ConvBias::make(
            x, w1, b1, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3375 3376 3377
    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 已提交
3378 3379 3380
    auto conv2 = opr::ConvBias::make(
            conv1, w2, b2, param_conv_bias, {},
            OperatorNodeConfig{dtype::QuantizedS8{2.5f}});
3381 3382 3383 3384 3385 3386 3387 3388 3389
    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 已提交
3390 3391 3392
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4,
            find_opr<opr::ConvBias>(y_opt).param().format);
3393 3394 3395

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3396 3397
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW4Ic3.json"));
3398 3399

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3400 3401
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3402 3403 3404 3405
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

3406 3407 3408 3409 3410 3411 3412 3413 3414
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 已提交
3415
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3416 3417 3418 3419
    };

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
M
Megvii Engine Team 已提交
3420
    //! Hybrid nchw88 mode
3421 3422 3423
    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 已提交
3424 3425
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
M
Megvii Engine Team 已提交
3426
    //! channel wise
3427 3428 3429 3430 3431 3432 3433 3434
    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);
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445
    //! 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);
3446 3447 3448 3449 3450
    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 已提交
3451
    auto resize = opr::ResizeForward::make(reduce1, subtensor * 2, param_resize);
3452 3453 3454 3455 3456
    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 已提交
3457
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
    //! 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;
3469 3470
    {
        auto options = gopt::OptimizeForInferenceOptions{};
3471
        options.enable_nchw88();
3472 3473
        unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
    }
M
Megvii Engine Team 已提交
3474 3475 3476 3477 3478 3479
    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);
3480 3481 3482

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

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3486 3487
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
    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);
}

3498 3499 3500 3501 3502 3503 3504 3505 3506
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 已提交
3507
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3508
    };
3509 3510 3511
    auto mkcvar_dtype = [&](const char* name, const TensorShape& shp,
                            const DType& dtype) {
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3512
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3513 3514
                dtype);
    };
3515 3516 3517

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
3518
    //! Hybrid nchw44 mode
3519 3520 3521
    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 已提交
3522 3523
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
3524 3525 3526 3527 3528

    //! 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 已提交
3529 3530
    auto conv1_f1 = opr::ConvBias::make(
            x, w1_f1, param_conv_bias_pad0, {}, OperatorNodeConfig("conv1_f1"));
3531 3532 3533 3534 3535

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

    //! s8 dense conv
3536 3537
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
3538 3539 3540 3541 3542 3543 3544 3545
    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
3546 3547
    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}),
3548
         conv2 = opr::ConvBias::make(conv_1_2_fp32, w2, b2, param_conv_bias);
3549 3550 3551
    //! 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);
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
    //! 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);
3563 3564 3565 3566 3567
    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 已提交
3568
    auto resize = opr::ResizeForward::make(reduce1, subtensor * 2, param_resize);
3569 3570 3571 3572 3573
    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 已提交
3574
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3575 3576 3577
    //! 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 已提交
3578 3579 3580
    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"));
3581 3582 3583 3584 3585 3586 3587
    //! 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 已提交
3588
                 OperatorNodeConfig{"conv_3_3_q", cn, dtype::QuantizedS8{6.25f}});
3589 3590 3591 3592
    auto conv3_3 = opr::TypeCvt::make(conv3_3_q, dtype::Float32());

    //! Dense
    param_conv_bias.sparse = opr::ConvBias::Param::Sparse::DENSE;
3593
    auto w4 = mkcvar("w4", {16, 32, 3, 3}), b4 = mkcvar("b4", {1, 16, 1, 1}),
M
Megvii Engine Team 已提交
3594 3595 3596 3597 3598 3599
         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"));
3600 3601 3602
    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 已提交
3603 3604
         conv5 = opr::ConvBias::make(
                 conv4_add, w5, b5, param_conv_bias, {}, OperatorNodeConfig("conv5"));
3605
    auto w6 = mkcvar("w6", {4, 6, 3, 3}), b6 = mkcvar("b6", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
3606 3607
         y = opr::ConvBias::make(
                 conv5, w6, b6, param_conv_bias, {}, OperatorNodeConfig("conv6"));
3608

3609
    SymbolVar y_opt;
3610
    auto options = gopt::OptimizeForInferenceOptions{};
3611
    options.enable_fuse_conv_bias_nonlinearity();
3612
    options.enable_nchw44();
3613
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);
3614

M
Megvii Engine Team 已提交
3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635
    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);
3636 3637

    graph->compile({{y_opt, {}}})
3638
            ->to_json()
M
Megvii Engine Team 已提交
3639
            ->writeto_fpath(output_file("TestGoptInference.ConvertFormatNCHW44.json"));
3640 3641

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3642 3643
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3644 3645 3646 3647 3648 3649 3650 3651 3652
    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);
}
3653

3654 3655 3656 3657 3658 3659 3660 3661 3662
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 已提交
3663
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674
    };

    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 已提交
3675
         elem0 = opr::Elemwise::make({conv1 + b + b}, opr::Elemwise::Param::Mode::RELU);
3676 3677 3678 3679 3680

    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 已提交
3681
         y = opr::Elemwise::make({conv2 + b1 + b}, opr::Elemwise::Param::Mode::RELU);
3682 3683 3684 3685 3686 3687

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

M
Megvii Engine Team 已提交
3688 3689 3690
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt).param().format);
3691 3692 3693 3694 3695 3696 3697

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

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3698 3699
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
    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 已提交
3711
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726
    };

    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 已提交
3727 3728 3729
    ASSERT_EQ(
            opr::Convolution::Param::Format::NCHW44,
            find_opr<opr::Convolution>(y_opt).param().format);
3730 3731 3732

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

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3737 3738
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3739 3740 3741 3742 3743
    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);
}

3744 3745 3746 3747 3748 3749 3750 3751 3752
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 已提交
3753
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3754
    };
3755 3756 3757
    auto mkcvar_dtype = [&](const char* name, const TensorShape& shp,
                            const DType& dtype) {
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
3758
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
3759 3760
                dtype);
    };
3761 3762 3763

    auto host_x = gen({2, 3, 16, 16}, cn);
    auto x = opr::Host2DeviceCopy::make(*graph, host_x);
3764
    //! Hybrid nchw44 mode
3765 3766 3767
    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 已提交
3768 3769 3770
         conv1 = opr::Convolution::make(
                 x, w1, param_conv, {}, OperatorNodeConfig("conv1"));
    printf("create conv1 %s\n", conv1.node()->owner_opr()->dyn_typeinfo()->name);
3771 3772 3773 3774 3775 3776
    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 已提交
3777 3778
    auto conv1_f1 = opr::ConvBias::make(
            x, w1_f1, b1, param_conv_bias_pad0, {}, OperatorNodeConfig("conv1_f1"));
3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791

    //! 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
3792 3793
    opr::ConvBias::Param param_conv_bias;
    param_conv_bias.pad_h = param_conv_bias.pad_w = 1;
3794 3795
    auto w1_2 = mkcvar_dtype("w1_2", {8, 8, 3, 3}, dtype::QuantizedS8(2.5f));
    auto conv_1_2 = opr::ConvBias::make(
3796
            conv_1_q8, w1_2, param_conv_bias, {},
3797 3798 3799 3800
            OperatorNodeConfig{"conv_1_2", cn, dtype::QuantizedS8{6.25f}});
    auto conv_1_2_fp32 = opr::TypeCvt::make(conv_1_2, dtype::Float32());

    //! channel wise
3801 3802
    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}),
3803
         conv2 = opr::ConvBias::make(conv_1_2_fp32, w2, b2, param_conv_bias);
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
    //! 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 已提交
3820
         elem = opr::Elemwise::make({warp + b}, opr::Elemwise::Param::Mode::RELU);
3821 3822 3823
    //! 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 已提交
3824 3825 3826
    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"));
3827 3828 3829 3830 3831 3832 3833
    //! 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 已提交
3834
                 OperatorNodeConfig{"conv_3_3_q", cn, dtype::QuantizedS8{6.25f}});
3835 3836 3837 3838 3839
    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 已提交
3840 3841
         conv4 = opr::ConvBias::make(
                 conv3_3, w4, b4, param_conv_bias, {}, OperatorNodeConfig("conv4"));
3842

3843
    auto w5 = mkcvar("w5", {6, 4, 3, 3}), b5 = mkcvar("b5", {1, 6, 1, 1}),
M
Megvii Engine Team 已提交
3844 3845
         conv5 = opr::ConvBias::make(
                 conv4, w5, b5, param_conv_bias, {}, OperatorNodeConfig("conv5"));
3846
    auto w6 = mkcvar("w6", {4, 6, 3, 3}), b6 = mkcvar("b6", {1, 4, 1, 1}),
M
Megvii Engine Team 已提交
3847 3848
         y = opr::ConvBias::make(
                 conv5, w6, b6, param_conv_bias, {}, OperatorNodeConfig("conv6"));
3849

3850
    SymbolVar y_opt;
3851
    auto options = gopt::OptimizeForInferenceOptions{};
3852
    options.enable_fuse_conv_bias_nonlinearity();
3853
    options.enable_nchw44_dot();
3854 3855
    unpack_vector(gopt::optimize_for_inference({y}, options), y_opt);

M
Megvii Engine Team 已提交
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879
    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);
3880 3881 3882

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
3883 3884
            ->writeto_fpath(
                    output_file("TestGoptInference.ConvertFormatNCHW44_DOT.json"));
3885 3886

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3887 3888
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898
    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);
}

3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910
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 已提交
3911
        return opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name);
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
    };

    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 已提交
3937 3938
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3939 3940 3941 3942
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-3);
}

3943 3944 3945
#if MGB_CUDA
TEST(TestGoptInference, PreProcessCase0) {
    REQUIRE_GPU(1);
M
Megvii Engine Team 已提交
3946 3947
    HostTensorGenerator<dtype::Quantized8Asymm, RandomDistribution::UNIFORM> gen(
            dt_quint8(0), dt_quint8(50), 1, 128, 1234);
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961
    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 已提交
3962
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975
    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 已提交
3976
            ->writeto_fpath(output_file("TestGoptInference.PreProcessCase0.json"));
3977 3978

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
3979 3980
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
    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 已提交
4005
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019
    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 已提交
4020
            ->writeto_fpath(output_file("TestGoptInference.PreProcessCase1.json"));
4021 4022

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4023 4024
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4025 4026 4027 4028 4029
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);

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

4031
TEST(TestGoptInference, WarpAndPreProcessCase0) {
4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044
    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 已提交
4045 4046
    auto mat_host =
            std::make_shared<HostTensorND>(cn, TensorShape{n, 3, 3}, dtype::Float32());
4047 4048 4049 4050 4051
    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 已提交
4052
    auto x_warp = opr::WarpPerspective::make(x, mat, TensorShape{h, w}, warp_param);
4053 4054 4055 4056 4057 4058
    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 已提交
4059
    auto pad_channel_tensor = opr::Broadcast::make(zero_tensor, {n, 1, h, w}, cn);
4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073
    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 已提交
4074 4075 4076
    ASSERT_EQ(
            opr::WarpPerspective::Param::Format::NHWC_NCHW4_IC_SMALL,
            find_opr<opr::WarpPerspective>(y_opt).param().format);
4077 4078 4079

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4080 4081
            ->writeto_fpath(
                    output_file("TestGoptInference.WarpAndPreProcessCase0.json"));
4082 4083

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4084 4085
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4086 4087 4088 4089
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}

4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
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 已提交
4104
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4105
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4106
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
                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 已提交
4126 4127 4128
    auto result = opr::ConvBias::make(
            x_s8, weight, bias, param, {},
            OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4129 4130 4131 4132 4133 4134 4135 4136 4137

    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 已提交
4138 4139
            ->writeto_fpath(
                    output_file("TestGoptInference.PreProcessCaseAutopadNCHW64.json"));
4140 4141

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4142 4143
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4144 4145
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
M
Megvii Engine Team 已提交
4146 4147 4148
    ASSERT_TRUE(
            find_opr<opr::RelayoutFormat>(y_opt).param().mode ==
            opr::RelayoutFormat::Param::Mode::NCHW_NCHW4);
4149 4150
}

4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164
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 已提交
4165
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4166
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4167
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179
                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 已提交
4180
    auto host_val = std::make_shared<HostTensorND>(cn, dtype::QuantizedS8(2.5f));
4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
    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 已提交
4198 4199 4200
    auto result = opr::ConvBias::make(
            nhwc_x, weight, bias, param, {},
            OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4201 4202 4203 4204 4205 4206 4207 4208
    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 已提交
4209 4210
            ->writeto_fpath(
                    output_file("TestGoptInference.PreProcessCaseAutopadNHWC.json"));
4211 4212

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4213 4214
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4215 4216
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
M
Megvii Engine Team 已提交
4217 4218 4219
    ASSERT_TRUE(
            find_opr<opr::RelayoutFormat>(y_opt).param().mode ==
            opr::RelayoutFormat::Param::Mode::NCHW_NCHW4);
4220 4221
}

4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235
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 已提交
4236 4237
    auto mat_host =
            std::make_shared<HostTensorND>(cn, TensorShape{n, 3, 3}, dtype::Float32());
4238 4239 4240 4241 4242
    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 已提交
4243
    auto x_warp = opr::WarpPerspective::make(x, mat, TensorShape{h, w}, warp_param);
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255
    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 已提交
4256 4257 4258
    ASSERT_EQ(
            opr::WarpPerspective::Param::Format::NHWC_NCHW,
            find_opr<opr::WarpPerspective>(y_opt).param().format);
4259 4260 4261

    graph->compile({{y_opt, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4262 4263
            ->writeto_fpath(
                    output_file("TestGoptInference.WarpAndPreProcessCase1.json"));
4264 4265

    HostTensorND host_y_opt, host_y;
M
Megvii Engine Team 已提交
4266 4267
    auto func = graph->compile(
            {make_callback_copy(y, host_y), make_callback_copy(y_opt, host_y_opt)});
4268 4269 4270
    func->execute();
    MGB_ASSERT_TENSOR_NEAR(host_y, host_y_opt, 1e-5);
}
4271

4272
#if CUDA_VERSION >= 10020
4273 4274 4275 4276
TEST(TestGoptInference, FoldingConvDimshuffle) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4277
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4278 4279 4280 4281

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4282
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4283
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4284
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4285
    };
M
Megvii Engine Team 已提交
4286
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4287
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4288
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
                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 已提交
4312 4313
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4314 4315 4316
    y = opr::TypeCvt::make(y, dtype::Float32());
    y = nchw42nchw(y);
    SymbolVar y_fuse, y_non_fuse;
M
Megvii Engine Team 已提交
4317 4318 4319 4320 4321 4322 4323 4324
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::ShuffleShuffleRemovePass>()
                    .add_pass<gopt::FoldingConvBiasDimshufflePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_fuse);
4325 4326 4327
    gopt::modify_opr_algo_strategy_inplace(
            {y_fuse},
            opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy::PROFILE);
4328 4329
    graph->compile({{y_fuse, {}}})
            ->to_json()
M
Megvii Engine Team 已提交
4330 4331 4332 4333 4334
            ->writeto_fpath(
                    output_file("TestGoptInference.FoldingConvDimshuffle.json"));
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4_NCHW,
            find_opr<opr::ConvBias>(y_fuse).param().format);
4335
    ASSERT_EQ(0u, find_opr_num<opr::Dimshuffle>(y_fuse));
M
Megvii Engine Team 已提交
4336
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4337
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4338 4339 4340
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4341 4342 4343 4344 4345 4346 4347
    func->execute();
}

TEST(TestGoptInference, FoldingConvDimshuffleNCHW4NCHW32) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4348
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4349 4350 4351 4352

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4353
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4354
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4355
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4356
    };
M
Megvii Engine Team 已提交
4357
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4358
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4359
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386
                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 已提交
4387 4388
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4389 4390 4391
    y = nchw42nchw32(y);
    y = opr::TypeCvt::make(y, dtype::Float32());
    SymbolVar y_fuse, y_non_fuse;
M
Megvii Engine Team 已提交
4392 4393 4394 4395 4396 4397 4398
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::FoldingConvBiasDimshufflePass>()
                    .add_pass<gopt::ParamFusePass>()
                    .apply({{y}})
                    .endpoint_vars(),
            y_fuse);
4399 4400 4401
    gopt::modify_opr_algo_strategy_inplace(
            {y_fuse},
            opr::mixin::AlgoChooserHelper::ExecutionPolicy::Strategy::PROFILE);
4402 4403 4404 4405
    graph->compile({{y_fuse, {}}})
            ->to_json()
            ->writeto_fpath(output_file(
                    "TestGoptInference.FoldingConvDimshuffleNCHW4NCHW32.json"));
M
Megvii Engine Team 已提交
4406 4407 4408
    ASSERT_EQ(
            opr::ConvBias::Param::Format::NCHW4_NCHW32,
            find_opr<opr::ConvBias>(y_fuse).param().format);
4409
    ASSERT_EQ(0u, find_opr_num<opr::Dimshuffle>(y_fuse));
M
Megvii Engine Team 已提交
4410
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4411
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4412 4413 4414
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4415 4416 4417 4418 4419 4420 4421 4422
    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();
4423
    REQUIRE_CUDA_COMPUTE_CAPABILITY(7, 5);
4424 4425 4426 4427

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4428
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4429
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4430
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4431
    };
M
Megvii Engine Team 已提交
4432
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4433
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4434
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448
                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 已提交
4449 4450
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4451
    param.stride_h = param.stride_w = 1;
M
Megvii Engine Team 已提交
4452 4453
    y = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469
    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 已提交
4470
            if (cb->param().format == opr::ConvBias::Param::Format::NCHW32_NCHW4)
4471 4472
                found = true;
        }
M
Megvii Engine Team 已提交
4473
    }}.add(y_fuse.node()->owner_opr());
4474
    EXPECT_TRUE(found);
M
Megvii Engine Team 已提交
4475
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4476
    HostTensorND host_y_fuse, host_y_non_fuse;
M
Megvii Engine Team 已提交
4477 4478 4479
    auto func = graph->compile(
            {make_callback_copy(y_fuse, host_y_fuse),
             make_callback_copy(y_non_fuse, host_y_non_fuse)});
4480 4481 4482
    func->execute();
    MGB_ASSERT_TENSOR_EQ(host_y_fuse, host_y_non_fuse);
}
4483 4484 4485 4486 4487

TEST(TestGoptInference, FoldingConvDimshuffleNCHW4NHWC) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4488
    REQUIRE_CUDA_COMPUTE_CAPABILITY(7, 5);
4489 4490 4491 4492

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4493
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4494
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4495
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4496
    };
M
Megvii Engine Team 已提交
4497
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4498
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4499
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4500 4501 4502 4503
                dtype);
    };

    auto x = mkvar("x", {32, 4, 23, 40}, dtype::QuantizedS8(2.5f)),
4504 4505 4506
         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 已提交
4507
         b1 = mkcvar("b1", {1, 32, 1, 1}, dtype::QuantizedS32(12.34567f * 1.234f));
4508 4509 4510 4511 4512 4513 4514
    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 已提交
4515
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(12.34567f)});
4516
    y = opr::TypeCvt::make(y, dtype::QuantizedS4(12.34567f));
M
Megvii Engine Team 已提交
4517 4518
    y = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS4(56.71234f)});
4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
    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);
4537
    ASSERT_EQ(2u, nr_dimshuffle);
4538 4539 4540 4541 4542 4543 4544
    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 已提交
4545
    }}.add(y_fuse.node()->owner_opr());
4546
    EXPECT_TRUE(found);
M
Megvii Engine Team 已提交
4547
    unpack_vector(gopt::GraphOptimizer{}.apply({{y}}).endpoint_vars(), y_non_fuse);
4548 4549
    gopt::modify_opr_algo_strategy_inplace({y_non_fuse}, strategy);
    HostTensorND host_y_non_fuse;
M
Megvii Engine Team 已提交
4550
    auto func2 = graph->compile({make_callback_copy(y_non_fuse, host_y_non_fuse)});
4551 4552 4553
    func2->execute();
    MGB_ASSERT_TENSOR_EQ(host_y_fuse, host_y_non_fuse);
}
4554
#endif
4555 4556 4557 4558 4559

TEST(TestGoptInference, PaddingChannels) {
    REQUIRE_GPU(1);
    auto cn = CompNode::load("gpu0");
    cn.activate();
4560
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4561 4562 4563 4564

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4565
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4566
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4567
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4568
    };
M
Megvii Engine Team 已提交
4569
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4570
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4571
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583
                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 已提交
4584 4585
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4586 4587
    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 已提交
4588 4589
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4590 4591
    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 已提交
4592 4593
    auto y2 = opr::ConvBias::make(
            y1, w2, b2, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4594 4595 4596 4597 4598 4599
    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 已提交
4600 4601 4602 4603 4604 4605
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y3}})
                    .endpoint_vars(),
            y3_pad);
4606 4607 4608 4609 4610 4611 4612 4613 4614
    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);
4615
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629
    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();
4630
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
M
Megvii Engine Team 已提交
4631

4632 4633 4634
    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4635
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4636
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4637
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4638
    };
M
Megvii Engine Team 已提交
4639
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4640
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4641
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653
                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 已提交
4654 4655
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4656 4657
    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 已提交
4658 4659
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4660 4661 4662 4663
    // 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 已提交
4664 4665 4666 4667 4668 4669
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y2}})
                    .endpoint_vars(),
            y2_pad);
4670 4671 4672 4673 4674 4675 4676 4677 4678
    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);
4679
    ASSERT_EQ(oprs[0]->output(0)->shape()[1], 32);
4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690
    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);
4691 4692
    auto cn = CompNode::load("gpu0");
    cn.activate();
4693
    REQUIRE_CUDA_COMPUTE_CAPABILITY(6, 1);
4694 4695 4696 4697

    HostTensorGenerator<dtype::Int8> gen;
    auto graph = ComputingGraph::make();
    graph->options().graph_opt_level = 0;
M
Megvii Engine Team 已提交
4698
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4699
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4700
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4701
    };
M
Megvii Engine Team 已提交
4702
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4703
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4704
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716
                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 已提交
4717 4718
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4719 4720
    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 已提交
4721 4722
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4723 4724 4725 4726 4727 4728

    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 已提交
4729 4730 4731 4732 4733 4734
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y1_pad);
4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758
    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 已提交
4759
    auto mkvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4760
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4761
                opr::Host2DeviceCopy::make(*graph, gen(shp, cn)).rename(name), dtype);
4762
    };
M
Megvii Engine Team 已提交
4763
    auto mkcvar = [&](const char* name, const TensorShape& shp, const DType& dtype) {
4764
        return opr::TypeCvt::make(
M
Megvii Engine Team 已提交
4765
                opr::SharedDeviceTensor::make(*graph, *gen(shp, cn)).rename(name),
4766 4767 4768
                dtype);
    };

M
Megvii Engine Team 已提交
4769 4770
    std::shared_ptr<HostTensorND> mat =
            std::make_shared<HostTensorND>(cn, TensorShape{16, 3, 3}, dtype::Float32());
4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
    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 已提交
4783 4784
    auto y = opr::ConvBias::make(
            x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4785 4786
    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 已提交
4787 4788
    auto y1 = opr::ConvBias::make(
            y, w1, b1, param, {}, OperatorNodeConfig{dtype::QuantizedS8(2.5f)});
4789 4790 4791

    opr::WarpPerspective::Param warp_param;
    warp_param.format = opr::WarpPerspective::Param::Format::NCHW;
M
Megvii Engine Team 已提交
4792
    y1 = opr::WarpPerspective::make(y1, mat_var, TensorShape{14, 14}, warp_param);
4793 4794
    y1 = opr::TypeCvt::make(y1, dtype::Float32());
    SymbolVar y1_pad;
M
Megvii Engine Team 已提交
4795 4796 4797 4798 4799 4800
    unpack_vector(
            gopt::GraphOptimizer{}
                    .add_pass<gopt::PaddingChannelPass>()
                    .apply({{y1}})
                    .endpoint_vars(),
            y1_pad);
4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816
    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);
}
4817

4818 4819
#endif

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