interpreter_impl.cpp 55.6 KB
Newer Older
M
Megvii Engine Team 已提交
1
/**
2
 * \file imperative/src/impl/interpreter/interpreter_impl.cpp
M
Megvii Engine Team 已提交
3 4
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
M
Megvii Engine Team 已提交
6 7 8 9 10 11
 *
 * 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.
 */

12
#include "./interpreter_impl.h"
13

14 15
#include "range/v3/all.hpp"

16
#include "megbrain/common.h"
17 18
#include "megbrain/imperative/opr_utility.h"
#include "megbrain/imperative/ops/autogen.h"
19 20
#include "megbrain/imperative/ops/backward_graph.h"
#include "megbrain/imperative/ops/opr_attr.h"
21
#include "megbrain/imperative/ops/utility.h"
22 23
#include "megbrain/imperative/utils/to_string.h"

24
#include "../blob_manager_impl.h"
25 26 27
#include "../event_pool.h"
#include "../op_trait.h"

28 29 30 31 32
using namespace mgb;
using namespace imperative;
using namespace interpreter;
using namespace interpreter::intl;

33 34 35 36 37 38 39 40 41 42
namespace {
    auto tinfo_to_tid(SmallVector<TensorInfo*> tinfo) {
        SmallVector<uint64_t> tid;
        for (auto* ptinfo: tinfo) {
            tid.push_back(ptinfo->id);
        }
        return tid;
    };
}

43 44 45 46
namespace mgb {
    using namespace profiler;
}

47 48 49 50 51
#if defined(_WIN32) || defined(_WIN64)
#define SYMBOL_EXPORT __declspec(dllexport)
#else
#define SYMBOL_EXPORT __attribute__((visibility("default")))
#endif
52 53 54 55 56 57 58

namespace mgb {

/**
 * USAGE
 *
 *   header:
59
 *     namespace mgb { void imperative_log_profile(const char* message); }
60 61 62 63 64
 *
 *   code:
 *     mgb::imperative_log_profile("MY MESSAGE");
 *
 **/
65
SYMBOL_EXPORT
66
void imperative_log_profile_begin(const char* message) {
67
    MGB_RECORD_EVENT(CustomEvent, std::string{message});
68 69
}

70
SYMBOL_EXPORT
71
void imperative_log_profile_end(const char* message) {
72
    MGB_RECORD_EVENT(CustomFinishEvent, std::string{message});
73 74
}

75
SYMBOL_EXPORT
76 77 78 79 80
void imperative_log_profile(const char* message){
    imperative_log_profile_begin(message);
    imperative_log_profile_end(message);
}

81 82 83 84 85 86 87 88 89 90 91 92 93 94
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);
    MGB_RECORD_EVENT(RecordDeviceEvent, EventPool::with_timer().alloc_shared(comp_node));
}

SYMBOL_EXPORT
void imperative_log_profile_end(const char* message, const char* device) {
    auto comp_node = CompNode::load(device);
    MGB_RECORD_EVENT(RecordDeviceEvent, EventPool::with_timer().alloc_shared(comp_node));
    MGB_RECORD_EVENT(CustomFinishEvent, std::string{message}, {}, comp_node);
}

95 96
}

97 98 99 100 101 102 103 104 105 106 107 108 109 110
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;
}

111 112 113 114 115 116 117 118 119 120
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();
    OpDef::set_allocator([&](CompNode device, size_t size) {
        auto blob = Blob::make(device, size);
        m_owner->alloc_tensor_with_evict(blob.get());
        return blob->storage();
    });
}

121
// Do not use m_xxx_state directly
122 123 124
#define m_channel_state
#define m_worker_state

125 126 127 128 129 130 131 132 133
std::unique_ptr<Interpreter::Channel> InterpreterImpl::create_channel() {
    return std::make_unique<ChannelImpl>();
}

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

134
Handle ChannelImpl::put(const HostTensorND& value, bool no_cache) {
135
    MGB_LOCK_GUARD(m_spin);
136
    mgb_assert(check_available(), "Channel already closed");
137
    auto& state = get_channel_state();
138
    auto _ = StackManager::Guard{"Put", &state.stack_manager};
139
    auto info = put_impl(value, no_cache);
M
Megvii Engine Team 已提交
140
    return reinterpret_cast<Handle>(info);
141 142 143
}

TensorInfo* ChannelImpl::put_impl(const HostTensorND& value, bool no_cache) {
144 145 146 147 148
    if (value.empty()) {
        auto layout = value.layout();
        layout.init_contiguous_stride();
        const_cast<HostTensorND&>(value).reset(value.storage(), layout);
    }
149
    auto info = alloc();
150
    init(info, {value.layout(), value.comp_node(), value.proxy_to_default_cpu()});
151
    info->mem_desc.id = StorageIdentifier::make(++m_storage_id);
152
    info->h_value = value;
153
    m_buffer.enqueue(Put{info, value, no_cache});
154
    if (m_async_level == 0) {
155
        sync_impl();
156 157
        info->desc.comp_node.sync();
    }
158 159 160
    return info;
}

161
Handle ChannelImpl::put(const DeviceTensorND& data, const HostTensorND& hvalue) {
162
    MGB_LOCK_GUARD(m_spin);
163
    mgb_assert(check_available(), "Channel already closed");
M
Megvii Engine Team 已提交
164
    return reinterpret_cast<Handle>(put_impl(data, hvalue));
165 166 167
}
TensorInfo* ChannelImpl::put_impl(const DeviceTensorND& data, const HostTensorND& hvalue) {
    auto& state = get_channel_state();
168
    auto _ = StackManager::Guard{"Put", &state.stack_manager};
M
Megvii Engine Team 已提交
169
    auto info = alloc();
170
    MGB_RECORD_EVENT(TensorCommandEvent, info->id, TensorCommandKind::Put);
171
    init(info, {data.layout(), data.comp_node()});
172
    info->mem_desc.id = StorageIdentifier::make(++m_storage_id);
173
    info->ptr = Tensor::make(data, hvalue);
174
    MGB_RECORD_EVENT(TensorProduceEvent, info->id, info->desc.layout, info->desc.comp_node, data.raw_ptr());
175
    info->status = TensorInfo::Produced;
176
    MGB_RECORD_EVENT(TensorCommandFinishEvent, info->id, TensorCommandKind::Put);
M
Megvii Engine Team 已提交
177 178 179
    return info;
}

180
void ChannelImpl::del(Handle handle) {
181
    MGB_LOCK_GUARD(m_spin);
182 183 184
    if (!check_available()){
        return;
    }
185 186 187 188
    del_impl(handle);
}

void ChannelImpl::del_impl(Handle handle) {
189 190 191 192
    mgb_assert(m_valid_handle.count(handle), "invalid handle: %p", handle);
    auto* info = reinterpret_cast<TensorInfo*>(handle);
    m_valid_handle.erase(handle);
    m_buffer.enqueue(Del{info});
193 194
}

195
void ChannelImpl::swap_in(Handle handle) {
196
    MGB_LOCK_GUARD(m_spin);
197
    mgb_assert(check_available(), "Channel already closed");
198 199
    auto& state = get_channel_state();
    if (state.options.enable_swap) {
200 201
        mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
                "invalid handle: %p", handle);
202 203
        auto* info = reinterpret_cast<TensorInfo*>(handle);
        m_buffer.enqueue(SwapIn{info});
204 205 206
    }
}

207
void ChannelImpl::swap_out(Handle handle) {
208
    MGB_LOCK_GUARD(m_spin);
209
    mgb_assert(check_available(), "Channel already closed");
210 211
    auto& state = get_channel_state();
    if (state.options.enable_swap) {
212 213
        mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
                "invalid handle: %p", handle);
214 215
        auto* info = reinterpret_cast<TensorInfo*>(handle);
        m_buffer.enqueue(SwapOut{info});
216 217 218
    }
}

