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

#include "megbrain/opr/blas.h"
M
Megvii Engine Team 已提交
13
#include <random>
14 15
#include "megbrain/comp_node_env.h"
#include "megbrain/opr/basic_arith_wrapper.h"
M
Megvii Engine Team 已提交
16
#include "megbrain/opr/io.h"
17
#include "megbrain/opr/tensor_gen.h"
M
Megvii Engine Team 已提交
18
#include "megbrain/opr/tensor_manip.h"
19
#include "megbrain/serialization/serializer.h"
M
Megvii Engine Team 已提交
20 21 22
#include "megbrain/test/autocheck.h"
#include "megbrain/test/helper.h"
#include "megbrain/test/megdnn_helper.h"
23 24 25 26 27

using namespace mgb;

namespace {
template <typename dt_src, typename dt_dst>
M
Megvii Engine Team 已提交
28 29 30
void brute_force_gemm(
        size_t M, size_t N, size_t K, bool transa, bool transb, const dt_src* x,
        const dt_src* y, dt_dst* z) {
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    for (size_t m = 0; m < M; ++m)
        for (size_t n = 0; n < N; ++n) {
            dt_dst cur = dt_dst(0);
            for (size_t k = 0; k < K; ++k) {
                cur += x[transa ? (k * M + m) : (m * K + k)] *
                       y[transb ? (n * K + k) : (k * N + n)];
            }
            z[m * N + n] = cur;
        }
}

float brute_force_dot(const HostTensorND& a, const HostTensorND& b) {
    auto sz = std::max(a.shape(0), b.shape(0));
    size_t ap = 0, bp = 0;
    float ret = 0;
    auto pa = a.ptr<float>(), pb = b.ptr<float>();
    auto as = a.layout().stride[0], bs = b.layout().stride[0];
    if (a.shape(0) != sz)
        as = 0;
    if (b.shape(0) != sz)
        bs = 0;
    for (size_t i = 0; i < sz; ++i) {
        ret += pa[ap] * pb[bp];
        ap += as;
        bp += bs;
    }
    return ret;
}

// (m,k) * (k,n) = (m,n)
void run_sgemm_test(bool transa, bool transb) {
    using Checker = AutoOprChecker<2, 1>;
M
Megvii Engine Team 已提交
63
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
64 65 66 67 68 69 70 71 72 73 74
        auto param = opr::MatrixMul::Param{transa, transb};
        return {opr::MatrixMul::make(inputs[0], inputs[1], param)};
    };
    auto fwd = [&](Checker::NumOutArray& dest, Checker::NumInpArray inp) {
        size_t M, N, K;
        M = inp[0]->shape().shape[0];
        K = inp[0]->shape().shape[1];
        if (transa)
            std::swap(M, K);
        N = inp[1]->shape().shape[transb ? 0 : 1];

M
Megvii Engine Team 已提交
75
        auto z = dest[0].comp_node(inp[0]->comp_node()).resize({M, N}).ptr<float>();
76
        // brute-force gemm
M
Megvii Engine Team 已提交
77 78
        brute_force_gemm(
                M, N, K, transa, transb, inp[0]->ptr<float>(), inp[1]->ptr<float>(), z);
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    };

    auto mkshp = [](bool trans, size_t m, size_t k) {
        TensorShape rst{m, k};
        if (trans)
            std::swap(rst.shape[0], rst.shape[1]);
        return rst;
    };
    using namespace std::placeholders;
    auto mkx = std::bind(mkshp, transa, _1, _2);
    auto mky = std::bind(mkshp, transb, _1, _2);

    Checker::RunOptions opt;
    opt.numdiff_eps = 1;
    Checker(make_graph, fwd)
            .run({mkx(4, 6), mky(6, 2)}, opt)
            .run({mkx(2, 3), mky(3, 100)}, opt)
96 97 98
            .run({mkx(20, 3), mky(3, 20)}, opt)
            .run({mkx(10, 0), mky(0, 10)}, opt)
            .run({mkx(0, 0), mky(0, 0)}, opt);
99 100
}

M
Megvii Engine Team 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
#define FWD_BATCH_GEMM(dt_src, dt_dst)                                             \
    [transa, transb](Checker::NumOutArray& dest, Checker::NumInpArray inp) {       \
        bool ta(transa), tb(transb);                                               \
        HostTensorND a, b;                                                         \
        size_t B, M, N, K;                                                         \
        a.copy_from(*(inp[0]));                                                    \
        b.copy_from(*(inp[1]));                                                    \
        B = a.shape().shape[0];                                                    \
        M = a.shape().shape[1];                                                    \
        K = a.shape().shape[2];                                                    \
        N = b.shape().shape[tb ? 1 : 2];                                           \
        if (ta)                                                                    \
            std::swap(M, K);                                                       \
        auto x = a.ptr<dt_src>(), y = b.ptr<dt_src>();                             \
        auto z = dest[0].resize({B, M, N}).ptr<dt_dst>();                          \
        for (size_t b = 0; b < B; ++b) {                                           \
            brute_force_gemm(                                                      \
                    M, N, K, ta, tb, x + b * M * K, y + b * K * N, z + b * M * N); \
        }                                                                          \
120 121 122 123
    }

