serializer_oss.cpp 34.8 KB
Newer Older
1 2
#if MGB_ENABLE_FBS_SERIALIZATION

M
Megvii Engine Team 已提交
3 4
#include "megbrain/opr/basic_arith_wrapper.h"
#include "megbrain/opr/dnn/convolution.h"
5
#include "megbrain/opr/dnn/softmax.h"
6 7 8
#include "megbrain/opr/io.h"
#include "megbrain/opr/tensor_manip.h"
#include "megbrain/opr/utility.h"
M
Megvii Engine Team 已提交
9
#include "megbrain/serialization/serializer.h"
10 11 12 13 14
#include "megbrain/test/helper.h"

using namespace mgb;
using namespace serialization;

15 16
#define GET_OUTPUT_FILE(format) \
    output_file(ssprintf("TestSerializer2.line%d.V%d", __LINE__, (int)format))
17

18 19 20
namespace {
void test_graph_load_dump(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
21 22 23 24 25 26 27

    auto orig_id = -1;
    auto dump = [&]() {
        auto cn = CompNode::load("cpu0");
        auto graph = ComputingGraph::make();
        auto x = opr::ImmutableTensor::make(*graph, 1926.0817f, {cn});
        x.rename("varz");
28
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
29 30 31 32 33 34 35 36 37
        auto rst = dumper->dump({x});
        ASSERT_EQ(rst.nr_opr, 1);
        ASSERT_EQ(rst.inputs.size(), 0);
        ASSERT_EQ(rst.outputs.size(), 1);
        ASSERT_EQ(rst.params.size(), 0);
        orig_id = x.node()->id();
        mgb_log("%zu of %zu", rst.tensor_value_bytes, rst.tot_bytes);
    };
    auto load = [&]() {
38
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
39 40 41 42 43 44 45
        auto rst = loader->load();
        ASSERT_EQ(rst.tensor_map.size(), 0);
        ASSERT_EQ(rst.output_var_list.size(), 1);
        ASSERT_EQ(rst.output_var_map.size(), 1);
        ASSERT_EQ(rst.output_var_map_id.size(), 1);
        ASSERT_EQ(rst.output_var_map.count("varz"), 1);
        ASSERT_EQ(rst.output_var_map_id.count(orig_id), 1);
M
Megvii Engine Team 已提交
46

47
        HostTensorND host_x;
M
Megvii Engine Team 已提交
48 49 50

        auto func =
                rst.graph_compile({make_callback_copy(rst.output_var_list[0], host_x)});
51 52 53 54 55 56 57
        func->execute().wait();
        EXPECT_NEAR(*host_x.ptr<float>(), 1926.0817f, 1e-6);
    };
    dump();
    load();
}

58 59
void test_multi_graph_dump_load(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
60 61 62 63 64 65

    auto dump = [&]() {
        auto cn = CompNode::load("cpu0");
        auto graph = ComputingGraph::make();
        auto x = opr::ImmutableTensor::make(*graph, 1926.0817f, {cn});
        x.rename("varz");
66
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
67 68 69 70 71 72
        // dump twice
        dumper->dump({x});
        dumper->dump({x});
    };
    auto load = [&]() {
        GraphLoader::LoadConfig load_config = {};
73
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
74 75 76 77 78 79 80 81 82 83
        // load twice
        loader->load(load_config, false);
        loader = GraphLoader::make(loader->reset_file(), loader->format());
        loader->load(load_config, false);
    };

    dump();
    load();
}

84 85
void test_metadata(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    TensorShape shape{2, 3};

    auto dump = [&]() {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape),
             host_y = std::make_shared<HostTensorND>(cn, shape);
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}),
             y = opr::Host2DeviceCopy::make(*graph, host_y, {"y"});
        using Mode = opr::Elemwise::Mode;
        auto z = opr::Elemwise::make({x, y}, Mode::ADD, {"add(x, y)"});

        Metadata metadata;
        metadata.user_info = "TEST_METADATA";
        metadata.has_user_info = true;

102
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
103 104 105 106 107
        auto rst = dumper->dump({z.rename("z")}, {}, metadata);
    };

    auto load = [&]() {
        HostTensorGenerator<> gen;
108
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
109 110 111 112 113 114 115 116 117 118
        auto rst = loader->load();
        auto metadata = rst.metadata;
        int cmp = strcmp(metadata.user_info.c_str(), "TEST_METADATA");
        EXPECT_EQ(cmp, 0);
    };

    dump();
    load();
}

