blas.cpp 32.1 KB
Newer Older
1
#include "megbrain/opr/blas.h"
M
Megvii Engine Team 已提交
2
#include <random>
3 4
#include "megbrain/comp_node_env.h"
#include "megbrain/opr/basic_arith_wrapper.h"
M
Megvii Engine Team 已提交
5
#include "megbrain/opr/io.h"
6
#include "megbrain/opr/tensor_gen.h"
M
Megvii Engine Team 已提交
7
#include "megbrain/opr/tensor_manip.h"
8
#include "megbrain/serialization/serializer.h"
M
Megvii Engine Team 已提交
9 10 11
#include "megbrain/test/autocheck.h"
#include "megbrain/test/helper.h"
#include "megbrain/test/megdnn_helper.h"
12
#include "megdnn/algorithm_cache.h"
13 14 15 16 17

using namespace mgb;

namespace {
template <typename dt_src, typename dt_dst>
M
Megvii Engine Team 已提交
18 19 20
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) {
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    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 已提交
53
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
54 55 56 57 58 59 60 61 62 63 64
        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 已提交
65
        auto z = dest[0].comp_node(inp[0]->comp_node()).resize({M, N}).ptr<float>();
66
        // brute-force gemm
M
Megvii Engine Team 已提交
67 68
        brute_force_gemm(
                M, N, K, transa, transb, inp[0]->ptr<float>(), inp[1]->ptr<float>(), z);
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    };

    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)
86 87 88
            .run({mkx(20, 3), mky(3, 20)}, opt)
            .run({mkx(10, 0), mky(0, 10)}, opt)
            .run({mkx(0, 0), mky(0, 0)}, opt);
89 90
}

M
Megvii Engine Team 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
#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); \
        }                                                                          \
110 111 112 113
    }

void run_batched_sgemm_test(bool transa, bool transb) {
    using Checker = AutoOprChecker<2, 1>;
M
Megvii Engine Team 已提交
114 115
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
        return {opr::BatchedMatrixMul::make(inputs[0], inputs[1], {transa, transb})};
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    };

    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)
135 136 137
            .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);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
}

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 已提交
154 155
    HostTensorGenerator<dtype::Int8, RandomDistribution::UNIFORM> int8_generator{
            -128, 127};
156 157 158 159 160
    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 已提交
161 162
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
        return {opr::BatchedMatrixMul::make(inputs[0], inputs[1], {transa, transb})};
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    };
    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)
190
            .run({mkx(64, 10, 0), mky(64, 0, 10)}, opt)
191 192 193 194 195
            .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 已提交
196 197
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
        return {opr::BatchedMatrixMul::make(inputs[0], inputs[1], {transa, transb})};
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    };

    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)
227
            .run({mkx(64, 10, 0), mky(64, 0, 10)}, opt)
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            .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 已提交
246
    auto do_trans = [](SymbolVar x) { return opr::Dimshuffle::make(x, {1, 0}); };
247 248 249 250 251 252 253 254 255 256 257 258
    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());
    }
259
    auto z = opr::MatrixMul::make(x, y, {}, {}, config);
260 261 262 263 264 265 266 267 268 269 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
    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;

349
    auto z = opr::BatchedMatrixMul::make(x, y, {}, {}, OperatorNodeConfig{});
350 351 352
    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 已提交
353 354 355 356
        *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}));
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
        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 已提交
377 378
                        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]];
379 380
                        mul_add(xv, yv, sum);
                    }
M
Megvii Engine Team 已提交
381 382
                    MGB_ASSERT_FLOAT_NEAR(
                            getter(sum), getter(pz[(b * M + i) * N + j]), 5e-3)
383 384 385 386 387 388 389 390 391
                            << trans_a << ' ' << trans_b;
                }
    };
    run(2, 4, 8, 12);
    run(2, 8, 12, 16);
}

}  // anonymous namespace

