interpreter_impl.cpp 59.3 KB
Newer Older
1
#include "./interpreter_impl.h"
2

3 4
#include "range/v3/all.hpp"

5
#include "megbrain/common.h"
6 7
#include "megbrain/imperative/opr_utility.h"
#include "megbrain/imperative/ops/autogen.h"
8 9
#include "megbrain/imperative/ops/backward_graph.h"
#include "megbrain/imperative/ops/opr_attr.h"
10
#include "megbrain/imperative/ops/utility.h"
11 12
#include "megbrain/imperative/utils/to_string.h"

13
#include "../blob_manager_impl.h"
14 15
#include "../event_pool.h"
#include "../op_trait.h"
16
#include "megbrain/imperative/backtrace.h"
17 18 19 20 21
using namespace mgb;
using namespace imperative;
using namespace interpreter;
using namespace interpreter::intl;

22
namespace {
M
Megvii Engine Team 已提交
23 24 25 26 27 28 29 30
auto tinfo_to_tid(SmallVector<TensorInfo*> tinfo) {
    SmallVector<uint64_t> tid;
    for (auto* ptinfo : tinfo) {
        tid.push_back(ptinfo->id);
    }
    return tid;
};
}  // namespace
31

32
namespace mgb {
M
Megvii Engine Team 已提交
33
using namespace profiler;
34 35
}

36 37 38 39 40
#if defined(_WIN32) || defined(_WIN64)
#define SYMBOL_EXPORT __declspec(dllexport)
#else
#define SYMBOL_EXPORT __attribute__((visibility("default")))
#endif
41 42 43 44 45 46 47

namespace mgb {

/**
 * USAGE
 *
 *   header:
48
 *     namespace mgb { void imperative_log_profile(const char* message); }
49 50 51 52 53
 *
 *   code:
 *     mgb::imperative_log_profile("MY MESSAGE");
 *
 **/
54
SYMBOL_EXPORT
55
void imperative_log_profile_begin(const char* message) {
56
    MGB_RECORD_EVENT(CustomEvent, std::string{message});
57 58
}

59
SYMBOL_EXPORT
60
void imperative_log_profile_end(const char* message) {
61
    MGB_RECORD_EVENT(CustomFinishEvent, std::string{message});
62 63
}

64
SYMBOL_EXPORT
M
Megvii Engine Team 已提交
65
void imperative_log_profile(const char* message) {
66 67 68 69
    imperative_log_profile_begin(message);
    imperative_log_profile_end(message);
}

70 71 72 73
SYMBOL_EXPORT
void imperative_log_profile_begin(const char* message, const char* device) {
    auto comp_node = CompNode::load(device);
    MGB_RECORD_EVENT(CustomEvent, std::string{message}, {}, comp_node);
M
Megvii Engine Team 已提交
74 75
    MGB_RECORD_EVENT(
            RecordDeviceEvent, EventPool::with_timer().alloc_shared(comp_node));
76 77 78 79 80
}

SYMBOL_EXPORT
void imperative_log_profile_end(const char* message, const char* device) {
    auto comp_node = CompNode::load(device);
M
Megvii Engine Team 已提交
81 82
    MGB_RECORD_EVENT(
            RecordDeviceEvent, EventPool::with_timer().alloc_shared(comp_node));
83 84 85
    MGB_RECORD_EVENT(CustomFinishEvent, std::string{message}, {}, comp_node);
}

M
Megvii Engine Team 已提交
86
}  // namespace mgb
87

88 89 90 91 92 93 94 95 96 97 98 99 100 101
std::thread::id ChannelImpl::get_worker_tid() {
    return m_worker_state.tid;
}

ChannelImpl::ChannelState& ChannelImpl::get_channel_state() {
    assert_in_channel();
    return m_channel_state;
}

ChannelImpl::WorkerState& ChannelImpl::get_worker_state() {
    assert_in_worker();
    return m_worker_state;
}

102 103 104
void ChannelImpl::WorkQueue::on_async_queue_worker_thread_start() {
    sys::set_thread_name("worker");
    m_owner->m_worker_state.tid = std::this_thread::get_id();
105
    auto custom_allocator = [&](CompNode device, size_t size) {
106 107 108
        auto blob = Blob::make(device, size);
        m_owner->alloc_tensor_with_evict(blob.get());
        return blob->storage();
109 110
    };
    OpDef::set_allocator(custom_allocator);
111 112
}

113
// Do not use m_xxx_state directly
114 115 116
#define m_channel_state
#define m_worker_state

117
std::unique_ptr<Interpreter::Channel> InterpreterImpl::create_channel() {
118 119 120 121 122 123 124 125 126 127 128 129
    auto ret = std::make_unique<ChannelImpl>();
#if !(defined(_WIN32) || defined(_WIN64))
    auto disable_channels = [](void) -> void {
        for (ChannelImpl* channel : ChannelImpl::m_all_active_channels) {
            if (channel->worker_started()) {
                channel->update_status_to_forked();
            }
        }
    };
    pthread_atfork(nullptr, nullptr, static_cast<void (*)(void)>(disable_channels));
#endif
    return ret;
130 131 132 133 134 135 136
}

Interpreter& Interpreter::inst() {
    static InterpreterImpl inst_;
    return inst_;
}

137
Handle ChannelImpl::put(const HostTensorND& value, bool no_cache) {
138
    MGB_LOCK_GUARD(m_spin);
139
    assert_available();
140 141 142 143 144
    std::optional<StackManager::Guard> guard;
    if (Profiler::is_profiling()) {
        auto& state = get_channel_state();
        guard.emplace("Put", &state.stack_manager);
    }
145
    auto info = put_impl(value, no_cache);
M
Megvii Engine Team 已提交
146
    return reinterpret_cast<Handle>(info);
147 148 149
}

TensorInfo* ChannelImpl::put_impl(const HostTensorND& value, bool no_cache) {
150 151 152 153 154
    if (value.empty()) {
        auto layout = value.layout();
        layout.init_contiguous_stride();
        const_cast<HostTensorND&>(value).reset(value.storage(), layout);
    }
155
    auto info = alloc();
156 157 158 159 160 161
    constexpr int size_threshold = TensorShape::MAX_NDIM;
    init(info, {value.layout(), value.comp_node()});
    if (value.layout().total_nr_elems() <= size_threshold) {
        info->h_value = value;
        info->desc.value = value.proxy_to_default_cpu();
    }
162 163 164 165 166 167 168 169 170 171
    if (Profiler::is_profiling()) {
        m_worker.add_task(
                {Profiler::next_id(), Put{info, value, no_cache},
                 get_channel_state().stack_manager.dump()});
    } else {
        m_worker.add_task({
                Profiler::next_id(),
                Put{info, value, no_cache},
        });
    }
172 173

    if (get_channel_state().options.async_level == 0) {
174
        sync_impl();
175
        info->desc.comp_node.sync();
176 177
        auto err = info->desc.comp_node.check_async_error();
        mgb_assert(!err, "%s", err->what());
178
    }
179 180 181
    return info;
}

182
Handle ChannelImpl::put(const DeviceTensorND& data, const HostTensorND& hvalue) {
183
    MGB_LOCK_GUARD(m_spin);
184
    assert_available();
M
Megvii Engine Team 已提交
185
    return reinterpret_cast<Handle>(put_impl(data, hvalue));
186
}
M
Megvii Engine Team 已提交
187 188
TensorInfo* ChannelImpl::put_impl(
        const DeviceTensorND& data, const HostTensorND& hvalue) {
189 190 191 192 193
    std::optional<StackManager::Guard> guard;
    if (Profiler::is_profiling()) {
        auto& state = get_channel_state();
        guard.emplace("Put", &state.stack_manager);
    }
M
Megvii Engine Team 已提交
194
    auto info = alloc();
195
    MGB_RECORD_EVENT(TensorCommandEvent, info->id, TensorCommandKind::Put);
196
    constexpr int size_threshold = TensorShape::MAX_NDIM;
197
    init(info, {data.layout(), data.comp_node()});
198 199 200
    if ((!hvalue.empty()) && info->desc.layout.total_nr_elems() <= size_threshold) {
        info->desc.value = hvalue.proxy_to_default_cpu();
    }
201
    info->ptr = Tensor::make(data, hvalue);
M
Megvii Engine Team 已提交
202 203 204
    MGB_RECORD_EVENT(
            TensorProduceEvent, info->id, info->desc.layout, info->desc.comp_node,
            data.raw_ptr());
205
    info->status = TensorInfo::Produced;
206
    MGB_RECORD_EVENT(TensorCommandFinishEvent, info->id, TensorCommandKind::Put);
M
Megvii Engine Team 已提交
207 208 209
    return info;
}

210
void ChannelImpl::del(Handle handle) {
211
    MGB_LOCK_GUARD(m_spin);
M
Megvii Engine Team 已提交
212
    if (!check_available()) {
213 214
        return;
    }
215 216 217 218
    del_impl(handle);
}

void ChannelImpl::del_impl(Handle handle) {
219 220 221
    mgb_assert(m_valid_handle.count(handle), "invalid handle: %p", handle);
    auto* info = reinterpret_cast<TensorInfo*>(handle);
    m_valid_handle.erase(handle);
222 223 224 225 226 227 228 229 230 231
    if (Profiler::is_profiling()) {
        m_worker.add_task(
                {Profiler::next_id(), Del{info},
                 get_channel_state().stack_manager.dump()});
    } else {
        m_worker.add_task({
                Profiler::next_id(),
                Del{info},
        });
    }
232 233
}