219
void ChannelImpl::drop(Handle handle) {
220
    MGB_LOCK_GUARD(m_spin);
221
    mgb_assert(check_available(), "Channel already closed");
222 223
    auto& state = get_channel_state();
    if (state.options.enable_drop) {
224 225
        mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
                "invalid handle: %p", handle);
226 227
        auto* info = reinterpret_cast<TensorInfo*>(handle);
        m_buffer.enqueue(Drop{info});
228 229 230
    }
}

231
void ChannelImpl::dispatch_default_cpu(
232
        std::shared_ptr<OpDef> op,
233 234 235
        const SmallVector<TensorInfo*>& input_infos,
        const SmallVector<LogicalTensorDesc>& input_descs,
        SmallVector<Handle>* outputs) {
236
    auto& state = get_channel_state();
237 238

    auto name = op->trait()->make_name(*op);
239
    auto _ = StackManager::Guard(name, &state.stack_manager);
240

241
    auto [output_descs, validated] = OpDef::infer_output_attrs_fallible(*op, input_descs);
242
    MGB_RECORD_EVENT(ShapeInferEvent, validated);
243

244 245 246
    SmallVector<DeviceTensorND> input_tensornds;
    input_tensornds.reserve(input_descs.size());
    CompNode output_cn;
247 248
    {
        MGB_LOCK_GUARD(m_mutex);
249
        for (auto&& info : input_infos) {
250
            auto input_cn = info->desc.comp_node;
251
            if (!output_cn.valid()) {
252 253 254 255 256 257 258
                output_cn = input_cn;
            } else {
                mgb_assert(output_cn == input_cn, "cannot decide output comp node");
            }

            if (info->ptr && info->ptr->try_get_value()) {
                input_tensornds.emplace_back(info->ptr->get_value().proxy_to_default_cpu());
259
            } else {
260
                // It's OK for SwapOut. We assign h_value before drop ptr
261 262
                mgb_assert(!info->h_value.empty(), "inp->h_value is empty!");
                input_tensornds.emplace_back(info->h_value.proxy_to_default_cpu());
263 264 265 266 267 268 269 270 271 272 273 274 275 276
            }
        }
    }

    outputs->reserve(output_descs.size());
    SmallVector<DeviceTensorND> output_tensornds;
    output_tensornds.reserve(output_descs.size());
    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
        output_tensornds.emplace_back(HostTensorND(output_cn, desc.layout).proxy_to_default_cpu());
    }

277
    uint64_t op_id = Profiler::next_id();
278

279 280 281 282 283 284 285
    OpDef::apply_on_device_tensornd(*op, input_tensornds, &output_tensornds);

    SmallVector<TensorInfo*> output_infos;
    output_infos.reserve(output_descs.size());
    for (auto&& tensornd : output_tensornds) {
        HostTensorND host_tensornd = HostTensorND::make_proxy(tensornd)
            .proxy_to_comp_node(output_cn);
286
        // use `put` for consistency
287
        auto info = reinterpret_cast<TensorInfo*>(put_impl(host_tensornd, false));
288
        mgb_assert(info->desc.layout.ndim != 0);
289
        output_infos.push_back(info);
M
Megvii Engine Team 已提交
290
        outputs->push_back(reinterpret_cast<Handle>(info));
291
    }
292 293 294 295 296 297 298 299
    auto op_info_getter = [op]{
        std::unordered_map<std::string, std::string> op_info;
        auto props = OpDef::props(*op);
        for (auto&& [key, value]: props) {
            op_info[key] = value;
        }
        return op_info;
    };
300
    MGB_RECORD_EVENT(OpDispatchEvent, op_id, name, op_info_getter,
301 302
                 tinfo_to_tid(input_infos), tinfo_to_tid(output_infos),
                 state.stack_manager.dump());
303
}
304

305 306 307 308 309
void ChannelImpl::dispatch_kernel(
        std::shared_ptr<OpDef> op,
        const SmallVector<TensorInfo*>& input_infos,
        const SmallVector<LogicalTensorDesc>& input_descs,
        SmallVector<Handle>* outputs) {
310
    auto& state = get_channel_state();
311 312 313
    auto& options = state.options;

    auto name = op->trait()->make_name(*op);
314
    auto _  = StackManager::Guard{name, &state.stack_manager};
315

316
    auto [output_descs, validated] = OpDef::infer_output_attrs_fallible(*op, input_descs);
317
    MGB_RECORD_EVENT(ShapeInferEvent, validated);
318

319
    ApplyOp cmd{Profiler::next_id(), std::move(op)};
320
    cmd.inputs = std::move(input_infos);
321
    cmd.outputs.reserve(output_descs.size());
322
    outputs->reserve(output_descs.size());
323 324
    for (int i = 0; i < output_descs.size(); ++i) {
        auto&& desc = output_descs[i];
325
        auto info = alloc();
326
        init(info, desc);
327 328 329 330 331
        // make sure desc's value is consistent with h_value
        if (!info->desc.value.empty()) {
            info->h_value = HostTensorND::make_proxy(desc.value)
                .proxy_to_comp_node(desc.comp_node);
        }
332
        cmd.outputs.push_back(info);
M
Megvii Engine Team 已提交
333
        outputs->push_back(reinterpret_cast<Handle>(info));
334
    }
335 336 337 338 339 340 341 342
    auto op_info_getter = [op=cmd.op]{
        std::unordered_map<std::string, std::string> op_info;
        auto props = OpDef::props(*op);
        for (auto&& [key, value]: props) {
            op_info[key] = value;
        }
        return op_info;
    };
343
    MGB_RECORD_EVENT(OpDispatchEvent, cmd.id, name, op_info_getter,
344 345
                 tinfo_to_tid(cmd.inputs), tinfo_to_tid(cmd.outputs),
                 state.stack_manager.dump());
346
    m_buffer.enqueue(std::move(cmd));
347
    if (!validated && options.async_level == 1) {
348
        sync_impl();
349
    } else if (options.async_level == 0) {
350
        sync_impl();
351
        // check device error
352
        for (auto&& oup : *outputs) {
353 354
            auto info = reinterpret_cast<TensorInfo*>(oup);
            info->ptr->comp_node().sync();
355
        }
356
    }
357 358 359 360 361
}

SmallVector<Handle> ChannelImpl::apply_op(
        std::shared_ptr<OpDef> op,
        const SmallVector<Handle>& inputs) {
362
    MGB_LOCK_GUARD(m_spin);
363
    mgb_assert(check_available(), "Channel already closed");
364 365 366 367 368 369
    return apply_op_impl(std::move(op), inputs);
}

SmallVector<Handle> ChannelImpl::apply_op_impl(
        std::shared_ptr<OpDef> op,
        const SmallVector<Handle>& inputs) {
370
    auto& state = get_channel_state();
371 372 373 374 375 376 377 378 379 380 381 382
    for (auto i : inputs) {
        mgb_assert(m_valid_handle.find(i) != m_valid_handle.end(),
                "invalid handle: %p", i);
    }
    SmallVector<TensorInfo*> input_infos;
    input_infos.reserve(inputs.size());
    SmallVector<LogicalTensorDesc> input_descs;
    input_descs.reserve(inputs.size());
    {
        MGB_LOCK_GUARD(m_mutex);
        for (auto i : inputs) {
            auto info = reinterpret_cast<TensorInfo*>(i);
383
            mgb_assert(!info->invalid, "an input tensor is unusable due to previous error");
384 385 386 387 388 389
            input_infos.push_back(info);
            input_descs.push_back(info->desc);
        }
    }

    SmallVector<Handle> outputs;
390
    DispatchMode dispatch_mode = state.options.enable_host_compute
391 392 393
            ? OpDef::decide_dispatch_mode(*op, input_descs)
            : DispatchMode::KERNEL;
    switch (dispatch_mode) {
394 395 396 397 398 399 400 401 402
        case DEFAULT_CPU: {
            dispatch_default_cpu(op, input_infos, input_descs, &outputs);
            break;
        }
        case KERNEL: {
            dispatch_kernel(op, input_infos, input_descs, &outputs);
            break;
        }
    }
403 404 405
    return outputs;
}