void run_batched_sgemm_test(bool transa, bool transb) {
    using Checker = AutoOprChecker<2, 1>;
M
Megvii Engine Team 已提交
124 125
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
        return {opr::BatchedMatrixMul::make(inputs[0], inputs[1], {transa, transb})};
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    };

    auto fwd = FWD_BATCH_GEMM(float, float);

    auto mkshp = [](bool trans, size_t b, size_t m, size_t k) {
        TensorShape rst{b, m, k};
        if (trans)
            std::swap(rst.shape[1], rst.shape[2]);
        return rst;
    };
    using namespace std::placeholders;
    auto mkx = std::bind(mkshp, transa, _1, _2, _3);
    auto mky = std::bind(mkshp, transb, _1, _2, _3);

    Checker::RunOptions opt;
    opt.numdiff_eps = 1;
    Checker(make_graph, fwd)
            .run({mkx(3, 5, 7), mky(3, 7, 2)}, opt)
            .run({mkx(64, 1, 2), mky(64, 2, 1)}, opt)
145 146 147
            .run({mkx(1, 2, 3), mky(1, 3, 4)}, opt)
            .run({mkx(3, 0, 2), mky(3, 2, 0)}, opt)
            .run({mkx(64, 10, 0), mky(64, 0, 10)}, opt);
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
}

auto gen_fp16 = [](HostTensorND& dest) {
    RNGxorshf rng{next_rand_seed()};
    auto rand_real = [&rng]() {
        std::uniform_real_distribution<float> dist(-1, 1);
        return dist(rng);
    };
    auto ptr = dest.ptr<dt_float16>();
    size_t elems = dest.shape().total_nr_elems();
    for (size_t i = 0; i < elems; i++) {
        ptr[i] = dt_float16(rand_real());
    }
};

auto gen_int8 = [](HostTensorND& dest) {
M
Megvii Engine Team 已提交
164 165
    HostTensorGenerator<dtype::Int8, RandomDistribution::UNIFORM> int8_generator{
            -128, 127};
166 167 168 169 170
    dest = *int8_generator(dest.shape(), dest.comp_node());
};

void run_batched_hgemm_test(bool transa, bool transb) {
    using Checker = AutoOprChecker<2, 1>;
M
Megvii Engine Team 已提交
171 172
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
        return {opr::BatchedMatrixMul::make(inputs[0], inputs[1], {transa, transb})};
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    };
    auto fwd = FWD_BATCH_GEMM(dt_float16, dt_float16);
    auto mkshp = [](bool trans, size_t b, size_t m, size_t k) {
        TensorShape rst{b, m, k};
        if (trans)
            std::swap(rst.shape[1], rst.shape[2]);
        return rst;
    };

    using namespace std::placeholders;
    auto mkx = std::bind(mkshp, transa, _1, _2, _3);
    auto mky = std::bind(mkshp, transb, _1, _2, _3);

    Checker checker(make_graph, fwd);
    Checker::RunOptions opt;
    opt.outputs_max_err = 1e-2;

    checker.set_input_dtype(0, dtype::Float16())
            .set_input_dtype(1, dtype::Float16())
            .set_input_generator(0, gen_fp16)
            .set_input_generator(1, gen_fp16)
            .set_input_allow_grad(0, false)
            .set_input_allow_grad(1, false)
            .set_output_allow_grad(0, false);

    checker.run({mkx(3, 5, 7), mky(3, 7, 2)}, opt)
            .run({mkx(64, 1, 2), mky(64, 2, 1)}, opt)
200
            .run({mkx(64, 10, 0), mky(64, 0, 10)}, opt)
201 202 203 204 205
            .run({mkx(1, 2, 3), mky(1, 3, 4)}, opt);
}

void run_batched_igemm_test(bool transa, bool transb) {
    using Checker = AutoOprChecker<2, 1>;
M
Megvii Engine Team 已提交
206 207
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
        return {opr::BatchedMatrixMul::make(inputs[0], inputs[1], {transa, transb})};
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    };

    auto fwd = FWD_BATCH_GEMM(int8_t, int32_t);

    auto mkshp = [](bool trans, size_t b, size_t m, size_t k) {
        TensorShape rst{b, m, k};
        if (trans)
            std::swap(rst.shape[1], rst.shape[2]);
        return rst;
    };

    using namespace std::placeholders;
    auto mkx = std::bind(mkshp, transa, _1, _2, _3);
    auto mky = std::bind(mkshp, transb, _1, _2, _3);

    Checker::RunOptions opt;
    opt.numdiff_eps = 1;
    Checker checker(make_graph, fwd);

    checker.set_input_dtype(0, dtype::Int8())
            .set_input_dtype(1, dtype::Int8())
            .set_input_generator(0, gen_int8)
            .set_input_generator(1, gen_int8)
            .set_input_allow_grad(0, false)
            .set_input_allow_grad(1, false)
            .set_output_allow_grad(0, false);

    checker.run({mkx(3, 5, 7), mky(3, 7, 2)}, opt)
            .run({mkx(64, 1, 2), mky(64, 2, 1)}, opt)