234
void ChannelImpl::drop(Handle handle) {
235
    MGB_LOCK_GUARD(m_spin);
236
    assert_available();
237 238
    auto& state = get_channel_state();
    if (state.options.enable_drop) {
M
Megvii Engine Team 已提交
239 240
        mgb_assert(
                m_valid_handle.find(handle) != m_valid_handle.end(),
241
                "invalid handle: %p", handle);
242
        auto* info = reinterpret_cast<TensorInfo*>(handle);
243 244 245 246 247 248 249 250 251 252
        if (Profiler::is_profiling()) {
            m_worker.add_task(
                    {Profiler::next_id(), Drop{info},
                     get_channel_state().stack_manager.dump()});
        } else {
            m_worker.add_task({
                    Profiler::next_id(),
                    Drop{info},
            });
        }
253 254 255
    }
}

256
void ChannelImpl::dispatch_default_cpu(
M
Megvii Engine Team 已提交
257
        std::shared_ptr<OpDef> op, const SmallVector<TensorInfo*>& input_infos,
258 259
        const SmallVector<LogicalTensorDesc>& input_descs,
        SmallVector<Handle>* outputs) {
260
    auto& state = get_channel_state();
261

262 263 264 265
    std::optional<StackManager::Guard> guard;
    if (Profiler::is_profiling()) {
        guard.emplace(op->trait()->make_name(*op), &state.stack_manager);
    }
266

M
Megvii Engine Team 已提交
267 268
    auto [output_descs, validated] =
            OpDef::infer_output_attrs_fallible(*op, input_descs);
269
    MGB_RECORD_EVENT(ShapeInferEvent, validated);
270

271 272
    SmallVector<DeviceTensorND> input_tensornds;
    CompNode output_cn;
273 274
    {
        MGB_LOCK_GUARD(m_mutex);
275
        for (auto&& info : input_infos) {
276
            auto input_cn = info->desc.comp_node;
277
            if (!output_cn.valid()) {
278 279 280 281 282 283
                output_cn = input_cn;
            } else {
                mgb_assert(output_cn == input_cn, "cannot decide output comp node");
            }

            if (info->ptr && info->ptr->try_get_value()) {
M
Megvii Engine Team 已提交
284 285
                input_tensornds.emplace_back(
                        info->ptr->get_value().proxy_to_default_cpu());
286
            } else {
287
                // We assign h_value before drop ptr
288 289
                mgb_assert(!info->h_value.empty(), "inp->h_value is empty!");
                input_tensornds.emplace_back(info->h_value.proxy_to_default_cpu());
290 291 292 293 294 295 296 297 298
            }
        }
    }

    SmallVector<DeviceTensorND> output_tensornds;
    for (auto&& desc : output_descs) {
        // TODO: may conflict with condtake, which need alloc inside
        mgb_assert(!desc.layout.is_empty());
        // use HostTensorND alloc_host for cuda pinned memory
M
Megvii Engine Team 已提交
299 300
        output_tensornds.emplace_back(
                HostTensorND(output_cn, desc.layout).proxy_to_default_cpu());
301 302
    }

303
    uint64_t op_id = Profiler::next_id();
304

305 306 307 308 309 310 311 312 313
    if (op->trait()->apply_on_device_tensornd) {
        OpDef::apply_on_device_tensornd(*op, input_tensornds, &output_tensornds);
    } else {
        // proxy to apply_on_physical_tensor
        SmallVector<TensorPtr> input_tensors;
        for (auto&& input_tensornd : input_tensornds) {
            input_tensors.push_back(Tensor::make(
                    input_tensornd, HostTensorND::make_proxy(input_tensornd)));
        }
314 315
        auto output_tensors = OpDef::apply_on_physical_tensor(
                *op, input_tensors, output_descs, validated);
316 317 318 319
        for (size_t i = 0; i < output_tensors.size(); ++i) {
            output_tensornds[i].copy_from_fixlayout(output_tensors[i]->dev_tensor());
        }
    }
320 321 322

    SmallVector<TensorInfo*> output_infos;
    for (auto&& tensornd : output_tensornds) {
M
Megvii Engine Team 已提交
323 324
        HostTensorND host_tensornd =
                HostTensorND::make_proxy(tensornd).proxy_to_comp_node(output_cn);
325
        // use `put` for consistency
326
        auto info = reinterpret_cast<TensorInfo*>(put_impl(host_tensornd, false));
327
        mgb_assert(info->shape_valid());
328
        output_infos.push_back(info);
M
Megvii Engine Team 已提交
329
        outputs->push_back(reinterpret_cast<Handle>(info));
330
    }
331 332
    auto& bt = get_backtrace();
    auto op_info_getter = [op, bt] {
333 334
        std::unordered_map<std::string, std::string> op_info;
        auto props = OpDef::props(*op);
M
Megvii Engine Team 已提交
335
        for (auto&& [key, value] : props) {
336 337
            op_info[key] = value;
        }
338 339 340 341 342 343
        if (bt != nullptr) {
            if (bt->py_stack_info != nullptr)
                op_info["python_backtrace"] = bt->py_traceback();
            if (bt->trans_stack_info.size() > 0)
                op_info["transformation_backtrace"] = bt->transformation_traceback();
        }
344 345
        return op_info;
    };
M
Megvii Engine Team 已提交
346
    MGB_RECORD_EVENT(
347 348 349
            OpDispatchEvent, op_id, guard.value().name(), op_info_getter,
            tinfo_to_tid(input_infos), tinfo_to_tid(output_infos),
            state.stack_manager.dump());
350
}
351

352
void ChannelImpl::dispatch_kernel(
M
Megvii Engine Team 已提交
353
        std::shared_ptr<OpDef> op, const SmallVector<TensorInfo*>& input_infos,
354 355
        const SmallVector<LogicalTensorDesc>& input_descs,
        SmallVector<Handle>* outputs) {
356
    auto& state = get_channel_state();
357 358
    auto& options = state.options;

359 360 361 362
    std::optional<StackManager::Guard> guard;
    if (Profiler::is_profiling()) {
        guard.emplace(op->trait()->make_name(*op), &state.stack_manager);
    }
363

M
Megvii Engine Team 已提交
364 365
    auto [output_descs, validated] =
            OpDef::infer_output_attrs_fallible(*op, input_descs);
366
    MGB_RECORD_EVENT(ShapeInferEvent, validated);
367

368 369 370 371
    SmallVector<TensorInfo*> output_infos;
    output_infos.reserve(output_descs.size());

    outputs->reserve(output_descs.size());
372 373
    for (int i = 0; i < output_descs.size(); ++i) {
        auto&& desc = output_descs[i];
374
        auto info = alloc();
375
        init(info, std::move(desc));
376 377
        // make sure desc's value is consistent with h_value
        if (!info->desc.value.empty()) {
378 379
            info->h_value = HostTensorND::make_proxy(info->desc.value)
                                    .proxy_to_comp_node(info->desc.comp_node);
380
        }
381
        output_infos.push_back(info);
M
Megvii Engine Team 已提交
382
        outputs->push_back(reinterpret_cast<Handle>(info));
383
    }
384 385 386
    auto& bt = get_backtrace();
    ApplyOp cmd{Profiler::next_id(),     std::move(op), std::move(input_infos),
                std::move(output_infos), validated,     bt};
387
    if (Profiler::is_profiling()) {
388
        auto op_info_getter = [op = cmd.op, bt = cmd.bt] {
389 390 391 392 393
            std::unordered_map<std::string, std::string> op_info;
            auto props = OpDef::props(*op);
            for (auto&& [key, value] : props) {
                op_info[key] = value;
            }
394 395 396 397 398 399 400
            if (bt != nullptr) {
                if (bt->py_stack_info != nullptr)
                    op_info["python_backtrace"] = bt->py_traceback();
                if (bt->trans_stack_info.size() > 0)
                    op_info["transformation_backtrace"] =
                            bt->transformation_traceback();
            }
401 402
            return op_info;
        };
403
        MGB_RECORD_EVENT(
404 405 406
                OpDispatchEvent, cmd.id, guard.value().name(), op_info_getter,
                tinfo_to_tid(cmd.inputs), tinfo_to_tid(cmd.outputs),
                state.stack_manager.dump());
407
        m_worker.add_task(
408
                {Profiler::next_id(), std::move(cmd),
409 410 411 412
                 get_channel_state().stack_manager.dump()});
    } else {
        m_worker.add_task({
                Profiler::next_id(),
413
                std::move(cmd),
414 415
        });
    }
416
    if (!validated && options.async_level == 1) {
417
        sync_impl();
418
    } else if (options.async_level == 0) {
419
        sync_impl();
420
        // check device error
421
        for (auto&& oup : *outputs) {
422 423
            auto info = reinterpret_cast<TensorInfo*>(oup);
            info->ptr->comp_node().sync();
424 425
            auto err = info->ptr->comp_node().check_async_error();
            mgb_assert(!err, "%s", err->what());
426
        }
427
    }
428 429 430
}