119 120
void test_serializer_APlusB(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
121 122 123 124 125 126 127 128 129 130
    TensorShape shape{2, 3};

    auto dump = [&]() {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape),
             host_y = std::make_shared<HostTensorND>(cn, shape);
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}),
             y = opr::Host2DeviceCopy::make(*graph, host_y, {"y"});

131
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
132 133 134 135 136 137 138
        // test dump duplicated
        auto rst = dumper->dump({(x + y).rename("z"), x + y});
        ASSERT_EQ(2u, rst.outputs.size());
    };

    auto load = [&]() {
        HostTensorGenerator<> gen;
139
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
140 141 142 143 144 145 146 147 148
        auto rst = loader->load();
        auto xv = rst.tensor_map.at("x");
        auto yv = rst.tensor_map.at("y");
        ASSERT_EQ(shape, xv->shape());
        ASSERT_EQ(shape, yv->shape());
        *xv = *gen(shape);
        *yv = *gen(shape);
        HostTensorND host_z, host_z_expect;
        host_z_expect.copy_from(*xv);
M
Megvii Engine Team 已提交
149
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
150 151 152 153 154 155 156 157 158 159 160
            host_z_expect.ptr<float>()[i] += yv->ptr<float>()[i];
        auto func = rst.graph_compile(
                {make_callback_copy(rst.output_var_map.at("z"), host_z)});
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_z_expect, host_z);
    };

    dump();
    load();
}

161
void test_serializer_APlusB_param(GraphDumpFormat format) {
162
    auto cns = load_multiple_xpus(2);
163
    auto fname = GET_OUTPUT_FILE(format);
164 165 166 167 168 169 170 171 172 173 174 175 176 177
    TensorShape shape{2, 3};

    HostTensorGenerator<> gen;
    auto bias = std::make_shared<DeviceTensorND>();
    auto bias_hv = gen(shape, cns[0]);
    bias->copy_from(*bias_hv);

    {
        // dump
        auto host_x = std::make_shared<HostTensorND>(cns[0], shape);
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}),
             y = opr::SharedDeviceTensor::make(*graph, bias, {"y"});

178
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
179 180 181 182
        GraphDumper::DumpConfig config;
        config.keep_param_name = true;
        dumper->dump({(x + y).rename("z")}, config);
    }
183
    auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
184 185 186

    auto load = [&](CompNode dest_cn) {
        auto dest_cn_loc = dest_cn.locator_logical();
M
Megvii Engine Team 已提交
187
        auto rst = loader->load({[&](CompNode::Locator& loc) { loc = dest_cn_loc; }});
188 189 190 191 192 193
        auto xv = rst.tensor_map.at("x");
        ASSERT_EQ(1u, rst.tensor_map.size());
        ASSERT_EQ(shape, xv->shape());
        *xv = *gen(shape, cns[0]);
        HostTensorND host_z, host_z_expect;
        host_z_expect.copy_from(*xv);
M
Megvii Engine Team 已提交
194
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
195 196 197 198 199 200 201 202
            host_z_expect.ptr<float>()[i] += bias_hv->ptr<float>()[i];
        auto func = rst.graph_compile(
                {make_callback_copy(rst.output_var_map.at("z"), host_z)});
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_z_expect, host_z);
    };

    load(cns[0]);
M
Megvii Engine Team 已提交
203
    auto&& shmap = loader->shared_tensor_name_map();
204 205 206 207
    ASSERT_EQ(1u, shmap.at("y")->size());
    load(cns[0].change_stream(1));
    ASSERT_EQ(1u, shmap.at("y")->size());
    load(cns[1]);
M
Megvii Engine Team 已提交
208
    ASSERT_EQ(1u + (cns[1].mem_node() != cns[0].mem_node()), shmap.at("y")->size());
209 210
}

211 212
void test_serializer_immutable(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
213 214 215 216 217 218 219
    TensorShape shape{2, 3};

    auto dump = [&]() {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape);
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"});
220
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
221 222 223 224 225
        dumper->dump({(x + 1.f).rename("y")});
    };

    auto load = [&]() {
        HostTensorGenerator<> gen;
226
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
227 228 229 230 231 232
        auto rst = loader->load();
        auto xv = rst.tensor_map.at("x");
        ASSERT_EQ(shape, xv->shape());
        *xv = *gen(shape);
        HostTensorND host_y, host_y_expect;
        host_y_expect.copy_from(*xv);
M
Megvii Engine Team 已提交
233
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
234 235 236 237 238 239 240 241 242 243 244
            host_y_expect.ptr<float>()[i] += 1;
        auto func = rst.graph_compile(
                {make_callback_copy(rst.output_var_map.at("y"), host_y)});
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y_expect, host_y);
    };

    dump();
    load();
}