406
HostTensorND ChannelImpl::get_value(Handle handle) {
407
    MGB_LOCK_GUARD(m_spin);
408
    mgb_assert(check_available(), "Channel already closed");
409 410 411
    mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
               "invalid handle: %p", handle);
    auto info = reinterpret_cast<TensorInfo*>(handle);
412
    // donnot use info->value_fetched, it's unsafe
413
    mgb_assert(!info->invalid, "tensor is unusable due to previous error");
414
    return wait_tensor(info, TensorProp::HostValue)->get_value();
415 416
}

417
TensorShape ChannelImpl::get_shape(Handle handle) {
418
    MGB_LOCK_GUARD(m_spin);
419
    mgb_assert(check_available(), "Channel already closed");
420 421 422 423 424 425
    mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
               "invalid handle: %p", handle);
    auto info = reinterpret_cast<TensorInfo*>(handle);
    if (info->desc.layout.ndim != 0) {
        return info->desc.layout;
    }
426
    TensorShape ret = wait_tensor(info, TensorProp::Shape)->layout();
427 428 429 430
    mgb_assert(ret.ndim != 0);
    return ret;
}

431
DType ChannelImpl::get_dtype(Handle handle) {
432
    MGB_LOCK_GUARD(m_spin);
433
    mgb_assert(check_available(), "Channel already closed");
434 435 436
    mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
               "invalid handle: %p", handle);
    auto info = reinterpret_cast<TensorInfo*>(handle);
437
    MGB_RECORD_EVENT(TensorGetPropEvent, info->id, TensorProp::DType);
438 439 440 441 442
    auto ret = info->desc.layout.dtype;
    mgb_assert(ret.valid());
    return ret;
}

443
CompNode ChannelImpl::get_device(Handle handle) {
444
    MGB_LOCK_GUARD(m_spin);
445
    mgb_assert(check_available(), "Channel already closed");
446 447 448
    mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
               "invalid handle: %p", handle);
    auto info = reinterpret_cast<TensorInfo*>(handle);
449
    MGB_RECORD_EVENT(TensorGetPropEvent, info->id, TensorProp::Device);
450 451 452 453 454
    auto ret = info->desc.comp_node;
    mgb_assert(ret.valid());
    return ret;
}

455
DeviceTensorND ChannelImpl::get_dev_tensor(Handle handle) {
456
    MGB_LOCK_GUARD(m_spin);
457
    mgb_assert(check_available(), "Channel already closed");
458 459 460
    mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
               "invalid handle: %p", handle);
    auto info = reinterpret_cast<TensorInfo*>(handle);
461
    return wait_tensor(info, TensorProp::DevValue)->dev_tensor();
462 463 464
}

void ChannelImpl::sync() {
465
    MGB_LOCK_GUARD(m_spin);
466
    mgb_assert(check_available(), "Channel already closed");
467 468 469 470
    sync_impl();
}

void ChannelImpl::sync_impl() {
471
    m_buffer.flush();
472 473 474 475 476 477
    m_worker.wait_all_task_finish();
    MGB_LOCK_GUARD(m_mutex);
    check_worker_exc_unsafe();
}

void ChannelImpl::close() {
478
    MGB_LOCK_GUARD(m_spin);
479 480 481 482 483
    if (!check_available()) {
        return;
    }
    std::vector<Handle> valid_handles(m_valid_handle.begin(), m_valid_handle.end());
    for (auto* handle: valid_handles) {
484
        del_impl(handle);
485 486 487
    }
    mgb_assert(m_valid_handle.empty());
    mgb_log_debug("%ld tensor exists before channel close", (long)valid_handles.size());
488
    sync_impl();
489
    m_closed = true;
490 491
}

492
size_t ChannelImpl::get_option(std::string name) {
493
    MGB_LOCK_GUARD(m_spin);
494
    mgb_assert(check_available(), "Channel already closed");
495 496
    auto& state = get_channel_state();
    return state.options.get_option(name);
497 498
}

499
void ChannelImpl::set_option(std::string name, size_t value) {
500
    MGB_LOCK_GUARD(m_spin);
501
    mgb_assert(check_available(), "Channel already closed");
502 503
    auto& state = get_channel_state();
    state.options.set_option(name, value);
504
    m_buffer.enqueue(SetOption{name, value});
505 506 507
}

TensorInfo* ChannelImpl::alloc() {
508
    auto& state = get_channel_state();
509 510 511 512 513 514
    auto info = [this]{
        MGB_LOCK_GUARD(m_mutex);
        return m_pool.alloc();
    }();
    info->id = Profiler::next_id();
    if (Profiler::is_profiling()) {
515 516
        size_t tensor_id = state.stack_manager.current()->next_id("tensor");
        info->name = state.stack_manager.dump().to_string() + ssprintf(":%zu", tensor_id);
517
    }
518
    return info;
519 520
}

521
void ChannelImpl::init(TensorInfo* info, LogicalTensorDesc desc) {
M
Megvii Engine Team 已提交
522
    m_valid_handle.insert(reinterpret_cast<Handle>(info));
523
    MGB_RECORD_EVENT(TensorDeclareEvent, info->id, info->name);
524 525
    info->status = TensorInfo::Allocated;
    info->desc = std::move(desc);
526 527 528
    info->mem_desc.layout = info->desc.layout;
    info->mem_desc.cn = info->desc.comp_node;
    info->mem_desc.offset = 0;
529 530
}

531 532 533 534 535 536 537 538 539 540 541 542

void ChannelImpl::do_drop(TensorInfo* ptr, bool user=false) {
    if (!ptr->producer) {
        if (user) {
            mgb_log_warn("the input that produced tensor %p has been deleted, this drop operation will be ignored", ptr);
        }
        return;
    }
    if (ptr->evict_type != EvictType::NONE) {
        return;
    }
    ptr->evict_type = EvictType::DROP;
543
    ptr->status = TensorInfo::Dropped;
544 545 546
    release_tensor(ptr);
}

547
void ChannelImpl::free(TensorInfo* ptr) {
548 549
    auto& state = get_worker_state();
    if (state.options.enable_dtr_auto_drop) {
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        // 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) {
565
    MGB_RECORD_EVENT(TensorCommandEvent, ptr->id, TensorCommandKind::RecFree);
566
    SmallVector<TensorInfo*> inps;
567 568 569 570 571 572 573 574 575 576 577 578 579
    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);
        }
    }
580
    MGB_RECORD_EVENT(TensorCommandFinishEvent, ptr->id, TensorCommandKind::RecFree);
581 582 583
}

void ChannelImpl::real_free(TensorInfo* ptr) {
584 585
    auto& state = get_worker_state();
    if (ptr->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
586 587 588 589
        m_dtr.erase_candidate(ptr);
    }
    detach_users(ptr);
    ptr->detach_producer();
590 591
    bool has_value = ptr->ptr != nullptr;
    if (has_value) {
592
        MGB_RECORD_EVENT(TensorReleaseEvent, ptr->id);
593
    }
594
    MGB_RECORD_EVENT(TensorEraseEvent, ptr->id, ptr->ptr_use_count);
595
    ptr->status = TensorInfo::Deleted;
596
    MGB_LOCK_GUARD(m_mutex);
597 598 599
    m_pool.free(ptr);
}