SmallVector<Handle> ChannelImpl::apply_op(
M
Megvii Engine Team 已提交
431
        std::shared_ptr<OpDef> op, const SmallVector<Handle>& inputs) {
432
    MGB_LOCK_GUARD(m_spin);
433
    assert_available();
434
    auto* input = reinterpret_cast<TensorInfo*>(inputs[0]);
435
    if (op->same_type<GetVarShape>() && input->shape_valid()) {
436 437 438 439 440 441 442 443 444
        size_t ndim = input->desc.layout.ndim;
        auto& gvs = op->cast_final_safe<GetVarShape>();
        if (gvs.axis == MEGDNN_MAX_NDIM) {
            HostTensorND shape_tensor{input->desc.comp_node, {ndim}, dtype::Int32()};
            DeviceTensorND shape_tensor_device = shape_tensor.proxy_to_default_cpu();
            cg::copy_shape_to_tensor_value(shape_tensor_device, input->desc.layout);
            return {reinterpret_cast<Handle>(put_impl(shape_tensor, false))};
        }
    }
445 446 447 448
    return apply_op_impl(std::move(op), inputs);
}

SmallVector<Handle> ChannelImpl::apply_op_impl(
M
Megvii Engine Team 已提交
449
        std::shared_ptr<OpDef> op, const SmallVector<Handle>& inputs) {
450
    auto& state = get_channel_state();
451
    for (auto i : inputs) {
M
Megvii Engine Team 已提交
452 453 454
        mgb_assert(
                m_valid_handle.find(i) != m_valid_handle.end(), "invalid handle: %p",
                i);
455 456 457 458
    }
    SmallVector<TensorInfo*> input_infos;
    SmallVector<LogicalTensorDesc> input_descs;
    {
459
        MGB_LOCK_GUARD(m_info_spin);
460 461
        for (auto i : inputs) {
            auto info = reinterpret_cast<TensorInfo*>(i);
M
Megvii Engine Team 已提交
462 463 464
            mgb_assert(
                    !info->invalid,
                    "an input tensor is unusable due to previous error");
465 466 467 468 469 470
            input_infos.push_back(info);
            input_descs.push_back(info->desc);
        }
    }

    SmallVector<Handle> outputs;
471
    DispatchMode dispatch_mode = state.options.enable_host_compute
M
Megvii Engine Team 已提交
472 473
                                       ? OpDef::decide_dispatch_mode(*op, input_descs)
                                       : DispatchMode::KERNEL;
474
    switch (dispatch_mode) {
475 476 477 478 479 480 481 482 483
        case DEFAULT_CPU: {
            dispatch_default_cpu(op, input_infos, input_descs, &outputs);
            break;
        }
        case KERNEL: {
            dispatch_kernel(op, input_infos, input_descs, &outputs);
            break;
        }
    }
484 485 486
    return outputs;
}

487
HostTensorND ChannelImpl::get_value(Handle handle) {
488
    MGB_LOCK_GUARD(m_spin);
489
    assert_available();
M
Megvii Engine Team 已提交
490 491 492
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
493
    auto info = reinterpret_cast<TensorInfo*>(handle);
494
    // donnot use info->value_fetched, it's unsafe
495
    mgb_assert(!info->invalid, "tensor is unusable due to previous error");
496 497 498 499 500 501 502 503 504 505 506 507

    // pin
    SmallVector<TensorInfo*> vec({info});
    m_dtr.pin(vec);

    auto ret = wait_tensor(info, TensorProp::HostValue)->get_value();

    // unpin
    auto& state = get_channel_state();
    auto dtr_evictee_minimum_size = state.options.dtr_evictee_minimum_size;
    m_dtr.unpin(vec, dtr_evictee_minimum_size);
    return ret;
508 509
}

510
TensorShape ChannelImpl::get_shape(Handle handle) {
511
    MGB_LOCK_GUARD(m_spin);
512
    assert_available();
M
Megvii Engine Team 已提交
513 514 515
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
516
    auto info = reinterpret_cast<TensorInfo*>(handle);
517
    if (info->shape_valid()) {
518 519
        return info->desc.layout;
    }
520
    TensorShape ret = wait_tensor(info, TensorProp::Shape)->layout();
521
    mgb_assert(ret.ndim > 0);
522 523 524
    return ret;
}

525
DType ChannelImpl::get_dtype(Handle handle) {
526
    MGB_LOCK_GUARD(m_spin);
527
    assert_available();
M
Megvii Engine Team 已提交
528 529 530
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
531
    auto info = reinterpret_cast<TensorInfo*>(handle);
532
    MGB_RECORD_EVENT(TensorGetPropEvent, info->id, TensorProp::DType);
533 534 535 536 537
    auto ret = info->desc.layout.dtype;
    mgb_assert(ret.valid());
    return ret;
}

538
CompNode ChannelImpl::get_device(Handle handle) {
539
    MGB_LOCK_GUARD(m_spin);
540
    assert_available();
M
Megvii Engine Team 已提交
541 542 543
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
544
    auto info = reinterpret_cast<TensorInfo*>(handle);
545
    MGB_RECORD_EVENT(TensorGetPropEvent, info->id, TensorProp::Device);
546 547 548 549 550
    auto ret = info->desc.comp_node;
    mgb_assert(ret.valid());
    return ret;
}

551
DeviceTensorND ChannelImpl::get_dev_tensor(Handle handle) {
552
    MGB_LOCK_GUARD(m_spin);
553
    assert_available();
M
Megvii Engine Team 已提交
554 555 556
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
557
    auto info = reinterpret_cast<TensorInfo*>(handle);
558
    return wait_tensor(info, TensorProp::DevValue)->dev_tensor();
559 560 561
}

void ChannelImpl::sync() {
562
    MGB_LOCK_GUARD(m_spin);
563
    assert_available();
564 565 566 567
    sync_impl();
}

void ChannelImpl::sync_impl() {
568 569 570 571 572 573
    m_worker.wait_all_task_finish();
    MGB_LOCK_GUARD(m_mutex);
    check_worker_exc_unsafe();
}

void ChannelImpl::close() {
574
    MGB_LOCK_GUARD(m_spin);
575 576 577 578
    if (!check_available()) {
        return;
    }
    std::vector<Handle> valid_handles(m_valid_handle.begin(), m_valid_handle.end());
M
Megvii Engine Team 已提交
579
    for (auto* handle : valid_handles) {
580
        del_impl(handle);
581 582 583
    }
    mgb_assert(m_valid_handle.empty());
    mgb_log_debug("%ld tensor exists before channel close", (long)valid_handles.size());
584
    sync_impl();
585
    m_status = ChannelRunningStatus::CLOSED;
586 587
}

588
size_t ChannelImpl::get_option(std::string name) {
589
    MGB_LOCK_GUARD(m_spin);
590
    assert_available();
591 592
    auto& state = get_channel_state();
    return state.options.get_option(name);
593 594
}

595
void ChannelImpl::set_option(std::string name, size_t value) {
596
    MGB_LOCK_GUARD(m_spin);
597
    assert_available();
598 599
    auto& state = get_channel_state();
    state.options.set_option(name, value);
600 601 602 603 604 605 606 607 608
    // FIXME
    if (name == "enable_dtr_auto_drop" && value) {
        auto custom_allocator = [&](CompNode device, size_t size) {
            auto blob = Blob::make(device, size);
            alloc_tensor_with_evict(blob.get());
            return blob->storage();
        };
        BlobManager::inst()->set_allocator(custom_allocator);
    }
609 610 611 612 613 614 615 616 617 618
    if (Profiler::is_profiling()) {
        m_worker.add_task(
                {Profiler::next_id(), SetOption{name, value},
                 get_channel_state().stack_manager.dump()});
    } else {
        m_worker.add_task({
                Profiler::next_id(),
                SetOption{name, value},
        });
    }
619 620
}

621 622
void ChannelImpl::clear_candidates() {
    MGB_LOCK_GUARD(m_spin);
623
    assert_available();
624 625 626
    m_dtr.candidates.clear();
}

627
TensorInfo* ChannelImpl::alloc() {
628
    auto& state = get_channel_state();
M
Megvii Engine Team 已提交
629
    auto info = [this] {
630
        MGB_LOCK_GUARD(m_pool_spin);
631
        return m_pool.alloc();
632 633 634
    }();
    info->id = Profiler::next_id();
    if (Profiler::is_profiling()) {
635
        size_t tensor_id = state.stack_manager.current()->next_id("tensor");
M
Megvii Engine Team 已提交
636 637
        info->name =
                state.stack_manager.dump().to_string() + ssprintf(":%zu", tensor_id);
638
    }
639
    return info;
640 641
}

642
void ChannelImpl::init(TensorInfo* info, LogicalTensorDesc&& desc) {
M
Megvii Engine Team 已提交
643
    m_valid_handle.insert(reinterpret_cast<Handle>(info));
644
    MGB_RECORD_EVENT(TensorDeclareEvent, info->id, info->name);
645
    mgb_assert(desc.comp_node.valid(), "comp_node invalid");
646
    info->status = TensorInfo::Allocated;
647
    info->desc = std::move(desc);
648 649
}

