serializer_oss.cpp 42.1 KB
Newer Older
1
#include "megbrain/opr/nn_int.h"
2 3
#if MGB_ENABLE_FBS_SERIALIZATION

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

using namespace mgb;
using namespace serialization;

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

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

    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");
29
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
30 31 32 33 34 35 36 37 38
        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 = [&]() {
39
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
40 41 42 43 44 45 46
        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 已提交
47

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

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

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

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

    dump();
    load();
}

85 86
void test_metadata(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    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;

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

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

    dump();
    load();
}

120 121
void test_serializer_APlusB(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
122 123 124 125 126 127 128 129 130 131
    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"});

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

    auto load = [&]() {
        HostTensorGenerator<> gen;
140
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
141 142 143 144 145 146 147 148 149
        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 已提交
150
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
151 152 153 154 155 156 157 158 159 160 161
            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();
}

162
void test_serializer_APlusB_param(GraphDumpFormat format) {
163
    auto cns = load_multiple_xpus(2);
164
    auto fname = GET_OUTPUT_FILE(format);
165 166 167 168 169 170 171 172 173 174 175 176 177 178
    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"});

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

    auto load = [&](CompNode dest_cn) {
        auto dest_cn_loc = dest_cn.locator_logical();
M
Megvii Engine Team 已提交
188
        auto rst = loader->load({[&](CompNode::Locator& loc) { loc = dest_cn_loc; }});
189 190 191 192 193 194
        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 已提交
195
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
196 197 198 199 200 201 202 203
            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 已提交
204
    auto&& shmap = loader->shared_tensor_name_map();
205 206 207 208
    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 已提交
209
    ASSERT_EQ(1u + (cns[1].mem_node() != cns[0].mem_node()), shmap.at("y")->size());
210 211
}

212 213
void test_serializer_immutable(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
214 215 216 217 218 219 220
    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"});
221
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
222 223 224 225 226
        dumper->dump({(x + 1.f).rename("y")});
    };

    auto load = [&]() {
        HostTensorGenerator<> gen;
227
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
228 229 230 231 232 233
        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 已提交
234
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
235 236 237 238 239 240 241 242 243 244 245
            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();
}

246 247
void test_serializer_custom_loader(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
248 249 250 251 252 253
    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 已提交
254 255 256
                                       OutputFile& fout,
                                       const cg::OperatorNodeBase& opr,
                                       const HostTensorND& tensor) {
257 258 259 260 261 262
        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 已提交
263 264 265
                                       void* ptr, const TensorLayout& layout,
                                       InputFile& fin) {
        ++load_nr_call;
266 267
        size_t idx;
        if (!ptr) {
M
Megvii Engine Team 已提交
268
            load_nr_null_ptr++;
269 270 271 272
            fin.skip(sizeof(idx));
            return;
        }
        fin.read(&idx, sizeof(idx));
M
Megvii Engine Team 已提交
273
        auto&& val = saved_val.at(idx);
274 275 276 277 278 279 280 281 282 283 284 285 286
        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");
287
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
288 289 290 291 292 293 294 295
        GraphDumpConfig config;
        config.tensor_value_dumper = tensor_value_dumper;
        dumper->dump({z}, config);
    };
    dump();

    GraphLoadConfig config;
    config.tensor_value_loader = tensor_value_loader;
296
    auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
297 298 299 300 301 302 303 304 305
    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 已提交
306
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i) {
307 308 309 310 311 312 313 314 315 316 317
            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());
318 319 320 321
    if (GraphDumpFormat::FLATBUFFERS_V2 != format) {
        ASSERT_EQ(2, load_nr_null_ptr);  // immutable tensor is also shared
        ASSERT_EQ(4, load_nr_call);
    }
322 323
}