245 246
void test_serializer_custom_loader(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
247 248 249 250 251 252
    TensorShape shape{2, 3};

    int load_nr_null_ptr = 0, load_nr_call = 0;
    std::vector<HostTensorND> saved_val;

    auto tensor_value_dumper = [&saved_val](
M
Megvii Engine Team 已提交
253 254 255
                                       OutputFile& fout,
                                       const cg::OperatorNodeBase& opr,
                                       const HostTensorND& tensor) {
256 257 258 259 260 261
        size_t idx = saved_val.size();
        saved_val.emplace_back();
        saved_val.back().copy_from(tensor);
        fout.write(&idx, sizeof(idx));
    };
    auto tensor_value_loader = [&saved_val, &load_nr_null_ptr, &load_nr_call](
M
Megvii Engine Team 已提交
262 263 264
                                       void* ptr, const TensorLayout& layout,
                                       InputFile& fin) {
        ++load_nr_call;
265 266
        size_t idx;
        if (!ptr) {
M
Megvii Engine Team 已提交
267
            load_nr_null_ptr++;
268 269 270 271
            fin.skip(sizeof(idx));
            return;
        }
        fin.read(&idx, sizeof(idx));
M
Megvii Engine Team 已提交
272
        auto&& val = saved_val.at(idx);
273 274 275 276 277 278 279 280 281 282 283 284 285
        ASSERT_TRUE(val.layout().eq_layout(layout));
        memcpy(ptr, val.raw_ptr(), layout.span().high_byte);
    };

    auto dump = [&]() {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape);
        HostTensorND y_val(cn, {1});
        y_val.ptr<float>()[0] = 2.3f;
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}),
             y = opr::SharedDeviceTensor::make(*graph, y_val),
             z = ((x + 1.f) * y).rename("z");
286
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
287 288 289 290 291 292 293 294
        GraphDumpConfig config;
        config.tensor_value_dumper = tensor_value_dumper;
        dumper->dump({z}, config);
    };
    dump();

    GraphLoadConfig config;
    config.tensor_value_loader = tensor_value_loader;
295
    auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
296 297 298 299 300 301 302 303 304
    auto load = [&]() {
        HostTensorGenerator<> gen;
        auto rst = loader->load(config);
        auto xv = rst.tensor_map.at("x");
        ASSERT_EQ(shape, xv->shape());
        *xv = *gen(shape);
        HostTensorND host_y, host_y_expect;
        host_y_expect.copy_from(*xv);
        auto py = host_y_expect.ptr<float>();
M
Megvii Engine Team 已提交
305
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i) {
306 307 308 309 310 311 312 313 314 315 316
            py[i] = (py[i] + 1.f) * 2.3f;
        }
        auto func = rst.graph_compile(
                {make_callback_copy(rst.output_var_map.at("z"), host_y)});
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y_expect, host_y);
    };

    load();
    load();
    ASSERT_EQ(2u, saved_val.size());
M
Megvii Engine Team 已提交
317
    ASSERT_EQ(1, load_nr_null_ptr);  // immutable tensor is not shared
318 319 320
    ASSERT_EQ(4, load_nr_call);
}