M
Megvii Engine Team 已提交
650
void ChannelImpl::do_drop(TensorInfo* ptr, bool user = false) {
651 652
    if (!ptr->producer) {
        if (user) {
M
Megvii Engine Team 已提交
653 654 655 656
            mgb_log_warn(
                    "the input that produced tensor %p has been deleted, this drop "
                    "operation will be ignored",
                    ptr);
657 658 659 660 661 662 663
        }
        return;
    }
    if (ptr->evict_type != EvictType::NONE) {
        return;
    }
    ptr->evict_type = EvictType::DROP;
664
    ptr->status = TensorInfo::Dropped;
665 666 667
    release_tensor(ptr);
}

668
void ChannelImpl::free(TensorInfo* ptr) {
669 670
    auto& state = get_worker_state();
    if (state.options.enable_dtr_auto_drop) {
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        // Evicting a tensor, rather than freeing it, can avoid pinning
        // potentially exploding amounts of memory and allow us to save
        // more memory.
        ptr->allow_delete = true;
        if (!ptr->ref_cnt) {
            recursive_free(ptr);
        } else {
            do_drop(ptr);
        }
    } else {
        real_free(ptr);
    }
}

void ChannelImpl::recursive_free(TensorInfo* ptr) {
686
    MGB_RECORD_EVENT(TensorCommandEvent, ptr->id, TensorCommandKind::RecFree);
687
    SmallVector<TensorInfo*> inps;
688 689 690 691 692 693 694 695 696 697 698 699 700
    if (ptr->producer) {
        for (auto i : ptr->producer->inputs) {
            if (i && --i->ref_cnt == 0) {
                inps.push_back(i);
            }
        }
    }
    real_free(ptr);
    for (auto i : inps) {
        if (i->allow_delete) {
            recursive_free(i);
        }
    }
701
    MGB_RECORD_EVENT(TensorCommandFinishEvent, ptr->id, TensorCommandKind::RecFree);
702 703 704
}

void ChannelImpl::real_free(TensorInfo* ptr) {
705 706
    auto& state = get_worker_state();
    if (ptr->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
707 708 709 710
        m_dtr.erase_candidate(ptr);
    }
    detach_users(ptr);
    ptr->detach_producer();
711 712
    bool has_value = ptr->ptr != nullptr;
    if (has_value) {
713
        MGB_RECORD_EVENT(TensorReleaseEvent, ptr->id);
714
    }
715
    MGB_RECORD_EVENT(TensorEraseEvent, ptr->id, ptr->ptr_use_count);
716
    ptr->status = TensorInfo::Deleted;
717
    MGB_LOCK_GUARD(m_pool_spin);
718 719 720
    m_pool.free(ptr);
}

721 722 723 724 725 726 727
std::unordered_set<ChannelImpl*> ChannelImpl::m_all_active_channels{};
MGB_MUTEX ChannelImpl::m_all_active_channels_mutex{};

ChannelImpl::ChannelImpl() : m_worker(this) {
    MGB_LOCK_GUARD(m_all_active_channels_mutex);
    m_all_active_channels.emplace(this);
}
728

729 730
ChannelImpl::~ChannelImpl() {
    close();
731 732
    MGB_LOCK_GUARD(m_all_active_channels_mutex);
    m_all_active_channels.erase(this);
733
}
734

735
void ChannelImpl::produce_tensor(TensorInfo* dest, TensorPtr ptr) {
736
    auto& state = get_worker_state();
737
    MGB_LOCK_GUARD(m_mutex);
738
    MGB_LOCK_GUARD(m_info_spin);
739
    m_dtr.update_used_time(dest);
M
Megvii Engine Team 已提交
740 741
    MGB_RECORD_EVENT(
            TensorProduceEvent, dest->id, ptr->layout(), ptr->comp_node(),
742
            ptr->raw_ptr_not_for_readwrite());
743
    // update tensor desc for static infer
744
    dest->update_layout(ptr->layout());
745 746
    // in order to avoid performance impact,
    // memory forwarding is disabled when DTR is enabled
747
    if (state.options.enable_dtr_auto_drop || state.options.disable_memory_forwarding) {
748 749
        ptr->to_contiguous_inplace();
    }
750
    dest->desc.comp_node = ptr->comp_node();
751
    dest->memory = ptr->blob()->size();
752
    dest->ptr = std::move(ptr);
753
    dest->evict_type = EvictType::NONE;
754
    dest->status = TensorInfo::Produced;
755 756
    if (dest->pinned == 0 &&
        dest->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
757 758
        m_dtr.insert_candidate(dest);
    }
759
    notify_tensor_unsafe(dest);
760 761
}

762
void ChannelImpl::release_tensor(TensorInfo* dest) {
763
    MGB_RECORD_EVENT(TensorReleaseEvent, dest->id);
764 765
    MGB_LOCK_GUARD(m_mutex);
    dest->ptr.reset();
766 767 768 769
    auto& state = get_worker_state();
    if (dest->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
        m_dtr.erase_candidate(dest);
    }
770 771
}

772
void ChannelImpl::regenerate(TensorInfo* dest) {
773
    if (dest->evict_type == EvictType::DROP) {
M
Megvii Engine Team 已提交
774 775
        auto&& path = dest->producer;
        m_apply_stack.push(
776 777
                {ApplyOp{path->id, path->op, path->inputs, path->outputs}, 0, dest,
                 "dtr"});
M
Megvii Engine Team 已提交
778 779
        if (!m_applying)
            flush_apply_stack();
780 781 782
    }
}