324 325
void test_serializer_many_io_var(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
326 327 328 329 330
    constexpr size_t NR_VARS = 32;
    auto dump = [&]() {
        auto graph = ComputingGraph::make();
        SymbolVarArray xs;
        cg::OperatorNodeConfig::CompNodeArray y_comp_nodes;
M
Megvii Engine Team 已提交
331
        for (size_t i = 0; i < NR_VARS; ++i) {
332 333 334 335 336 337
            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 已提交
338
            xs.push_back(opr::Host2DeviceCopy::make(*graph, host_x, std::to_string(i)));
339 340 341 342 343

            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 已提交
344 345
        auto ys = opr::Split::make(
                con,
346
                opr::Split::Options::make_partition(
M
Megvii Engine Team 已提交
347
                        con, 0, std::vector<size_t>(NR_VARS, 1)),
348 349
                OperatorNodeConfig{}.comp_node_arr(y_comp_nodes));

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

    auto load = [&]() {
        HostTensorGenerator<> gen;
356
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
357 358 359 360
        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 已提交
361
        for (size_t i = 0; i < NR_VARS; ++i) {
362 363 364 365 366 367
            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 已提交
368
            auto&& inp = rst.tensor_map.at(std::to_string(i));
369 370 371 372
            inp->resize({1}).ptr<float>()[0] = i;
        }
        auto func = rst.graph_compile(out_spec);
        func->execute();
M
Megvii Engine Team 已提交
373 374
        for (size_t i = 0; i < NR_VARS; ++i) {
            auto&& val = host_ys[i];
375 376 377 378 379 380 381 382 383
            ASSERT_EQ(TensorShape{1}, val.shape());
            ASSERT_EQ(static_cast<float>(i * 2 + 1), val.ptr<float>()[0]);
        }
    };

    dump();
    load();
}

384 385
void test_serializer_remove_set_grad(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    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));

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

    auto load = [&]() {
        HostTensorGenerator<> gen;
411
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
412 413 414 415 416 417 418 419 420
        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 已提交
421
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
422 423
            host_z_expect.ptr<float>()[i] += yv->ptr<float>()[i];
        ASSERT_EQ(2u, rst.output_var_list.size());
M
Megvii Engine Team 已提交
424 425 426
        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)}});
427 428 429 430 431 432 433 434 435
        func->execute();
        MGB_ASSERT_TENSOR_EQ(host_z_expect, host_z0);
        MGB_ASSERT_TENSOR_EQ(host_z_expect, host_z1);
    };

    dump();
    load();
}

436 437
void test_serializer_multiple_param(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
438 439 440 441 442 443 444 445 446 447
    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 已提交
448
        for (int i = 0; i < ndim; ++i)
449 450 451
            shp[i] = i + 1;

        auto cur = std::make_shared<DeviceTensorND>(cn, shp, dtype);
M
Megvii Engine Team 已提交
452 453
        uint8_t* ptr = reinterpret_cast<uint8_t*>(cur->raw_ptr());
        for (size_t i = 0, it = cur->layout().span().dist_byte(); i < it; ++i) {
454 455 456 457 458 459 460 461 462 463
            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 已提交
464
            auto dv = add_value(stream++, ndim, dtype);
465 466
            auto var = opr::SharedDeviceTensor::make(*graph, dv);
            var = opr::TypeCvt::make(
M
Megvii Engine Team 已提交
467
                    opr::reduce_sum(var, var.make_scalar(1)), dtype::Int32());
468 469 470 471
            var = opr::Copy::make(var, CompNode::load("cpu1"));
            return var;
        };
        auto x = mkvar(1, dtype::Float32());
M
Megvii Engine Team 已提交
472
        for (size_t ndim = 1; ndim <= TensorShape::MAX_NDIM; ++ndim) {
473 474 475 476 477
#define cb(_dt) x = x + mkvar(ndim, _dt());
            MEGDNN_FOREACH_COMPUTING_DTYPE(cb)
#undef cb
        }
        ASSERT_GT(values.size(), 8u);
478
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
479 480 481 482
        dumper->dump({x});
    };

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

    dump();
    load();
}