600
ChannelImpl::ChannelImpl() : m_worker(this), m_buffer(this){}
601

602 603 604
ChannelImpl::~ChannelImpl() {
    close();
}
605

606
void ChannelImpl::produce_tensor(TensorInfo* dest, TensorPtr ptr) {
607
    auto& state = get_worker_state();
608
    MGB_LOCK_GUARD(m_mutex);
609
    m_dtr.update_used_time(dest);
610
    MGB_RECORD_EVENT(TensorProduceEvent, dest->id, ptr->layout(), ptr->comp_node(), ptr->dev_tensor().raw_ptr());
611 612 613
    // update tensor desc for static infer
    dest->desc.layout = ptr->layout();
    dest->desc.comp_node = ptr->comp_node();
614
    dest->memory = ptr->blob()->size();
615
    dest->ptr = std::move(ptr);
616
    dest->evict_type = EvictType::NONE;
617
    dest->status = TensorInfo::Produced;
618
    if (dest->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
619 620
        m_dtr.insert_candidate(dest);
    }
621
    notify_tensor_unsafe(dest);
622 623
}

624
void ChannelImpl::release_tensor(TensorInfo* dest) {
625
    MGB_RECORD_EVENT(TensorReleaseEvent, dest->id);
626 627 628 629
    MGB_LOCK_GUARD(m_mutex);
    dest->ptr.reset();
}

630
void ChannelImpl::regenerate(TensorInfo* dest) {
631
    if (dest->evict_type == EvictType::DROP) {
632
        auto &&path = dest->producer;
633
        m_apply_stack.push({ApplyOp{path->id, path->op, path->inputs, path->outputs, {}}, 0, dest, "dtr"});
634
        if (!m_applying) flush_apply_stack();
635
    } else if (dest->evict_type == EvictType::SWAP) {
636
        MGB_RECORD_EVENT(TensorCommandEvent, dest->id, TensorCommandKind::ReGen);
637
        produce_tensor(dest, Tensor::make(dest->h_value));
638
        MGB_RECORD_EVENT(TensorCommandFinishEvent, dest->id, TensorCommandKind::ReGen);
639 640 641
    }
}

642
void ChannelImpl::do_apply_op(const ApplyOp& cmd, std::string reason) {
643 644
    using namespace ranges;
    using namespace ranges::views;
645
    auto& state = get_worker_state();
646
    bool profiling_device = Profiler::is_profiling() && Profiler::get_option("profile_device", 0);
647
    uint64_t apply_id = cmd.id;
648 649 650 651 652 653
    struct TensorWithDesc {
        TensorPtr tensor;
        MemoryDesc desc;
    };
    SmallVector<TensorWithDesc> inputs;
    inputs.reserve(cmd.inputs.size());
654 655 656
    // refcnt == 1, owners: [TensorInfo::ptr]
    for (auto i : cmd.inputs) {
        mgb_assert(i->ptr, "Invalid input tensor ptr!");
657
        // refcnt ++, owners: [i->ptr, tensor_inputs]
658 659
        // tensor_inputs.push_back(i->ptr);
        inputs.push_back({i->ptr, i->mem_desc});
660
    }
661 662 663
    if (state.options.enable_dtr_auto_drop && state.options.dtr_eviction_threshold > 0) {
        auto_evict(0);
    }
664 665 666
    auto apply_on_physical_tensor = [&](auto&& self, const OpDef& def, SmallVector<TensorWithDesc> inputs) -> SmallVector<TensorWithDesc> {
        auto apply_functor = [&](std::shared_ptr<OpDef> op, SmallVector<TensorWithDesc> inputs, size_t nr_outputs) -> SmallVector<TensorWithDesc> {
            auto opname = op->trait()->make_name(*op);
667
            imperative_log_profile_begin(opname.c_str());
668
            auto outputs = self(self, *op, inputs);
669
            imperative_log_profile_end(opname.c_str());
670 671 672 673 674 675 676 677 678 679
            return outputs;
        };
        auto const_functor = [&](TensorPtr value) -> TensorWithDesc {
            return {value, MemoryDesc{value->layout(), 0, value->comp_node(), StorageIdentifier::make()}};
        };
        if (def.trait()->make_forward_graph) {
            // apply recursivily
            SmallVector<LogicalTensorDesc> input_descs;
            for (auto&& input: inputs) {
                input_descs.push_back({{{}, input.tensor->dtype()}, input.tensor->comp_node()});
680
            }
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
            auto forward_graph = OpDef::make_forward_graph(def, input_descs);
            auto outputs = forward_graph.apply(inputs, apply_functor, const_functor);
            return outputs;
        }
        SmallVector<TensorPtr> input_tensors;
        SmallVector<MemoryDesc> input_descs;
        for (auto&& input: inputs) {
            input_tensors.push_back(input.tensor);
            input_descs.push_back(input.desc);
        }
        auto [output_descs, output_tensors, workspaces] = init_output_and_workspace(def, input_tensors, input_descs);
        if (!output_descs.empty()) {
            OpDef::execute(def, input_tensors, output_tensors, workspaces);
        } else {
            output_tensors = OpDef::apply_on_physical_tensor(def, input_tensors);
            for (auto&& output_tensor: output_tensors) {
                output_descs.push_back(MemoryDesc{output_tensor->layout(), 0, output_tensor->comp_node(), StorageIdentifier::make()});
698 699
            }
        }
700 701 702 703 704 705
        SmallVector<TensorWithDesc> outputs;
        for (auto&& [output_tensor, output_desc]: ranges::zip_view(output_tensors, output_descs)) {
            outputs.push_back({output_tensor, output_desc});
        }
        return outputs;
    };
706
    MGB_RECORD_EVENT(OpExecuteEvent, apply_id, {}, reason);
707
    // Begin profiling operator
708 709 710 711
    SmallVector<std::pair<CompNode, uint64_t>> kernels;
    if (profiling_device) {
        // Collecting devices
        SmallVector<CompNode> devices;
712 713 714
        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);
715
                kernels.push_back({i->desc.comp_node, Profiler::next_id()});
716 717 718
            }
        }
    }
719 720
    for (auto* input: cmd.inputs) {
        auto input_id = input->id;
721 722 723
        MGB_RECORD_EVENT(OpInputEvent, input_id);
        MGB_RECORD_EVENT(TensorUsageEvent, input_id);
        MGB_RECORD_EVENT(OpInputFinishEvent, input_id);
724 725 726 727
    }
    // Fused by command buffer. @see: CommandBuffer::fuse_del
    // Now if dest is inplacable, it's refcnt would be decreased to 1 and owned by tensor_inputs after Del.
    // Note for exprs like 'y = x op x', inplace is unsupported yet but Del would be also fused.
728
    for (auto* del : cmd.dels) {
729 730 731
        // refcnt --, owners: [tensor_inputs]
        // if it's decreased to 1, would be detected at @see: proxy_graph_detail::apply_on_physical_tensor
        uint64_t del_id = del->id;
732
        MGB_RECORD_EVENT(TensorCommandEvent, del_id, TensorCommandKind::Del);
733
        free(del);
734
        MGB_RECORD_EVENT(TensorCommandFinishEvent, del_id, TensorCommandKind::Del);
735
    }
736 737 738 739
    // Before wait
    //TODO: split operator wait and execute so that OpWait could be corrected recorded.
    // Before execute
    for (auto&& [device, kernel_id]: kernels) {
740
        MGB_RECORD_EVENT(KernelLaunchEvent, apply_id, kernel_id, device);
741
        MGB_RECORD_EVENT_IF((Profiler::get_option("profile_device", 0)), RecordDeviceEvent, Timer::record_device(device));
742 743 744
    }
    // Apply op
    // Here std::move is REQUIRED for removing duplicated references.
