interpreter_impl.cpp 50.7 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
#include "megbrain/imperative/utils/stats.h"
23 24
#include "megbrain/imperative/utils/to_string.h"

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

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

34
namespace {
M
Megvii Engine Team 已提交
35 36 37 38 39 40 41 42
auto tinfo_to_tid(SmallVector<TensorInfo*> tinfo) {
    SmallVector<uint64_t> tid;
    for (auto* ptinfo : tinfo) {
        tid.push_back(ptinfo->id);
    }
    return tid;
};
}  // namespace
43

44
namespace mgb {
M
Megvii Engine Team 已提交
45
using namespace profiler;
46 47
}

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

namespace mgb {

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

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

76
SYMBOL_EXPORT
M
Megvii Engine Team 已提交
77
void imperative_log_profile(const char* message) {
78 79 80 81
    imperative_log_profile_begin(message);
    imperative_log_profile_end(message);
}

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

SYMBOL_EXPORT
void imperative_log_profile_end(const char* message, const char* device) {
    auto comp_node = CompNode::load(device);
M
Megvii Engine Team 已提交
93 94
    MGB_RECORD_EVENT(
            RecordDeviceEvent, EventPool::with_timer().alloc_shared(comp_node));
95 96 97
    MGB_RECORD_EVENT(CustomFinishEvent, std::string{message}, {}, comp_node);
}

M
Megvii Engine Team 已提交
98
}  // namespace mgb
99

100 101 102 103 104 105 106 107 108 109 110 111 112 113
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;
}

114 115 116 117 118 119 120 121 122 123
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();
    });
}

124
// Do not use m_xxx_state directly
125 126 127
#define m_channel_state
#define m_worker_state

128 129 130 131 132 133 134 135 136
std::unique_ptr<Interpreter::Channel> InterpreterImpl::create_channel() {
    return std::make_unique<ChannelImpl>();
}

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
    mgb_assert(check_available(), "Channel already closed");
140
    auto& state = get_channel_state();
141
    auto _ = StackManager::Guard{"Put", &state.stack_manager};
142
    auto info = put_impl(value, no_cache);
M
Megvii Engine Team 已提交
143
    return reinterpret_cast<Handle>(info);
144 145 146
}

TensorInfo* ChannelImpl::put_impl(const HostTensorND& value, bool no_cache) {
147 148 149 150 151
    if (value.empty()) {
        auto layout = value.layout();
        layout.init_contiguous_stride();
        const_cast<HostTensorND&>(value).reset(value.storage(), layout);
    }
152
    auto info = alloc();
153 154 155 156 157 158
    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();
    }
159 160 161
    m_worker.add_task(
            {Profiler::next_id(), Put{info, value, no_cache},
             get_channel_state().stack_manager.dump()});
162
    if (m_async_level == 0) {
163
        sync_impl();
164
        info->desc.comp_node.sync();
165 166
        auto err = info->desc.comp_node.check_async_error();
        mgb_assert(!err, "%s", err->what());
167
    }
168 169 170
    return info;
}

171
Handle ChannelImpl::put(const DeviceTensorND& data, const HostTensorND& hvalue) {
172
    MGB_LOCK_GUARD(m_spin);
173
    mgb_assert(check_available(), "Channel already closed");
M
Megvii Engine Team 已提交
174
    return reinterpret_cast<Handle>(put_impl(data, hvalue));
175
}
M
Megvii Engine Team 已提交
176 177
TensorInfo* ChannelImpl::put_impl(
        const DeviceTensorND& data, const HostTensorND& hvalue) {
178
    auto& state = get_channel_state();
179
    auto _ = StackManager::Guard{"Put", &state.stack_manager};
M
Megvii Engine Team 已提交
180
    auto info = alloc();
181
    MGB_RECORD_EVENT(TensorCommandEvent, info->id, TensorCommandKind::Put);
182
    constexpr int size_threshold = TensorShape::MAX_NDIM;
183
    init(info, {data.layout(), data.comp_node()});
184 185 186
    if ((!hvalue.empty()) && info->desc.layout.total_nr_elems() <= size_threshold) {
        info->desc.value = hvalue.proxy_to_default_cpu();
    }
187
    info->ptr = Tensor::make(data, hvalue);
M
Megvii Engine Team 已提交
188 189 190
    MGB_RECORD_EVENT(
            TensorProduceEvent, info->id, info->desc.layout, info->desc.comp_node,
            data.raw_ptr());
191
    info->status = TensorInfo::Produced;
192
    MGB_RECORD_EVENT(TensorCommandFinishEvent, info->id, TensorCommandKind::Put);
M
Megvii Engine Team 已提交
193 194 195
    return info;
}

196
void ChannelImpl::del(Handle handle) {
197
    MGB_LOCK_GUARD(m_spin);
M
Megvii Engine Team 已提交
198
    if (!check_available()) {
199 200
        return;
    }
201 202 203 204
    del_impl(handle);
}

void ChannelImpl::del_impl(Handle handle) {
205 206 207
    mgb_assert(m_valid_handle.count(handle), "invalid handle: %p", handle);
    auto* info = reinterpret_cast<TensorInfo*>(handle);
    m_valid_handle.erase(handle);
208 209
    m_worker.add_task(
            {Profiler::next_id(), Del{info}, get_channel_state().stack_manager.dump()});
210 211
}

212
void ChannelImpl::drop(Handle handle) {
213
    MGB_LOCK_GUARD(m_spin);
214
    mgb_assert(check_available(), "Channel already closed");
215 216
    auto& state = get_channel_state();
    if (state.options.enable_drop) {
M
Megvii Engine Team 已提交
217 218
        mgb_assert(
                m_valid_handle.find(handle) != m_valid_handle.end(),
219
                "invalid handle: %p", handle);
220
        auto* info = reinterpret_cast<TensorInfo*>(handle);
221 222 223
        m_worker.add_task(
                {Profiler::next_id(), Drop{info},
                 get_channel_state().stack_manager.dump()});
224 225 226
    }
}