321 322
void test_serializer_many_io_var(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
323 324 325 326 327
    constexpr size_t NR_VARS = 32;
    auto dump = [&]() {
        auto graph = ComputingGraph::make();
        SymbolVarArray xs;
        cg::OperatorNodeConfig::CompNodeArray y_comp_nodes;
M
Megvii Engine Team 已提交
328
        for (size_t i = 0; i < NR_VARS; ++i) {
329 330 331 332 333 334
            CompNode::Locator loc;
            loc.type = CompNode::DeviceType::CPU;
            loc.device = 0;
            loc.stream = i;
            auto cn = CompNode::load(loc);
            auto host_x = std::make_shared<HostTensorND>(cn, TensorShape{1});
M
Megvii Engine Team 已提交
335
            xs.push_back(opr::Host2DeviceCopy::make(*graph, host_x, std::to_string(i)));
336 337 338 339 340

            loc.device = 1;
            y_comp_nodes.push_back(CompNode::load(loc));
        }
        auto con = opr::Concat::make(xs, 0, CompNode::load("cpu2")) * 2 + 1;
M
Megvii Engine Team 已提交
341 342
        auto ys = opr::Split::make(
                con,
343
                opr::Split::Options::make_partition(
M
Megvii Engine Team 已提交
344
                        con, 0, std::vector<size_t>(NR_VARS, 1)),
345 346
                OperatorNodeConfig{}.comp_node_arr(y_comp_nodes));

347
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
348 349 350 351 352
        auto rst = dumper->dump(ys);
    };

    auto load = [&]() {
        HostTensorGenerator<> gen;
353
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
354 355 356 357
        auto rst = loader->load();
        ASSERT_EQ(NR_VARS, rst.output_var_list.size());
        ComputingGraph::OutputSpec out_spec(NR_VARS);
        std::vector<HostTensorND> host_ys(NR_VARS);
M
Megvii Engine Team 已提交
358
        for (size_t i = 0; i < NR_VARS; ++i) {
359 360 361 362 363 364
            auto y = rst.output_var_list[i];
            auto loc = y.node()->comp_node().locator_logical();
            ASSERT_EQ(1, loc.device);
            ASSERT_EQ(static_cast<int>(i), loc.stream);
            out_spec[i] = make_callback_copy(y, host_ys[i]);

M
Megvii Engine Team 已提交
365
            auto&& inp = rst.tensor_map.at(std::to_string(i));
366 367 368 369
            inp->resize({1}).ptr<float>()[0] = i;
        }
        auto func = rst.graph_compile(out_spec);
        func->execute();
M
Megvii Engine Team 已提交
370 371
        for (size_t i = 0; i < NR_VARS; ++i) {
            auto&& val = host_ys[i];
372 373 374 375 376 377 378 379 380
            ASSERT_EQ(TensorShape{1}, val.shape());
            ASSERT_EQ(static_cast<float>(i * 2 + 1), val.ptr<float>()[0]);
        }
    };

    dump();
    load();
}

381 382
void test_serializer_remove_set_grad(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    TensorShape shape{2, 3};

    auto dump = [&]() {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape),
             host_y = std::make_shared<HostTensorND>(cn, shape);
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}),
             y = opr::Host2DeviceCopy::make(*graph, host_y, {"y"});

        auto sg = [](SymbolVar var) {
            return opr::SetGrad::make(var, opr::SetGrad::zero_grad);
        };

        // SetGrad as output
        auto z0 = sg(x + y);
        // SetGrad as internal
        auto z1 = sg(x) + sg(sg(y));

402
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
403 404 405 406 407
        dumper->dump({z0, z1});
    };

    auto load = [&]() {
        HostTensorGenerator<> gen;
408
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
409 410 411 412 413 414 415 416 417
        auto rst = loader->load();
        auto xv = rst.tensor_map.at("x");
        auto yv = rst.tensor_map.at("y");
        ASSERT_EQ(shape, xv->shape());
        ASSERT_EQ(shape, yv->shape());
        *xv = *gen(shape);
        *yv = *gen(shape);
        HostTensorND host_z0, host_z1, host_z_expect;
        host_z_expect.copy_from(*xv);
M
Megvii Engine Team 已提交
418
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
419 420
            host_z_expect.ptr<float>()[i] += yv->ptr<float>()[i];
        ASSERT_EQ(2u, rst.output_var_list.size());
M
Megvii Engine Team 已提交
421 422 423
        auto func = rst.graph_compile(
                {{make_callback_copy(rst.output_var_list[0], host_z0)},
                 {make_callback_copy(rst.output_var_list[1], host_z1)}});
424 425 426 427 428 429 430 431 432
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_z_expect, host_z0);
        MGB_ASSERT_TENSOR_EQ(host_z_expect, host_z1);
    };

    dump();
    load();
}