237
            .run({mkx(64, 10, 0), mky(64, 0, 10)}, opt)
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
            .run({mkx(1, 2, 3), mky(1, 3, 4)}, opt);
}

template <typename ctype>
float getter(ctype val) {
    return val;
}

template <>
float getter<dt_qint32>(dt_qint32 val) {
    return (float)val.as_int32();
}

template <typename dt_src, typename dt_dst>
void run_trans_inp_test_case(bool trans_a, bool trans_b) {
    HostTensorGenerator<typename DTypeTrait<dt_src>::dtype> gen;
    std::shared_ptr<HostTensorND> host_x = gen({1, 1}), host_y = gen({1, 1});
    auto graph = ComputingGraph::make();
M
Megvii Engine Team 已提交
256
    auto do_trans = [](SymbolVar x) { return opr::Dimshuffle::make(x, {1, 0}); };
257 258 259 260 261 262 263 264 265 266 267 268
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y);
    if (trans_a) {
        x = do_trans(x);
    }
    if (trans_b) {
        y = do_trans(y);
    }
    OperatorNodeConfig config;
    if (DTypeTrait<dt_dst>::enumv == DTypeEnum::Int16) {
        config.output_dtype(dtype::Int16());
    }
269
    auto z = opr::MatrixMul::make(x, y, {}, {}, config);
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    HostTensorND host_z;
    auto func = graph->compile({make_callback_copy(z, host_z)});

    auto run = [&](size_t M, size_t K, size_t N) {
        *host_x = *(trans_a ? gen({K, M}) : gen({M, K}));
        *host_y = *(trans_b ? gen({N, K}) : gen({K, N}));
        func->execute();
        ASSERT_EQ(TensorShape({M, N}), host_z.shape());
        ASSERT_EQ(!trans_a, x.node()->dev_tensor().layout().is_contiguous());
        ASSERT_EQ(!trans_b, y.node()->dev_tensor().layout().is_contiguous());

        auto px = host_x->ptr<dt_src>(), py = host_y->ptr<dt_src>();
        auto pz = host_z.ptr<dt_dst>();
        auto make_strd = [](bool trans, int h, int w, int* dst) {
            if (trans) {
                dst[0] = 1;
                dst[1] = h;
            } else {
                dst[0] = w;
                dst[1] = 1;
            }
        };
        int strd_x[2], strd_y[2];
        make_strd(trans_a, M, K, strd_x);
        make_strd(trans_b, K, N, strd_y);
        for (size_t i = 0; i < M; ++i) {
            for (size_t j = 0; j < N; ++j) {
                dt_dst sum = 0;
                for (size_t k = 0; k < K; ++k) {
                    dt_dst xv = px[i * strd_x[0] + k * strd_x[1]],
                           yv = py[k * strd_y[0] + j * strd_y[1]];
                    sum += xv * yv;
                }
                MGB_ASSERT_FLOAT_EQ(getter(sum), getter(pz[i * N + j]))
                        << trans_a << ' ' << trans_b;
            }
        }
    };
    run(4, 8, 12);
    run(8, 12, 16);
}

template <typename dt_src, typename dt_dst>
void run_trans_inp_test() {
    for (bool ta : {false, true}) {
        for (bool tb : {false, true}) {
            run_trans_inp_test_case<dt_src, dt_dst>(ta, tb);
        }
    }
}

template <typename dt_src, typename dt_dst>
void inline mul_add(dt_src& a, dt_src& b, dt_dst& c) {
    c += dt_dst(a) * dt_dst(b);
}

template <>
void inline mul_add(dt_qint8& a, dt_qint8& b, dt_qint32& c) {
    c += dt_qint32(a.as_int8()) * dt_qint32(b.as_int8());
}

template <typename dt_gen>
std::shared_ptr<HostTensorND> bgemm_gen(const TensorShape& shp) {
    HostTensorGenerator<typename DTypeTrait<dt_gen>::dtype> gen;
    return gen(shp);
}

template <>
std::shared_ptr<HostTensorND> bgemm_gen<dt_float16>(const TensorShape& shp) {
    CompNode cn = CompNode::load("xpu0");
    std::shared_ptr<HostTensorND> ret =
            std::make_shared<HostTensorND>(cn, dtype::Float16{});
    (*ret).resize(shp);
    gen_fp16(*ret);
    return ret;
}