227
void ChannelImpl::dispatch_default_cpu(
M
Megvii Engine Team 已提交
228
        std::shared_ptr<OpDef> op, const SmallVector<TensorInfo*>& input_infos,
229 230
        const SmallVector<LogicalTensorDesc>& input_descs,
        SmallVector<Handle>* outputs) {
231
    auto& state = get_channel_state();
232 233

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

M
Megvii Engine Team 已提交
236 237
    auto [output_descs, validated] =
            OpDef::infer_output_attrs_fallible(*op, input_descs);
238
    MGB_RECORD_EVENT(ShapeInferEvent, validated);
239

240 241 242
    SmallVector<DeviceTensorND> input_tensornds;
    input_tensornds.reserve(input_descs.size());
    CompNode output_cn;
243 244
    {
        MGB_LOCK_GUARD(m_mutex);
245
        for (auto&& info : input_infos) {
246
            auto input_cn = info->desc.comp_node;
247
            if (!output_cn.valid()) {
248 249 250 251 252 253
                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 已提交
254 255
                input_tensornds.emplace_back(
                        info->ptr->get_value().proxy_to_default_cpu());
256
            } else {
257
                // We assign h_value before drop ptr
258 259
                mgb_assert(!info->h_value.empty(), "inp->h_value is empty!");
                input_tensornds.emplace_back(info->h_value.proxy_to_default_cpu());
260 261 262 263 264 265 266 267 268 269 270
            }
        }
    }

    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
M
Megvii Engine Team 已提交
271 272
        output_tensornds.emplace_back(
                HostTensorND(output_cn, desc.layout).proxy_to_default_cpu());
273 274
    }

275
    uint64_t op_id = Profiler::next_id();
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290
    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)));
        }
        auto output_tensors = OpDef::apply_on_physical_tensor(*op, input_tensors);
        for (size_t i = 0; i < output_tensors.size(); ++i) {
            output_tensornds[i].copy_from_fixlayout(output_tensors[i]->dev_tensor());
        }
    }
291 292 293 294

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

316
void ChannelImpl::dispatch_kernel(
M
Megvii Engine Team 已提交
317
        std::shared_ptr<OpDef> op, const SmallVector<TensorInfo*>& input_infos,
318 319
        const SmallVector<LogicalTensorDesc>& input_descs,
        SmallVector<Handle>* outputs) {
320
    auto& state = get_channel_state();
321 322 323
    auto& options = state.options;

    auto name = op->trait()->make_name(*op);
M
Megvii Engine Team 已提交
324
    auto _ = StackManager::Guard{name, &state.stack_manager};
325

M
Megvii Engine Team 已提交
326 327
    auto [output_descs, validated] =
            OpDef::infer_output_attrs_fallible(*op, input_descs);
328
    MGB_RECORD_EVENT(ShapeInferEvent, validated);
329

330
    ApplyOp cmd{Profiler::next_id(), std::move(op)};
331
    cmd.inputs = std::move(input_infos);
332
    cmd.outputs.reserve(output_descs.size());
333
    outputs->reserve(output_descs.size());
334 335
    for (int i = 0; i < output_descs.size(); ++i) {
        auto&& desc = output_descs[i];
336
        auto info = alloc();
337
        init(info, desc);
338 339 340
        // make sure desc's value is consistent with h_value
        if (!info->desc.value.empty()) {
            info->h_value = HostTensorND::make_proxy(desc.value)
M
Megvii Engine Team 已提交
341
                                    .proxy_to_comp_node(desc.comp_node);
342
        }
343
        cmd.outputs.push_back(info);
M
Megvii Engine Team 已提交
344
        outputs->push_back(reinterpret_cast<Handle>(info));
345
    }
M
Megvii Engine Team 已提交
346
    auto op_info_getter = [op = cmd.op] {
347 348
        std::unordered_map<std::string, std::string> op_info;
        auto props = OpDef::props(*op);
M
Megvii Engine Team 已提交
349
        for (auto&& [key, value] : props) {
350 351 352 353
            op_info[key] = value;
        }
        return op_info;
    };
M
Megvii Engine Team 已提交
354 355 356
    MGB_RECORD_EVENT(
            OpDispatchEvent, cmd.id, name, op_info_getter, tinfo_to_tid(cmd.inputs),
            tinfo_to_tid(cmd.outputs), state.stack_manager.dump());
357 358 359
    m_worker.add_task(
            {Profiler::next_id(), std::move(cmd),
             get_channel_state().stack_manager.dump()});
360
    if (!validated && options.async_level == 1) {
361
        sync_impl();
362
    } else if (options.async_level == 0) {
363
        sync_impl();
364
        // check device error
365
        for (auto&& oup : *outputs) {
366 367
            auto info = reinterpret_cast<TensorInfo*>(oup);
            info->ptr->comp_node().sync();
368 369
            auto err = info->ptr->comp_node().check_async_error();
            mgb_assert(!err, "%s", err->what());
370
        }
371
    }
372 373 374
}

SmallVector<Handle> ChannelImpl::apply_op(
M
Megvii Engine Team 已提交
375
        std::shared_ptr<OpDef> op, const SmallVector<Handle>& inputs) {
376
    MGB_LOCK_GUARD(m_spin);
377
    mgb_assert(check_available(), "Channel already closed");
378 379 380 381 382 383 384 385 386 387 388
    auto* input = reinterpret_cast<TensorInfo*>(inputs[0]);
    if (op->same_type<GetVarShape>() && input->desc.layout.ndim) {
        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))};
        }
    }
389 390 391 392
    return apply_op_impl(std::move(op), inputs);
}