392
TEST(TestOprBlas, MatrixMul_NN) {
393
    run_sgemm_test(false, false);
394 395 396
}

TEST(TestOprBlas, MatrixMul_NT) {
397
    run_sgemm_test(false, true);
398 399 400
}

TEST(TestOprBlas, MatrixMul_TN) {
401
    run_sgemm_test(true, false);
402 403 404
}

TEST(TestOprBlas, MatrixMul_TT) {
405 406 407
    run_sgemm_test(true, true);
}

408 409 410 411 412 413 414 415 416
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 已提交
417 418 419
    for (auto strategy : SmallVector<S>{
                 S::PROFILE, S::HEURISTIC, S::PROFILE | S::REPRODUCIBLE,
                 S::PROFILE | S::HEURISTIC}) {
420
#else
M
Megvii Engine Team 已提交
421
    for (auto strategy : {S : HEURISTIC, S::PROFILE | S::HEURISTIC}) {
422 423 424 425 426 427
#endif

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

        auto mkvar = [&](const char* name, const TensorShape& shp) {
M
Megvii Engine Team 已提交
428
            return opr::Host2DeviceCopy::make(*graph, gen(shp), cn).rename(name);
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        };

        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();
    }
}

444
TEST(TestOprBlas, BatchedMatrixMulFp32_NN) {
445
    run_batched_sgemm_test(false, false);
446 447 448
}

TEST(TestOprBlas, BatchedMatrixMulFp32_NT) {
449
    run_batched_sgemm_test(false, true);
450 451 452
}

TEST(TestOprBlas, BatchedMatrixMulFp32_TN) {
453
    run_batched_sgemm_test(true, false);
454 455 456
}

TEST(TestOprBlas, BatchedMatrixMulFp32_TT) {
457 458 459
    run_batched_sgemm_test(true, true);
}

460
TEST(TestOprBlas, BatchedMatrixMulFp16_NN) {
461
    run_batched_hgemm_test(false, false);
462 463 464
}

TEST(TestOprBlas, BatchedMatrixMulFp16_NT) {
465
    run_batched_hgemm_test(false, true);
466 467 468
}

TEST(TestOprBlas, BatchedMatrixMulFp16_TN) {
469
    run_batched_hgemm_test(true, false);
470 471 472
}

TEST(TestOprBlas, BatchedMatrixMulFp16_TT) {
473 474 475
    run_batched_hgemm_test(true, true);
}

476
TEST(TestOprBlas, BatchedMatrixMulInt8_NN) {
477 478 479 480 481
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
    run_batched_igemm_test(false, false);
482 483 484 485 486 487 488
}

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

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

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

508
TEST(TestOprBlas, TransBatchedMatrixMulFp32_NN) {
509
    run_bgemm_trans_inp_test_case<float, float>(false, false);
510 511 512
}

TEST(TestOprBlas, TransBatchedMatrixMulFp32_NT) {
513
    run_bgemm_trans_inp_test_case<float, float>(false, true);
514 515 516
}

TEST(TestOprBlas, TransBatchedMatrixMulFp32_TN) {
517
    run_bgemm_trans_inp_test_case<float, float>(true, false);
518 519 520
}

TEST(TestOprBlas, TransBatchedMatrixMulFp32_TT) {
521 522 523
    run_bgemm_trans_inp_test_case<float, float>(true, true);
}

524
TEST(TestOprBlas, TransBatchedMatrixMulInt8_NN) {
525 526 527 528 529
    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);
530 531 532 533 534 535 536
}

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

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

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

556
TEST(TestOprBlas, TransBatchedMatrixMulFp16_NN) {
557
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(false, false);
558 559 560
}

TEST(TestOprBlas, TransBatchedMatrixMulFp16_NT) {
561
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(false, true);
562 563 564
}

TEST(TestOprBlas, TransBatchedMatrixMulFp16_TN) {
565
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(true, false);
566 567 568
}