783
void ChannelImpl::do_apply_op(const ApplyOp& cmd, std::string reason) {
784 785
    using namespace ranges;
    using namespace ranges::views;
786
    auto& state = get_worker_state();
M
Megvii Engine Team 已提交
787 788
    bool profiling_device =
            Profiler::is_profiling() && Profiler::get_option("profile_device", 0);
789
    uint64_t apply_id = cmd.id;
790
    SmallVector<TensorPtr> inputs;
791
    inputs.reserve(cmd.inputs.size());
792 793 794
    // refcnt == 1, owners: [TensorInfo::ptr]
    for (auto i : cmd.inputs) {
        mgb_assert(i->ptr, "Invalid input tensor ptr!");
795
        // refcnt ++, owners: [i->ptr, tensor_inputs]
796
        // tensor_inputs.push_back(i->ptr);
797
        inputs.push_back(i->ptr);
798
    }
M
Megvii Engine Team 已提交
799 800
    if (state.options.enable_dtr_auto_drop &&
        state.options.dtr_eviction_threshold > 0) {
801 802
        auto_evict(0);
    }
M
Megvii Engine Team 已提交
803
    auto apply_on_physical_tensor =
804
            [&](auto&& self, const OpDef& def, SmallVector<TensorPtr>&& inputs,
805 806
                SmallVector<LogicalTensorDesc>& output_descs,
                const bool& validated) -> SmallVector<TensorPtr> {
807
        if (def.trait()->make_forward_graph) {
808 809 810 811 812 813 814 815 816 817
            auto apply_functor = [&](std::shared_ptr<OpDef> op,
                                     SmallVector<TensorPtr> inputs,
                                     size_t nr_outputs) -> SmallVector<TensorPtr> {
                auto opname = op->trait()->make_name(*op);
                imperative_log_profile_begin(opname.c_str());
                auto outputs = self(self, *op, std::move(inputs), output_descs, false);
                imperative_log_profile_end(opname.c_str());
                return outputs;
            };
            auto const_functor = [&](TensorPtr value) -> TensorPtr { return value; };
818 819
            // apply recursivily
            SmallVector<LogicalTensorDesc> input_descs;
M
Megvii Engine Team 已提交
820
            for (auto&& input : inputs) {
821
                input_descs.push_back({{{}, input->dtype()}, input->comp_node()});
822
            }
823
            auto forward_graph = OpDef::make_forward_graph(def, input_descs);
824 825
            auto outputs = forward_graph.apply<TensorPtr>(
                    inputs, apply_functor, const_functor);
826 827
            return outputs;
        }
828 829 830 831 832 833 834 835 836 837
        // Check Input Layout
        // Get the input layout constraints, and if the constraint is not satisfied
        // inplace update the layout and blob to make the tensor contiguous
        auto&& constraints = OpDef::get_input_layout_constraint(def, inputs);
        for (size_t idx = 0; idx < inputs.size(); ++idx) {
            auto&& layout_checker = constraints[idx];
            if (layout_checker) {
                inputs[idx]->to_contiguous_inplace(layout_checker);
            }
        }
838
        auto outputs = OpDef::apply_on_physical_tensor(
839
                def, std::move(inputs), output_descs, validated);
840 841 842 843 844
        for (auto& o : outputs) {
            o->set_ready_event(
                    record_event(o->comp_node(), def.same_type<imperative::Barrier>()));
        }
        return outputs;
845
    };
846
    MGB_RECORD_EVENT(OpExecuteEvent, apply_id, {}, reason);
847 848 849 850
    SmallVector<std::pair<CompNode, uint64_t>> kernels;
    if (profiling_device) {
        // Collecting devices
        SmallVector<CompNode> devices;
851 852 853
        for (auto&& i : concat(cmd.inputs, cmd.outputs)) {
            if (i != nullptr && count(devices, i->desc.comp_node) == 0) {
                devices.push_back(i->desc.comp_node);
854
                kernels.push_back({i->desc.comp_node, Profiler::next_id()});
855 856 857
            }
        }
    }
M
Megvii Engine Team 已提交
858
    for (auto* input : cmd.inputs) {
859
        auto input_id = input->id;
860 861 862
        MGB_RECORD_EVENT(OpInputEvent, input_id);
        MGB_RECORD_EVENT(TensorUsageEvent, input_id);
        MGB_RECORD_EVENT(OpInputFinishEvent, input_id);
863 864
    }
    // Before wait
M
Megvii Engine Team 已提交
865
    // TODO: split operator wait and execute so that OpWait could be corrected recorded.
866
    // Before execute
M
Megvii Engine Team 已提交
867
    for (auto&& [device, kernel_id] : kernels) {
868
        MGB_RECORD_EVENT(KernelLaunchEvent, apply_id, kernel_id, device);
M
Megvii Engine Team 已提交
869
        MGB_RECORD_EVENT_IF(
870 871
                (Profiler::get_option("profile_device", 0)), RecordDeviceEvent,
                Timer::record_device(device));
872 873
    }
    // Apply op
874
    SmallVector<LogicalTensorDesc> output_descs;
875 876 877 878 879 880
    bool validated = cmd.validated;
    if (!state.options.enable_dtr_auto_drop) {
        for (auto i : cmd.outputs) {
            output_descs.push_back(i->desc);
        }
    } else {
881
        // i may be null
882
        validated = false;
883 884 885
        for (auto i : cmd.outputs) {
            output_descs.push_back({});
        }
886
    }
887
    // Here std::move is REQUIRED for removing duplicated references.
888
    auto outputs = apply_on_physical_tensor(
889
            apply_on_physical_tensor, *cmd.op, std::move(inputs), output_descs,
890
            validated);
891
    // After execute
M
Megvii Engine Team 已提交
892 893
    for (auto&& [device, kernel_id] : kernels) {
        MGB_RECORD_EVENT_IF(
894 895
                (Profiler::get_option("profile_device", 0)), RecordDeviceEvent,
                Timer::record_device(device));
896
        MGB_RECORD_EVENT(KernelLaunchFinishEvent, apply_id, kernel_id, device);
897 898
    }
    // End profiling operator
899 900
    mgb_assert(outputs.size() == cmd.outputs.size());
    for (size_t i = 0; i < outputs.size(); ++i) {
901
        auto output = cmd.outputs[i];
902
        if (mgb_unlikely(output == nullptr)) {
903 904
            MGB_RECORD_EVENT(OpOutputEvent, 0);
            MGB_RECORD_EVENT(OpOutputFinishEvent, 0);
905
        } else if (mgb_unlikely(output->ptr != nullptr)) {
906 907
            MGB_RECORD_EVENT(OpOutputEvent, output->id);
            MGB_RECORD_EVENT(OpOutputFinishEvent, output->id);
908
        } else {
909
            MGB_RECORD_EVENT(OpOutputEvent, output->id);
910
            produce_tensor(output, outputs[i]);
911
            MGB_RECORD_EVENT(OpOutputFinishEvent, output->id);
912
            sample_on_device(output->desc.comp_node, false);
913 914 915 916 917 918 919 920
        }
    }

    if (state.options.enable_dtr_auto_drop) {
        double estimate_compute_time = 0;
        for (auto i : cmd.inputs) {
            estimate_compute_time += i->memory;
        }
921
        for (auto i : outputs) {
922
            estimate_compute_time += i->blob()->size();
923 924 925 926 927 928 929
        }
        m_dtr.estimate_timestamp += estimate_compute_time / 1e8;
        for (auto i : cmd.outputs) {
            if (i != nullptr) {
                i->compute_time = estimate_compute_time;
            }
        }
930 931 932
        auto& state = get_worker_state();
        auto dtr_evictee_minimum_size = state.options.dtr_evictee_minimum_size;
        m_dtr.unpin(cmd.inputs, dtr_evictee_minimum_size);
933
    }
934
    MGB_RECORD_EVENT(OpExecuteFinishEvent, apply_id, {}, reason);
935
    // End profiling operator
936
}
937

938 939
void ChannelImpl::flush_apply_stack() {
    m_applying = true;
940
    auto& state = get_worker_state();
941
    while (!m_apply_stack.empty()) {
M
Megvii Engine Team 已提交
942 943
        auto& [cmd, idx, recomp, reason] =
                m_apply_stack.top();  // cmd.inputs[0~idx-1] is in memory
944 945 946 947 948
        if (idx == 0) {
            if (state.options.enable_dtr_auto_drop) {
                m_dtr.pin(cmd.inputs);
            }
            if (recomp) {
M
Megvii Engine Team 已提交
949 950
                MGB_RECORD_EVENT(
                        TensorCommandEvent, recomp->id, TensorCommandKind::ReGen);
951 952 953
            }
        }
        bool regen = false;
M
Megvii Engine Team 已提交
954
        for (size_t i = idx; i < cmd.inputs.size(); i++) {
955 956 957 958 959 960
            auto&& p = cmd.inputs[i];
            if (state.options.enable_dtr_auto_drop) {
                m_dtr.update_used_time(p);
            }
            if (!p->ptr && p->evict_type != EvictType::NONE) {
                idx = i + 1;
M
Megvii Engine Team 已提交
961
                regenerate(p);  // add ApplyOp to the stack
962 963 964 965
                regen = true;
                break;
            }
        }
M
Megvii Engine Team 已提交
966 967
        if (regen)
            continue;
968
        // the required input tensors are already in memory
M
Megvii Engine Team 已提交
969 970
        auto [cmd_backup, recomp_backup, reason_backup] =
                std::make_tuple(cmd, recomp, reason);
971
        m_apply_stack.pop();
972
        do_apply_op(cmd_backup, reason_backup);
973
        if (recomp_backup) {
M
Megvii Engine Team 已提交
974 975 976
            MGB_RECORD_EVENT(
                    TensorCommandFinishEvent, recomp_backup->id,
                    TensorCommandKind::ReGen);
977 978
            for (auto o : cmd_backup.outputs) {
                if (o) {
979 980 981 982
                    m_dtr.update_dsu_after_recompute(o);
                }
            }
        }
983
    }
984
    m_applying = false;
985 986
}

987
bool ChannelImpl::auto_evict(size_t force_num) {
988
    auto& state = get_worker_state();
989
    if (!m_dtr.comp_node.valid()) {
990
        return false;
991 992
    }
    size_t current_memory = m_dtr.comp_node.get_used_memory();
993
    size_t flag = false;
M
Megvii Engine Team 已提交
994 995 996
    while ((state.options.dtr_eviction_threshold > 0 &&
            current_memory > state.options.dtr_eviction_threshold) ||
           force_num > 0) {
997
        MGB_RECORD_EVENT(AutoEvictEvent);
998
        sample_on_device(m_dtr.comp_node, false);
999
        auto best = m_dtr.find_best_tensor(state.options.enable_dtr_sqrt_sampling);
1000
        if (!best) {
1001
            MGB_RECORD_EVENT(AutoEvictFinishEvent);
1002 1003 1004 1005
            break;
        }
        if (best->ptr.unique() && best->ptr->blob().unique()) {
            current_memory -= best->memory;
1006
            if (force_num > 0) {
M
Megvii Engine Team 已提交
1007
                force_num--;
1008 1009
            }
            flag = true;
1010 1011 1012 1013
        }
        do_drop(best);
        if (best->evict_type == EvictType::DROP) {
            m_dtr.update_dsu_after_evict(best);
1014
        }
1015
        sample_on_device(m_dtr.comp_node, false);
1016
        MGB_RECORD_EVENT(AutoEvictFinishEvent);
1017
    }
1018
    return flag;
1019 1020
}

1021 1022
void ChannelImpl::detach_users(TensorInfo* dest) {
    SmallVector<TensorInfo::ComputePath*> users = dest->users;
M
Megvii Engine Team 已提交
1023
    for (auto* user : users) {
1024 1025
        SmallVector<TensorInfo*> outputs = user->outputs;
        SmallVector<TensorInfo*> inputs = user->inputs;
M
Megvii Engine Team 已提交
1026 1027 1028 1029 1030
        for (auto* output : outputs) {
            // When a `ComputePath` is detach from it's input,
            // there is no need to reserve it,
            // so we detach all output of this path
            // to decrease it's `ref_cnt` to zero.
1031 1032 1033 1034 1035
            if (output == nullptr) {
                continue;
            }
            regenerate(output);
            output->detach_producer();
M
Megvii Engine Team 已提交
1036 1037
            for (auto* input : inputs) {
                input->ref_cnt--;
1038
            }
1039
        }
1040
        // now user is dead
1041
    }
1042
    mgb_assert(dest->users.empty(), "ComputePath leaking");
1043 1044
}

1045
bool ChannelImpl::check_available() {
1046
    return m_status == ChannelRunningStatus::RUNING;
1047 1048
}

