trace.cpp 29.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
/**
 * \file imperative/src/impl/transformations/trace.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

#include "megbrain/imperative/transformations/trace.h"

#include <chrono>
#include <exception>

#include "megbrain/gopt/inference.h"
#include "megbrain/graph/helper.h"
#include "megbrain/imperative/ops/autogen.h"
#include "megbrain/opr/io.h"
#include "megbrain/opr/utility.h"
#include "megbrain/serialization/serializer.h"

#include "../event_pool.h"

#define trace_assert(_cond, _msg...)                                        \
    do {                                                                    \
        if (mgb_unlikely(!(_cond))) {                                       \
            auto exc = std::make_exception_ptr(TraceError(ssprintf(_msg))); \
            set_exception(exc);                                             \
            std::rethrow_exception(exc);                                    \
        }                                                                   \
    } while (0)

namespace mgb {
namespace imperative {

VarNodeArray TraceResult::dump(
        ComputingGraph& graph,
        std::vector<std::tuple<size_t, std::string, TensorShape>> inputs,
        std::vector<std::pair<size_t, std::string>> outputs, bool prefer_input_names) {
    // var -> VarNode
    std::vector<VarNode*> nodes(vars.size(), nullptr);
    // make h2d node for each input
    for (auto&& [input, name, shape] : inputs) {
        auto& var = vars[input];
        auto& node = nodes[input];
        // TODO: cambricon CompNode
        auto host = std::make_shared<HostTensorND>(
50
                CompNode::load("xpux"), shape, *var.dtype);
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        OperatorNodeConfig config;
        // if prefer_input_names, prefer names from dump args
        // else prefer names got from trace procedure
        if (prefer_input_names && !name.empty()) {
            config.name(name);
        } else if (!var.name.empty()) {
            config.name(var.name);
        } else if (!name.empty()) {
            config.name(name);
        }
        node = opr::Host2DeviceCopy::make(graph, host, {}, config).node();
    }
    // make const node for each constant
    for (size_t i = 0; i < vars.size(); ++i) {
        auto& var = vars[i];
        auto& node = nodes[i];
        if (!node) {
            if (var.kind != VarKind::Internal) {
                if (!var.bound_data) {
                    continue;
                }
                if (!var.name.empty()) {
                    node = opr::ImmutableTensor::make(
                                   graph, var.bound_data.numpy()->as_nd(), {var.name})
                                   .node();
                } else {
                    node = opr::ImmutableTensor::make(
                                   graph, var.bound_data.numpy()->as_nd())
                                   .node();
                }
            }
        }
    }
    std::unordered_map<std::string, std::vector<cg::OperatorNodeBase*>> name2ops;
    // iterate over opr_seq
    for (auto&& item : seq) {
        auto&& [op, inputs, outputs] = item;
        VarNodeArray input_nodes;
        for (auto&& input : inputs) {
            auto& node = nodes[input];
            input_nodes.push_back(node);
        }
        VarNodeArray output_nodes;
        if (op) {
            if (auto* bn = op->try_cast_final<BatchNorm>()) {
                mgb_assert(
                        bn->fwd_mode == BatchNorm::FwdMode::INFERENCE,
                        "can not dump BatchNorm in training mode, maybe you forget to "
                        "do model.eval()?");
            }
            output_nodes = OpDef::apply_on_var_node(*op, input_nodes);
            name2ops[output_nodes[0]->owner_opr()->name()].push_back(
                    output_nodes[0]->owner_opr());
        } else {
            // no opr, just forward VarNode
            mgb_assert(
                    inputs.size() == outputs.size(),
                    "output size not equals to input size when forwarding");
            output_nodes = input_nodes;
        }
        mgb_assert(output_nodes.size() == outputs.size(), "output size mismatch");
        for (size_t i = 0; i < outputs.size(); ++i) {
            auto output = outputs[i];
            auto& var = vars[output];
            auto& node = nodes[output];
            mgb_assert(var.kind == VarKind::Internal, "output node should be internal");
            if (!node) {
                node = output_nodes[i];
            }
            if (!var.name.empty()) {
                node->name(var.name);
            }
        }
    }
    for (auto&& [name, ops] : name2ops) {
        if (ops.size() <= 1) {
            continue;
        }
        // ops.size() > 1, need dedup (rename op)
        for (size_t i = 0; i < ops.size(); ++i) {
            auto& op = ops[i];
            auto new_name = ssprintf("%s[%zu]", name.c_str(), i);
            for (auto&& output : op->output()) {
                auto output_name = output->name();
                auto pos = output_name.find(name);
                if (pos != std::string::npos) {
                    output_name.replace(pos, name.length(), new_name);
                }
                output->name(output_name);
            }
            op->name(new_name);
        }
    }
    VarNodeArray output_nodes;
    for (auto&& [output, name] : outputs) {
        mgb_assert(output < vars.size(), "invalid output id %zu", output);
        mgb_assert(nodes[output], "output node invalid");
        if (!name.empty()) {
            nodes[output]->name(name);
        }
        output_nodes.push_back(nodes[output]);
    }
    return output_nodes;
}

156
ValueRefList TracingTransformation::apply_transformation(
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        const Operator& op, Span<ValueRef> inputs) {
    if (auto* op_value = op.as<ApplyOp>()) {
        SmallVector<ValueRef> unwrapped_inputs;
        SmallVector<TracingValue::ref_t> wrapped_inputs;
        SmallVector<size_t> input_ids;
        for (auto input : inputs) {
            auto tracing_value = input.as_ref<TracingValue>();
            if (!tracing_value) {
                tracing_value =
                        record_var(input, m_capture_as_const, VarKind::External);
            }
            unwrapped_inputs.push_back(tracing_value->value());
            wrapped_inputs.push_back(tracing_value);
            input_ids.push_back(tracing_value->id());
        }
        // TODO: remove OpDef::set_scope
        auto scopes = Transformation::scopes();
        std::string scopes_join;
        for (auto&& scope : scopes) {
            if (!scopes_join.empty()) {
                scopes_join.push_back('.');
            }
            scopes_join.append(scope);
        }
        const_cast<OpDef&>(op_value->op()).set_scope(scopes_join);
        auto unwrapped_outputs = imperative::apply(op, unwrapped_inputs);
183
        ValueRefList wrapped_outputs(unwrapped_outputs.size());
184
        SmallVector<size_t> output_ids;
185 186
        for (size_t i = 0; i < unwrapped_outputs.size(); ++i) {
            auto&& output = unwrapped_outputs[i];
187
            auto wrapped_output = record_var(output, false, VarKind::Internal);
188
            wrapped_outputs[i] = wrapped_output;
189 190 191 192 193 194 195 196 197 198
            output_ids.push_back(wrapped_output->id());
        }
        m_seq.push_back({op_value->op().shared_from_this(), input_ids, output_ids});
        return wrapped_outputs;
    } else if (auto* create_tensor = op.as<CreateTensor>()) {
        auto outputs = imperative::apply(op, inputs);
        if (create_tensor->kind() == CreateTensor::NoTrace) {
            return outputs;
        }
        bool is_const = create_tensor->kind() == CreateTensor::Const;
199
        bool as_const = is_const || m_capture_as_const;
200
        auto wrapped_input = record_var(
201 202 203
                outputs[0], as_const, is_const ? VarKind::Constant : VarKind::External);
        // bound data to outputs too to reduce runtime overhead for shape/value infer
        auto wrapped_output = record_var(outputs[0], as_const, VarKind::Internal);
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        auto input_id = wrapped_input->id();
        auto output_id = wrapped_output->id();
        m_seq.push_back({{}, {input_id}, {output_id}});
        return {wrapped_output};
    } else if (auto* get_attr = op.as<GetAttr>()) {
        auto unwrapped_input = unwrap_var(inputs[0]);
        auto outputs = imperative::apply(op, unwrapped_input);
        if (auto* tracing_value = inputs[0].as<TracingValue>()) {
            auto& var_info = m_vars[tracing_value->id()];
            switch (get_attr->attr()) {
                case GetAttr::Shape:
                    var_info.shape_required = true;
                    break;
                case GetAttr::Data:
                    var_info.data_required = true;
                    break;
                case GetAttr::Value:
                    var_info.value_required = true;
                    break;
                default:
                    break;
            }
        }
        return outputs;
    } else if (auto* trace_mark_var = op.as<TraceMarkVar>()) {
        mgb_assert(inputs.size() == 1, "TraceMarkVar expects exactly one input");
        auto input = inputs[0];
        auto tracing_var = input.as_ref<TracingValue>();
        if (!tracing_var) {
            bool is_input = trace_mark_var->mark().substr(0, 4) == "arg_" ||
                            trace_mark_var->mark().substr(0, 6) == "kwarg_";
            if (is_input) {
                tracing_var = record_var(input, false, VarKind::External);
            } else {
                tracing_var = record_var(input, m_capture_as_const, VarKind::External);
            }
        } else {
            input = tracing_var->value();
        }
        auto output = record_var(input, false, VarKind::Internal);
        m_vars[output->id()].mark = trace_mark_var->mark();
        m_seq.push_back({{}, {tracing_var->id()}, {output->id()}});
        return {output};
    } else if (auto* trace_name_var = op.as<RenameValue>()) {
        mgb_assert(inputs.size() == 1, "RenameValue expects exactly one input");
        auto input = inputs[0];
        auto tracing_var = input.as_ref<TracingValue>();
        if (!tracing_var) {
            tracing_var = record_var(input, m_capture_as_const, VarKind::External);
        } else {
            input = tracing_var->value();
        }
        auto output = record_var(input, false, VarKind::Internal);
        m_vars[output->id()].name = trace_name_var->name();
        m_seq.push_back({{}, {tracing_var->id()}, {output->id()}});
        return {output};
    } else if (op.is<GetName>()) {
        mgb_assert(inputs.size() == 1, "GetName expects exactly one input");
        auto input = inputs[0];
        if (auto tracing_var = input.as_ref<TracingValue>()) {
            auto name = m_vars[tracing_var->id()].name;
            if (!name.empty()) {
                return {StringValue::make(name)};
            } else {
                return {ValueRef()};
            }
        }
        return imperative::apply(op, inputs);
    } else {
        // TODO: handle DTRCommand and ...
        return op.fallback(inputs);
    }
}

void TracingTransformation::on_unregister() noexcept {
    for (auto&& weak_var : m_weak_vars) {
        if (auto tracing_value = weak_var.lock()) {
            auto& var_info = m_vars[tracing_value->id()];
            var_info.data_required = true;
            tracing_value.reset(tracing_value->value());
        }
    }
    m_weak_vars.clear();
}

void CompiledTransformation::compile() {
    // these ops require seq order, so we link them to an mm_io_link to ensure order
    static std::unordered_set<Typeinfo*> mm_io_ops = {
            CollectiveComm::typeinfo(), RemoteSend::typeinfo(), RemoteRecv::typeinfo()};
    mgb_assert(!m_executable, "already compiled");
    // FIXME: mm_io_link and io_links should be merged
    SymbolVarArray io_links;
    SymbolVar mm_io_link;
    auto make_input = [&](VarInfo* var_info) {
        mgb_assert(
                var_info->kind == VarKind::External, "input node should be external");
        VarAccessor accessor;
        auto box = make_box<DeviceTensorND>();
        // TODO: attach ref count, release early
        auto outputs = opr::InputCallback::make(
304 305
                *m_graph, [box] { return box->take_value(); }, *var_info->device,
                *var_info->dtype, var_info->shape, io_links, m_input_shape_static);
306 307 308 309 310 311 312 313 314
        // attach input_callback to io_links
        accessor.node = outputs[0].node();
        io_links = {outputs[1]};
        accessor.data_setter = [box](DeviceTensorND data) { box->try_set_value(data); };
        return accessor;
    };
    auto make_output = [&](TraceResult::VarInfo* var_info, SymbolVar node) {
        VarAccessor accessor;
        accessor.node = node.node();
315 316 317 318 319 320 321 322 323 324 325 326
        if (auto bound_data = var_info->bound_data) {
            accessor.shape_getter = [bound_data]() -> TensorShape {
                return bound_data.shape()->as_tensor_shape();
            };
            accessor.data_getter = [bound_data]() -> DeviceTensorND {
                return bound_data.dev_tensor()->as_nd();
            };
            accessor.value_getter = [bound_data]() -> HostTensorND {
                return bound_data.numpy()->as_nd();
            };
            return accessor;
        }
327 328 329 330 331
        if (var_info->data_required) {
            // reduce d2h when data is available
            // FIXME: compile should not change var_info in-place
            var_info->shape_required = false;
        }
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
        if (var_info->shape_required) {
            // TODO: use static infer manager for some vars?
            auto box = make_box<TensorShape>();
            auto callback = [box](DeviceTensorND data) {
                box->try_set_value(data.shape());
            };
            SymbolVarArray inputs = io_links;
            inputs.insert(inputs.begin(), node);
            auto output = opr::OutputCallback::make({callback, true, false}, inputs);
            io_links = {output};
            accessor.shape_getter = [box]() -> TensorShape { return box->get_value(); };
        }
        if (var_info->data_required) {
            auto box = make_box<DeviceTensorND>();
            auto callback = [box](DeviceTensorND data) { box->try_set_value(data); };
            SymbolVarArray inputs = io_links;
            inputs.insert(inputs.begin(), node);
            auto output = opr::OutputCallback::make({callback, false, false}, inputs);
            io_links = {output};
            accessor.data_getter = [box]() -> DeviceTensorND {
                return box->get_value();
            };
354 355 356 357 358 359
            if (!accessor.shape_getter) {
                // also implement shape_getter
                accessor.shape_getter = [box]() -> TensorShape {
                    return box->get_value().shape();
                };
            }
360 361 362 363 364 365 366
        }
        if (var_info->value_required) {
            struct ValueWithEvent {
                HostTensorND value;
                CompNode::Event* event = nullptr;
            };
            auto box = make_box<ValueWithEvent>();
367
            auto event = EventPool::without_timer().alloc_shared(*var_info->device);
368 369 370 371 372 373 374 375 376 377 378 379 380
            auto callback = [box, event](DeviceTensorND data) {
                HostTensorND host_val;
                host_val.copy_from(data);
                if (data.comp_node() != CompNode::default_cpu()) {
                    mgb_assert(data.comp_node() == event->comp_node());
                    event->record();
                    box->try_set_value({host_val, event.get()});
                } else {
                    box->try_set_value({host_val});
                }
            };
            SymbolVarArray inputs = io_links;
            inputs.insert(inputs.begin(), node);
381
            auto output = opr::OutputCallback::make({callback, true, true}, inputs);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
            io_links = {output};
            accessor.value_getter = [box]() -> HostTensorND {
                auto&& [value, event] = box->get_value();
                if (event) {
                    event->host_wait();
                }
                return value;
            };
        }
        return accessor;
    };
    auto make_const = [&](TraceResult::VarInfo* var_info) {
        VarAccessor accessor;
        mgb_assert(
                var_info->kind == VarKind::Constant, "const node should be constant");
        HostTensorND host_val = var_info->bound_data.numpy()->as_nd();
        accessor.node = opr::ImmutableTensor::make(*m_graph, host_val).node();
        return accessor;
    };
    std::vector<VarAccessor> var_accessors(m_vars.size());
402 403 404 405 406
    auto exc_setter = std::bind(
            &CompiledTransformation::set_exception, this, std::placeholders::_1);
    for (auto&& accessor : var_accessors) {
        accessor.exc_setter = exc_setter;
    }
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    for (auto&& item : m_seq) {
        bool require_link = bool(item.op) && mm_io_ops.count(item.op->dyn_typeinfo());
        VarNodeArray input_vars;
        for (auto&& input : item.inputs) {
            auto& var = m_vars[input];
            if (!var_accessors[input].node) {
                switch (var.kind) {
                    case VarKind::External:
                        var_accessors[input] = make_input(&var);
                        break;
                    case VarKind::Constant:
                        var_accessors[input] = make_const(&var);
                        break;
                    default:
                        mgb_throw(
                                AssertionError,
                                "internal node should be valid when used as input");
                }
            }
426 427 428 429 430 431 432 433 434 435 436
            auto& node = var_accessors[input].node;
            if (input_vars.empty() && require_link && mm_io_link.node()) {
                /*mgb_assert(
                        !input_vars.empty(),
                        "io-mm operator should have at least one input");*/
                auto comp_node = mm_io_link.node()->comp_node();
                // auto comp_node = input_vars[0]->comp_node();
                node = opr::VirtualDep::make({SymbolVar(node), mm_io_link}, comp_node)
                               .node();
            }
            input_vars.push_back(node);