745
    auto outputs = apply_on_physical_tensor(apply_on_physical_tensor, *cmd.op, inputs);
746
    // After execute
747
    for (auto&& [device, kernel_id]: kernels) {
748
        MGB_RECORD_EVENT_IF((Profiler::get_option("profile_device", 0)), RecordDeviceEvent, Timer::record_device(device));
749
        MGB_RECORD_EVENT(KernelLaunchFinishEvent, apply_id, kernel_id, device);
750 751
    }
    // End profiling operator
752 753
    mgb_assert(outputs.size() == cmd.outputs.size());
    for (size_t i = 0; i < outputs.size(); ++i) {
754
        auto output = cmd.outputs[i];
755
        if (output == nullptr) {
756 757
            MGB_RECORD_EVENT(OpOutputEvent, 0);
            MGB_RECORD_EVENT(OpOutputFinishEvent, 0);
758
        } else if (output->ptr != nullptr) {
759 760
            MGB_RECORD_EVENT(OpOutputEvent, output->id);
            MGB_RECORD_EVENT(OpOutputFinishEvent, output->id);
761
        } else {
762
            MGB_RECORD_EVENT(OpOutputEvent, output->id);
763 764
            produce_tensor(output, outputs[i].tensor);
            output->mem_desc = outputs[i].desc;
765
            MGB_RECORD_EVENT(OpOutputFinishEvent, output->id);
766
            sample_on_device(output->desc.comp_node, false);
767 768 769 770 771 772 773 774
        }
    }

    if (state.options.enable_dtr_auto_drop) {
        double estimate_compute_time = 0;
        for (auto i : cmd.inputs) {
            estimate_compute_time += i->memory;
        }
775 776
        for (auto i : outputs) {
            estimate_compute_time += i.tensor->blob()->size();
777 778 779 780 781 782 783 784 785
        }
        m_dtr.estimate_timestamp += estimate_compute_time / 1e8;
        for (auto i : cmd.outputs) {
            if (i != nullptr) {
                i->compute_time = estimate_compute_time;
            }
        }
        m_dtr.unpin(cmd.inputs);
    }
786
    MGB_RECORD_EVENT(OpExecuteFinishEvent, apply_id, {}, reason);
787
    // End profiling operator
788
}
789

790 791
void ChannelImpl::flush_apply_stack() {
    m_applying = true;
792
    auto& state = get_worker_state();
793
    while (!m_apply_stack.empty()) {
794
        auto& [cmd, idx, recomp, reason] = m_apply_stack.top(); // cmd.inputs[0~idx-1] is in memory
795 796 797 798 799
        if (idx == 0) {
            if (state.options.enable_dtr_auto_drop) {
                m_dtr.pin(cmd.inputs);
            }
            if (recomp) {
800
                MGB_RECORD_EVENT(TensorCommandEvent, recomp->id, TensorCommandKind::ReGen);
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
            }
        }
        bool regen = false;
        for (size_t i = idx; i < cmd.inputs.size(); i ++) {
            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;
                regenerate(p); // add ApplyOp to the stack
                regen = true;
                break;
            }
        }
        if (regen) continue;
        // the required input tensors are already in memory
818
        auto [cmd_backup, recomp_backup, reason_backup] = std::make_tuple(cmd, recomp, reason);
819
        m_apply_stack.pop();
820
        do_apply_op(cmd_backup, reason_backup);
821
        if (recomp_backup) {
822
            MGB_RECORD_EVENT(TensorCommandFinishEvent, recomp_backup->id, TensorCommandKind::ReGen);
823 824
            for (auto o : cmd_backup.outputs) {
                if (o) {
825 826 827 828
                    m_dtr.update_dsu_after_recompute(o);
                }
            }
        }
829
    }
830
    m_applying = false;
831 832
}

833
bool ChannelImpl::auto_evict(size_t force_num) {
834
    auto& state = get_worker_state();
835
    if (!m_dtr.comp_node.valid()) {
836
        return false;
837 838
    }
    size_t current_memory = m_dtr.comp_node.get_used_memory();
839 840
    size_t flag = false;
    while ((state.options.dtr_eviction_threshold > 0 && current_memory > state.options.dtr_eviction_threshold) || force_num > 0) {
841
        MGB_RECORD_EVENT(AutoEvictEvent);
842
        sample_on_device(m_dtr.comp_node, false);
843
        auto best = m_dtr.find_best_tensor(state.options.enable_dtr_sqrt_sampling && !force_num);
844
        if (!best) {
845
            MGB_RECORD_EVENT(AutoEvictFinishEvent);
846 847 848 849
            break;
        }
        if (best->ptr.unique() && best->ptr->blob().unique()) {
            current_memory -= best->memory;
850 851 852 853
            if (force_num > 0) {
                force_num --;
            }
            flag = true;
854 855 856 857
        }
        do_drop(best);
        if (best->evict_type == EvictType::DROP) {
            m_dtr.update_dsu_after_evict(best);
858
        }
859
        sample_on_device(m_dtr.comp_node, false);
860
        MGB_RECORD_EVENT(AutoEvictFinishEvent);
861
    }
862
    return flag;
863 864
}

865 866 867
void ChannelImpl::detach_users(TensorInfo* dest) {
    SmallVector<TensorInfo::ComputePath*> users = dest->users;
    for (auto* user: users) {
868 869 870
        SmallVector<TensorInfo*> outputs = user->outputs;
        SmallVector<TensorInfo*> inputs = user->inputs;
        for (auto* output: outputs) {
871 872 873 874
        // 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.
875 876 877 878 879
            if (output == nullptr) {
                continue;
            }
            regenerate(output);
            output->detach_producer();
880 881 882
            for (auto* input: inputs) {
                input->ref_cnt --;
            }
883
        }
884
        // now user is dead
885
    }
886
    mgb_assert(dest->users.empty(), "ComputePath leaking");
887 888
}

889 890 891 892
bool ChannelImpl::check_available() {
    return !m_closed;
}

893 894 895 896 897 898
TensorPtr ChannelImpl::wait_tensor(TensorInfo* info, TensorProp prop) {
    m_buffer.flush();
    std::unique_lock<decltype(m_mutex)> lock(m_mutex);
    mgb_assert(!m_waitee, "duplicate waitee");
    m_waitee = info;
    m_waitee_id = Profiler::next_id();
899
    MGB_RECORD_EVENT(TensorWaitPropEvent, info->id, m_waitee_id, prop);
900
    bool require_host = prop == TensorProp::HostValue;
901 902 903 904 905 906 907 908 909 910
    auto host_available = [&]{
        return info->ptr && info->ptr->value_fetched();
    };
    if (require_host && !host_available()) {
        // avoid dead lock
        lock.unlock();
        m_buffer.enqueue(GetValue{info});
        m_buffer.flush();
        lock.lock();
    }
911 912
    m_cv.wait(lock, [&]() {
        check_worker_exc_unsafe();
913
        return require_host ? host_available() : static_cast<bool>(info->ptr);
914
    });
915
    MGB_RECORD_EVENT(TensorWaitPropFinishEvent, info->id, m_waitee_id, prop);
916
    m_waitee = nullptr;
917 918 919 920 921
    return info->ptr;
}

void ChannelImpl::notify_tensor_unsafe(TensorInfo* info) {
    if (info == m_waitee) {
922
        MGB_RECORD_EVENT(TensorNotifyPropEvent, info->id);
923
        m_cv.notify_all();
924
    }
925 926 927 928 929 930 931
}

std::unordered_set<TensorInfo*> ChannelImpl::collect_valid_tensors() {
    std::unordered_set<TensorInfo*> valid_tensors;
    for (auto* handle: m_valid_handle) {
        auto* info = reinterpret_cast<TensorInfo*>(handle);
        valid_tensors.insert(info);
932
    }
933
    return valid_tensors;
934 935
}