1049 1050 1051 1052 1053
TensorPtr ChannelImpl::wait_tensor(TensorInfo* info, TensorProp prop) {
    std::unique_lock<decltype(m_mutex)> lock(m_mutex);
    mgb_assert(!m_waitee, "duplicate waitee");
    m_waitee = info;
    m_waitee_id = Profiler::next_id();
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    auto backtrace_getter = [bt = get_backtrace()]() {
        std::unordered_map<std::string, std::string> infos;
        if (bt != nullptr) {
            if (bt->py_stack_info != nullptr)
                infos["python_backtrace"] = bt->py_traceback();
            if (bt->trans_stack_info.size() > 0)
                infos["transformation_backtrace"] = bt->transformation_traceback();
        }
        return infos;
    };
    MGB_RECORD_EVENT(
            TensorWaitPropEvent, info->id, m_waitee_id, prop, backtrace_getter);
1066
    bool require_host = prop == TensorProp::HostValue;
1067
    bool require_dev = prop == TensorProp::DevValue;
M
Megvii Engine Team 已提交
1068
    auto host_available = [&] { return info->ptr && info->ptr->value_fetched(); };
1069
    auto dev_available = [&] { return info->ptr; };
1070
    bool wait_host = false;
1071
    bool wait_regen = false;
1072
    if (require_host && !host_available()) {
1073 1074
        // avoid dead lock
        lock.unlock();
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        if (Profiler::is_profiling()) {
            m_worker.add_task(
                    {Profiler::next_id(), GetValue{info},
                     get_channel_state().stack_manager.dump()});
        } else {
            m_worker.add_task({
                    Profiler::next_id(),
                    GetValue{info},
            });
        }
1085
        lock.lock();
1086
        wait_host = true;
1087
    }
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    if (require_dev && !dev_available()) {
        lock.unlock();
        if (Profiler::is_profiling()) {
            m_worker.add_task(
                    {Profiler::next_id(), StartRegen{info},
                     get_channel_state().stack_manager.dump()});
        } else {
            m_worker.add_task({
                    Profiler::next_id(),
                    StartRegen{info},
            });
        }
        lock.lock();
        wait_regen = true;
    }
    if (require_dev) {
        m_cv.wait(lock, [&]() {
            check_worker_exc_unsafe();
            return dev_available();
        });
    } else {
        m_cv.wait(lock, [&]() {
            check_worker_exc_unsafe();
            return require_host ? host_available() : static_cast<bool>(info->ptr);
        });
    }
1114
    auto ptr = info->ptr;
1115 1116
    MGB_RECORD_EVENT(
            TensorWaitPropFinishEvent, info->id, m_waitee_id, prop, backtrace_getter);
1117
    m_waitee = nullptr;
1118
    if (wait_host) {
1119
        auto err = ptr->comp_node().check_async_error();
1120 1121
        mgb_assert(!err, "%s", err->what());
    }
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    if (wait_regen) {
        lock.unlock();
        if (Profiler::is_profiling()) {
            m_worker.add_task(
                    {Profiler::next_id(), StopRegen{info},
                     get_channel_state().stack_manager.dump()});
        } else {
            m_worker.add_task({
                    Profiler::next_id(),
                    StopRegen{info},
            });
        }
        lock.lock();
    }
1136
    return ptr;
1137 1138 1139 1140
}

void ChannelImpl::notify_tensor_unsafe(TensorInfo* info) {
    if (info == m_waitee) {
1141
        MGB_RECORD_EVENT(TensorNotifyPropEvent, info->id);
1142
        m_cv.notify_all();
1143
    }
1144 1145 1146 1147
}

std::unordered_set<TensorInfo*> ChannelImpl::collect_valid_tensors() {
    std::unordered_set<TensorInfo*> valid_tensors;
M
Megvii Engine Team 已提交
1148
    for (auto* handle : m_valid_handle) {
1149 1150
        auto* info = reinterpret_cast<TensorInfo*>(handle);
        valid_tensors.insert(info);
1151
    }
1152
    return valid_tensors;
1153 1154
}

1155
void ChannelImpl::alloc_tensor_with_evict(OwnedBlob* x) {
1156
    bool in_worker = (get_worker_tid() == std::this_thread::get_id());
1157 1158 1159 1160 1161 1162
    auto reserve_size = [&](size_t size) {
        if (!m_dtr.comp_node.valid()) {
            return false;
        }
        while (size > m_dtr.comp_node.get_max_block_size_available()) {
            bool evict_suc = auto_evict(1);
M
Megvii Engine Team 已提交
1163 1164
            if (!evict_suc)
                return false;
1165 1166 1167 1168
        }
        return true;
    };
    auto pre_level = set_log_level(LogLevel::NO_LOG);
1169 1170 1171
    if (in_worker) {
        reserve_size(x->size());
    }
1172
    if (!BlobManager::inst()->try_alloc_direct(x, x->size())) {
1173
        bool suc = false;
1174 1175 1176 1177 1178
        if (in_worker) {
            while (!suc) {
                if (!auto_evict(1)) {
                    break;
                }
1179 1180 1181
                if (BlobManager::inst()->try_alloc_direct(x, x->size())) {
                    suc = true;
                }
1182 1183 1184 1185
            }
        }
        if (!suc) {
            set_log_level(pre_level);
M
Megvii Engine Team 已提交
1186 1187 1188
            mgb_log_warn(
                    "reallocating all cuda memory to alleviate fragmentation, the "
                    "performance may be affected");
1189
            set_log_level(LogLevel::NO_LOG);
1190
            imperative_log_profile_begin("defrag");
1191
            BlobManager::inst()->defrag(x->comp_node());
1192
            imperative_log_profile_end("defrag");
1193 1194 1195
            mgb_assert(
                    BlobManager::inst()->try_alloc_direct(x, x->size()),
                    "allocation failed after defrag");
1196
        }
1197
    }
1198 1199 1200
    set_log_level(pre_level);
}