template <typename dt_src, typename dt_dst>
void run_bgemm_trans_inp_test_case(bool trans_a, bool trans_b) {
    std::shared_ptr<HostTensorND> host_x = bgemm_gen<dt_src>({1, 1, 1}),
                                  host_y = bgemm_gen<dt_src>({1, 1, 1});

    auto graph = ComputingGraph::make();
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y);

    trans_a ? (x = opr::Dimshuffle::make(x, {0, 2, 1})) : 0;
    trans_b ? (y = opr::Dimshuffle::make(y, {0, 2, 1})) : 0;

359
    auto z = opr::BatchedMatrixMul::make(x, y, {}, {}, OperatorNodeConfig{});
360 361 362
    HostTensorND host_z;
    auto func = graph->compile({make_callback_copy(z, host_z)});
    auto run = [&](size_t B, size_t M, size_t K, size_t N) {
M
Megvii Engine Team 已提交
363 364 365 366
        *host_x = *(
                trans_a ? bgemm_gen<dt_src>({B, K, M}) : bgemm_gen<dt_src>({B, M, K}));
        *host_y = *(
                trans_b ? bgemm_gen<dt_src>({B, N, K}) : bgemm_gen<dt_src>({B, K, N}));
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
        func->execute();
        ASSERT_EQ(TensorShape({B, M, N}), host_z.shape());
        ASSERT_EQ(!trans_a, x.node()->dev_tensor().layout().is_contiguous());
        ASSERT_EQ(!trans_b, y.node()->dev_tensor().layout().is_contiguous());

        int strd_x[3], strd_y[3];
        auto px = host_x->ptr<dt_src>(), py = host_y->ptr<dt_src>();
        auto pz = host_z.ptr<dt_dst>();
        auto make_strd = [](bool trans, int h, int w, int* dst) {
            dst[0] = h * w;
            dst[1] = trans ? 1 : w;
            dst[2] = trans ? h : 1;
        };
        make_strd(trans_a, M, K, strd_x);
        make_strd(trans_b, K, N, strd_y);
        for (size_t b = 0; b < B; ++b)
            for (size_t i = 0; i < M; ++i)
                for (size_t j = 0; j < N; ++j) {
                    dt_dst sum = dt_dst(0);
                    for (size_t k = 0; k < K; ++k) {
M
Megvii Engine Team 已提交
387 388
                        dt_src xv = px[b * strd_x[0] + i * strd_x[1] + k * strd_x[2]],
                               yv = py[b * strd_y[0] + k * strd_y[1] + j * strd_y[2]];
389 390
                        mul_add(xv, yv, sum);
                    }
M
Megvii Engine Team 已提交
391 392
                    MGB_ASSERT_FLOAT_NEAR(
                            getter(sum), getter(pz[(b * M + i) * N + j]), 5e-3)
393 394 395 396 397 398 399 400 401
                            << trans_a << ' ' << trans_b;
                }
    };
    run(2, 4, 8, 12);
    run(2, 8, 12, 16);
}

}  // anonymous namespace

402
TEST(TestOprBlas, MatrixMul_NN) {
403
    run_sgemm_test(false, false);
404 405 406
}

TEST(TestOprBlas, MatrixMul_NT) {
407
    run_sgemm_test(false, true);
408 409 410
}

TEST(TestOprBlas, MatrixMul_TN) {
411
    run_sgemm_test(true, false);
412 413 414
}

TEST(TestOprBlas, MatrixMul_TT) {
415 416 417
    run_sgemm_test(true, true);
}

418 419 420 421 422 423 424 425 426
TEST(TestOprDNN, MatrixMulExePolicy) {
    using Param = opr::MatrixMul::Param;
    Param param;
    using Policy = opr::MatrixMul::ExecutionPolicy;
    using S = Policy::Strategy;

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

#if MGB_ENABLE_FASTRUN
M
Megvii Engine Team 已提交
427 428 429
    for (auto strategy : SmallVector<S>{
                 S::PROFILE, S::HEURISTIC, S::PROFILE | S::REPRODUCIBLE,
                 S::PROFILE | S::HEURISTIC}) {
430
#else
M
Megvii Engine Team 已提交
431
    for (auto strategy : {S : HEURISTIC, S::PROFILE | S::HEURISTIC}) {
432 433 434 435 436 437
#endif

        auto graph = ComputingGraph::make();
        HostTensorGenerator<> gen;

        auto mkvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
438
            return opr::Host2DeviceCopy::make(*graph, gen(shp), cn).rename(name);
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
        };

        auto A = mkvar("A", {32, 64});
        auto B = mkvar("B", {64, 32});

        Policy policy;
        policy.strategy = strategy;

        auto C = opr::MatrixMul::make(A, B, param, policy);
        HostTensorND host_c;
        auto func = graph->compile({make_callback_copy(C, host_c)});
        func->execute();
    }
}

