megenginelite-sys 1.8.2

A safe megenginelite wrapper in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
190
191
192
193
194
195
196
197
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/**
 * \file src/core/test/graph/partial_execution.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

#include "megbrain/graph.h"

#if MGB_ENABLE_PARTIAL_EXECUTION

#include "megbrain/opr/basic_arith.h"
#include "megbrain/opr/io.h"
#include "megbrain/opr/tensor_manip.h"
#include "megbrain/opr/utility.h"
#include "megbrain/test/helper.h"
#include "megbrain/utils/timer.h"

using namespace mgb;

namespace mgb {
namespace cg {
class ComputingGraphImpl {
public:
    class MultiPartCompiler {
    public:
        static SmallVector<Typeinfo*> test_get_internal_opr_types();
    };
};
}  // namespace cg
}  // namespace mgb

// declare some opr types so ASSERT_OPR could work
namespace mgb {
namespace opr {
namespace {
static const SmallVector<Typeinfo*>& internal_opr_types() {
    static SmallVector<Typeinfo*> ret =
            cg::ComputingGraphImpl::MultiPartCompiler::test_get_internal_opr_types();
    return ret;
}
#define DEF(name, idx)                                                       \
    struct name {                                                            \
        static Typeinfo* typeinfo() { return internal_opr_types().at(idx); } \
    }
DEF(ShapeProvider, 0);
DEF(DeviceDataProvider, 1);
DEF(EmptyExecuteOpr, 2);
DEF(VarSinkOpr, 3);
#undef DEF
}  // anonymous namespace
}  // namespace opr
}  // namespace mgb

namespace {
ThinHashMap<Typeinfo*, size_t> get_opr_types(
        const std::unique_ptr<cg::AsyncExecutable>& func) {
    ThinHashMap<Typeinfo*, size_t> ret;
    cg::DepOprIter opr_iter{
            [&ret](cg::OperatorNodeBase* opr) { ++ret[opr->dyn_typeinfo()]; }};

    auto on_opr = [&opr_iter](cg::OperatorNodeBase* opr) {
        opr_iter.add(opr);
        return true;
    };
    func->iter_opr_seq(on_opr);
    return ret;
}
#define ASSERT_OPR(_set, _type, _num) \
    ASSERT_EQ(_num##u, _set.at(opr::_type::typeinfo()))
#define ASSERT_NO_OPR(_set, _type) ASSERT_EQ(0u, _set.count(opr::_type::typeinfo()))

class TrackableDynamicMemAlloc final : public cg::DeviceMemoryAllocator {
    std::atomic_size_t m_nr_alive{0};

public:
    void alloc_dynamic(VarNode*, DeviceTensorStorage& dest, size_t size) override {
        auto ptr = dest.comp_node().alloc_device(size);
        ++m_nr_alive;
        auto del = [this, cn = dest.comp_node()](void* ptr) {
            cn.free_device(ptr);
            --m_nr_alive;
        };
        dest.reset(dest.comp_node(), size, {static_cast<dt_byte*>(ptr), del});
    }

    size_t nr_alive() const { return m_nr_alive; }

    ~TrackableDynamicMemAlloc() { EXPECT_EQ(0u, nr_alive()); }
};

}  // anonymous namespace

TEST(TestPartialExecution, Simple) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3}), host_delta = gen({1});
    int call0 = 0, call1 = 0;
    auto make_expect = [&host_x](float delta) {
        HostTensorND hv;
        auto ptr = hv.copy_from(*host_x).ptr<float>();
        for (int i = 0; i < 6; ++i)
            ptr[i] += delta;
        return hv;
    };
    auto cb0 = [&call0, &make_expect](DeviceTensorND& dv) {
        HostTensorND hv;
        hv.copy_from(dv).sync();
        MGB_ASSERT_TENSOR_EQ(make_expect(0), hv);
        ++call0;
    };
    auto cb1 = [&call1, &make_expect](DeviceTensorND& dv) {
        HostTensorND hv;
        hv.copy_from(dv).sync();
        MGB_ASSERT_TENSOR_EQ(make_expect(1), hv);
        ++call1;
    };
    host_delta->ptr<float>()[0] = -1;
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         delta = opr::Host2DeviceCopy::make(*graph, host_delta),
         y0 = opr::CallbackInjector::make(x, cb0),
         y1 = opr::CallbackInjector::make(x + delta, cb1) + delta;

    // it should execute in part2 albeit with high priority
    set_priority(delta, -100);
    HostTensorND host_y1;
    auto funcs =
            graph->compile_multi_part({{{y0, {}}}, {make_callback_copy(y1, host_y1)}});
    ASSERT_EQ(2u, funcs.size());

    for (int i = 0; i < 4; ++i) {
        *host_x = *gen({2, 3});
        ASSERT_EQ(0, call0);
        funcs[0]->execute();
        ASSERT_TRUE(host_y1.empty());
        ASSERT_EQ(1, call0);
        ASSERT_EQ(0, call1);

        host_delta->ptr<float>()[0] = 1;
        funcs[1]->execute();
        ASSERT_EQ(1, call0);
        ASSERT_EQ(1, call1);
        MGB_ASSERT_TENSOR_EQ(make_expect(2), host_y1);

        call0 = call1 = 0;
        host_y1.resize({});
    }
}

TEST(TestPartialExecution, AddUpdate) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto dv = std::make_shared<DeviceTensorND>();
    auto hv = gen({2, 3});
    dv->copy_from(*hv);
    auto make_expect = [&hv](float delta) {
        HostTensorND ret;
        auto ptr = ret.copy_from(*hv).ptr<float>();
        for (int i = 0; i < 6; ++i)
            ptr[i] += delta;
        return ret;
    };
    auto cur_dv = [&dv]() { return HostTensorND{}.copy_from(*dv).sync(); };
    auto x = opr::SharedDeviceTensor::make(*graph, dv), y0 = x + 2.3f,
         y1 = opr::AddUpdate::make(x, x.make_scalar(-1.2f)) + 0.3f;

    HostTensorND host_y0, host_y1;
    auto funcs = graph->compile_multi_part(
            {{make_callback_copy(y0, host_y0)}, {make_callback_copy(y1, host_y1)}});

    funcs[0]->execute();
    MGB_ASSERT_TENSOR_EQ(make_expect(2.3), host_y0);
    MGB_ASSERT_TENSOR_EQ(*hv, cur_dv());

    funcs[1]->execute();
    MGB_ASSERT_TENSOR_EQ(make_expect(-1.2f), cur_dv());
    MGB_ASSERT_TENSOR_EQ(make_expect(-0.9f), host_y1);
}

TEST(TestPartialExecution, CompOrderDep) {
    constexpr float SLEEP_TIME = 0.3;
    auto graph = ComputingGraph::make();
    graph->options().var_sanity_check_first_run = false;
    auto cns = load_multiple_xpus(2);
    HostTensorGenerator<> gen;
    auto dv = std::make_shared<DeviceTensorND>();
    auto hv = gen({2, 3}, cns[0]), host_bias = gen({1}, cns[1]);
    dv->copy_from(*hv).sync();
    auto make_expect = [&hv](float delta) {
        HostTensorND ret;
        auto ptr = ret.copy_from(*hv).ptr<float>();
        for (int i = 0; i < 6; ++i)
            ptr[i] += delta;
        return ret;
    };
    auto cur_dv = [&dv]() { return HostTensorND{}.copy_from(*dv).sync(); };
    auto x = opr::SharedDeviceTensor::make(*graph, dv),
         bias = opr::Host2DeviceCopy::make(*graph, host_bias),
         y0 = opr::Copy::make(x, cns[1]) + opr::Sleep::make(bias, SLEEP_TIME),
         y1 = opr::AddUpdate::make(x, x.make_scalar(-1.2f)) + 0.3f;

    HostTensorND host_y0, host_y1;
    auto funcs = graph->compile_multi_part(
            {{make_callback_copy(y0, host_y0, false)},
             {make_callback_copy(y1, host_y1)}});

    RealTimer timer;
    funcs[0]->execute();
    // sleep kernel in cuda is easily affected by the frequency change of GPU,
    // so we just print warn log instead assert. more refer to
    // XPU-226
    auto use_time = timer.get_secs();
    if (use_time >= SLEEP_TIME / 2) {
        mgb_log_warn(
                "expect time [%f < %f], got %f", use_time, SLEEP_TIME / 2, use_time);
    }
    MGB_ASSERT_TENSOR_EQ(*hv, cur_dv());
    ASSERT_EQ(hv->shape(), host_y0.shape());

    funcs[1]->execute();
    // sleep kernel in cuda is easily affected by the frequency change of GPU,
    // so we just print warn log instead assert. more refer to
    // XPU-226
    use_time = timer.get_secs();
    if (use_time <= SLEEP_TIME) {
        mgb_log_warn("expect time [%f > %f], got %f", use_time, SLEEP_TIME, use_time);
    }
    MGB_ASSERT_TENSOR_EQ(make_expect(-1.2f), cur_dv());
    MGB_ASSERT_TENSOR_EQ(make_expect(-0.9f), host_y1);
    host_y0.sync();
    MGB_ASSERT_TENSOR_EQ(make_expect(host_bias->ptr<float>()[0]), host_y0);
}

TEST(TestPartialExecution, MultiDepType) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3}), host_y = gen({6});
    auto p0_x = opr::Host2DeviceCopy::make(*graph, host_x).rename("x"),
         p0_y = opr::Host2DeviceCopy::make(*graph, host_y).rename("y"),
         p0_y_shp = p0_y.symshape(), p0_z = p0_x.reshape(p0_y_shp) + p0_y,

         // host value dep
            p1_z = opr::MarkDynamicVar::make(p0_x).reshape(p0_y_shp) + p0_y,

         // shape dep
            p2_z = p0_x.reshape(p0_z.symshape()) + p0_y;

    HostTensorND host_z0, host_z1, host_z2;
    auto funcs = graph->compile_multi_part(
            {{make_callback_copy(p0_z, host_z0)},
             {make_callback_copy(p1_z, host_z1)},
             {make_callback_copy(p2_z, host_z2)}});

    auto oprs_1 = get_opr_types(funcs[1]), oprs_2 = get_opr_types(funcs[2]);

    ASSERT_OPR(oprs_1, Host2DeviceCopy, 1);
    ASSERT_OPR(oprs_1, MarkDynamicVar, 1);
    ASSERT_OPR(oprs_1, DeviceDataProvider, 2);
    ASSERT_NO_OPR(oprs_1, ShapeProvider);
    ASSERT_NO_OPR(oprs_1, GetVarShape);

    ASSERT_NO_OPR(oprs_2, Host2DeviceCopy);
    ASSERT_OPR(oprs_2, GetVarShape, 1);
    ASSERT_OPR(oprs_2, DeviceDataProvider, 2);
    ASSERT_OPR(oprs_2, Reshape, 1);
    ASSERT_OPR(oprs_2, ShapeProvider, 1);

    for (size_t i = 0; i < 3; ++i) {
        funcs[0]->execute();
        auto host_z0_cp = host_z0;
        host_z0.resize({});
        ASSERT_TRUE(host_z1.empty());
        funcs[1]->execute();
        ASSERT_TRUE(host_z2.empty());
        funcs[2]->execute();
        ASSERT_TRUE(host_z0.empty());

        MGB_ASSERT_TENSOR_EQ(host_z0_cp, host_z1);
        MGB_ASSERT_TENSOR_EQ(host_z0_cp, host_z2);

        host_z1.resize({});
        host_z2.resize({});

        *host_x = *gen({i + 5, 3});
        *host_y = *gen({(i + 5) * 3});
    }
}

TEST(TestPartialExecution, InternalValue) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3});
    auto x = opr::Host2DeviceCopy::make(*graph, host_x), y = x + 1, z = x * 2;
    HostTensorND host_y0, host_y1, host_z;
    auto funcs = graph->compile_multi_part(
            {{make_callback_copy(y, host_y0)},
             {make_callback_copy(y, host_y1), make_callback_copy(z, host_z)}});
    funcs[0]->execute();
    ASSERT_FALSE(host_y0.empty());
    ASSERT_TRUE(host_y1.empty());
    funcs[1]->execute();
    ASSERT_FALSE(host_y1.empty());

    auto oprs_0 = get_opr_types(funcs[0]), oprs_1 = get_opr_types(funcs[1]);
    ASSERT_OPR(oprs_0, Elemwise, 1);
    ASSERT_OPR(oprs_1, Elemwise, 1);
    ASSERT_OPR(oprs_1, DeviceDataProvider, 2);

    auto px = host_x->ptr<float>(), py0 = host_y0.ptr<float>(),
         py1 = host_y1.ptr<float>(), pz = host_z.ptr<float>();
    for (size_t i = 0; i < 6; ++i) {
        auto xv = px[i];
        ASSERT_EQ(xv + 1.f, py0[i]);
        ASSERT_EQ(xv + 1.f, py1[i]);
        ASSERT_EQ(xv * 2, pz[i]);
    }
}

TEST(TestPartialExecution, ValueReuse) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3}), host_y = gen({2, 3});
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y);
    HostTensorND out0, out1, out2;
    auto funcs = graph->compile_multi_part(
            {{make_callback_copy(x, out0)},
             {make_callback_copy(x * y + 2, out1)},
             {make_callback_copy(y, out2)}});

    funcs[0]->execute();
    MGB_ASSERT_TENSOR_EQ(*host_x, out0);

    funcs[1]->execute();
    HostTensorND out1_expect;
    graph->compile({make_callback_copy(x * y + 2, out1_expect)})->execute();
    MGB_ASSERT_TENSOR_EQ(out1_expect, out1);
    ASSERT_TRUE(out2.empty());

    funcs[2]->execute();
    MGB_ASSERT_TENSOR_EQ(*host_y, out2);
}

TEST(TestPartialExecution, MemoryManagement) {
    auto graph = ComputingGraph::make();
    auto allocator = std::make_shared<TrackableDynamicMemAlloc>();
    graph->set_device_memory_allocator(allocator);
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3});
    auto cb0 = [&](DeviceTensorND&) { ASSERT_EQ(1u, allocator->nr_alive()); };
    auto cb1 = [&](DeviceTensorND&) { ASSERT_EQ(0u, allocator->nr_alive()); };
    auto x = opr::Host2DeviceCopy::make(*graph, host_x), y = x + 1,
         z = opr::CallbackInjector::make(opr::CallbackInjector::make(y, cb0) * 2, cb1);
    HostTensorND host_y, host_z;
    auto funcs = graph->compile_multi_part(
            {{make_callback_copy(y, host_y)}, {make_callback_copy(z, host_z)}});

    for (size_t i = 0; i < 3; ++i) {
        funcs[0]->execute();
        ASSERT_EQ(1u, allocator->nr_alive());
        funcs[1]->execute();
        ASSERT_EQ(0u, allocator->nr_alive());

        auto px = host_x->ptr<float>(), py = host_y.ptr<float>(),
             pz = host_z.ptr<float>();
        for (size_t i = 0, it = host_x->layout().total_nr_elems(); i < it; ++i) {
            ASSERT_EQ(px[i] + 1.f, py[i]);
            ASSERT_EQ((px[i] + 1.f) * 2.f, pz[i]);
        }

        *host_x = *gen({i / 2 + 4, 5});
    }
}

TEST(TestPartialExecution, MemoryManagementAbort) {
    auto graph = ComputingGraph::make();
    auto allocator = std::make_shared<TrackableDynamicMemAlloc>();
    graph->set_device_memory_allocator(allocator);
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3});
    auto x = opr::Host2DeviceCopy::make_no_fwd(*graph, host_x), y = x + 1;
    graph->options().graph_opt_level = 0;
    HostTensorND out0, out1, out2;
    auto funcs = graph->compile_multi_part(
            {{make_callback_copy(x, out0)},
             {make_callback_copy(y, out1)},
             {make_callback_copy(y * 2, out2)}});

    funcs[0]->execute();
    ASSERT_EQ(1u, allocator->nr_alive());
    funcs[1]->execute();
    ASSERT_EQ(1u, allocator->nr_alive());

    // memory should be reclaimed when execution aborts

    *host_x = *gen({4, 5});
    funcs[0]->execute();
    ASSERT_EQ(1u, allocator->nr_alive());
    ASSERT_TRUE(out2.empty());
    funcs[1]->execute();
    ASSERT_EQ(1u, allocator->nr_alive());
    funcs[2]->execute();
    ASSERT_EQ(0u, allocator->nr_alive());

    HostTensorND out1_expect, out2_expect;
    graph->compile({make_callback_copy(y, out1_expect),
                    make_callback_copy(y * 2, out2_expect)})
            ->execute();
    MGB_ASSERT_TENSOR_EQ(*host_x, out0);
    MGB_ASSERT_TENSOR_EQ(out1_expect, out1);
    MGB_ASSERT_TENSOR_EQ(out2_expect, out2);
}

TEST(TestPartialExecution, Priority) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3}), host_y = gen({2, 3});
    auto x = opr::Host2DeviceCopy::make_no_fwd(*graph, host_x),
         y = opr::Host2DeviceCopy::make_no_fwd(*graph, host_y), z = x + y;
    set_priority(x, 3);
    set_priority(y, -5);
    set_priority(z, -100);
    auto funcs = graph->compile_multi_part({{{x, {}}, {y, {}}}, {{z, {}}}});
    SmallVector<opr::Host2DeviceCopy*> oprs_f0;
    funcs[0]->iter_opr_seq([&](cg::OperatorNodeBase* opr) {
        if (opr->same_type<opr::VarSinkOpr>()) {
            return true;
        }
        oprs_f0.emplace_back(&opr->cast_final_safe<opr::Host2DeviceCopy>());
        return true;
    });

    int nr_dev_data = 0;
    opr::Elemwise* opr_f1 = nullptr;
    funcs[1]->iter_opr_seq([&](cg::OperatorNodeBase* opr) {
        if (opr->same_type<opr::DeviceDataProvider>()) {
            ++nr_dev_data;
            return true;
        }
        EXPECT_EQ(nullptr, opr_f1);
        opr_f1 = &opr->cast_final_safe<opr::Elemwise>();
        return true;
    });
    ASSERT_EQ(2, nr_dev_data);

    ASSERT_EQ(2u, oprs_f0.size());
    ASSERT_EQ(host_y.get(), oprs_f0[0]->host_data().get());
    ASSERT_EQ(host_x.get(), oprs_f0[1]->host_data().get());
    ASSERT_NE(nullptr, opr_f1);

    // priorities are remapped to consecutive integers
    ASSERT_EQ(-3, oprs_f0[0]->node_prop().attribute().priority);
    ASSERT_EQ(-2, oprs_f0[1]->node_prop().attribute().priority);
    ASSERT_EQ(-1, opr_f1->node_prop().attribute().priority);
}

TEST(TestPartialExecution, OrderCheck) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3}), host_y = gen({2, 3});
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y);
    auto funcs = graph->compile_multi_part({{{x, {}}}, {{y, {}}}, {{x + y, {}}}});

    funcs[0]->execute();
    funcs[1]->execute();
    funcs[2]->execute();

    funcs[0]->execute();
    funcs[1]->execute();

    // cancel previous execution
    funcs[0]->execute();
    funcs[1]->execute();
    funcs[2]->execute();

    // order violation
    ASSERT_THROW(funcs[1]->execute(), GraphError);

    funcs[0]->execute();
    funcs[1]->execute();
    // duplicated
    ASSERT_THROW(funcs[1]->execute(), GraphError);
}

#if MGB_ENABLE_EXCEPTION
TEST(TestPartialExecution, AsyncError) {
    auto graph = ComputingGraph::make();
    HostTensorGenerator<> gen;
    auto host_x = gen({2, 3}), host_y = gen({2, 3});
    host_y->ptr<float>()[0] = host_x->ptr<float>()[0] + 1;
    auto x = opr::Host2DeviceCopy::make(*graph, host_x),
         y = opr::Host2DeviceCopy::make(*graph, host_y);

    for (int i = 0; i < 2; ++i) {
        auto funcs = graph->compile_multi_part(
                {{{x, {}}}, {{opr::AssertEqual::make(x, y), {}}}, {{y, {}}}});

        funcs[0]->execute();
        funcs[1]->execute();
        funcs[2]->execute();

        if (i == 0) {
            funcs[0]->wait();
            funcs[2]->wait();
            ASSERT_THROW(funcs[1]->wait(), MegBrainError);
        } else {
            // implicit wait
            ASSERT_THROW(funcs[0]->execute(), MegBrainError);
        }
    }
}
#endif  // MGB_ENABLE_EXCEPTION

#endif  // MGB_ENABLE_PARTIAL_EXECUTION

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