936
void ChannelImpl::alloc_tensor_with_evict(Blob* x) {
937 938 939 940 941 942 943 944 945 946 947
    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);
            if (!evict_suc) return false;
        }
        return true;
    };
    auto pre_level = set_log_level(LogLevel::NO_LOG);
948 949
    reserve_size(x->size());
    MGB_TRY { BlobManager::inst()->alloc_direct(x, x->size()); }
950 951 952 953 954 955
    MGB_CATCH(MemAllocError&, {
        bool suc = false;
        while (!suc) {
            if (!auto_evict(1)) {
                break;
            }
956
            MGB_TRY { BlobManager::inst()->alloc_direct(x, x->size()); }
957 958 959 960 961 962 963
            MGB_CATCH(MemAllocError&, { continue; });
            suc = true;
        }
        if (!suc) {
            set_log_level(pre_level);
            mgb_log_warn("reallocating all cuda memory to alleviate fragmentation, the performance may be affected");
            set_log_level(LogLevel::NO_LOG);
964
            imperative_log_profile_begin("defrag");
965
            BlobManager::inst()->defrag(x->comp_node());
966
            imperative_log_profile_end("defrag");
967
            BlobManager::inst()->alloc_direct(x, x->size());
968 969 970 971 972
        }
    });
    set_log_level(pre_level);
}

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
std::tuple<SmallVector<MemoryDesc>, SmallVector<TensorPtr>, SmallVector<TensorPtr>> ChannelImpl::init_output_and_workspace(
        const OpDef& def,
        SmallVector<TensorPtr> inputs,
        SmallVector<MemoryDesc> inputs_mem_desc) {

    auto [outputs_desc, workspaces_desc] = OpDef::infer_output_mem_desc(def, inputs, inputs_mem_desc);
    if (!outputs_desc.size()) {
        // failed to infer memplan
        return {{}, {}, {}};
    }
    // refine storage id to make it unique
    for (auto&& desc : outputs_desc) {
        if (desc.id->is_sys_alloc()) {
            // TODO: there may be some outputs sharing the same storage id
            desc.id->id = ++ m_storage_id;
        }
    }
990
    auto& state = get_worker_state();
991 992 993 994 995
    auto alloc_storage = [&](SmallVector<MemoryDesc>& desc) {
        SmallVector<TensorPtr> tensors;
        for (size_t i = 0; i < desc.size(); i ++) {
            if (desc[i].id->is_sys_alloc()) {
                tensors.push_back(Tensor::make(desc[i].layout, desc[i].cn));
996
                if (state.options.enable_dtr_auto_drop && !desc[i].layout.is_empty()) {
997
                    alloc_tensor_with_evict(tensors.back()->blob().get());
998
                }
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
            } else if (desc[i].id->is_from_other()) {
                for (size_t j = 0; j < inputs_mem_desc.size();j ++) {
                    if (inputs_mem_desc[j].id->desc == desc[i].id->desc) {
                        tensors.push_back(inputs[j]->sub(desc[i].offset, desc[i].layout));
                        break;
                    }
                }
            } else if (desc[i].id->is_device_ptr()) {
                tensors.push_back(desc[i].id->ptr);
            } else {
                mgb_assert(0, "not implemented");
            }
        }
        return tensors;
    };
1014

1015 1016 1017
    return {outputs_desc, alloc_storage(outputs_desc), alloc_storage(workspaces_desc)};
}

1018
void ChannelImpl::process_one_task(Command& icmd) {
1019 1020
    using namespace ranges;
    using namespace ranges::views;
1021
    auto& state = get_worker_state();
1022
    auto& options = state.options;
1023
    //TODO: remove std::visit for support osx 10.12
1024 1025
    auto cmd_visitor = [&](const auto& cmd) {
            using T = std::decay_t<decltype(cmd)>;
1026
            if constexpr (std::is_same_v<T, Put>) {
1027
                MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::Put);
1028
                MGB_RECORD_EVENT_IF((Profiler::get_option("profile_device", 0)), RecordDeviceEvent, Timer::record_device(cmd.value.comp_node()));
1029
                auto value = cmd.no_cache ? std::make_shared<Tensor>(cmd.value) : Tensor::make(cmd.value);
1030
                MGB_RECORD_EVENT_IF((Profiler::get_option("profile_device", 0)), RecordDeviceEvent, Timer::record_device(cmd.value.comp_node()));
1031
                produce_tensor(cmd.dest, std::move(value));
1032
                MGB_RECORD_EVENT(TensorCommandFinishEvent, cmd.dest->id, TensorCommandKind::Put);
1033
                sample_on_device(cmd.dest->desc.comp_node, false);
1034
            } else if constexpr (std::is_same_v<T, ApplyOp>) {
1035 1036 1037 1038 1039 1040 1041 1042 1043
                for (auto& i : cmd.inputs) {
                    if (i->invalid) {
                        MGB_LOCK_GUARD(m_mutex);
                        for (auto& i : cmd.outputs) {
                            i->invalid = true;
                        }
                        return;
                    }
                }
1044
                m_apply_stack.push({cmd, 0, nullptr, "cmd"});
1045
                flush_apply_stack();
1046 1047 1048
                for (size_t i = 0; i < cmd.outputs.size(); ++i) {
                    auto output = cmd.outputs[i];
                    if (output == nullptr) {
1049 1050
                        continue;
                    }
1051
                    if (state.options.enable_dtr_auto_drop) {
1052
                        output->dsu_ptr = std::make_shared<DsuNode>(output->compute_time);
1053 1054
                    }
                }
1055 1056 1057 1058 1059 1060
                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;
1061
                        }
1062 1063
                        return input->ptr->blob()->storage() == output->ptr->blob()->storage();
                    };
1064 1065 1066 1067 1068 1069 1070
                    // 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();
                        }
                        return opdef.dyn_typeinfo()->name;
                    };
1071 1072 1073 1074 1075 1076 1077

                    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);
1078

1079 1080
                    if (!inplace && !cross_cn && !m_dtr.is_bad_op(get_name(*cmd.op))) {
                        TensorInfo::ComputePath::make(cmd.id, cmd.op, cmd.inputs, cmd.outputs);
1081
                        size_t detach_cnt = 0;
1082 1083 1084 1085 1086 1087 1088
                        if (!strcmp(get_name(*cmd.op), "BatchNorm") && cmd.outputs.size() == 5) {
                            cmd.outputs[0]->detach_producer(); // detach running_mean
                            cmd.outputs[1]->detach_producer(); // detach running_var
                            for (auto input : cmd.inputs) {
                                input->ref_cnt -= 2;
                            }
                        }
1089
                        for (auto output : cmd.outputs) {
1090
                            if (output->producer && !output->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
1091 1092 1093 1094 1095 1096 1097 1098
                                output->detach_producer();
                                detach_cnt ++;
                            }
                        }
                        for (auto input : cmd.inputs) {
                            input->ref_cnt -= detach_cnt;
                        }
                    }
1099 1100
                }
            } else if constexpr (std::is_same_v<T, Del>) {
1101
                MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::Del);
1102 1103
                CompNode device = cmd.dest->desc.comp_node;
                uint64_t tensor_id = cmd.dest->id;
1104
                free(cmd.dest);
1105
                MGB_RECORD_EVENT(TensorCommandFinishEvent, tensor_id, TensorCommandKind::Del);
1106
                sample_on_device(device, false);