454
TEST(TestOprBlas, BatchedMatrixMulFp32_NN) {
455
    run_batched_sgemm_test(false, false);
456 457 458
}

TEST(TestOprBlas, BatchedMatrixMulFp32_NT) {
459
    run_batched_sgemm_test(false, true);
460 461 462
}

TEST(TestOprBlas, BatchedMatrixMulFp32_TN) {
463
    run_batched_sgemm_test(true, false);
464 465 466
}

TEST(TestOprBlas, BatchedMatrixMulFp32_TT) {
467 468 469
    run_batched_sgemm_test(true, true);
}

470
TEST(TestOprBlas, BatchedMatrixMulFp16_NN) {
471
    run_batched_hgemm_test(false, false);
472 473 474
}

TEST(TestOprBlas, BatchedMatrixMulFp16_NT) {
475
    run_batched_hgemm_test(false, true);
476 477 478
}

TEST(TestOprBlas, BatchedMatrixMulFp16_TN) {
479
    run_batched_hgemm_test(true, false);
480 481 482
}

TEST(TestOprBlas, BatchedMatrixMulFp16_TT) {
483 484 485
    run_batched_hgemm_test(true, true);
}

486
TEST(TestOprBlas, BatchedMatrixMulInt8_NN) {
487 488 489 490 491
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
    run_batched_igemm_test(false, false);
492 493 494 495 496 497 498
}

TEST(TestOprBlas, BatchedMatrixMulInt8_NT) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
499
    run_batched_igemm_test(false, true);
500 501 502 503 504 505 506
}

TEST(TestOprBlas, BatchedMatrixMulInt8_TN) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
507
    run_batched_igemm_test(true, false);
508 509 510 511 512 513 514
}

TEST(TestOprBlas, BatchedMatrixMulInt8_TT) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
515 516 517
    run_batched_igemm_test(true, true);
}

518
TEST(TestOprBlas, TransBatchedMatrixMulFp32_NN) {
519
    run_bgemm_trans_inp_test_case<float, float>(false, false);
520 521 522
}

TEST(TestOprBlas, TransBatchedMatrixMulFp32_NT) {
523
    run_bgemm_trans_inp_test_case<float, float>(false, true);
524 525 526
}

TEST(TestOprBlas, TransBatchedMatrixMulFp32_TN) {
527
    run_bgemm_trans_inp_test_case<float, float>(true, false);
528 529 530
}

TEST(TestOprBlas, TransBatchedMatrixMulFp32_TT) {
531 532 533
    run_bgemm_trans_inp_test_case<float, float>(true, true);
}

534
TEST(TestOprBlas, TransBatchedMatrixMulInt8_NN) {
535 536 537 538 539
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
    run_bgemm_trans_inp_test_case<int8_t, int32_t>(false, false);
540 541 542 543 544 545 546
}

TEST(TestOprBlas, TransBatchedMatrixMulInt8_NT) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
547
    run_bgemm_trans_inp_test_case<int8_t, int32_t>(false, true);
548 549 550 551 552 553 554
}

TEST(TestOprBlas, TransBatchedMatrixMulInt8_TN) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
555
    run_bgemm_trans_inp_test_case<int8_t, int32_t>(true, false);
556 557 558 559 560 561 562
}

TEST(TestOprBlas, TransBatchedMatrixMulInt8_TT) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
563 564 565
    run_bgemm_trans_inp_test_case<int8_t, int32_t>(true, true);
}

566
TEST(TestOprBlas, TransBatchedMatrixMulFp16_NN) {
567
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(false, false);
568 569 570
}

TEST(TestOprBlas, TransBatchedMatrixMulFp16_NT) {
571
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(false, true);
572 573 574
}

TEST(TestOprBlas, TransBatchedMatrixMulFp16_TN) {
575
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(true, false);
576 577 578
}

TEST(TestOprBlas, TransBatchedMatrixMulFp16_TT) {
579 580 581
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(true, true);
}

582
TEST(TestOprBlas, TransBatchedMatrixMulQS8_NN) {
583 584 585 586 587
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
    run_bgemm_trans_inp_test_case<dt_qint8, dt_qint32>(false, false);
588 589 590 591 592 593 594
}

TEST(TestOprBlas, TransBatchedMatrixMulQS8_NT) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
595
    run_bgemm_trans_inp_test_case<dt_qint8, dt_qint32>(false, true);
596 597 598 599 600 601 602
}

TEST(TestOprBlas, TransBatchedMatrixMulQS8_TN) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
603
    run_bgemm_trans_inp_test_case<dt_qint8, dt_qint32>(true, false);
604 605 606 607 608 609 610
}

TEST(TestOprBlas, TransBatchedMatrixMulQS8_TT) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
611 612 613 614 615 616 617 618
    run_bgemm_trans_inp_test_case<dt_qint8, dt_qint32>(true, true);
}