SmallVector<Handle> ChannelImpl::apply_op_impl(
M
Megvii Engine Team 已提交
393
        std::shared_ptr<OpDef> op, const SmallVector<Handle>& inputs) {
394
    auto& state = get_channel_state();
395
    for (auto i : inputs) {
M
Megvii Engine Team 已提交
396 397 398
        mgb_assert(
                m_valid_handle.find(i) != m_valid_handle.end(), "invalid handle: %p",
                i);
399 400 401 402 403 404 405 406 407
    }
    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);
M
Megvii Engine Team 已提交
408 409 410
            mgb_assert(
                    !info->invalid,
                    "an input tensor is unusable due to previous error");
411 412 413 414 415 416
            input_infos.push_back(info);
            input_descs.push_back(info->desc);
        }
    }

    SmallVector<Handle> outputs;
417
    DispatchMode dispatch_mode = state.options.enable_host_compute
M
Megvii Engine Team 已提交
418 419
                                       ? OpDef::decide_dispatch_mode(*op, input_descs)
                                       : DispatchMode::KERNEL;
420
    switch (dispatch_mode) {
421 422 423 424 425 426 427 428 429
        case DEFAULT_CPU: {
            dispatch_default_cpu(op, input_infos, input_descs, &outputs);
            break;
        }
        case KERNEL: {
            dispatch_kernel(op, input_infos, input_descs, &outputs);
            break;
        }
    }
430 431 432
    return outputs;
}

433
HostTensorND ChannelImpl::get_value(Handle handle) {
434
    MGB_LOCK_GUARD(m_spin);
435
    mgb_assert(check_available(), "Channel already closed");
M
Megvii Engine Team 已提交
436 437 438
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
439
    auto info = reinterpret_cast<TensorInfo*>(handle);
440
    // donnot use info->value_fetched, it's unsafe
441
    mgb_assert(!info->invalid, "tensor is unusable due to previous error");
442
    return wait_tensor(info, TensorProp::HostValue)->get_value();
443 444
}

445
TensorShape ChannelImpl::get_shape(Handle handle) {
446
    MGB_LOCK_GUARD(m_spin);
447
    mgb_assert(check_available(), "Channel already closed");
M
Megvii Engine Team 已提交
448 449 450
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
451 452 453 454
    auto info = reinterpret_cast<TensorInfo*>(handle);
    if (info->desc.layout.ndim != 0) {
        return info->desc.layout;
    }
455
    TensorShape ret = wait_tensor(info, TensorProp::Shape)->layout();
456 457 458 459
    mgb_assert(ret.ndim != 0);
    return ret;
}

460
DType ChannelImpl::get_dtype(Handle handle) {
461
    MGB_LOCK_GUARD(m_spin);
462
    mgb_assert(check_available(), "Channel already closed");
M
Megvii Engine Team 已提交
463 464 465
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
466
    auto info = reinterpret_cast<TensorInfo*>(handle);
467
    MGB_RECORD_EVENT(TensorGetPropEvent, info->id, TensorProp::DType);
468 469 470 471 472
    auto ret = info->desc.layout.dtype;
    mgb_assert(ret.valid());
    return ret;
}

473
CompNode ChannelImpl::get_device(Handle handle) {
474
    MGB_LOCK_GUARD(m_spin);
475
    mgb_assert(check_available(), "Channel already closed");
M
Megvii Engine Team 已提交
476 477 478
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
479
    auto info = reinterpret_cast<TensorInfo*>(handle);
480
    MGB_RECORD_EVENT(TensorGetPropEvent, info->id, TensorProp::Device);
481 482 483 484 485
    auto ret = info->desc.comp_node;
    mgb_assert(ret.valid());
    return ret;
}

486
DeviceTensorND ChannelImpl::get_dev_tensor(Handle handle) {
487
    MGB_LOCK_GUARD(m_spin);
488
    mgb_assert(check_available(), "Channel already closed");
M
Megvii Engine Team 已提交
489 490 491
    mgb_assert(
            m_valid_handle.find(handle) != m_valid_handle.end(), "invalid handle: %p",
            handle);
492
    auto info = reinterpret_cast<TensorInfo*>(handle);
493
    return wait_tensor(info, TensorProp::DevValue)->dev_tensor();
494 495 496
}

void ChannelImpl::sync() {
497
    MGB_LOCK_GUARD(m_spin);
498
    mgb_assert(check_available(), "Channel already closed");
499 500 501 502
    sync_impl();
}

void ChannelImpl::sync_impl() {
503 504 505 506 507 508
    m_worker.wait_all_task_finish();
    MGB_LOCK_GUARD(m_mutex);
    check_worker_exc_unsafe();
}

void ChannelImpl::close() {
509
    MGB_LOCK_GUARD(m_spin);
510 511 512 513
    if (!check_available()) {
        return;
    }
    std::vector<Handle> valid_handles(m_valid_handle.begin(), m_valid_handle.end());
M
Megvii Engine Team 已提交
514
    for (auto* handle : valid_handles) {
515
        del_impl(handle);
516 517 518
    }
    mgb_assert(m_valid_handle.empty());
    mgb_log_debug("%ld tensor exists before channel close", (long)valid_handles.size());
519
    sync_impl();
520
    m_closed = true;
521 522
}

523
size_t ChannelImpl::get_option(std::string name) {
524
    MGB_LOCK_GUARD(m_spin);
525
    mgb_assert(check_available(), "Channel already closed");
526 527
    auto& state = get_channel_state();
    return state.options.get_option(name);
528 529
}

530
void ChannelImpl::set_option(std::string name, size_t value) {
531
    MGB_LOCK_GUARD(m_spin);
532
    mgb_assert(check_available(), "Channel already closed");
533 534
    auto& state = get_channel_state();
    state.options.set_option(name, value);
535 536 537
    m_worker.add_task(
            {Profiler::next_id(), SetOption{name, value},
             get_channel_state().stack_manager.dump()});
538 539
}