1107
            } else if constexpr (std::is_same_v<T, GetValue>) {
1108
                if (cmd.dest->invalid) return;
1109
                imperative_log_profile_begin("GetValue");
1110 1111 1112
                if (!cmd.dest->ptr && cmd.dest->evict_type != EvictType::NONE) {
                    regenerate(cmd.dest);
                }
1113 1114
                cmd.dest->ptr->fetch_value();
                MGB_LOCK_GUARD(m_mutex);
1115
                notify_tensor_unsafe(cmd.dest);
1116
                imperative_log_profile_end("GetValue");
1117
            } else if constexpr (std::is_same_v<T, SwapIn>) {
1118
                if (cmd.dest->invalid) return;
1119
                MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::SwapIn);
1120
                produce_tensor(cmd.dest, Tensor::make(cmd.dest->h_value));
1121
                MGB_RECORD_EVENT(TensorCommandFinishEvent, cmd.dest->id, TensorCommandKind::SwapIn);
1122
                sample_on_device(cmd.dest->desc.comp_node, false);
1123
            } else if constexpr (std::is_same_v<T, SwapOut>) {
1124
                if (cmd.dest->invalid) return;
1125
                MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::SwapOut);
1126
                cmd.dest->h_value = cmd.dest->ptr->get_value();
1127 1128
                if (cmd.dest->evict_type == EvictType::NONE) {
                    cmd.dest->evict_type = EvictType::SWAP;
1129 1130
                    cmd.dest->status = TensorInfo::Swapped;
                    release_tensor(cmd.dest);
1131
                }
1132
                MGB_RECORD_EVENT(TensorCommandFinishEvent, cmd.dest->id, TensorCommandKind::SwapOut);
1133
                sample_on_device(cmd.dest->desc.comp_node, false);
1134
            } else if constexpr (std::is_same_v<T, Drop>) {
1135
                if (cmd.dest->invalid) return;
1136
                MGB_RECORD_EVENT(TensorCommandEvent, cmd.dest->id, TensorCommandKind::Drop);
1137
                do_drop(cmd.dest, true);
1138
                MGB_RECORD_EVENT(TensorCommandFinishEvent, cmd.dest->id, TensorCommandKind::Drop);
1139
            } else if constexpr (std::is_same_v<T, SetOption>) {
1140
                options.set_option(cmd.key, cmd.value);
1141
            } else if constexpr (std::is_same_v<T, StartProfile>) {
1142
                MGB_RECORD_EVENT(StartProfileEvent);
1143
                CompNode::sync_all();
1144
                for (auto* info: cmd.capture_tensors) {
1145
                    MGB_RECORD_EVENT(TensorDeclareEvent, info->id, info->name);
1146 1147
                    if (info->status == TensorInfo::Produced) {
                        // TODO: handle swap/drop
1148
                        MGB_RECORD_EVENT(TensorProduceEvent, info->id, info->desc.layout, info->desc.comp_node, info->ptr->dev_tensor().raw_ptr());
1149 1150 1151
                    }
                }
                CompNode::foreach([&](CompNode device){
1152
                    sample_on_device(device, true);
1153
                    MGB_RECORD_EVENT_IF((Profiler::get_option("profile_device", 0)), RecordDeviceEvent, Timer::record_device(device));
1154
                });
1155
                MGB_RECORD_EVENT(StartProfileFinishEvent);
1156
            } else if constexpr (std::is_same_v<T, StopProfile>) {
1157
                MGB_RECORD_EVENT(StopProfileEvent);
1158 1159 1160
                for (auto* info: cmd.escape_tensors) {
                    bool has_value = info->status == TensorInfo::Produced;
                    if (has_value) {
1161
                        MGB_RECORD_EVENT(TensorReleaseEvent, info->id);
1162
                    }
1163
                    MGB_RECORD_EVENT(TensorEraseEvent, info->id);
1164
                }
1165
                CompNode::foreach([&](CompNode device){
1166
                    sample_on_device(device, true);
1167
                });
1168
                MGB_RECORD_EVENT(StopProfileFinishEvent);
1169
            } else if constexpr (std::is_same_v<T, PushScope>) {
1170
                MGB_RECORD_EVENT(ScopeEvent, cmd.scope_name);
1171
            } else if constexpr (std::is_same_v<T, PopScope>) {
1172
                MGB_RECORD_EVENT(ScopeFinishEvent, cmd.scope_name);
1173
            } else {
1174
                static_assert(!std::is_same_v<T, T>);
1175
            }
1176
    };
1177
    std::visit([&](const auto& cmd){
1178
        using T = std::decay_t<decltype(cmd)>;
1179
        if (!options.catch_worker_execption) {
1180 1181 1182 1183 1184
            cmd_visitor(cmd);
            return;
        }
        try {
            cmd_visitor(cmd);
1185 1186
        } catch (...) {
            MGB_LOCK_GUARD(m_mutex);
1187 1188 1189 1190 1191 1192 1193
            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;
            }
1194
            m_worker_exc = std::current_exception();
1195
            MGB_RECORD_EVENT(WorkerExceptionEvent);
1196 1197 1198
            if (m_waitee) {
                notify_tensor_unsafe(m_waitee);
            }
1199
        }
1200
    }, icmd.data);
1201 1202 1203 1204
}

void ChannelImpl::check_worker_exc_unsafe() {
    if (m_worker_exc) {
1205 1206
        // for reuse interpreter_for_py after some exception tests
        m_waitee = nullptr;
1207 1208
        std::exception_ptr exc;
        std::swap(exc, m_worker_exc);
1209 1210 1211 1212 1213
        try {
            std::rethrow_exception(exc);
        } catch (...) {
            throw AsyncError();
        }
1214 1215
    }
}
1216

1217 1218
void ChannelImpl::CommandBuffer::enqueue(CommandData cmd) {
    auto& state = m_owner->get_channel_state();
1219 1220 1221
    if (std::get_if<Del>(&cmd) && fuse_del(std::get<Del>(cmd))) {
        return;
    }
1222
    // mgb_log_debug("%s Enqueued", to_string(cmd).c_str());
1223
    m_commands.push_back({Profiler::next_id(), std::move(cmd), state.stack_manager.dump()});
1224 1225 1226 1227
    auto flush_pos = flush_pos_for(m_commands.back());
    flush(flush_pos);
}

1228 1229 1230 1231
void ChannelImpl::CommandBuffer::flush() {
    flush(m_commands.end());
}

1232 1233
void ChannelImpl::CommandBuffer::flush(Handle pos) {
    for (auto iter = m_commands.begin(); iter != pos; ++iter) {
1234 1235 1236
        if (Profiler::is_profiling()) {
            mgb_log_debug("%s Flushed", to_string(*iter).c_str());
        }
1237
        m_owner->m_worker.add_task(std::move(*iter));
1238 1239 1240 1241 1242
    }
    m_commands.erase(m_commands.begin(), pos);
}

auto ChannelImpl::CommandBuffer::flush_pos_for(const Command& cmd) -> Handle {
1243
    auto& state = m_owner->get_channel_state();
1244
    return std::visit([this, &state](const auto& cmd) {
1245 1246 1247 1248 1249 1250 1251
        using T = std::decay_t<decltype(cmd)>;
        if constexpr (std::is_same_v<T, ApplyOp>) {
            auto* op_type = cmd.op->dyn_typeinfo();
            if (op_type == RemoteRecv::typeinfo() ||
                op_type == RemoteSend::typeinfo() ||
                op_type == CollectiveComm::typeinfo() ||
                op_type == opr::InputCallback::typeinfo() ||
1252
                op_type == opr::OutputCallback::typeinfo()) {
1253 1254 1255 1256 1257
                return m_commands.end();
            }
        } else if constexpr (std::is_same_v<T, GetValue>) {
            return m_commands.end();
        }
1258
        size_t buffer_length = state.options.buffer_length;
1259 1260
        if (m_commands.size() > buffer_length) {
            return m_commands.begin() + (m_commands.size() - buffer_length);
1261 1262
        }
        return m_commands.begin();
1263
    }, cmd.data);
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
}