433 434
void test_serializer_multiple_param(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
435 436 437 438 439 440 441 442 443 444
    std::vector<std::shared_ptr<DeviceTensorND>> values;
    auto add_value = [&](int stream, int ndim, DType dtype) {
        CompNode::Locator loc;
        loc.type = CompNode::DeviceType::CPU;
        loc.device = 0;
        loc.stream = stream;
        auto cn = CompNode::load(loc);

        TensorShape shp;
        shp.ndim = ndim;
M
Megvii Engine Team 已提交
445
        for (int i = 0; i < ndim; ++i)
446 447 448
            shp[i] = i + 1;

        auto cur = std::make_shared<DeviceTensorND>(cn, shp, dtype);
M
Megvii Engine Team 已提交
449 450
        uint8_t* ptr = reinterpret_cast<uint8_t*>(cur->raw_ptr());
        for (size_t i = 0, it = cur->layout().span().dist_byte(); i < it; ++i) {
451 452 453 454 455 456 457 458 459 460
            ptr[i] = i;
        }

        values.push_back(cur);
        return cur;
    };
    auto dump = [&]() {
        auto graph = ComputingGraph::make();
        int stream = 0;
        auto mkvar = [&](int ndim, DType dtype) {
M
Megvii Engine Team 已提交
461
            auto dv = add_value(stream++, ndim, dtype);
462 463
            auto var = opr::SharedDeviceTensor::make(*graph, dv);
            var = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
464
                    opr::reduce_sum(var, var.make_scalar(1)), dtype::Int32());
465 466 467 468
            var = opr::Copy::make(var, CompNode::load("cpu1"));
            return var;
        };
        auto x = mkvar(1, dtype::Float32());
M
Megvii Engine Team 已提交
469
        for (size_t ndim = 1; ndim <= TensorShape::MAX_NDIM; ++ndim) {
470 471 472 473 474
#define cb(_dt) x = x + mkvar(ndim, _dt());
            MEGDNN_FOREACH_COMPUTING_DTYPE(cb)
#undef cb
        }
        ASSERT_GT(values.size(), 8u);
475
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
476 477 478 479
        dumper->dump({x});
    };

    auto load = [&]() {
480
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
481 482
        ASSERT_THROW(loader->shared_tensor_id_map(), MegBrainError);
        loader->load();
M
Megvii Engine Team 已提交
483
        auto&& got = loader->shared_tensor_id_map();
484
        ASSERT_EQ(values.size(), got.size());
M
Megvii Engine Team 已提交
485
        for (size_t i = 0; i < values.size(); ++i) {
486 487 488 489 490
            ASSERT_EQ(1u, got[i].second.size());
            auto &&vi = *values[i], &&gi = *got[i].second.begin()->second;
            ASSERT_EQ(vi.shape(), gi.shape());
            ASSERT_EQ(vi.comp_node(), gi.comp_node());
            ASSERT_EQ(vi.dtype(), gi.dtype());
M
Megvii Engine Team 已提交
491 492 493
            ASSERT_EQ(
                    0,
                    memcmp(vi.raw_ptr(), gi.raw_ptr(), vi.layout().span().dist_byte()));
494 495 496 497 498 499 500
        }
    };

    dump();
    load();
}

501 502
void test_serializer_const_var_shape(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
503 504 505 506 507 508 509 510
    TensorShape shape{2, 3};
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3});

    {
        // dump
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"});
511
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
512 513 514 515
        dumper->dump({x + 1.f});
    }

    auto run_and_check = [&](const GraphLoadConfig& config) {
516
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
517 518 519 520
        auto rst = loader->load(config);
        rst.tensor_map.at("x")->copy_from(*host_x);
        auto y = rst.output_var_list[0];
        ASSERT_EQ(shape, y.shape());
M
Megvii Engine Team 已提交
521 522 523 524
        auto infer_type = y.node()->owner_graph()
                                  ->static_infer_manager()
                                  .get_infer_type(y.node())
                                  .shape;
525 526 527 528 529 530 531
        if (config.const_var_shape) {
            ASSERT_EQ(cg::static_infer::InferType::CONST, infer_type);
        } else {
            ASSERT_EQ(cg::static_infer::InferType::RT_STATIC, infer_type);
        }
        HostTensorND host_y, host_y_expect;
        host_y_expect.copy_from(*host_x);
M
Megvii Engine Team 已提交
532
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
533 534 535 536 537 538 539 540 541 542 543
            host_y_expect.ptr<float>()[i] += 1;
        auto func = rst.graph_compile({make_callback_copy(y, host_y)});
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_y_expect, host_y);

        if (config.const_var_shape) {
            rst.tensor_map.at("x")->resize({4, 5});
            ASSERT_THROW(func->execute(), MegBrainError);
        }
    };

M
Megvii Engine Team 已提交
544
    for (bool const_shape : {false, true}) {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
        GraphLoadConfig config;
        config.const_var_shape = const_shape;
        run_and_check(config);
    };

    // test const shape with tensor modifier
    {
        int nr_tensor = 0, nr_mod = 0;
        shape = {7, 6};
        *host_x = *gen(shape);
        GraphLoadConfig config;
        config.const_var_shape = true;
        config.tensor_modifier = [&](const std::string& name, bool has_value,
                                     HostTensorND& tensor) {
            ++nr_tensor;
            if (!has_value) {
                ASSERT_EQ("x", name);
                tensor.resize(shape);
                ++nr_mod;
            }
        };
        run_and_check(config);
        ASSERT_EQ(2, nr_tensor);
        ASSERT_EQ(1, nr_mod);
    }
}