504 505
void test_serializer_const_var_shape(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
506 507 508 509 510 511 512 513
    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"});
514
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
515 516 517 518
        dumper->dump({x + 1.f});
    }

    auto run_and_check = [&](const GraphLoadConfig& config) {
519
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
520 521 522 523
        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 已提交
524 525 526 527
        auto infer_type = y.node()->owner_graph()
                                  ->static_infer_manager()
                                  .get_infer_type(y.node())
                                  .shape;
528 529 530 531 532 533 534
        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 已提交
535
        for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i)
536 537 538 539 540 541 542 543 544 545 546
            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 已提交
547
    for (bool const_shape : {false, true}) {
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        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);
570
        ASSERT_EQ(1, nr_tensor);  // immutable tensor is shared tensor
571 572 573 574
        ASSERT_EQ(1, nr_mod);
    }
}

575 576
void test_serializer_const_var_shape_output_name(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
577 578 579 580 581 582 583 584 585 586
    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");
587
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
588 589 590 591 592
        dumper->dump({y});
    }

    {
        // load
593
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
594 595 596 597 598 599 600 601 602
        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>());
    }
}

603 604
void test_serializer_priority(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
605 606 607 608 609 610 611 612 613 614 615 616 617
    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);

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

    auto load = [&](bool has_pri) {
627
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
628
        auto rst = loader->load();
M
Megvii Engine Team 已提交
629 630 631
        VarNode *x, *y;
        unpack_vector(rst.output_var_list.front().node()->owner_opr()->input(), x, y);
        auto get_pri = [](VarNode* var) {
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
            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);
}

651 652
void test_serializer_multiple_params(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
653 654 655 656 657 658 659 660 661 662
    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));
        }
663
        GraphDumper::make(OutputFile::make_fs(fname.c_str()), format)->dump(outputs);
664 665 666
    };

    auto load = [&]() {
667
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        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();
}

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

    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 已提交
695
            host_x->ptr<dt_quint8>()[i] = dt_quint8(static_cast<uint8_t>(i & 255));
696 697 698 699
        }
        auto graph = ComputingGraph::make();
        auto x = opr::Host2DeviceCopy::make(*graph, host_x, {"x"});
        auto rst = opr::Dimshuffle::make(x, {1, 2, 0});
700
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
701 702 703 704
        dumper->dump({rst});
    };

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

    dump();
    load();
}

715 716
void test_serializer_operator_name(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
717 718 719 720 721 722 723 724 725 726 727 728
    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)"});

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

    auto load = [&]() {
        HostTensorGenerator<> gen;
735
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
736 737 738 739 740 741 742 743 744 745
        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();
}
746

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

    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 已提交
765
                x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS32(0.05f)});
766
        auto y1 = opr::ConvBias::make(
M
Megvii Engine Team 已提交
767
                x, w, b, param, {}, OperatorNodeConfig{dtype::QuantizedS8(0.3f)});
768
        auto dumper = GraphDumper::make(OutputFile::make_fs(fname.c_str()), format);
769 770 771
        dumper->dump({y0, y1});
    };

M
Megvii Engine Team 已提交
772 773 774 775
    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();
776 777 778 779 780
        ASSERT_TRUE(dtype.valid());
        ASSERT_EQ(dtype, expected_dtype);
    };

    auto load = [&]() {
781
        auto loader = GraphLoader::make(InputFile::make_fs(fname.c_str()), format);
782 783 784 785 786 787 788 789 790 791
        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();
}