437
        }
438
        /*if (require_link && mm_io_link.node()) {
439 440 441
            mgb_assert(
                    !input_vars.empty(),
                    "io-mm operator should have at least one input");
442 443 444 445 446 447
            auto comp_node = mm_io_link.node()->comp_node();
            // auto comp_node = input_vars[0]->comp_node();
            input_vars[0] = opr::VirtualDep::make(
                                    {SymbolVar(input_vars[0]), mm_io_link}, comp_node)
                                    .node();
        }*/
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
        VarNodeArray output_vars;
        if (item.op) {
            output_vars = OpDef::apply_on_var_node(*item.op, input_vars);
        } else {
            // forward inputs to outputs
            mgb_assert(
                    item.inputs.size() == item.outputs.size(),
                    "output size not equals to input size when forwarding");
            for (auto&& input_var : input_vars) {
                output_vars.push_back(input_var);
            }
        }
        if (require_link) {
            mgb_assert(
                    !item.outputs.empty(),
                    "io-mm operator should have at least one output");
            mm_io_link = SymbolVar(output_vars[0]);
        }
        // init output accessors
        for (size_t i = 0; i < output_vars.size(); ++i) {
            auto output = item.outputs[i];
            auto& node = output_vars[i];
            auto& var = m_vars[output];
            var_accessors[output] = make_output(&var, node);
        }
    }
    ComputingGraph::OutputSpec output_specs;
    // avoid input/output/callback from being optimized
    for (auto&& io_link : io_links) {
        output_specs.push_back({io_link, {}});
    }
    // avoid remote io ops from being optimized
    if (mm_io_link.node()) {
        output_specs.push_back({mm_io_link, {}});
    }
    {
        // set_priority_to_id
        // workaround for having mm_io_link and io_links separated
        auto on_opr = [](mgb::cg::OperatorNodeBase* opr) {
            if (opr->node_prop().attribute().priority == 0) {
                opr->node_prop().attribute().priority = opr->id();
            }
        };
        mgb::cg::DepOprIter dep_iter{on_opr};
        for (const auto& output_spec : output_specs) {
            dep_iter.add(output_spec.first);
        }
    }
    m_executable = m_graph->compile(output_specs);
    m_var_accessors = var_accessors;
    m_output_spec = output_specs;
}