572 573
void test_serializer_const_var_shape_output_name(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
574 575 576 577 578 579 580 581 582 583
    TensorShape shape{2, 3};
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3});

    {
        // dump
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}),
             y = opr::GetVarShape::make(x) + 1;
        y.rename("out");
584
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
585 586 587 588 589
        dumper->dump({y});
    }

    {
        // load
590
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
591 592 593 594 595 596 597 598 599
        GraphLoadConfig config;
        config.const_var_shape = true;
        auto rst = loader->load(config);
        ASSERT_EQ(1u, rst.tensor_map.count("x"));
        auto y = rst.output_var_map.at("out");
        ASSERT_TRUE(y.node()->owner_opr()->same_type<opr::ImmutableTensor>());
    }
}

600 601
void test_serializer_priority(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
602 603 604 605 606 607 608 609 610 611 612 613 614
    TensorShape shape{2, 3};

    auto dump = [&](bool keep_pri) {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape),
             host_y = std::make_shared<HostTensorND>(cn, shape);
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}) + 1,
             y = opr::Host2DeviceCopy::make(*graph, host_y, {"y"}) + 1;

        set_priority(x, 1);
        set_priority(y, 2);

615
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
616 617 618 619 620 621 622 623
        GraphDumper::DumpConfig config;
        if (keep_pri) {
            config.keep_opr_priority = true;
        }
        dumper->dump({x * y}, config);
    };

    auto load = [&](bool has_pri) {
624
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
625
        auto rst = loader->load();
M
Megvii Engine Team 已提交
626 627 628
        VarNode *x, *y;
        unpack_vector(rst.output_var_list.front().node()->owner_opr()->input(), x, y);
        auto get_pri = [](VarNode* var) {
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
            return var->owner_opr()->node_prop().attribute().priority;
        };
        int xpri = get_pri(x), ypri = get_pri(y);
        if (has_pri) {
            ASSERT_EQ(1, xpri);
            ASSERT_EQ(2, ypri);
        } else {
            ASSERT_EQ(0, xpri);
            ASSERT_EQ(0, ypri);
        }
    };

    dump(false);
    load(false);

    dump(true);
    load(true);
}

648 649
void test_serializer_multiple_params(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
650 651 652 653 654 655 656 657 658 659
    HostTensorGenerator<> gen;
    std::vector<std::shared_ptr<HostTensorND>> tensors{
            gen({2, 3}), gen({1}), gen({3, 2}), gen({1, 1})};

    auto dump = [&]() {
        auto graph = ComputingGraph::make();
        SymbolVarArray outputs;
        for (auto&& i : tensors) {
            outputs.push_back(opr::SharedDeviceTensor::make(*graph, *i));
        }
660
        GraphDumper::make(OutputFile::make_fs(fname.c_str()), format)->dump(outputs);
661 662 663
    };

    auto load = [&]() {
664
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
        auto rst = loader->load();
        ASSERT_EQ(tensors.size(), rst.output_var_list.size());
        for (size_t i = 0; i < tensors.size(); ++i) {
            HostTensorND got;
            got.copy_from(rst.output_var_list[i]
                                  .node()
                                  ->owner_opr()
                                  ->cast_final_safe<opr::SharedDeviceTensor>()
                                  .get_dev_tensor())
                    .sync();
            MGB_ASSERT_TENSOR_EQ(*tensors[i], got);
        }
    };

    dump();
    load();
}