792 793
void test_serializer_log_exp(GraphDumpFormat format) {
    auto fname = GET_OUTPUT_FILE(format);
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    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);

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

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

    dump();
    load();

    inplace_opt = !inplace_opt;
    dump();
    load();
}
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
void test_serializer_memshare(GraphDumpFormat format) {
    std::vector<uint8_t> buf;
    HostTensorGenerator<> gen;
    constexpr size_t SIZE = 127;
    auto xval = gen({SIZE}, "cpu0"), bval = gen({1}, "cpu0");

    auto dump = [&]() {
        auto graph = ComputingGraph::make();
        auto x0 = opr::SharedDeviceTensor::make(*graph, *xval).rename("x0");
        auto x1 = opr::SharedDeviceTensor::make(*graph, *xval).rename("x1");
        auto x2 = opr::SharedDeviceTensor::make(*graph, *xval).rename("x2");
        auto x3 = opr::SharedDeviceTensor::make(*graph, *xval).rename("x3");
        auto i4 = opr::ImmutableTensor::make(*graph, *xval).rename("i4");
        auto i5 = opr::ImmutableTensor::make(*graph, *xval).rename("i5");
        auto b = opr::SharedDeviceTensor::make(*graph, *bval).rename("b");
        auto dumper = GraphDumper::make(OutputFile::make_vector_proxy(&buf), format);
        dumper->dump({((x0 + x1) + b) + (x2 + x3) + i4 + i5, x0, i4});
    };

    HostTensorND expected;
    expected.copy_from(*xval);
    for (size_t i = 0; i < SIZE; ++i) {
        auto&& v = expected.ptr<float>()[i];
        v = v * 6 + bval->ptr<float>()[0];
    }

    std::vector<uint8_t> buf_al;
    auto load = [&](bool share) {
        std::unique_ptr<InputFile> fin;
        if (share) {
            buf_al.resize(buf.size());
            memcpy(buf_al.data(), buf.data(), buf.size());

            fin = InputFile::make_mem_proxy(
                    std::shared_ptr<void>{std::shared_ptr<void>{}, buf_al.data()},
                    buf.size());
        } else {
            fin = InputFile::make_mem_proxy(buf.data(), buf.size());
        }
        auto loader = GraphLoader::make(std::move(fin), format);
        auto rst = loader->load();
        auto x = rst.output_var_map.at("x0");
        auto i4 = rst.output_var_map.at("i4");
        auto&& opr = x.node()->owner_opr()->cast_final_safe<opr::SharedDeviceTensor>();
        auto&& opr_imm =
                i4.node()->owner_opr()->cast_final_safe<opr::ImmutableTensor>();
        HostTensorND val;
        auto func =
                rst.graph_compile({make_callback_copy(rst.output_var_list[0], val)});
        func->execute();
        return std::make_pair(
                val, std::vector<DeviceTensorND>{*opr.dev_data(), opr_imm.value()});
    };

    auto in_range = [](const std::vector<uint8_t>& buf, DeviceTensorND& dv) {
        auto p0 = reinterpret_cast<uint8_t*>(dv.raw_ptr()),
             p1 = reinterpret_cast<uint8_t*>(p0 + dv.layout().span().high_byte);
        return buf.data() <= p0 && p1 <= buf.data() + buf.size();
    };

    for (bool share : {false, true}) {
        buf.clear();
        dump();
        auto get = load(share);
        MGB_ASSERT_TENSOR_EQ(*xval, HostTensorND{}.copy_from(get.second[0]).sync());
        MGB_ASSERT_TENSOR_EQ(expected, get.first);
        ASSERT_EQ(share, in_range(buf_al, get.second[0]));
        ASSERT_EQ(share, in_range(buf_al, get.second[1]));
    }
}

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 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
}  // 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);
}

1003 1004 1005 1006
TEST(TestSerializer2, CustomLoaderV2) {
    test_serializer_custom_loader(GraphDumpFormat::FLATBUFFERS_V2);
}

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
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);
}