void CompiledTransformation::recompile() {
    mgb_assert(m_executable);
    m_executable = m_graph->compile(m_output_spec);
}

void CompiledTransformation::assert_tensor_equal(ValueRef lhs, ValueRef rhs) {
507 508 509 510 511 512
    if (!lhs.is<HostValue>()) {
        lhs = lhs.numpy();
    }
    if (!rhs.is<HostValue>()) {
        rhs = rhs.numpy();
    }
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    trace_assert(m_value_comparator(lhs, rhs), "tensors not equals");
}

void CompiledTransformation::trace_input(size_t id, ValueRef value) {
    try {
        auto& var = m_vars[id];
        auto& var_accessor = m_var_accessors[id];
        switch (var.kind) {
            case VarKind::External: {
                trace_assert(
                        !value.is<TracedValue>(), "expect external node, got internal");
                if (var.bound_data) {
                    assert_tensor_equal(var.bound_data, value);
                } else {
                    DType dtype = *value.dtype();
                    CompNode device = *value.device();
                    trace_assert(
530 531
                            *var.dtype == dtype, "dtype mismatch: %s vs %s",
                            var.dtype->name(), dtype.name());
532
                    trace_assert(
533 534 535
                            *var.device == device, "comp_node mismatch: %s vs %s",
                            var.device->to_string().c_str(),
                            device.to_string().c_str());
536 537 538 539 540
                }
                var_accessor.data_setter(value.dev_tensor()->as_nd());
                break;
            }
            case VarKind::Constant: {
541
                // expect host value here
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
                mgb_assert(var.bound_data, "const var without data bound");
                assert_tensor_equal(var.bound_data, value);
                break;
            }
            case VarKind::Internal: {
                trace_assert(
                        value.is<TracedValue>(), "expect internal node, got external");
                auto& traced_value = value.cast<TracedValue>();
                trace_assert(traced_value.id() == id, "input id mismatch");
                break;
            }
        }
    } catch (TraceError&) {
        throw;
    } catch (...) {
        mgb_assert(false, "unexpected error");
    }
}