540 541 542 543 544 545
void ChannelImpl::clear_candidates() {
    MGB_LOCK_GUARD(m_spin);
    mgb_assert(check_available(), "Channel already closed");
    m_dtr.candidates.clear();
}

546
TensorInfo* ChannelImpl::alloc() {
547
    auto& state = get_channel_state();
M
Megvii Engine Team 已提交
548
    auto info = [this] {
549 550 551 552 553
        MGB_LOCK_GUARD(m_mutex);
        return m_pool.alloc();
    }();
    info->id = Profiler::next_id();
    if (Profiler::is_profiling()) {
554
        size_t tensor_id = state.stack_manager.current()->next_id("tensor");
M
Megvii Engine Team 已提交
555 556
        info->name =
                state.stack_manager.dump().to_string() + ssprintf(":%zu", tensor_id);
557
    }
558
    return info;
559 560
}

561
void ChannelImpl::init(TensorInfo* info, LogicalTensorDesc desc) {
M
Megvii Engine Team 已提交
562
    m_valid_handle.insert(reinterpret_cast<Handle>(info));
563
    MGB_RECORD_EVENT(TensorDeclareEvent, info->id, info->name);
564 565 566 567
    info->status = TensorInfo::Allocated;
    info->desc = std::move(desc);
}

M
Megvii Engine Team 已提交
568
void ChannelImpl::do_drop(TensorInfo* ptr, bool user = false) {
569 570
    if (!ptr->producer) {
        if (user) {
M
Megvii Engine Team 已提交
571 572 573 574
            mgb_log_warn(
                    "the input that produced tensor %p has been deleted, this drop "
                    "operation will be ignored",
                    ptr);
575 576 577 578 579 580 581
        }
        return;
    }
    if (ptr->evict_type != EvictType::NONE) {
        return;
    }
    ptr->evict_type = EvictType::DROP;
582
    ptr->status = TensorInfo::Dropped;
583 584 585
    release_tensor(ptr);
}

586
void ChannelImpl::free(TensorInfo* ptr) {
587 588
    auto& state = get_worker_state();
    if (state.options.enable_dtr_auto_drop) {
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        // 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) {
604
    MGB_RECORD_EVENT(TensorCommandEvent, ptr->id, TensorCommandKind::RecFree);
605
    SmallVector<TensorInfo*> inps;
606 607 608 609 610 611 612 613 614 615 616 617 618
    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);
        }
    }
619
    MGB_RECORD_EVENT(TensorCommandFinishEvent, ptr->id, TensorCommandKind::RecFree);
620 621 622
}

void ChannelImpl::real_free(TensorInfo* ptr) {
623 624
    auto& state = get_worker_state();
    if (ptr->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
625 626 627 628
        m_dtr.erase_candidate(ptr);
    }
    detach_users(ptr);
    ptr->detach_producer();
629 630
    bool has_value = ptr->ptr != nullptr;
    if (has_value) {
631
        MGB_RECORD_EVENT(TensorReleaseEvent, ptr->id);
632
    }
633
    MGB_RECORD_EVENT(TensorEraseEvent, ptr->id, ptr->ptr_use_count);
634
    ptr->status = TensorInfo::Deleted;
635
    MGB_LOCK_GUARD(m_mutex);
636 637 638
    m_pool.free(ptr);
}

639
ChannelImpl::ChannelImpl() : m_worker(this) {}
640

641 642 643
ChannelImpl::~ChannelImpl() {
    close();
}
644

645
void ChannelImpl::produce_tensor(TensorInfo* dest, TensorPtr ptr) {
646
    auto& state = get_worker_state();
647
    MGB_LOCK_GUARD(m_mutex);
648
    m_dtr.update_used_time(dest);
M
Megvii Engine Team 已提交
649 650 651
    MGB_RECORD_EVENT(
            TensorProduceEvent, dest->id, ptr->layout(), ptr->comp_node(),
            ptr->dev_tensor().raw_ptr());
652
    // update tensor desc for static infer
653 654 655 656 657 658
    if (dest->desc.layout.ndim) {
        mgb_assert(
                dest->desc.layout.eq_shape(ptr->layout()),
                "shape infer error, %s vs %s", dest->desc.layout.to_string().c_str(),
                ptr->layout().to_string().c_str());
    }
659 660
    dest->desc.layout = ptr->layout();
    dest->desc.comp_node = ptr->comp_node();
661
    dest->memory = ptr->blob()->size();
662
    dest->ptr = std::move(ptr);
663
    dest->evict_type = EvictType::NONE;
664
    dest->status = TensorInfo::Produced;
665 666
    if (dest->pinned == 0 &&
        dest->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
667 668
        m_dtr.insert_candidate(dest);
    }
669
    notify_tensor_unsafe(dest);
670 671
}

672
void ChannelImpl::release_tensor(TensorInfo* dest) {
673
    MGB_RECORD_EVENT(TensorReleaseEvent, dest->id);
674 675
    MGB_LOCK_GUARD(m_mutex);
    dest->ptr.reset();
676 677 678 679
    auto& state = get_worker_state();
    if (dest->size_exceeds_thd(state.options.dtr_evictee_minimum_size)) {
        m_dtr.erase_candidate(dest);
    }
680 681
}

682
void ChannelImpl::regenerate(TensorInfo* dest) {
683
    if (dest->evict_type == EvictType::DROP) {
M
Megvii Engine Team 已提交
684 685
        auto&& path = dest->producer;
        m_apply_stack.push(
686
                {ApplyOp{path->id, path->op, path->inputs, path->outputs}, 0, dest,
M
Megvii Engine Team 已提交
687 688 689
                 "dtr"});
        if (!m_applying)
            flush_apply_stack();
690 691 692
    }
}