TEST(TestOprBlas, TransBatchedMatrixMulFp16_TT) {
569 570 571
    run_bgemm_trans_inp_test_case<dt_float16, dt_float16>(true, true);
}

572
TEST(TestOprBlas, TransBatchedMatrixMulQS8_NN) {
573 574 575 576 577
    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);
578 579 580 581 582 583 584
}

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

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

TEST(TestOprBlas, TransBatchedMatrixMulQS8_TT) {
    if (CompNode::load("xpux").device_type() == CompNode::DeviceType::CUDA &&
        !check_compute_capability(6, 1)) {
        return;
    }
601 602 603 604 605 606 607 608
    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 已提交
609
         y = opr::Host2DeviceCopy::make(*graph, host_y), z = opr::Dot::make(x, y);
610 611 612
    HostTensorND host_z;
    auto func = graph->compile({make_callback_copy(z, host_z)});
    func->execute();
M
Megvii Engine Team 已提交
613
    MGB_ASSERT_FLOAT_EQ(brute_force_dot(*host_x, *host_y), *host_z.ptr<float>());
614 615 616 617 618
}

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

M
Megvii Engine Team 已提交
619
    auto make_graph = [&](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
620 621 622 623 624 625 626 627 628 629 630 631 632
        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}})
633 634
            .run({TensorShape{1000}, TensorShape{1000}})
            .run({TensorShape{0}, TensorShape{0}});
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
}

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 已提交
659
    auto make_graph = [](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        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 已提交
676
            auto ptr_a = inp[0]->ptr<float>({i * 2}), ptr_c = dest[0].ptr<float>({i});
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            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 已提交
695
    auto make_graph = [=](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
696 697 698
        return {opr::MatrixInverse::make(inputs[0])};
    };
    auto fwd = [=](Checker::NumOutArray& dest, Checker::NumInpArray inp) {
M
Megvii Engine Team 已提交
699
        auto opr = megdnn_naive_handle()->create_operator<megdnn::MatrixInverse>();
700

M
Megvii Engine Team 已提交
701
        auto wk_size = opr->get_workspace_in_bytes(inp[0]->layout(), inp[0]->layout());
702
        std::unique_ptr<dt_byte[]> wk{new dt_byte[wk_size]};
M
Megvii Engine Team 已提交
703 704 705
        opr->exec(
                inp[0]->as_megdnn(), dest[0].resize(inp[0]->shape()).as_megdnn(),
                {wk.get(), wk_size});
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    };
    // 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) {
721 722 723 724
#if __cplusplus >= 201703L
            std::default_random_engine rng_engine;
            std::shuffle(perm.begin(), perm.end(), rng_engine);
#else
725
            std::random_shuffle(perm.begin(), perm.end());
726
#endif
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
            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 已提交
787 788 789
        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);
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
        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 已提交
824
    auto make_graph = [=](const Checker::SymInpArray& inputs) -> Checker::SymOutArray {
825 826 827 828 829 830 831 832
        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 已提交
833
        auto wk_size = opr->get_workspace_in_bytes(inp[0]->layout(), ul, sl, vtl);
834
        auto wk = std::make_unique<dt_byte[]>(wk_size);
M
Megvii Engine Team 已提交
835 836 837 838
        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});
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    };
    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>();
}

861 862 863 864 865 866 867 868 869 870 871 872
#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 已提交
873 874 875
    auto on_get = [&nr_get](
                          const std::string&, const void*, size_t, const void*,
                          size_t) { ++nr_get; };
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    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();
893
    ASSERT_EQ(nr_get, 0);
894
    megdnn::AlgorithmCache::instance().clear();
895 896 897
    graph->options().no_profiling_on_shape_change = false;
    func = graph->compile({make_callback_copy(matmul, host_y)});
    func->execute();
898
    ASSERT_GT(nr_get, 0);
899 900 901
}
#endif

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
#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
936
// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
937
//