561 562
auto CompiledTransformation::trace_output(size_t id) -> TracedValue::ref_t {
    auto traced_value = TracedValue::make(id, &m_vars[id], &m_var_accessors[id]);
563 564 565 566 567 568 569 570 571
    m_weak_values.push_back(traced_value);
    return traced_value;
}

TraceResult::SeqItem& CompiledTransformation::next_instruction() {
    trace_assert(m_pc < m_seq.size(), "too many instructions");
    return m_seq[m_pc++];
}

572 573 574 575 576 577 578 579 580
ShapeValue::ref_t CompiledTransformation::TracedInfo::shape() const {
    if (!m_shape) {
        trace_assert(m_accessor->shape_getter, "shape unreadable");
        m_shape = ShapeValue::make(ValueShape::from(m_accessor->shape_getter()));
    }
    return m_shape;
}

DTypeValue::ref_t CompiledTransformation::TracedInfo::dtype() const {
581
    return m_var->dtype;
582 583 584
}

CompNodeValue::ref_t CompiledTransformation::TracedInfo::comp_node() const {
585
    return m_var->device;
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
}
auto CompiledTransformation::TracedInfo::accessor() const -> const VarAccessor& {
    return *m_accessor;
}

ValueRefList CompiledTransformation::apply_op(
        const ApplyOp& apply_op, Span<ValueRef> inputs) {
    auto& item = next_instruction();
    trace_assert(inputs.size() == item.inputs.size(), "input size mismatch");
    trace_assert(apply_op.op().is_same(*item.op), "operator mismatch");
    for (size_t i = 0; i < inputs.size(); ++i) {
        trace_input(item.inputs[i], inputs[i]);
    }
    ValueRefList outputs(item.outputs.size());
    for (size_t i = 0; i < item.outputs.size(); ++i) {
        outputs[i] = trace_output(item.outputs[i]);
    }
    return outputs;
}