693
void ChannelImpl::do_apply_op(const ApplyOp& cmd, std::string reason) {
694 695
    using namespace ranges;
    using namespace ranges::views;
696
    auto& state = get_worker_state();
M
Megvii Engine Team 已提交
697 698
    bool profiling_device =
            Profiler::is_profiling() && Profiler::get_option("profile_device", 0);
699
    uint64_t apply_id = cmd.id;
700
    SmallVector<TensorPtr> inputs;
701
    inputs.reserve(cmd.inputs.size());
702 703 704
    // refcnt == 1, owners: [TensorInfo::ptr]
    for (auto i : cmd.inputs) {
        mgb_assert(i->ptr, "Invalid input tensor ptr!");
705
        // refcnt ++, owners: [i->ptr, tensor_inputs]
706
        // tensor_inputs.push_back(i->ptr);
707
        inputs.push_back(i->ptr);
708
    }
M
Megvii Engine Team 已提交
709 710
    if (state.options.enable_dtr_auto_drop &&
        state.options.dtr_eviction_threshold > 0) {
711 712
        auto_evict(0);
    }
M
Megvii Engine Team 已提交
713 714
    auto apply_on_physical_tensor =
            [&](auto&& self, const OpDef& def,
715
                SmallVector<TensorPtr> inputs) -> SmallVector<TensorPtr> {
M
Megvii Engine Team 已提交
716
        auto apply_functor = [&](std::shared_ptr<OpDef> op,
717 718
                                 SmallVector<TensorPtr> inputs,
                                 size_t nr_outputs) -> SmallVector<TensorPtr> {
719
            auto opname = op->trait()->make_name(*op);
720
            imperative_log_profile_begin(opname.c_str());
721
            auto outputs = self(self, *op, inputs);
722
            imperative_log_profile_end(opname.c_str());
723 724
            return outputs;
        };
725
        auto const_functor = [&](TensorPtr value) -> TensorPtr { return value; };
726 727 728
        if (def.trait()->make_forward_graph) {
            // apply recursivily
            SmallVector<LogicalTensorDesc> input_descs;
M
Megvii Engine Team 已提交
729
            for (auto&& input : inputs) {
730
                input_descs.push_back({{{}, input->dtype()}, input->comp_node()});
731
            }
732 733 734 735
            auto forward_graph = OpDef::make_forward_graph(def, input_descs);
            auto outputs = forward_graph.apply(inputs, apply_functor, const_functor);
            return outputs;
        }
736
        return OpDef::apply_on_physical_tensor(def, inputs);
737
    };
738
    MGB_RECORD_EVENT(OpExecuteEvent, apply_id, {}, reason);
739
    // Begin profiling operator
740 741 742 743
    SmallVector<std::pair<CompNode, uint64_t>> kernels;
    if (profiling_device) {
        // Collecting devices
        SmallVector<CompNode> devices;
744 745 746
        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);
747
                kernels.push_back({i->desc.comp_node, Profiler::next_id()});
748 749 750
            }
        }
    }
M
Megvii Engine Team 已提交
751
    for (auto* input : cmd.inputs) {
752
        auto input_id = input->id;
753 754 755
        MGB_RECORD_EVENT(OpInputEvent, input_id);
        MGB_RECORD_EVENT(TensorUsageEvent, input_id);
        MGB_RECORD_EVENT(OpInputFinishEvent, input_id);
756 757
    }
    // Before wait
M
Megvii Engine Team 已提交
758
    // TODO: split operator wait and execute so that OpWait could be corrected recorded.
759
    // Before execute
M
Megvii Engine Team 已提交
760
    for (auto&& [device, kernel_id] : kernels) {
761
        MGB_RECORD_EVENT(KernelLaunchEvent, apply_id, kernel_id, device);
M
Megvii Engine Team 已提交
762 763 764
        MGB_RECORD_EVENT_IF(
                (Profiler::get_option("profile_device", 0)), RecordDeviceEvent,
                Timer::record_device(device));
765 766 767
    }
    // Apply op
    // Here std::move is REQUIRED for removing duplicated references.
768
    auto outputs = apply_on_physical_tensor(apply_on_physical_tensor, *cmd.op, inputs);
769
    // After execute
M
Megvii Engine Team 已提交
770 771 772 773
    for (auto&& [device, kernel_id] : kernels) {
        MGB_RECORD_EVENT_IF(
                (Profiler::get_option("profile_device", 0)), RecordDeviceEvent,
                Timer::record_device(device));
774
        MGB_RECORD_EVENT(KernelLaunchFinishEvent, apply_id, kernel_id, device);
775 776
    }
    // End profiling operator
777 778
    mgb_assert(outputs.size() == cmd.outputs.size());
    for (size_t i = 0; i < outputs.size(); ++i) {
779
        auto output = cmd.outputs[i];
780
        if (output == nullptr) {
781 782
            MGB_RECORD_EVENT(OpOutputEvent, 0);
            MGB_RECORD_EVENT(OpOutputFinishEvent, 0);
783
        } else if (output->ptr != nullptr) {
784 785
            MGB_RECORD_EVENT(OpOutputEvent, output->id);
            MGB_RECORD_EVENT(OpOutputFinishEvent, output->id);
786
        } else {
787
            MGB_RECORD_EVENT(OpOutputEvent, output->id);
788
            produce_tensor(output, outputs[i]);
789
            MGB_RECORD_EVENT(OpOutputFinishEvent, output->id);
790
            sample_on_device(output->desc.comp_node, false);
791 792 793 794 795 796 797 798
        }
    }

    if (state.options.enable_dtr_auto_drop) {
        double estimate_compute_time = 0;
        for (auto i : cmd.inputs) {
            estimate_compute_time += i->memory;
        }
799
        for (auto i : outputs) {
800
            estimate_compute_time += i->blob()->size();
801 802 803 804 805 806 807
        }
        m_dtr.estimate_timestamp += estimate_compute_time / 1e8;
        for (auto i : cmd.outputs) {
            if (i != nullptr) {
                i->compute_time = estimate_compute_time;
            }
        }
808
        m_dtr.unpin(cmd.inputs, state);
809
    }