TEST(TestOprBlas, DotBasic) {
    HostTensorGenerator<> gen;
    auto host_x = gen({123}), host_y = gen({123});
    auto graph = ComputingGraph::make();
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
M
Megvii Engine Team 已提交
619
         y = opr::Host2DeviceCopy::make(*graph, host_y), z = opr::Dot::make(x, y);
620 621 622
    HostTensorND host_z;
    auto func = graph->compile({make_callback_copy(z, host_z)});
    func->execute();
M
Megvii Engine Team 已提交
623
    MGB_ASSERT_FLOAT_EQ(brute_force_dot(*host_x, *host_y), *host_z.ptr<float>());
624 625 626 627 628
}

TEST(TestOprBlas, Dot) {
    using Checker = AutoOprChecker<2, 1>;

M
Megvii Engine Team 已提交
629
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
630 631 632 633 634 635 636 637 638 639 640 641 642
        return {opr::Dot::make(inputs[0], inputs[1])};
    };

    auto fwd = [](Checker::NumOutArray& dest, Checker::NumInpArray inp) {
        auto &&i0 = *inp[0], &&i1 = *inp[1];
        auto&& out = dest[0].resize({1});
        *out.ptr<float>() = brute_force_dot(i0, i1);
    };

    Checker(make_graph, fwd)
            .run({TensorShape{15}, TensorShape{1}})
            .run({TensorShape{1}, TensorShape{16}})
            .run({TensorShape{23}, TensorShape{23}})
643 644
            .run({TensorShape{1000}, TensorShape{1000}})
            .run({TensorShape{0}, TensorShape{0}});
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
}

TEST(TestOprBlas, TransMatMul) {
    run_trans_inp_test<float, float>();
}

TEST(TestOprBlas, TransMatMul8x8x16) {
    if (CompNode::load("xpux").device_type() != CompNode::DeviceType::CUDA) {
        run_trans_inp_test<dt_int8, dt_int16>();
    } else {
        printf("testcase skipped on unsupported arch\n");
    }
}

TEST(TestOprBlas, TransMatMul8x8x32) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
    run_trans_inp_test<dt_int8, dt_int32>();
}

TEST(TestOprBlas, NonContigMatmul) {
    using Checker = AutoOprChecker<2, 1>;
M
Megvii Engine Team 已提交
669
    auto make_graph = [](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        using Ad = opr::Subtensor::AxisIndexer;
        auto x = inputs[0],
             xsub = opr::Subtensor::make(
                     x, {Ad::make_interval(0, None, None, x.make_scalar(2))}),
             y = inputs[1],
             ysub = opr::Subtensor::make(
                     y, {Ad::make_interval(1, None, None, x.make_scalar(3))});
        return {opr::MatrixMul::make(xsub, ysub)};
    };
    auto fwd = [](Checker::NumOutArray& dest, Checker::NumInpArray inp) {
        auto &&shp0 = inp[0]->shape(), &&shp1 = inp[1]->shape();
        size_t m = (shp0.shape[0] + 1) / 2, k = shp0.shape[1],
               n = (shp1.shape[1] + 2) / 3;
        auto dptr = dest[0].resize({m, n}).ptr<float>();
        memset(dptr, 0, sizeof(float) * m * n);
        for (size_t i = 0; i < m; ++i) {
M
Megvii Engine Team 已提交
686
            auto ptr_a = inp[0]->ptr<float>({i * 2}), ptr_c = dest[0].ptr<float>({i});
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
            for (size_t kk = 0; kk < k; ++kk) {
                auto va = ptr_a[kk];
                auto ptr_b = inp[1]->ptr<float>({kk});
                for (size_t j = 0; j < n; ++j) {
                    ptr_c[j] += va * ptr_b[j * 3];
                }
            }
        }
    };

    Checker(make_graph, fwd)
            .run({TensorShape{2, 1}, TensorShape{1, 3}})
            .run({TensorShape{5, 2}, TensorShape{2, 6}})
            .run({TensorShape{6, 3}, TensorShape{3, 8}});
}