1201
void ChannelImpl::process_one_task(Command& icmd) {
1202 1203
    using namespace ranges;
    using namespace ranges::views;
1204
    auto& state = get_worker_state();
1205
    auto& options = state.options;
M
Megvii Engine Team 已提交
1206
    // TODO: remove std::visit for support osx 10.12
1207
    auto cmd_visitor = [&](const auto& cmd) {
M
Megvii Engine Team 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
        using T = std::decay_t<decltype(cmd)>;
        if constexpr (std::is_same_v<T, Put>) {
            MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::Put);
            MGB_RECORD_EVENT_IF(
                    (Profiler::get_option("profile_device", 0)), RecordDeviceEvent,
                    Timer::record_device(cmd.value.comp_node()));
            auto value = cmd.no_cache ? std::make_shared<Tensor>(cmd.value)
                                      : Tensor::make(cmd.value);
            MGB_RECORD_EVENT_IF(
                    (Profiler::get_option("profile_device", 0)), RecordDeviceEvent,
                    Timer::record_device(cmd.value.comp_node()));
            produce_tensor(cmd.dest, std::move(value));
            MGB_RECORD_EVENT(
                    TensorCommandFinishEvent, cmd.dest->id, TensorCommandKind::Put);
            sample_on_device(cmd.dest->desc.comp_node, false);
        } else if constexpr (std::is_same_v<T, ApplyOp>) {
            for (auto& i : cmd.inputs) {
1225
                if (mgb_unlikely(i->invalid)) {
M
Megvii Engine Team 已提交
1226 1227 1228
                    MGB_LOCK_GUARD(m_mutex);
                    for (auto& i : cmd.outputs) {
                        i->invalid = true;
1229
                    }
M
Megvii Engine Team 已提交
1230 1231 1232
                    return;
                }
            }
1233 1234 1235 1236 1237 1238 1239 1240
            if (state.options.enable_dtr_auto_drop) {
                m_apply_stack.push({cmd, 0, nullptr, "cmd"});
                flush_apply_stack();
                for (size_t i = 0; i < cmd.outputs.size(); ++i) {
                    auto output = cmd.outputs[i];
                    if (output == nullptr) {
                        continue;
                    }
M
Megvii Engine Team 已提交
1241
                    output->dsu_ptr = std::make_shared<DsuNode>(output->compute_time);
1242
                }
1243 1244
            } else {
                do_apply_op(cmd, "cmd");
M
Megvii Engine Team 已提交
1245 1246 1247 1248 1249 1250 1251
            }
            if (state.options.enable_drop && state.options.record_computing_path) {
                auto is_inplace = [](std::tuple<TensorInfo*, TensorInfo*> tuple2) {
                    auto& input = std::get<0>(tuple2);
                    auto& output = std::get<1>(tuple2);
                    if (!input->ptr || !output->ptr) {
                        return false;
1252
                    }
M
Megvii Engine Team 已提交
1253 1254 1255 1256 1257 1258 1259
                    return input->ptr->blob()->storage() ==
                           output->ptr->blob()->storage();
                };
                // FIXME: do not use opname as identifier
                auto get_name = [](const OpDef& opdef) {
                    if (auto attr = opdef.try_cast_final<OprAttr>()) {
                        return attr->type.c_str();
1260
                    }
M
Megvii Engine Team 已提交
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
                    return opdef.dyn_typeinfo()->name;
                };

                auto is_cross_cn = [comp_node = m_dtr.comp_node](TensorInfo* info) {
                    return info->desc.comp_node != comp_node;
                };

                bool cross_cn = any_of(concat(cmd.inputs, cmd.outputs), is_cross_cn);
                bool inplace =
                        any_of(cartesian_product(cmd.inputs, cmd.outputs), is_inplace);

                if (!inplace && !cross_cn && !m_dtr.is_bad_op(get_name(*cmd.op))) {
                    TensorInfo::ComputePath::make(
1274
                            cmd.id, cmd.op, cmd.inputs, cmd.outputs);
M
Megvii Engine Team 已提交
1275 1276
                    size_t detach_cnt = 0;
                    if (!strcmp(get_name(*cmd.op), "BatchNorm") &&
1277
                        cmd.outputs.size() == 6) {
M
Megvii Engine Team 已提交
1278 1279
                        cmd.outputs[0]->detach_producer();  // detach running_mean
                        cmd.outputs[1]->detach_producer();  // detach running_var
1280
                        for (auto input : cmd.inputs) {
M
Megvii Engine Team 已提交
1281
                            input->ref_cnt -= 2;
1282 1283
                        }
                    }
M
Megvii Engine Team 已提交
1284 1285 1286 1287 1288 1289 1290
                    for (auto output : cmd.outputs) {
                        if (output->producer &&
                            !output->size_exceeds_thd(
                                    state.options.dtr_evictee_minimum_size)) {
                            output->detach_producer();
                            detach_cnt++;
                        }
1291
                    }
M
Megvii Engine Team 已提交
1292 1293
                    for (auto input : cmd.inputs) {
                        input->ref_cnt -= detach_cnt;
1294
                    }
1295
                }
1296
            }
M
Megvii Engine Team 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
        } else if constexpr (std::is_same_v<T, Del>) {
            MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::Del);
            CompNode device = cmd.dest->desc.comp_node;
            uint64_t tensor_id = cmd.dest->id;
            free(cmd.dest);
            MGB_RECORD_EVENT(
                    TensorCommandFinishEvent, tensor_id, TensorCommandKind::Del);
            sample_on_device(device, false);
        } else if constexpr (std::is_same_v<T, GetValue>) {
            if (cmd.dest->invalid)
                return;
            imperative_log_profile_begin("GetValue");
            if (!cmd.dest->ptr && cmd.dest->evict_type != EvictType::NONE) {
                regenerate(cmd.dest);
            }
            cmd.dest->ptr->fetch_value();
1313
            MGB_LOCK_GUARD(m_mutex);
M
Megvii Engine Team 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
            notify_tensor_unsafe(cmd.dest);
            imperative_log_profile_end("GetValue");
        } else if constexpr (std::is_same_v<T, Drop>) {
            if (cmd.dest->invalid)
                return;
            MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::Drop);
            do_drop(cmd.dest, true);
            MGB_RECORD_EVENT(
                    TensorCommandFinishEvent, cmd.dest->id, TensorCommandKind::Drop);
        } else if constexpr (std::is_same_v<T, SetOption>) {
            options.set_option(cmd.key, cmd.value);
        } else if constexpr (std::is_same_v<T, StartProfile>) {
            MGB_RECORD_EVENT(StartProfileEvent);
            CompNode::sync_all();
            for (auto* info : cmd.capture_tensors) {
                MGB_RECORD_EVENT(TensorDeclareEvent, info->id, info->name);
                if (info->status == TensorInfo::Produced) {
1331
                    // TODO: handle drop
M
Megvii Engine Team 已提交
1332 1333 1334
                    MGB_RECORD_EVENT(
                            TensorProduceEvent, info->id, info->desc.layout,
                            info->desc.comp_node, info->ptr->dev_tensor().raw_ptr());
1335 1336
                }
            }
M
Megvii Engine Team 已提交
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
            CompNode::foreach ([&](CompNode device) {
                sample_on_device(device, true);
                MGB_RECORD_EVENT_IF(
                        (Profiler::get_option("profile_device", 0)), RecordDeviceEvent,
                        Timer::record_device(device));
            });
            MGB_RECORD_EVENT(StartProfileFinishEvent);
        } else if constexpr (std::is_same_v<T, StopProfile>) {
            MGB_RECORD_EVENT(StopProfileEvent);
            for (auto* info : cmd.escape_tensors) {
                bool has_value = info->status == TensorInfo::Produced;
                if (has_value) {
                    MGB_RECORD_EVENT(TensorReleaseEvent, info->id);
                }
                MGB_RECORD_EVENT(TensorEraseEvent, info->id);
1352
            }
M
Megvii Engine Team 已提交
1353 1354 1355
            CompNode::foreach (
                    [&](CompNode device) { sample_on_device(device, true); });
            MGB_RECORD_EVENT(StopProfileFinishEvent);
1356 1357
        } else if constexpr (std::is_same_v<T, StopStep>) {
            MGB_RECORD_EVENT(StopStepEvent);
M
Megvii Engine Team 已提交
1358 1359 1360 1361
        } else if constexpr (std::is_same_v<T, PushScope>) {
            MGB_RECORD_EVENT(ScopeEvent, cmd.scope_name);
        } else if constexpr (std::is_same_v<T, PopScope>) {
            MGB_RECORD_EVENT(ScopeFinishEvent, cmd.scope_name);
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
        } else if constexpr (std::is_same_v<T, StartRegen>) {
            if (cmd.dest->invalid)
                return;
            cmd.dest->pin();
            if (!cmd.dest->ptr && cmd.dest->evict_type != EvictType::NONE) {
                regenerate(cmd.dest);
            }
            MGB_LOCK_GUARD(m_mutex);
            notify_tensor_unsafe(cmd.dest);
        } else if constexpr (std::is_same_v<T, StopRegen>) {
            cmd.dest->unpin();
M
Megvii Engine Team 已提交
1373 1374
        } else {
            static_assert(!std::is_same_v<T, T>);
1375
        }
M
Megvii Engine Team 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    };
    std::visit(
            [&](const auto& cmd) {
                using T = std::decay_t<decltype(cmd)>;
                if (!options.catch_worker_execption) {
                    cmd_visitor(cmd);
                    return;
                }
                try {
                    cmd_visitor(cmd);
                } catch (...) {
                    MGB_LOCK_GUARD(m_mutex);
                    if constexpr (std::is_same_v<T, ApplyOp>) {
                        for (auto oup : cmd.outputs) {
                            oup->invalid = true;
                        }
                    } else if constexpr (std::is_same_v<T, Put>) {
                        cmd.dest->invalid = true;
                    }
                    m_worker_exc = std::current_exception();
                    MGB_RECORD_EVENT(WorkerExceptionEvent);
                    if (m_waitee) {
                        notify_tensor_unsafe(m_waitee);
                    }
                }
            },
            icmd.data);
1403 1404 1405 1406
}

void ChannelImpl::check_worker_exc_unsafe() {
    if (m_worker_exc) {
1407 1408
        // for reuse interpreter_for_py after some exception tests
        m_waitee = nullptr;
1409 1410
        std::exception_ptr exc;
        std::swap(exc, m_worker_exc);
1411 1412 1413 1414 1415
        try {
            std::rethrow_exception(exc);
        } catch (...) {
            throw AsyncError();
        }
1416 1417
    }
}
1418

1419
void ChannelImpl::start_profile() {
1420
    MGB_LOCK_GUARD(m_spin);
1421
    assert_available();
1422 1423
    auto capture_tensors = collect_valid_tensors();
    if (capture_tensors.size() > 0) {
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
        if (Profiler::is_profiling()) {
            m_worker.add_task(
                    {Profiler::next_id(), StartProfile{std::move(capture_tensors)},
                     get_channel_state().stack_manager.dump()});
        } else {
            m_worker.add_task({
                    Profiler::next_id(),
                    StartProfile{std::move(capture_tensors)},
            });
        }
1434
    }
1435 1436
}

1437
void ChannelImpl::stop_profile() {
1438
    MGB_LOCK_GUARD(m_spin);
1439
    assert_available();
1440 1441
    auto escape_tensors = collect_valid_tensors();
    if (escape_tensors.size() > 0) {
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
        if (Profiler::is_profiling()) {
            m_worker.add_task(
                    {Profiler::next_id(), StopProfile{std::move(escape_tensors)},
                     get_channel_state().stack_manager.dump()});
        } else {
            m_worker.add_task({
                    Profiler::next_id(),
                    StopProfile{std::move(escape_tensors)},
            });
        }
1452
    }
1453 1454
}

1455 1456 1457 1458 1459 1460 1461 1462 1463
void ChannelImpl::stop_step() {
    MGB_LOCK_GUARD(m_spin);
    assert_available();
    mgb_assert(Profiler::is_profiling() == true, "Profiler isn't profiling!");
    m_worker.add_task(
            {Profiler::next_id(), StopStep{},
             get_channel_state().stack_manager.dump()});
}

1464
void ChannelImpl::push_scope(std::string name) {
1465
    MGB_LOCK_GUARD(m_spin);
1466
    assert_available();
1467
    auto& state = get_channel_state();
1468
    state.stack_manager.enter(name);
1469
    MGB_RECORD_EVENT(ScopeEvent, name);
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
    if (Profiler::is_profiling()) {
        m_worker.add_task(
                {Profiler::next_id(), PushScope{name},
                 get_channel_state().stack_manager.dump()});
    } else {
        m_worker.add_task({
                Profiler::next_id(),
                PushScope{name},
        });
    }
1480 1481 1482
}