810
    MGB_RECORD_EVENT(OpExecuteFinishEvent, apply_id, {}, reason);
811
    // End profiling operator
812
}
813

814 815
void ChannelImpl::flush_apply_stack() {
    m_applying = true;
816
    auto& state = get_worker_state();
817
    while (!m_apply_stack.empty()) {
M
Megvii Engine Team 已提交
818 819
        auto& [cmd, idx, recomp, reason] =
                m_apply_stack.top();  // cmd.inputs[0~idx-1] is in memory
820 821 822 823 824
        if (idx == 0) {
            if (state.options.enable_dtr_auto_drop) {
                m_dtr.pin(cmd.inputs);
            }
            if (recomp) {
M
Megvii Engine Team 已提交
825 826
                MGB_RECORD_EVENT(
                        TensorCommandEvent, recomp->id, TensorCommandKind::ReGen);
827 828 829
            }
        }
        bool regen = false;
M
Megvii Engine Team 已提交
830
        for (size_t i = idx; i < cmd.inputs.size(); i++) {
831 832 833 834 835 836
            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 已提交
837
                regenerate(p);  // add ApplyOp to the stack
838 839 840 841
                regen = true;
                break;
            }
        }
M
Megvii Engine Team 已提交
842 843
        if (regen)
            continue;
844
        // the required input tensors are already in memory
M
Megvii Engine Team 已提交
845 846
        auto [cmd_backup, recomp_backup, reason_backup] =
                std::make_tuple(cmd, recomp, reason);
847
        m_apply_stack.pop();
848
        do_apply_op(cmd_backup, reason_backup);
849
        if (recomp_backup) {
M
Megvii Engine Team 已提交
850 851 852
            MGB_RECORD_EVENT(
                    TensorCommandFinishEvent, recomp_backup->id,
                    TensorCommandKind::ReGen);
853 854
            for (auto o : cmd_backup.outputs) {
                if (o) {
855 856 857 858
                    m_dtr.update_dsu_after_recompute(o);
                }
            }
        }
859
    }
860
    m_applying = false;
861 862
}

863
bool ChannelImpl::auto_evict(size_t force_num) {
864
    auto& state = get_worker_state();
865
    if (!m_dtr.comp_node.valid()) {
866
        return false;
867 868
    }
    size_t current_memory = m_dtr.comp_node.get_used_memory();
869
    size_t flag = false;
M
Megvii Engine Team 已提交
870 871 872
    while ((state.options.dtr_eviction_threshold > 0 &&
            current_memory > state.options.dtr_eviction_threshold) ||
           force_num > 0) {
873
        MGB_RECORD_EVENT(AutoEvictEvent);
874
        sample_on_device(m_dtr.comp_node, false);
875
        auto best = m_dtr.find_best_tensor(state.options.enable_dtr_sqrt_sampling);
876
        if (!best) {
877
            MGB_RECORD_EVENT(AutoEvictFinishEvent);
878 879 880 881
            break;
        }
        if (best->ptr.unique() && best->ptr->blob().unique()) {
            current_memory -= best->memory;
882
            if (force_num > 0) {
M
Megvii Engine Team 已提交
883
                force_num--;
884 885
            }
            flag = true;
886 887 888 889
        }
        do_drop(best);
        if (best->evict_type == EvictType::DROP) {
            m_dtr.update_dsu_after_evict(best);
890
        }
891
        sample_on_device(m_dtr.comp_node, false);
892
        MGB_RECORD_EVENT(AutoEvictFinishEvent);
893
    }
894
    return flag;
895 896
}

897 898
void ChannelImpl::detach_users(TensorInfo* dest) {
    SmallVector<TensorInfo::ComputePath*> users = dest->users;
M
Megvii Engine Team 已提交
899
    for (auto* user : users) {
900 901
        SmallVector<TensorInfo*> outputs = user->outputs;
        SmallVector<TensorInfo*> inputs = user->inputs;
M
Megvii Engine Team 已提交
902 903 904 905 906
        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.
907 908 909 910 911
            if (output == nullptr) {
                continue;
            }
            regenerate(output);
            output->detach_producer();
M
Megvii Engine Team 已提交
912 913
            for (auto* input : inputs) {
                input->ref_cnt--;
914
            }
915
        }
916
        // now user is dead
917
    }
918
    mgb_assert(dest->users.empty(), "ComputePath leaking");
919 920
}

921 922 923 924
bool ChannelImpl::check_available() {
    return !m_closed;
}

925 926 927 928 929
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();
930
    MGB_RECORD_EVENT(TensorWaitPropEvent, info->id, m_waitee_id, prop);
931
    bool require_host = prop == TensorProp::HostValue;
M
Megvii Engine Team 已提交
932
    auto host_available = [&] { return info->ptr && info->ptr->value_fetched(); };
933 934
    bool wait_host = false;
    if (require_host && !host_available()) {
935 936
        // avoid dead lock
        lock.unlock();
937 938 939
        m_worker.add_task(
                {Profiler::next_id(), GetValue{info},
                 get_channel_state().stack_manager.dump()});
940
        lock.lock();
941
        wait_host = true;
942
    }
943 944
    m_cv.wait(lock, [&]() {
        check_worker_exc_unsafe();
945
        return require_host ? host_available() : static_cast<bool>(info->ptr);
946
    });
947
    MGB_RECORD_EVENT(TensorWaitPropFinishEvent, info->id, m_waitee_id, prop);
948
    m_waitee = nullptr;
949
    if (wait_host) {
950 951 952
        auto err = info->ptr->comp_node().check_async_error();
        mgb_assert(!err, "%s", err->what());
    }
953 954 955 956 957
    return info->ptr;
}

void ChannelImpl::notify_tensor_unsafe(TensorInfo* info) {
    if (info == m_waitee) {
958
        MGB_RECORD_EVENT(TensorNotifyPropEvent, info->id);
959
        m_cv.notify_all();
960
    }
961 962 963 964
}