TEST(TestOprBlas, MatrixInverse) {
    using Checker = AutoOprChecker<1, 1>;
M
Megvii Engine Team 已提交
705
    auto make_graph = [=](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
706 707 708
        return {opr::MatrixInverse::make(inputs[0])};
    };
    auto fwd = [=](Checker::NumOutArray& dest, Checker::NumInpArray inp) {
M
Megvii Engine Team 已提交
709
        auto opr = megdnn_naive_handle()->create_operator<megdnn::MatrixInverse>();
710

M
Megvii Engine Team 已提交
711
        auto wk_size = opr->get_workspace_in_bytes(inp[0]->layout(), inp[0]->layout());
712
        std::unique_ptr<dt_byte[]> wk{new dt_byte[wk_size]};
M
Megvii Engine Team 已提交
713 714 715
        opr->exec(
                inp[0]->as_megdnn(), dest[0].resize(inp[0]->shape()).as_megdnn(),
                {wk.get(), wk_size});
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    };
    // ensure low condition number for generated matrices
    auto input_coord = [](const Checker::NumInpArray& inp) {
        auto shp = inp[0]->shape();
        size_t n = shp[shp.ndim - 1];
        size_t batch = 1;
        for (size_t i = 0; i < shp.ndim - 2; ++i) {
            batch *= shp[i];
        }
        std::vector<int> perm(n);
        for (size_t i = 0; i < n; ++i) {
            perm[i] = i;
        }
        auto ptr = inp[0]->ptr<float>();
        for (size_t i = 0; i < batch; ++i, ptr += n * n) {
731 732 733 734
#if __cplusplus >= 201703L
            std::default_random_engine rng_engine;
            std::shuffle(perm.begin(), perm.end(), rng_engine);
#else
735
            std::random_shuffle(perm.begin(), perm.end());
736
#endif
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
            for (size_t j = 0; j < n; ++j) {
                ptr[j * n + perm[j]] += 5;
            }
        }
    };

    Checker{make_graph, fwd}
            .set_input_coordinator(input_coord)
            .run({TensorShape{5, 5}})
            .run({TensorShape{2, 5, 5}})
            .run({TensorShape{2, 6, 3, 3}});
}

namespace {

void gen_svd_input(HostTensorND& dest) {
    auto ptr = dest.ptr<float>();
    auto dim = dest.layout().ndim;
    size_t n = dest.layout().shape[dim - 2], m = dest.layout().shape[dim - 1];
    size_t j = 0, k = 0;
    float batch_off = 0;
    float max_val = std::min(m, n) * std::min(m, n) + 0.99;
    for (size_t i = 0, it = dest.layout().total_nr_elems(); i < it; ++i) {
        if (i % (n * m) == 0) {
            batch_off += 0.32;
            j = k = 0;
        }
        if (!((i % (n * m)) % (m + 1)))
            ptr[i] = (j++) + ((++k / 10.0));
        else
            ptr[i] = (j++);
        ptr[i] += batch_off;
        ptr[i] = std::fmod(ptr[i], max_val);
    }
}

template <int have_u, int have_s, int have_v>
void run_svd_empty_grad_test() {
    using Checker = AutoOprChecker<1, have_u + have_s + have_v>;
    auto make_graph = [=](const typename Checker::SymInpArray& inputs) {
        auto out = opr::SVD::make(inputs[0], opr::SVD::Param{false, true});
        typename Checker::SymOutArray ret;
        int idx = 0;
        if (have_u) {
            ret[idx++] = out[0];
        }
        if (have_s) {
            ret[idx++] = out[1];
        }
        if (have_v) {
            ret[idx++] = out[2];
        }
        return ret;
    };
    auto fwd = [=](typename Checker::NumOutArray& dest,
                   typename Checker::NumInpArray inp) {
        auto opr = megdnn_naive_handle()->create_operator<megdnn::SVDForward>();
        opr->param().compute_uv = true;
        TensorLayout ul, sl, vtl;
        opr->deduce_layout(inp[0]->layout(), ul, sl, vtl);
M
Megvii Engine Team 已提交
797 798 799
        HostTensorND tmp_u{dest[0].comp_node(), ul}, tmp_s{dest[0].comp_node(), sl},
                tmp_v{dest[0].comp_node(), vtl};
        auto wk_size = opr->get_workspace_in_bytes(inp[0]->layout(), ul, sl, vtl);
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
        auto wk = std::make_unique<dt_byte[]>(wk_size);
        auto out0 = tmp_u.as_megdnn(), out1 = tmp_s.as_megdnn(),
             out2 = tmp_v.as_megdnn();
        int idx = 0;
        if (have_u) {
            out0 = dest[idx++].resize(ul).as_megdnn();
        }
        if (have_s) {
            out1 = dest[idx++].resize(sl).as_megdnn();
        }
        if (have_v) {
            out2 = dest[idx++].resize(vtl).as_megdnn();
        }
        opr->exec(inp[0]->as_megdnn(), out0, out1, out2, {wk.get(), wk_size});
    };
    Checker checker{make_graph, fwd};
    checker.set_input_generator(0, gen_svd_input);
    if (have_u) {
        checker.set_output_allow_check(0, false);
    }
    if (have_v) {
        checker.set_output_allow_check(have_u + have_s, false);
    }
    checker.run({TensorShape{3, 3}})
            .run({TensorShape{2, 3, 3}})
            .run({TensorShape{2, 4, 2}})
            .run({TensorShape{3, 1, 2, 4}})
            .run({TensorShape{2, 3, 2, 3}});
}

}  // anonymous namespace