ValueRefList CompiledTransformation::apply_get_attr(
        const GetAttr& get_attr, Span<ValueRef> inputs) {
    if (auto* traced_value = inputs[0].as<TracedValue>()) {
        ValueRef output;
        auto& var_accessor = traced_value->accessor();
        switch (get_attr.attr()) {
            case GetAttr::Shape:
                output = traced_value->shape();
                break;
            case GetAttr::Data:
                trace_assert(var_accessor.data_getter, "data unreadable");
                output = DeviceValue::make(var_accessor.data_getter());
                break;
            case GetAttr::Value:
                trace_assert(var_accessor.value_getter, "value unreadable");
                output = HostValue::make(var_accessor.value_getter());
                break;
            case GetAttr::DType:
                output = traced_value->dtype();
                break;
            case GetAttr::Device:
                output = traced_value->comp_node();
            default:
                break;
        }
        return {output};
    } else {
        return imperative::apply(get_attr, inputs);
    }
}

ValueRefList CompiledTransformation::apply_create_tensor(
        const CreateTensor& create_tensor, Span<ValueRef> inputs) {
    if (create_tensor.kind() == CreateTensor::NoTrace) {
        return imperative::apply(create_tensor, inputs);
    }
    auto& item = next_instruction();
    trace_assert(item.op == nullptr, "operator mismatch");
    auto input_id = item.inputs[0];
    auto output_id = item.outputs[0];
646 647 648 649 650 651 652 653 654 655 656
    ValueRef tensor;
    if (create_tensor.kind() == CreateTensor::Const) {
        auto args = create_tensor.parse(inputs);
        if (args.host) {
            // performance issue
            tensor = HostValue::make(*args.host);
        }
    }
    if (!tensor) {
        tensor = imperative::apply(create_tensor, inputs)[0];
    }
657 658 659 660 661
    trace_input(input_id, tensor);
    return {trace_output(output_id)};
}