std::unordered_set<TensorInfo*> ChannelImpl::collect_valid_tensors() {
    std::unordered_set<TensorInfo*> valid_tensors;
M
Megvii Engine Team 已提交
965
    for (auto* handle : m_valid_handle) {
966 967
        auto* info = reinterpret_cast<TensorInfo*>(handle);
        valid_tensors.insert(info);
968
    }
969
    return valid_tensors;
970 971
}

972
void ChannelImpl::alloc_tensor_with_evict(Blob* x) {
973 974 975 976 977 978
    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 已提交
979 980
            if (!evict_suc)
                return false;
981 982 983 984
        }
        return true;
    };
    auto pre_level = set_log_level(LogLevel::NO_LOG);
985 986
    reserve_size(x->size());
    MGB_TRY { BlobManager::inst()->alloc_direct(x, x->size()); }
987 988 989 990 991 992
    MGB_CATCH(MemAllocError&, {
        bool suc = false;
        while (!suc) {
            if (!auto_evict(1)) {
                break;
            }
993
            MGB_TRY { BlobManager::inst()->alloc_direct(x, x->size()); }
994 995 996 997 998
            MGB_CATCH(MemAllocError&, { continue; });
            suc = true;
        }
        if (!suc) {
            set_log_level(pre_level);
M
Megvii Engine Team 已提交
999 1000 1001
            mgb_log_warn(
                    "reallocating all cuda memory to alleviate fragmentation, the "
                    "performance may be affected");
1002
            set_log_level(LogLevel::NO_LOG);
1003
            imperative_log_profile_begin("defrag");
1004
            BlobManager::inst()->defrag(x->comp_node());
1005
            imperative_log_profile_end("defrag");
1006
            BlobManager::inst()->alloc_direct(x, x->size());
1007 1008 1009 1010 1011
        }
    });
    set_log_level(pre_level);
}

1012
void ChannelImpl::process_one_task(Command& icmd) {
1013 1014
    using namespace ranges;
    using namespace ranges::views;
1015
    auto& state = get_worker_state();
1016
    auto& options = state.options;
M
Megvii Engine Team 已提交
1017
    // TODO: remove std::visit for support osx 10.12
1018
    auto cmd_visitor = [&](const auto& cmd) {
M
Megvii Engine Team 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        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) {
                if (i->invalid) {
                    MGB_LOCK_GUARD(m_mutex);
                    for (auto& i : cmd.outputs) {
                        i->invalid = true;
1040
                    }
M
Megvii Engine Team 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
                    return;
                }
            }
            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;
                }
                if (state.options.enable_dtr_auto_drop) {
                    output->dsu_ptr = std::make_shared<DsuNode>(output->compute_time);
1053
                }
M
Megvii Engine Team 已提交
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
                    }
M
Megvii Engine Team 已提交
1062 1063 1064 1065 1066 1067 1068
                    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();
1069
                    }
M
Megvii Engine Team 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
                    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(
                            cmd.id, cmd.op, cmd.inputs, cmd.outputs);
                    size_t detach_cnt = 0;
                    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
1089
                        for (auto input : cmd.inputs) {
M
Megvii Engine Team 已提交
1090
                            input->ref_cnt -= 2;
1091 1092
                        }
                    }
M
Megvii Engine Team 已提交
1093 1094 1095 1096 1097 1098 1099
                    for (auto output : cmd.outputs) {
                        if (output->producer &&
                            !output->size_exceeds_thd(
                                    state.options.dtr_evictee_minimum_size)) {
                            output->detach_producer();
                            detach_cnt++;
                        }
1100
                    }
M
Megvii Engine Team 已提交
1101 1102
                    for (auto input : cmd.inputs) {
                        input->ref_cnt -= detach_cnt;
1103
                    }
1104
                }
1105
            }
M
Megvii Engine Team 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
        } 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();
1122
            MGB_LOCK_GUARD(m_mutex);
M
Megvii Engine Team 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
            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) {
1140
                    // TODO: handle drop
M
Megvii Engine Team 已提交
1141 1142 1143
                    MGB_RECORD_EVENT(
                            TensorProduceEvent, info->id, info->desc.layout,
                            info->desc.comp_node, info->ptr->dev_tensor().raw_ptr());
1144 1145
                }
            }
M
Megvii Engine Team 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
            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);
1161
            }
M
Megvii Engine Team 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170
            CompNode::foreach (
                    [&](CompNode device) { sample_on_device(device, true); });
            MGB_RECORD_EVENT(StopProfileFinishEvent);
        } 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);
        } else {
            static_assert(!std::is_same_v<T, T>);
1171
        }
M
Megvii Engine Team 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    };
    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);
1199 1200 1201 1202
}

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

1215
void ChannelImpl::start_profile() {
1216
    MGB_LOCK_GUARD(m_spin);
1217
    mgb_assert(check_available(), "Channel already closed");
1218 1219
    auto capture_tensors = collect_valid_tensors();
    if (capture_tensors.size() > 0) {
1220 1221 1222
        m_worker.add_task(
                {Profiler::next_id(), StartProfile{std::move(capture_tensors)},
                 get_channel_state().stack_manager.dump()});
1223
    }
1224 1225
}

1226
void ChannelImpl::stop_profile() {
1227
    MGB_LOCK_GUARD(m_spin);
1228
    mgb_assert(check_available(), "Channel already closed");
1229 1230
    auto escape_tensors = collect_valid_tensors();
    if (escape_tensors.size() > 0) {
1231 1232 1233
        m_worker.add_task(
                {Profiler::next_id(), StopProfile{std::move(escape_tensors)},
                 get_channel_state().stack_manager.dump()});
1234
    }
1235 1236 1237
}