683 684
void test_serializer_paramerized_dtype(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
685
    TensorShape shape{2, 3, 3};
M
Megvii Engine Team 已提交
686
    dtype::Quantized8Asymm dtype(0.01f, (uint8_t)123);
687 688 689 690 691

    auto dump = [&]() {
        auto cn = CompNode::load("cpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape, dtype);
        for (size_t i = 0; i < host_x->layout().span().dist_elem(); i++) {
M
Megvii Engine Team 已提交
692
            host_x->ptr<dt_quint8>()[i] = dt_quint8(static_cast<uint8_t>(i & 255));
693 694 695 696
        }
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"});
        auto rst = opr::Dimshuffle::make(x, {1, 2, 0});
697
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
698 699 700 701
        dumper->dump({rst});
    };

    auto load = [&]() {
702
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
703 704 705 706 707 708 709 710 711
        auto rst = loader->load();
        ASSERT_EQ(rst.output_var_list.size(), 1u);
        EXPECT_EQ(rst.output_var_list.front().node()->dtype(), dtype);
    };

    dump();
    load();
}

712 713
void test_serializer_operator_name(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
714 715 716 717 718 719 720 721 722 723 724 725
    TensorShape shape{2, 3};

    auto dump = [&]() {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape),
             host_y = std::make_shared<HostTensorND>(cn, shape);
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"}),
             y = opr::Host2DeviceCopy::make(*graph, host_y, {"y"});
        using Mode = opr::Elemwise::Mode;
        auto z = opr::Elemwise::make({x, y}, Mode::ADD, {"add(x, y)"});

726
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
727 728 729 730 731
        auto rst = dumper->dump({z.rename("z")});
    };

    auto load = [&]() {
        HostTensorGenerator<> gen;
732
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
733 734 735 736 737 738 739 740 741 742
        auto rst = loader->load();
        auto z = rst.output_var_map.at("z");
        auto op_name = z.node()->owner_opr()->cname();
        int cmp = strcmp(op_name, "add(x, y)");
        EXPECT_EQ(cmp, 0);
    };

    dump();
    load();
}
743

744 745
void test_serializer_has_output_dtype(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

    HostTensorGenerator<> gen;

    auto graph = ComputingGraph::make();

    auto gen_tensor = [&](const TensorShape& shape, const DType& dtype) {
        return opr::TypeCvt::make(
                opr::Host2DeviceCopy::make(*graph, gen(shape)), dtype);
    };

    auto dump = [&]() {
        auto x = gen_tensor({20, 4, 56, 56}, dtype::QuantizedS8(0.5f));
        auto w = gen_tensor({4, 4, 1, 1}, dtype::QuantizedS8(0.1f));
        auto b = gen_tensor({1, 4, 1, 1}, dtype::QuantizedS32(0.05f));
        opr::ConvBias::Param param;
        auto y0 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
762
                x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS32(0.05f)});
763
        auto y1 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
764
                x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(0.3f)});
765
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
766 767 768
        dumper->dump({y0, y1});
    };

M
Megvii Engine Team 已提交
769 770 771 772
    auto check = [](const serialization::GraphLoader::LoadResult& rst, size_t idx,
                    const DType& expected_dtype) {
        auto&& dtype =
                rst.output_var_list[idx].node()->owner_opr()->config().output_dtype();
773 774 775 776 777
        ASSERT_TRUE(dtype.valid());
        ASSERT_EQ(dtype, expected_dtype);
    };

    auto load = [&]() {
778
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
779 780 781 782 783 784 785 786 787 788
        auto rst = loader->load();
        ASSERT_EQ(rst.output_var_list.size(), 2u);
        check(rst, 0, dtype::QuantizedS32(0.05f));
        check(rst, 1, dtype::QuantizedS8(0.3f));
    };

    dump();
    load();
}

789 790
void test_serializer_log_exp(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
    TensorShape shape{2, 3};
    using Mode = opr::Elemwise::Mode;
    bool inplace_opt = true;
    auto dump = [&]() {
        auto cn = CompNode::load("xpu0");
        auto host_x = std::make_shared<HostTensorND>(cn, shape);
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
            host_x->ptr<float>()[i] = 0.0;  // To avoid NAN
        auto graph = ComputingGraph::make();
        if (!inplace_opt)
            graph->options().graph_opt_level = 0;
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"});
        auto y = opr::Elemwise::make({x}, Mode::EXP);
        auto z = opr::Elemwise::make({y}, Mode::LOG);

806
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
807
        auto rst = dumper->dump({z.rename("z"), z});
M
Megvii Engine Team 已提交
808
        size_t expected_nr_opr = inplace_opt ? 1 : 3;
809 810 811 812
        ASSERT_EQ(expected_nr_opr, rst.nr_opr);
    };

    auto load = [&]() {
813
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
814 815 816 817 818 819 820 821 822 823
        auto rst = loader->load();
    };

    dump();
    load();

    inplace_opt = !inplace_opt;
    dump();
    load();
}
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 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 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

}  // namespace