ValueRefList CompiledTransformation::apply_transformation(
662 663
        const Operator& op, Span<ValueRef> inputs) {
    if (auto* op_value = op.as<ApplyOp>()) {
664
        return apply_op(*op_value, inputs);
665
    } else if (auto* create_tensor = op.as<CreateTensor>()) {
666
        return apply_create_tensor(*create_tensor, inputs);
667
    } else if (auto* get_attr = op.as<GetAttr>()) {
668
        return apply_get_attr(*get_attr, inputs);
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    } else if (auto* trace_mark_var = op.as<TraceMarkVar>()) {
        auto& item = next_instruction();
        trace_assert(item.op == nullptr, "operator mismatch");
        trace_assert(item.inputs.size() == 1, "inputs size mismatch");
        trace_assert(item.outputs.size() == 1, "inputs output mismatch");
        trace_input(item.inputs[0], inputs[0]);
        trace_assert(
                trace_mark_var->mark() == m_vars[item.outputs[0]].mark,
                "mark mismatch");
        return {trace_output(item.outputs[0])};
    } else if (auto* trace_name_var = op.as<RenameValue>()) {
        auto& item = next_instruction();
        trace_assert(item.op == nullptr, "operator mismatch");
        trace_assert(item.inputs.size() == 1, "inputs size mismatch");
        trace_assert(item.outputs.size() == 1, "outputs size mismatch");
        trace_input(item.inputs[0], inputs[0]);
        trace_assert(
                trace_name_var->name() == m_vars[item.outputs[0]].name,
                "name mismatch");
        return {trace_output(item.outputs[0])};
    } else {
        return op.fallback(inputs);
    }
}