void ChannelImpl::pop_scope(std::string name) {
1483
    MGB_LOCK_GUARD(m_spin);
1484
    assert_available();
1485
    auto& state = get_channel_state();
1486
    state.stack_manager.exit(name);
1487
    MGB_RECORD_EVENT(ScopeFinishEvent, name);
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
    if (Profiler::is_profiling()) {
        m_worker.add_task(
                {Profiler::next_id(), PopScope{name},
                 get_channel_state().stack_manager.dump()});
    } else {
        m_worker.add_task({
                Profiler::next_id(),
                PopScope{name},
        });
    }
1498 1499
}

1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
BackTraceInfoPtr& ChannelImpl::get_backtrace() {
    return m_bt;
}

void ChannelImpl::set_backtrace(BackTraceInfoPtr bt) {
    m_bt = std::move(bt);
}

void ChannelImpl::clear_backtrace() {
    m_bt = nullptr;
}

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
bool ChannelImpl::worker_started() const {
    return m_worker.worker_started();
}

void ChannelImpl::update_status_to_forked(void) {
    MGB_LOCK_GUARD(m_spin);
    m_status = ChannelRunningStatus::FORKED;
}

void ChannelImpl::assert_available() const {
    if (m_status == ChannelRunningStatus::RUNING) {
        return;
    } else if (m_status == ChannelRunningStatus::CLOSED) {
        mgb_assert(false, "Channel already closed");
    } else if (m_status == ChannelRunningStatus::FORKED) {
        mgb_assert(
                false,
                "your program is forked and megengine is be disabled in subprocess, if "
                "you want to use megengine in subprocess, please DO NOT setup and use "
                "megengine before fork");
    } else {
        mgb_assert(false, "impossible, Channel status is undefined");
    }
}

1537
void ChannelImpl::assert_in_channel() {
M
Megvii Engine Team 已提交
1538 1539 1540
    mgb_assert(
            get_worker_tid() != std::this_thread::get_id(),
            "this method cannot be called in worker thread");
1541 1542 1543
}

void ChannelImpl::assert_in_worker() {
M
Megvii Engine Team 已提交
1544 1545 1546
    mgb_assert(
            get_worker_tid() == std::this_thread::get_id(),
            "this method can only be called in worker thread");
1547 1548
}

1549
void ChannelImpl::sample_on_device(CompNode device, bool force) {
1550 1551 1552
    if (!Profiler::is_profiling()) {
        return;
    }
1553 1554
    if (!force) {
        thread_local int last_sample_id = 0;
1555
        int sample_rate = Profiler::get_option("sample_rate", 0);
1556 1557 1558 1559
        if (!sample_rate || ((++last_sample_id) % sample_rate != 0)) {
            return;
        }
    }
1560
    MGB_RECORD_EVENT(SampleDeviceEvent, device);
1561
    auto [total, free] = device.get_mem_status_bytes();
1562
    MGB_RECORD_EVENT(SampleDeviceFinishEvent, device, total, free);
1563 1564
}

1565 1566 1567
void ChannelImpl::DynamicSublinear::pin(const SmallVector<TensorInfo*>& vec) {
    for (auto i : vec) {
        i->pin();
1568
        erase_candidate(i);
1569 1570 1571
    }
}

1572
void ChannelImpl::DynamicSublinear::unpin(
1573
        const SmallVector<TensorInfo*>& vec, size_t& dtr_evictee_minimum_size) {
1574 1575
    for (auto i : vec) {
        i->unpin();
1576
        if (i->pinned == 0 && i->size_exceeds_thd(dtr_evictee_minimum_size) &&
1577 1578 1579
            i->cand_index == UINT_MAX) {
            insert_candidate(i);
        }
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
    }
}

void ChannelImpl::DynamicSublinear::update_dsu_after_recompute(TensorInfo* ptr) {
    auto&& dsu_fa = find_father(ptr->dsu_ptr);
    dsu_fa->t -= ptr->compute_time;
    ptr->dsu_ptr->parent.reset();
    ptr->dsu_ptr->t = ptr->compute_time;
}

void ChannelImpl::DynamicSublinear::update_dsu_after_evict(TensorInfo* ptr) {
    for (auto i : ptr->producer->inputs) {
        if (i->evict_type == EvictType::DROP) {
            merge(i->dsu_ptr, ptr->dsu_ptr);
        }
    }
    for (auto i : ptr->producer->outputs) {
        if (i && i->evict_type == EvictType::DROP) {
            merge(ptr->dsu_ptr, i->dsu_ptr);
        }
    }
}

double ChannelImpl::DynamicSublinear::estimate_neighbor_cost(TensorInfo* ptr) {
    double cost = 0;
    for (auto i : ptr->producer->inputs) {
        if (i->evict_type == EvictType::DROP) {
            double t = find_father(i->dsu_ptr)->t;
            if (t < i->compute_time) {
                t = i->compute_time;
            }
            cost += t;
        }
    }
    for (auto i : ptr->producer->outputs) {
        if (i && i->evict_type == EvictType::DROP) {
            double t = find_father(i->dsu_ptr)->t;
            if (t < i->compute_time) {
                t = i->compute_time;
            }
            cost += t;
        }
    }
    return cost;
}

M
Megvii Engine Team 已提交
1626 1627
TensorInfo* ChannelImpl::DynamicSublinear::find_best_tensor(
        bool enable_dtr_sqrt_sampling = false) {
1628 1629 1630
    if (candidates.empty())
        return nullptr;

1631 1632
    double min_msps = -1;
    TensorInfo* best = nullptr;
1633 1634
    size_t sz = 1;
    if (enable_dtr_sqrt_sampling) {
M
Megvii Engine Team 已提交
1635 1636
        while (sz * sz <= candidates.size())
            sz++;
1637
        sz--;
1638 1639 1640
    } else {
        sz = candidates.size();
    }
1641 1642 1643 1644 1645 1646 1647

    size_t ti = rand() % sz;
    for (size_t vi = 0; vi < sz; vi++) {
        if (!enable_dtr_sqrt_sampling) {
            ti = vi;
        }
        auto i = candidates[ti];
1648
        if (i->producer && i->ptr && i->evict_type == EvictType::NONE) {
1649
            double neighbor_cost = estimate_neighbor_cost(i);
M
Megvii Engine Team 已提交
1650 1651 1652 1653
            size_t begin_ptr =
                    reinterpret_cast<size_t>(i->ptr->blob()->storage().get());
            auto side_info = i->ptr->comp_node().get_free_left_and_right(
                    begin_ptr, begin_ptr + i->ptr->blob()->size());
1654
            double free_mem = side_info.first + side_info.second;
M
Megvii Engine Team 已提交
1655 1656
            double msps = i->eval_func(
                    neighbor_cost, free_mem, estimate_timestamp, 1.0, 1.0, 1.0, 1.0001);
1657 1658 1659 1660 1661
            if (min_msps < 0 || msps < min_msps) {
                min_msps = msps;
                best = i;
            }
        }
1662 1663 1664 1665 1666
        if (enable_dtr_sqrt_sampling) {
            ti += rand() % sz;
            if (ti > candidates.size())
                break;
        }
1667 1668 1669 1670
    }
    return best;
}

M
Megvii Engine Team 已提交
1671 1672
void ChannelImpl::DynamicSublinear::merge(
        std::shared_ptr<DsuNode>& x, std::shared_ptr<DsuNode>& y) {
1673 1674 1675 1676 1677 1678 1679 1680 1681
    auto&& f_x = find_father(x);
    auto&& f_y = find_father(y);
    if (f_x.get() == f_y.get()) {
        return;
    }
    f_y->t += f_x->t;
    f_x->parent = f_y;
}

M
Megvii Engine Team 已提交
1682 1683
std::shared_ptr<DsuNode> ChannelImpl::DynamicSublinear::find_father(
        std::shared_ptr<DsuNode>& x) {
1684 1685 1686 1687 1688 1689 1690 1691 1692
    if (x->is_root()) {
        return x;
    } else {
        auto&& fa = find_father(x->parent);
        return x->parent = fa;
    }
}

void ChannelImpl::DynamicSublinear::insert_candidate(TensorInfo* ptr) {
1693 1694 1695 1696 1697 1698
    // tensor to be inserted must be brand new
    mgb_assert(
            ptr->cand_index == UINT_MAX, "got wrong candidate index : %lu",
            ptr->cand_index);
    ptr->cand_index = candidates.size();
    candidates.push_back(ptr);
1699 1700 1701 1702 1703 1704
    if (!comp_node.valid()) {
        comp_node = ptr->ptr->comp_node();
    }
}

void ChannelImpl::DynamicSublinear::erase_candidate(TensorInfo* ptr) {
1705 1706 1707 1708 1709 1710
    // close dtr will just clear candidates, so nothing to erase
    if (candidates.empty()) {
        ptr->cand_index = UINT_MAX;
        return;
    }
    // some tensors may be erased already, just skip them
1711 1712 1713 1714 1715 1716
    if (ptr->cand_index != UINT_MAX) {
        std::swap(candidates[ptr->cand_index], candidates.back());
        candidates[ptr->cand_index]->cand_index = ptr->cand_index;
        candidates.pop_back();
        ptr->cand_index = UINT_MAX;
    }
1717 1718 1719 1720 1721
}

void ChannelImpl::DynamicSublinear::update_used_time(TensorInfo* ptr) {
    ptr->last_used_time = estimate_timestamp;
}