void ChannelImpl::push_scope(std::string name) {
1238
    MGB_LOCK_GUARD(m_spin);
1239
    mgb_assert(check_available(), "Channel already closed");
1240
    auto& state = get_channel_state();
1241
    state.stack_manager.enter(name);
1242
    MGB_RECORD_EVENT(ScopeEvent, name);
1243 1244 1245
    m_worker.add_task(
            {Profiler::next_id(), PushScope{name},
             get_channel_state().stack_manager.dump()});
1246 1247 1248
}

void ChannelImpl::pop_scope(std::string name) {
1249
    MGB_LOCK_GUARD(m_spin);
1250
    mgb_assert(check_available(), "Channel already closed");
1251
    auto& state = get_channel_state();
1252
    state.stack_manager.exit(name);
1253
    MGB_RECORD_EVENT(ScopeFinishEvent, name);
1254 1255 1256
    m_worker.add_task(
            {Profiler::next_id(), PopScope{name},
             get_channel_state().stack_manager.dump()});
1257 1258
}

1259
void ChannelImpl::assert_in_channel() {
M
Megvii Engine Team 已提交
1260 1261 1262
    mgb_assert(
            get_worker_tid() != std::this_thread::get_id(),
            "this method cannot be called in worker thread");
1263 1264 1265
}

void ChannelImpl::assert_in_worker() {
M
Megvii Engine Team 已提交
1266 1267 1268
    mgb_assert(
            get_worker_tid() == std::this_thread::get_id(),
            "this method can only be called in worker thread");
1269 1270
}

1271 1272 1273
void ChannelImpl::sample_on_device(CompNode device, bool force) {
    if (!force) {
        thread_local int last_sample_id = 0;
M
Megvii Engine Team 已提交
1274 1275
        int sample_rate =
                Profiler::is_profiling() ? Profiler::get_option("sample_rate", 0) : 0;
1276 1277 1278 1279
        if (!sample_rate || ((++last_sample_id) % sample_rate != 0)) {
            return;
        }
    }
1280
    MGB_RECORD_EVENT(SampleDeviceEvent, device);
1281
    auto [total, free] = device.get_mem_status_bytes();
1282
    MGB_RECORD_EVENT(SampleDeviceFinishEvent, device, total, free);
1283 1284
}

1285 1286 1287
void ChannelImpl::DynamicSublinear::pin(const SmallVector<TensorInfo*>& vec) {
    for (auto i : vec) {
        i->pin();
1288
        erase_candidate(i);
1289 1290 1291
    }
}

1292 1293
void ChannelImpl::DynamicSublinear::unpin(
        const SmallVector<TensorInfo*>& vec, WorkerState& state) {
1294 1295
    for (auto i : vec) {
        i->unpin();
1296 1297 1298 1299 1300
        if (i->pinned == 0 &&
            i->size_exceeds_thd(state.options.dtr_evictee_minimum_size) &&
            i->cand_index == UINT_MAX) {
            insert_candidate(i);
        }
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    }
}

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 已提交
1347 1348
TensorInfo* ChannelImpl::DynamicSublinear::find_best_tensor(
        bool enable_dtr_sqrt_sampling = false) {
1349 1350 1351
    if (candidates.empty())
        return nullptr;

1352 1353
    double min_msps = -1;
    TensorInfo* best = nullptr;
1354 1355
    size_t sz = 1;
    if (enable_dtr_sqrt_sampling) {
M
Megvii Engine Team 已提交
1356 1357
        while (sz * sz <= candidates.size())
            sz++;
1358
        sz--;
1359 1360 1361
    } else {
        sz = candidates.size();
    }
1362 1363 1364 1365 1366 1367 1368

    size_t ti = rand() % sz;
    for (size_t vi = 0; vi < sz; vi++) {
        if (!enable_dtr_sqrt_sampling) {
            ti = vi;
        }
        auto i = candidates[ti];
1369
        if (i->producer && i->ptr && i->evict_type == EvictType::NONE) {
1370
            double neighbor_cost = estimate_neighbor_cost(i);
M
Megvii Engine Team 已提交
1371 1372 1373 1374
            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());
1375
            double free_mem = side_info.first + side_info.second;
M
Megvii Engine Team 已提交
1376 1377
            double msps = i->eval_func(
                    neighbor_cost, free_mem, estimate_timestamp, 1.0, 1.0, 1.0, 1.0001);
1378 1379 1380 1381 1382
            if (min_msps < 0 || msps < min_msps) {
                min_msps = msps;
                best = i;
            }
        }
1383 1384 1385 1386 1387
        if (enable_dtr_sqrt_sampling) {
            ti += rand() % sz;
            if (ti > candidates.size())
                break;
        }
1388 1389 1390 1391
    }
    return best;
}

M
Megvii Engine Team 已提交
1392 1393
void ChannelImpl::DynamicSublinear::merge(
        std::shared_ptr<DsuNode>& x, std::shared_ptr<DsuNode>& y) {
1394 1395 1396 1397 1398 1399 1400 1401 1402
    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 已提交
1403 1404
std::shared_ptr<DsuNode> ChannelImpl::DynamicSublinear::find_father(
        std::shared_ptr<DsuNode>& x) {
1405 1406 1407 1408 1409 1410 1411 1412 1413
    if (x->is_root()) {
        return x;
    } else {
        auto&& fa = find_father(x->parent);
        return x->parent = fa;
    }
}

void ChannelImpl::DynamicSublinear::insert_candidate(TensorInfo* ptr) {
1414 1415 1416 1417 1418 1419
    // 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);
1420 1421 1422 1423 1424 1425
    if (!comp_node.valid()) {
        comp_node = ptr->ptr->comp_node();
    }
}

void ChannelImpl::DynamicSublinear::erase_candidate(TensorInfo* ptr) {
1426 1427 1428 1429 1430 1431
    // 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
1432 1433 1434 1435 1436 1437
    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;
    }
1438 1439 1440 1441 1442
}

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