/**
 * 1. Find ApplyOp(dest) in buffered commands
 * 2. Check if there are other usages between ApplyOp and Del, return false if not
 * 3. Fuse Del into ApplyOp, return true
 */
bool ChannelImpl::CommandBuffer::fuse_del(const Del& cmd) {
    auto* dest = cmd.dest;
    // TODO: eliminate Puts
    auto begin = m_commands.begin(), end = m_commands.end();
    auto apply_iter = std::find_if(begin, end, [dest](const Command& cmd){
1276
        if (auto* apply = std::get_if<ApplyOp>(&cmd.data)) {
1277 1278 1279 1280 1281 1282 1283
            return std::count(apply->inputs.begin(), apply->inputs.end(), dest) > 0;
        }
        return false;
    });
    if (apply_iter == end || find_last_usage(dest, {apply_iter+1, end}) != end) {
        return false;
    }
1284
    // mgb_log_debug("%s Fused", to_string(Command{cmd}).c_str());
1285
    std::get<ApplyOp>(apply_iter->data).dels.push_back(dest);
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    return true;
}

auto ChannelImpl::CommandBuffer::find_last_usage(TensorInfo* dest, Range range)
        -> Handle {
    auto found = range[1];
    for (auto iter = range[0]; iter != range[1]; ++iter) {
        std::visit([&](const auto& cmd) {
            using T = std::decay_t<decltype(cmd)>;
            if constexpr (std::is_same_v<T, ApplyOp>) {
                if (std::count(cmd.inputs.begin(), cmd.inputs.end(),
                               dest) > 0) {
                    found = iter;
                }
            } else if constexpr (std::is_same_v<T, GetValue>) {
                if (cmd.dest == dest) {
                    found = iter;
                }
            } else if constexpr (std::is_same_v<T, SwapIn> ||
                    std::is_same_v<T, SwapOut> ||
                    std::is_same_v<T, Drop>) {
                //TODO: ignore swap-like commands, just remove them from buffer
                if (cmd.dest == dest) {
                    found = iter;
                }
            }
1312
        }, iter->data);
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    };
    return found;
}

auto ChannelImpl::CommandBuffer::find_produce(TensorInfo* dest, Range range)
        -> Handle {
    return std::find_if(range[0], range[1], [dest](auto& cmd) {
        return std::visit([dest](const auto& cmd){
            using T = std::decay_t<decltype(cmd)>;
            if constexpr (std::is_same_v<T, ApplyOp>) {
                return std::count(cmd.outputs.begin(), cmd.outputs.end(), dest) > 0;
            } else if constexpr (std::is_same_v<T, Put>) {
                return cmd.dest == dest;
            }
            return false;
1328
        }, cmd.data);
1329 1330
    });
}
1331

1332
void ChannelImpl::start_profile() {
1333
    MGB_LOCK_GUARD(m_spin);
1334
    mgb_assert(check_available(), "Channel already closed");
1335 1336 1337 1338
    auto capture_tensors = collect_valid_tensors();
    if (capture_tensors.size() > 0) {
        m_buffer.enqueue(StartProfile{std::move(capture_tensors)});
    }
1339 1340
}

1341
void ChannelImpl::stop_profile() {
1342
    MGB_LOCK_GUARD(m_spin);
1343
    mgb_assert(check_available(), "Channel already closed");
1344
    m_buffer.flush();
1345 1346 1347 1348
    auto escape_tensors = collect_valid_tensors();
    if (escape_tensors.size() > 0) {
        m_buffer.enqueue(StopProfile{std::move(escape_tensors)});
    }
1349 1350 1351
}

void ChannelImpl::push_scope(std::string name) {
1352
    MGB_LOCK_GUARD(m_spin);
1353
    mgb_assert(check_available(), "Channel already closed");
1354
    auto& state = get_channel_state();
1355
    state.stack_manager.enter(name);
1356
    MGB_RECORD_EVENT(ScopeEvent, name);
1357
    m_buffer.enqueue(PushScope{name});
1358 1359 1360
}

void ChannelImpl::pop_scope(std::string name) {
1361
    MGB_LOCK_GUARD(m_spin);
1362
    mgb_assert(check_available(), "Channel already closed");
1363
    auto& state = get_channel_state();
1364
    state.stack_manager.exit(name);
1365
    MGB_RECORD_EVENT(ScopeFinishEvent, name);
1366
    m_buffer.enqueue(PopScope{name});
1367 1368
}

1369 1370 1371 1372 1373 1374 1375 1376
void ChannelImpl::assert_in_channel() {
    mgb_assert(get_worker_tid() != std::this_thread::get_id(), "this method cannot be called in worker thread");
}

void ChannelImpl::assert_in_worker() {
    mgb_assert(get_worker_tid() == std::this_thread::get_id(), "this method can only be called in worker thread");
}

1377 1378 1379 1380 1381 1382 1383 1384
void ChannelImpl::sample_on_device(CompNode device, bool force) {
    if (!force) {
        thread_local int last_sample_id = 0;
        int sample_rate = Profiler::is_profiling() ? Profiler::get_option("sample_rate", 0) : 0;
        if (!sample_rate || ((++last_sample_id) % sample_rate != 0)) {
            return;
        }
    }
1385
    MGB_RECORD_EVENT(SampleDeviceEvent, device);
1386
    auto [total, free] = device.get_mem_status_bytes();
1387
    MGB_RECORD_EVENT(SampleDeviceFinishEvent, device, total, free);
1388 1389
}

1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
void ChannelImpl::DynamicSublinear::pin(const SmallVector<TensorInfo*>& vec) {
    for (auto i : vec) {
        i->pin();
    }
}

void ChannelImpl::DynamicSublinear::unpin(const SmallVector<TensorInfo*>& vec) {
    for (auto i : vec) {
        i->unpin();
    }
}

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

1445
TensorInfo* ChannelImpl::DynamicSublinear::find_best_tensor(bool enable_dtr_sqrt_sampling=false) {
1446 1447
    double min_msps = -1;
    TensorInfo* best = nullptr;
1448 1449 1450 1451 1452 1453
    size_t sz = 1;
    if (enable_dtr_sqrt_sampling) {
        while (sz * sz <= candidates.size()) sz ++;
    } else {
        sz = candidates.size();
    }
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
    for (auto i : candidates) {
        if (i->producer && i->ptr && !i->pinned && i->evict_type == EvictType::NONE) {
            double neighbor_cost = estimate_neighbor_cost(i);
            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());
            double free_mem = side_info.first + side_info.second;
            double msps = i->eval_func(neighbor_cost, free_mem, estimate_timestamp, 1.0, 1.0, 1.0, 1.0001);
            if (min_msps < 0 || msps < min_msps) {
                min_msps = msps;
                best = i;
            }
        }
1466
        if (--sz == 0) break;
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
    }
    return best;
}

void ChannelImpl::DynamicSublinear::merge(std::shared_ptr<DsuNode> &x, std::shared_ptr<DsuNode> &y) {
    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;
}

std::shared_ptr<DsuNode> ChannelImpl::DynamicSublinear::find_father(std::shared_ptr<DsuNode>& x) {
    if (x->is_root()) {
        return x;
    } else {
        auto&& fa = find_father(x->parent);
        return x->parent = fa;
    }
}

void ChannelImpl::DynamicSublinear::insert_candidate(TensorInfo* ptr) {
    candidates.insert(ptr);
    if (!comp_node.valid()) {
        comp_node = ptr->ptr->comp_node();
    }
}

void ChannelImpl::DynamicSublinear::erase_candidate(TensorInfo* ptr) {
    candidates.erase(ptr);
}

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