TEST(TestSerializer2, GraphDumpLoad) {
    test_graph_load_dump(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, MultiGraphDumpLoad) {
    test_multi_graph_dump_load(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, Metadata) {
    test_metadata(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, APlusB) {
    test_serializer_APlusB(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, APlusBParam) {
    test_serializer_APlusB_param(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, Immutable) {
    test_serializer_immutable(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, CustomLoader) {
    test_serializer_custom_loader(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, ManyIOVars) {
    test_serializer_many_io_var(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, RemoveSetGrad) {
    test_serializer_remove_set_grad(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, MultipleParamNDIMDTypeCompNode) {
    test_serializer_multiple_param(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, ConstVarShape) {
    test_serializer_const_var_shape(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, ConstVarShapeOutputName) {
    test_serializer_const_var_shape_output_name(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, Priority) {
    test_serializer_priority(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, MultipleParams) {
    test_serializer_multiple_params(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, ParamerizedDType) {
    test_serializer_paramerized_dtype(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, OperatorName) {
    test_serializer_operator_name(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, HasOutputDtype) {
    test_serializer_has_output_dtype(GraphDumpFormat::FLATBUFFERS);
}

TEST(TestSerializer2, LOGEXP) {
    test_serializer_log_exp(GraphDumpFormat::FLATBUFFERS);
}

/******************** Flatbuffer V2 Test **********************/

TEST(TestSerializer2, GraphDumpLoadV2) {
    test_graph_load_dump(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, MultiGraphDumpLoadV2) {
    test_multi_graph_dump_load(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, MetadataV2) {
    test_metadata(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, APlusBV2) {
    test_serializer_APlusB(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, APlusBParamV2) {
    test_serializer_APlusB_param(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, ImmutableV2) {
    test_serializer_immutable(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, ManyIOVarsV2) {
    test_serializer_many_io_var(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, RemoveSetGradV2) {
    test_serializer_remove_set_grad(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, MultipleParamNDIMDTypeCompNodeV2) {
    test_serializer_multiple_param(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, ConstVarShapeV2) {
    test_serializer_const_var_shape(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, ConstVarShapeOutputNameV2) {
    test_serializer_const_var_shape_output_name(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, MultipleParamsV2) {
    test_serializer_multiple_params(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, ParamerizedDTypeV2) {
    test_serializer_paramerized_dtype(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, PriorityV2) {
    test_serializer_priority(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, OperatorNameV2) {
    test_serializer_operator_name(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, HasOutputDtypeV2) {
    test_serializer_has_output_dtype(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, LOGEXPV2) {
    test_serializer_log_exp(GraphDumpFormat::FLATBUFFERS_V2);
}

TEST(TestSerializer2, TestSoftMaxLoadDump) {
    auto fname = GET_OUTPUT_FILE(GraphDumpFormat::FLATBUFFERS_V2);
    TensorShape shape{2, 3};

    auto cn = CompNode::load("xpu0");
    std::shared_ptr<HostTensorND> host =
            std::make_shared<HostTensorND>(cn, shape, dtype::Float32{});
    HostTensorND dst_truth;
    for (int i = 0; i < 6; i++) {
        host->ptr<float>()[i] = i;
    }
    auto dump = [&]() {
        auto graph = ComputingGraph::make();
        auto h2d = opr::Host2DeviceCopy::make(*graph, host);
        auto x = opr::Softmax::make(h2d, {1}, {});
        x.rename("softmax_out");
        auto func = graph->compile({make_callback_copy(x, dst_truth)});
        auto dumper = GraphDumper::make(
                OutputFile::make_fs(fname.c_str()), GraphDumpFormat::FLATBUFFERS_V2);
        auto rst = dumper->dump({x});
        func->execute().wait();
990 991 992
        //! if convert to reduce and elemwise, nr_opr is 6
        // ASSERT_EQ(rst.nr_opr, 6);
        ASSERT_EQ(rst.nr_opr, 2);
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
        ASSERT_EQ(rst.inputs.size(), 1);
        ASSERT_EQ(rst.outputs.size(), 1);
        ASSERT_EQ(rst.params.size(), 0);
    };
    auto load = [&]() {
        auto loader = GraphLoader::make(
                InputFile::make_fs(fname.c_str()), GraphDumpFormat::FLATBUFFERS_V2);
        auto rst = loader->load();
        ASSERT_EQ(rst.tensor_map.size(), 1);
        ASSERT_EQ(rst.output_var_list.size(), 1);
        ASSERT_EQ(rst.output_var_map.size(), 1);
        ASSERT_EQ(rst.output_var_map.count("softmax_out"), 1);

        HostTensorND host_x;
        auto func =
                rst.graph_compile({make_callback_copy(rst.output_var_list[0], host_x)});
        rst.tensor_map.begin()->second->copy_from(*host).sync();
        func->execute().wait();
        for (int i = 0; i < 6; i++) {
            EXPECT_NEAR(host_x.ptr<float>()[i], dst_truth.ptr<float>()[i], 1e-6);
        }
    };
    dump();
    load();
}

1019
#endif