TEST(TestOprBlas, SingularValueDecomposition) {
    using Checker = AutoOprChecker<1, 3>;
M
Megvii Engine Team 已提交
834
    auto make_graph = [=](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
835 836 837 838 839 840 841 842
        auto out = opr::SVD::make(inputs[0], opr::SVD::Param{false, true});
        return {out[0], out[1], out[2]};
    };
    auto fwd = [=](Checker::NumOutArray& dest, Checker::NumInpArray inp) {
        auto opr = megdnn_naive_handle()->create_operator<megdnn::SVDForward>();
        opr->param().compute_uv = true;
        TensorLayout ul, sl, vtl;
        opr->deduce_layout(inp[0]->layout(), ul, sl, vtl);
M
Megvii Engine Team 已提交
843
        auto wk_size = opr->get_workspace_in_bytes(inp[0]->layout(), ul, sl, vtl);
844
        auto wk = std::make_unique<dt_byte[]>(wk_size);
M
Megvii Engine Team 已提交
845 846 847 848
        opr->exec(
                inp[0]->as_megdnn(), dest[0].resize(ul).as_megdnn(),
                dest[1].resize(sl).as_megdnn(), dest[2].resize(vtl).as_megdnn(),
                {wk.get(), wk_size});
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
    };
    Checker{make_graph, fwd}
            .set_input_generator(0, gen_svd_input)
            .set_output_allow_check(0, false)
            .set_output_allow_check(2, false)
            .run({TensorShape{3, 3}})
            .run({TensorShape{2, 3, 3}})
            .run({TensorShape{2, 4, 2}})
            .run({TensorShape{3, 1, 2, 4}})
            .run({TensorShape{2, 3, 2, 3}});
}

TEST(TestOprBlas, SingularValueDecompositionZeroGrad) {
    run_svd_empty_grad_test<0, 0, 1>();
    run_svd_empty_grad_test<0, 1, 0>();
    run_svd_empty_grad_test<0, 1, 1>();
    run_svd_empty_grad_test<1, 0, 0>();
    run_svd_empty_grad_test<1, 0, 1>();
    run_svd_empty_grad_test<1, 1, 0>();
    run_svd_empty_grad_test<1, 1, 1>();
}

871 872 873 874 875 876 877 878 879 880 881 882
#if MGB_ENABLE_FASTRUN
TEST(TestOprBlas, MatrixMulExePolicy) {
    using Param = opr::MatrixMul::Param;
    Param param;
    using Policy = opr::MatrixMul::ExecutionPolicy;
    using S = Policy::Strategy;
    Policy policy;
    policy.strategy = S::PROFILE;

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

    int nr_get = 0;
M
Megvii Engine Team 已提交
883 884 885
    auto on_get = [&nr_get](
                          const std::string&, const void*, size_t, const void*,
                          size_t) { ++nr_get; };
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    PersistentCacheHook cache_hook{on_get};

    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;

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

    auto a = mkvar("a", {20, 50});
    auto b = mkvar("b", {50, 40});
    auto matmul = opr::MatrixMul::make(a, b, param, policy, {});

    HostTensorND host_y;
    graph->options().no_profiling_on_shape_change = true;
    auto func = graph->compile({make_callback_copy(matmul, host_y)});
    func->execute();
903
    ASSERT_EQ(nr_get, 0);
904 905 906
    graph->options().no_profiling_on_shape_change = false;
    func = graph->compile({make_callback_copy(matmul, host_y)});
    func->execute();
907
    ASSERT_GT(nr_get, 0);
908 909 910
}
#endif

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
#if MGB_ENABLE_FBS_SERIALIZATION
TEST(TestOprDNN, MatrixMulSerialization) {
    using namespace serialization;

    auto fname = output_file("MatrixMulSerializationTest");
    auto dump = [&]() {
        opr::MatrixMul::Param param;

        auto cn = CompNode::load("cpu0");
        auto graph = ComputingGraph::make();
        HostTensorND a_host{cn, {24, 24}, dtype::Float32()};
        HostTensorND b_host{cn, {24, 24}, dtype::Float32()};
        auto a = opr::ImmutableTensor::make(*graph, a_host);
        auto b = opr::ImmutableTensor::make(*graph, b_host);
        auto opr = opr::MatrixMul::make(a, b, param, {});
        auto dumper = GraphDumper::make(
                OutputFile::make_fs(fname.c_str()), GraphDumpFormat::FLATBUFFERS);
        auto rst = dumper->dump({opr});
        ASSERT_EQ(rst.outputs.size(), 1u);
    };

    auto load = [&]() {
        auto loader = GraphLoader::make(
                InputFile::make_fs(fname.c_str()), GraphDumpFormat::FLATBUFFERS);
        auto rst = loader->load();
        ASSERT_EQ(rst.output_var_list.size(), 1u);
        auto opr = rst.output_var_list[0].node()->owner_opr();
        ASSERT_TRUE(opr->same_type<opr::MatrixMul>());
    };

    dump();
    load();
}
#endif
945
// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
946
//