void CompiledTransformation::on_unregister() noexcept {
    // resolve pending values
    for (auto&& weak_value : m_weak_values) {
        if (auto traced_value = weak_value.lock()) {
            auto& var_accessor = m_var_accessors[traced_value->id()];
            auto value = ([&]() -> ValueRef {
                try {
                    trace_assert(var_accessor.data_getter, "data unreadable");
                    auto dev_value = DeviceValue::make(var_accessor.data_getter());
                    return imperative::apply(
                            CreateTensor(
                                    CreateTensor::Common, dev_value->device(),
                                    dev_value->dtype(), dev_value->shape()),
                            DeviceStorage::make(dev_value->storage()))[0];
                } catch (...) {
                    set_exception(std::current_exception());
                    return ErrorValue::make("trace exit failed");
                }
            })();
            traced_value.reset(value);
        }
    }
    m_weak_values.clear();
}

void CompiledTransformation::execute() {
    mgb_assert(m_executable != nullptr);
    m_graph_executor = std::thread([&] {
        try {
            m_executable->execute();
            m_executable->wait();
        } catch (...) {
            auto exc = std::current_exception();
            set_exception(exc);
        }
    });
}

void CompiledTransformation::wait() {
    try {
        trace_assert(m_pc == m_seq.size(), "mismature end");
    } catch (...) {
    }
    mgb_assert(m_executable != nullptr);
    m_graph_executor.join();
    m_graph_executor = {};
    for (auto&& box : m_boxes) {
        box->reset();
    }
    m_pc = 0;
    std::exception_ptr graph_exc;
    std::swap(m_graph_exc, graph_exc);
    if (graph_exc) {
        // graph with exception cannot be reused
        recompile();
        std::rethrow_exception(graph_exc);
    }
}

std::exception_ptr CompiledTransformation::set_exception(
        std::exception_ptr exc) noexcept {
    MGB_LOCK_GUARD(m_mutex);
    if (m_graph_exc) {
        return m_graph_exc;
    }
    for (auto&& box : m_boxes) {
        box->try_set_exception(exc);
    }
    m_graph_exc = exc;
    return m_graph_exc;
}

}  // namespace imperative
}  // namespace mgb