1047 1048 1049 1050
TEST(TestSerializer2, ShareMemv2) {
    test_serializer_memshare(GraphDumpFormat::FLATBUFFERS_V2);
}

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
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();
1072 1073 1074
        //! if convert to reduce and elemwise, nr_opr is 6
        // ASSERT_EQ(rst.nr_opr, 6);
        ASSERT_EQ(rst.nr_opr, 2);
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
        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();
}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
TEST(TestSerializer2, TestElemwiseMultiTypeLoadDump) {
    auto fname = GET_OUTPUT_FILE(GraphDumpFormat::FLATBUFFERS_V2);
    TensorShape shape{3};
    auto cn = CompNode::load("xpu0");
    std::shared_ptr<HostTensorND> host0 =
            std::make_shared<HostTensorND>(cn, shape, dtype::Float32{});
    std::shared_ptr<HostTensorND> host1 =
            std::make_shared<HostTensorND>(cn, shape, dtype::Float32{});
    HostTensorND dst_truth;
    host0->ptr<float>()[0] = 2;
    host0->ptr<float>()[1] = 2;
    host0->ptr<float>()[2] = -1;
    host1->ptr<float>()[0] = 1;
    host1->ptr<float>()[1] = 2;
    host1->ptr<float>()[2] = 3;

    auto dump = [&](opr::ElemwiseMultiType::Param::Mode mode, size_t nr_opr) {
        auto graph = ComputingGraph::make();
        OperatorNodeConfig config;
        config.name("input0");
        auto h2d0 = opr::Host2DeviceCopy::make(*graph, host0, config);
        config.name("input1");
        auto h2d1 = opr::Host2DeviceCopy::make(*graph, host1, config);

        auto x = opr::ElemwiseMultiType::make(
                {h2d0, h2d1}, {mode}, OperatorNodeConfig{dtype::Bool()});
        x.rename("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();
        ASSERT_EQ(rst.nr_opr, nr_opr);
    };
    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(), 2);
        ASSERT_EQ(rst.output_var_map.count("out"), 1);

        HostTensorND host_x;
        auto func =
                rst.graph_compile({make_callback_copy(rst.output_var_list[0], host_x)});
        for (auto& input : rst.tensor_map) {
            if (input.first == "input0") {
                input.second->copy_from(*host0).sync();
            } else if (input.first == "input1") {
                input.second->copy_from(*host1).sync();
            }
        }
        func->execute().wait();
        for (int i = 0; i < 3; i++) {
            EXPECT_EQ(host_x.ptr<bool>()[i], dst_truth.ptr<bool>()[i]);
        }
    };
    dump(opr::ElemwiseMultiType::Param::Mode::EQ, 4);
    load();
    dump(opr::ElemwiseMultiType::Param::Mode::LT, 4);
    load();
    dump(opr::ElemwiseMultiType::Param::Mode::LEQ, 4);
    load();
    dump(opr::ElemwiseMultiType::Param::Mode::NEQ, 5);
    load();

    auto dump_single_input = [&](opr::ElemwiseMultiType::Param::Mode mode,
                                 size_t nr_opr) {
        auto graph = ComputingGraph::make();
        auto h2d0 = opr::Host2DeviceCopy::make(*graph, host0);
        auto x = opr::ElemwiseMultiType::make(
                {h2d0}, {mode}, OperatorNodeConfig{dtype::Bool()});
        x.rename("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();
        ASSERT_EQ(rst.nr_opr, nr_opr);
    };
    auto load_single_input = [&]() {
        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_map.count("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(*host0).sync();
        func->execute().wait();
        for (int i = 0; i < 3; i++) {
            EXPECT_EQ(host_x.ptr<bool>()[i], dst_truth.ptr<bool>()[i]);
        }
    };
    host0->ptr<float>()[2] = INFINITY;
    dump_single_input(opr::ElemwiseMultiType::Param::Mode::ISINF, 4);
    load_single_input();
    host0->ptr<float>()[2] = NAN;
    dump_single_input(opr::ElemwiseMultiType::Param::Mode::ISNAN, 4);
    load_single_input();
}

1204
#endif