io.cpp 31.4 KB
Newer Older
1 2 3 4
#include "megbrain/opr/io.h"
#include "megbrain/comp_node_env.h"
#include "megbrain/graph/event.h"
#include "megbrain/graph/exc_extra_info.h"
M
Megvii Engine Team 已提交
5
#include "megbrain/graph/grad_impl.h"
6 7 8 9 10 11 12 13 14
#include "megbrain/opr/internal/megdnn_opr_wrapper.h"
#include "megbrain/serialization/opr_load_dump.h"

using namespace mgb;
using namespace opr;

namespace {
//! helper for implementing oprs that hold a device tensor value
namespace dv_helper {
M
Megvii Engine Team 已提交
15 16 17 18 19
void add_output(
        cg::OperatorNodeBase& opr, DType dtype, const Maybe<std::string>& name = None);
void init_output_mem_plan(
        const DeviceTensorND& val, cg::OperatorNodeBase& opr, bool dynamic,
        size_t ovar_idx = 0);
20 21 22 23 24 25
void check_in_exec(const DeviceTensorND& val, VarNode* var);
}  // namespace dv_helper
}  // anonymous namespace

/* ===================== dv_helper ===================== */

M
Megvii Engine Team 已提交
26 27
void dv_helper::add_output(
        cg::OperatorNodeBase& opr, DType dtype, const Maybe<std::string>& name) {
28 29 30 31 32 33 34 35
    mgb_assert(dtype.valid());
    opr.add_output(name)
            ->add_flag(VarNode::Flag::NO_MEM_RECLAIM)
            .add_flag(VarNode::Flag::PERSISTENT_DEVICE_VALUE)
            .add_flag(VarNode::Flag::DISALLOW_RT_FORCE_DYNAMIC_MEM_ALLOC)
            .dtype(dtype);
}

M
Megvii Engine Team 已提交
36 37 38
void dv_helper::init_output_mem_plan(
        const DeviceTensorND& val, cg::OperatorNodeBase& opr, bool dynamic,
        size_t ovar_idx) {
39 40
    mgb_assert(!dynamic);
    auto ovar = opr.output(ovar_idx);
M
Megvii Engine Team 已提交
41 42 43 44
    mgb_assert(
            val.dtype() == ovar->dtype(), "dtype mismatch: get=%s expect=%s opr=%s{%s}",
            val.dtype().name(), ovar->dtype().name(), opr.cname(),
            opr.dyn_typeinfo()->name);
45 46 47 48 49
    ovar->init_mem_plan(&val);
}

void dv_helper::check_in_exec(const DeviceTensorND& val, VarNode* var) {
    auto&& oval = var->dev_tensor();
M
Megvii Engine Team 已提交
50 51 52
    if (!(val.comp_node().mem_node() == oval.comp_node().mem_node() &&
          val.raw_ptr() == oval.raw_ptr() && val.layout().eq_layout(oval.layout()) &&
          val.dtype() == var->dtype())) {
53
        var->owner_opr()->owner_graph()->record_async_error(
M
Megvii Engine Team 已提交
54 55 56 57 58 59 60 61 62 63
                cg::OperatorNodeExcExtraInfo::ExcMaker{var->owner_opr()}
                        .make_unique<MegBrainError>(ssprintf(
                                "value changed in DeviceTensorHolder: cn=(%s,%s), "
                                "ptr=(%p,%p), "
                                "layout=(%s,%s), dtype=(%s,%s)",
                                val.comp_node().to_string().c_str(),
                                oval.comp_node().to_string().c_str(), val.raw_ptr(),
                                oval.raw_ptr(), val.layout().to_string().c_str(),
                                oval.layout().to_string().c_str(), val.dtype().name(),
                                var->dtype().name())));
64 65 66 67 68 69 70
    }
}

/* ===================== HostIONodeBase ===================== */

void intl::HostIONodeBase::init_output_static_infer_desc() {
    using namespace cg::static_infer;
M
Megvii Engine Team 已提交
71 72
    auto&& mgr = owner_graph()->static_infer_manager();
    auto infer_shp = [this](TensorShape& dest, const InpVal&) -> bool {
73 74 75 76 77
        dest = get_output_shape();
        return dest.ndim;
    };

    auto shape_type = static_infer_src_type();
M
Megvii Engine Team 已提交
78 79 80 81
    auto opr_load_ctx =
            owner_graph()
                    ->options()
                    .user_data.get_user_data<serialization::OprLoadContext>();
82 83 84 85 86 87 88 89 90
    if (opr_load_ctx.second) {
        mgb_assert(opr_load_ctx.second == 1);
        if (opr_load_ctx.first[0]->config().const_var_shape) {
            shape_type = cg::static_infer::SourceType::CONSTANT;
        }
    }
    mgr.register_shape_infer(output(0), {shape_type, {}, infer_shp});

    if (fill_in_static_infer(nullptr)) {
M
Megvii Engine Team 已提交
91
        auto infer_val = [this](DeviceTensorND& dest, const InpVal&) -> bool {
92
            if (fill_in_static_infer(&dest) && dest.shape_valid()) {
93 94 95 96
                return true;
            }
            return false;
        };
M
Megvii Engine Team 已提交
97
        mgr.register_value_infer(output(0), {static_infer_src_type(), {}, infer_val});
98 99 100
    }
}

M
Megvii Engine Team 已提交
101
cg::static_infer::SourceType intl::HostIONodeBase::static_infer_src_type() const {
102 103 104 105 106 107 108 109 110 111 112 113 114 115
    return cg::static_infer::SourceType::MUTABLE;
}

/* ===================== DeviceTensorHolder ===================== */

class intl::DeviceTensorHolder::DevValueExecDep final : public ExecDependency {
    DeviceTensorStorage m_val;

public:
    explicit DevValueExecDep(DeviceTensorStorage val) : m_val{std::move(val)} {}
};

void intl::DeviceTensorHolder::init_output_format() {
    auto format = get_dev_tensor().format();
M
Megvii Engine Team 已提交
116 117 118
    mgb_assert(
            format.is_default() || format.is_lowbit_aligned(),
            "invalid tensor format: %s", format.to_string().c_str());
119
    output(0)->format(format);
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
}

void intl::DeviceTensorHolder::init_output_mem_plan(bool dynamic) {
    dv_helper::init_output_mem_plan(get_dev_tensor(), *this, dynamic);
}

void intl::DeviceTensorHolder::scn_do_execute() {
    dv_helper::check_in_exec(get_dev_tensor(), output(0));
}

void intl::DeviceTensorHolder::add_output(DType dtype) {
    mgb_assert(output().empty());
    dv_helper::add_output(*this, dtype);
}

void intl::DeviceTensorHolder::record_execute_deps(ExecDependencyArray& deps) {
136 137 138 139
    if (!output(0)->contain_flag(VarNode::Flag::MEMORY_NO_NEED)) {
        deps.emplace_back(
                std::make_unique<DevValueExecDep>(get_dev_tensor().storage()));
    }
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
}

/* ===================== Host2DeviceCopy ===================== */

class Host2DeviceCopy::HostValueExecDep final : public ExecDependency {
    std::shared_ptr<HostTensorND> m_hv;
    void* m_ptr;
    TensorShape m_shape;

public:
    explicit HostValueExecDep(std::shared_ptr<HostTensorND> hv)
            : m_hv{hv}, m_ptr{hv->raw_ptr()}, m_shape{hv->shape()} {}

    bool has_runtime_check() const override { return true; }

    void do_runtime_check() override {
M
Megvii Engine Team 已提交
156 157 158 159
        mgb_assert(
                m_hv->raw_ptr() == m_ptr && m_hv->shape().eq_shape(m_shape),
                "host tensor changed: %p(%s) vs %p(%s)", m_hv->raw_ptr(),
                m_hv->shape().to_string().c_str(), m_ptr, m_shape.to_string().c_str());
160 161 162 163
    }
};

MGB_DYN_TYPE_OBJ_FINAL_IMPL(Host2DeviceCopy);
M
Megvii Engine Team 已提交
164 165 166 167
Host2DeviceCopy::Host2DeviceCopy(
        ComputingGraph& graph, const std::shared_ptr<HostTensorND>& host_data,
        const Param& param, const OperatorNodeConfig& config)
        : Super{&graph, config, "h2d", {}}, m_param{param}, m_host_data{host_data} {
168 169 170 171 172 173
    auto out_cn = m_host_data->comp_node();
    if (config.has_comp_node_set())
        out_cn = config.get_single_comp_node();
    mgb_assert(out_cn.valid(), "can not get output comp node");

    if (param.allow_cpu_mem_fwd &&
M
Megvii Engine Team 已提交
174 175
        out_cn.mem_node() == CompNode::default_cpu().mem_node() &&
        host_data->comp_node().mem_node() == out_cn.mem_node()) {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        m_fwd_host_mem = true;
        dv_helper::add_output(*this, host_data->dtype());
    } else {
        m_fwd_host_mem = false;
        add_output(None)->dtype(host_data->dtype());
    }
    add_equivalence_component<ScalarHash<void*>>(host_data.get());
    add_equivalence_component<PODHash<Param>>(&m_param);

    this->comp_node(out_cn);

    output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
}

const TensorShape& Host2DeviceCopy::get_output_shape() {
    return m_host_data->shape();
}

bool Host2DeviceCopy::fill_in_static_infer(DeviceTensorND* dest) {
    if (!m_param.enable_value_infer) {
        return false;
    }
    if (!dest) {
        // query whether static infer is supported
        return true;
    }
    if (m_host_data->storage().has_no_real_storage()) {
        return false;
    }
    dest->copy_from(*m_host_data);
    return true;
}

void Host2DeviceCopy::scn_do_execute() {
    if (m_fwd_host_mem) {
M
Megvii Engine Team 已提交
211
        mgb_assert(m_host_data->comp_node().mem_node() == comp_node().mem_node());
212 213 214 215 216 217 218 219 220 221 222
        if (m_host_data_dev_cont_need_sync)
            m_host_data_dev_cont.copy_from_fixlayout(*m_host_data);
        dv_helper::check_in_exec(get_dev_tensor_in_mem_fwd(), output(0));
    } else {
        auto&& od = output(0)->dev_tensor();
        od.copy_from_fixlayout(*m_host_data);
    }
}

void Host2DeviceCopy::init_output_mem_plan(bool dynamic) {
    if (m_fwd_host_mem) {
M
Megvii Engine Team 已提交
223
        dv_helper::init_output_mem_plan(get_dev_tensor_in_mem_fwd(), *this, dynamic);
224 225 226 227 228
    } else {
        Super::init_output_mem_plan(dynamic);
    }
}

M
Megvii Engine Team 已提交
229
void Host2DeviceCopy::init_output_comp_node() {}
230 231 232 233 234

const DeviceTensorND& Host2DeviceCopy::get_dev_tensor_in_mem_fwd() const {
    mgb_assert(m_fwd_host_mem);
    if (!m_host_data->layout().is_contiguous()) {
        m_host_data_dev_cont_need_sync = true;
M
Megvii Engine Team 已提交
235 236 237
        m_host_data_dev_cont.comp_node(comp_node())
                .dtype(m_host_data->dtype())
                .resize(m_host_data->shape());
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
        return m_host_data_dev_cont;
    }
    m_host_data_dev_cont_need_sync = false;

    m_host_data_dev_proxy = DeviceTensorND::make_proxy(*m_host_data);
    return m_host_data_dev_proxy;
}

cg::OperatorNodeBase::NodeProp* Host2DeviceCopy::do_make_node_prop() const {
    auto ret = Super::do_make_node_prop();
    if (m_fwd_host_mem) {
        ret->add_flag(NodeProp::Flag::IMPURE_OUTPUT_MEM_PLAN);
    }
    return ret;
}

M
Megvii Engine Team 已提交
254 255 256 257 258 259 260
SymbolVar Host2DeviceCopy::make(
        ComputingGraph& graph, const std::shared_ptr<HostTensorND>& host_data,
        const Param& param, const OperatorNodeConfig& config) {
    return graph
            .insert_opr(
                    std::make_unique<Host2DeviceCopy>(graph, host_data, param, config))
            ->output(0);
261 262 263
}

void Host2DeviceCopy::record_execute_deps(ExecDependencyArray& deps) {
M
Megvii Engine Team 已提交
264
    deps.emplace_back(std::make_unique<HostValueExecDep>(std::move(m_host_data)));
265 266 267 268 269
}

/* ===================== SharedDeviceTensor related ===================== */

intl::SharedDeviceTensorBase::SharedDeviceTensorBase(
270 271 272 273 274
        ComputingGraph& graph, const std::shared_ptr<DeviceTensorND>& dev_data,
        bool const_value, const OperatorNodeConfig& config)
        : Super{&graph, config, "shared", {}},
          m_dev_data{dev_data},
          m_const_value(const_value) {
275 276 277 278 279 280 281 282 283 284 285 286 287
    if (config.has_comp_node_set()) {
        mgb_assert(config.get_single_comp_node() == dev_data->comp_node());
    }
    add_output(dev_data->dtype());
    add_equivalence_component<ScalarHash<void*>>(dev_data.get());
}

const TensorShape& intl::SharedDeviceTensorBase::get_output_shape() {
    return m_dev_data->shape();
}

void intl::SharedDeviceTensorBase::init_output_comp_node() {
    if (config().has_comp_node_set()) {
M
Megvii Engine Team 已提交
288 289
        mgb_throw_if(
                config().get_single_comp_node() != m_dev_data->comp_node(), GraphError,
290 291 292 293 294 295 296 297 298 299
                "SharedDeviceTensor: comp node in config differs from that in"
                " dev_data");
    }
    comp_node(m_dev_data->comp_node());
}

cg::static_infer::SourceType SharedDeviceTensor::static_infer_src_type() const {
    return cg::static_infer::SourceType::CONSTANT;
}

M
Megvii Engine Team 已提交
300 301 302 303 304 305 306
SymbolVar SharedDeviceTensor::make(
        ComputingGraph& graph, const std::shared_ptr<DeviceTensorND>& dev_data,
        bool const_value, const OperatorNodeConfig& config) {
    return graph
            .insert_opr(std::make_unique<SharedDeviceTensor>(
                    graph, dev_data, const_value, config))
            ->output(0);
307 308
}

M
Megvii Engine Team 已提交
309 310 311
SymbolVar SharedDeviceTensor::make(
        ComputingGraph& graph, const HostTensorND& value, bool const_value,
        const OperatorNodeConfig& config) {
312 313 314 315 316
    auto cn = value.comp_node();
    if (config.has_comp_node_set())
        cn = config.get_single_comp_node();
    auto dev_v = std::make_shared<DeviceTensorND>();
    dev_v->comp_node(cn).copy_from(value).sync();
317
    return make(graph, dev_v, const_value, config);
318 319 320 321
}

MGB_DYN_TYPE_OBJ_FINAL_IMPL(SharedDeviceTensor);

M
Megvii Engine Team 已提交
322
cg::OperatorNodeBase::NodeProp* VolatileSharedDeviceTensor::do_make_node_prop() const {
323 324 325 326 327
    auto ret = Super::do_make_node_prop();
    ret->add_flag(NodeProp::Flag::IMPURE_OUTPUT_MEM_PLAN);
    return ret;
}

328 329 330 331
void VolatileSharedDeviceTensor::init_output_format() {
    output(0)->format(get_dev_tensor().format());
}

M
Megvii Engine Team 已提交
332 333 334 335 336 337 338
SymbolVar VolatileSharedDeviceTensor::make(
        ComputingGraph& graph, const std::shared_ptr<DeviceTensorND>& dev_data,
        const OperatorNodeConfig& config) {
    return graph
            .insert_opr(std::make_unique<VolatileSharedDeviceTensor>(
                    graph, dev_data, false, config))
            ->output(0);
339 340 341 342 343 344 345 346 347 348 349
}

MGB_DYN_TYPE_OBJ_FINAL_IMPL(VolatileSharedDeviceTensor);

/* ============== SharedDeviceTensorWithFormat =============== */
void SharedDeviceTensorWithFormat::init_output_format() {
    output(0)->format(get_dev_tensor().format());
}

SymbolVar SharedDeviceTensorWithFormat::make(
        ComputingGraph& graph, const std::shared_ptr<DeviceTensorND>& dev_data,
350
        bool const_value, const OperatorNodeConfig& config) {
M
Megvii Engine Team 已提交
351 352 353
    auto&& opr = graph.insert_opr(std::make_unique<SharedDeviceTensorWithFormat>(
                                          graph, dev_data, const_value, config))
                         ->cast_final_safe<SharedDeviceTensorWithFormat>();
354 355 356
    return opr.output(0);
}

M
Megvii Engine Team 已提交
357 358
cg::static_infer::SourceType SharedDeviceTensorWithFormat::static_infer_src_type()
        const {
359 360 361 362 363 364 365 366 367 368
    return cg::static_infer::SourceType::CONSTANT;
}

MGB_DYN_TYPE_OBJ_FINAL_IMPL(SharedDeviceTensorWithFormat);

/* ===================== ImmutableTensor ===================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(ImmutableTensor);

class ImmutableTensor::Value {
369
    MGB_MUTEX m_mtx;
370 371
    std::shared_ptr<DeviceTensorND> m_dev = std::make_shared<DeviceTensorND>();
    DeviceTensorND m_static_infer;
372 373
    std::string m_summary;

M
Megvii Engine Team 已提交
374 375
public:
    void setup(CompNode cn, const HostTensorND& val);
376

377 378 379
    void setup(std::shared_ptr<DeviceTensorND> val);

    bool initialized() const { return m_dev->shape_valid(); }
380

M
Megvii Engine Team 已提交
381
    //! value on comp node
382
    const DeviceTensorND& dev() const { return *m_dev; }
383

M
Megvii Engine Team 已提交
384 385
    //! get value on static infer CPU node
    DeviceTensorND& static_infer();
386

M
Megvii Engine Team 已提交
387 388
    //! string summary of the value
    const std::string& summary() const { return m_summary; }
389 390
};

391 392 393 394 395 396
void ImmutableTensor::Value::setup(std::shared_ptr<DeviceTensorND> val) {
    mgb_assert(val);
    m_dev = val;
    m_summary = ssprintf("const%s", val->shape().to_string().c_str());
}

M
Megvii Engine Team 已提交
397
void ImmutableTensor::Value::setup(CompNode cn, const HostTensorND& val) {
398 399 400 401
    mgb_assert(m_dev->empty() && !m_dev->shape_valid());

    m_dev->comp_node(cn).copy_from(val).sync();
    mgb_assert(val.empty() == m_dev->empty());
402 403 404 405 406 407 408 409 410

    auto one_elem = [](const TensorShape& shape) {
        for (size_t i = 0; i < shape.ndim; ++i) {
            if (shape[i] != 1)
                return false;
        }
        return true;
    };

411
    if (!val.empty() && one_elem(val.shape())) {
412 413
        float v;
        static_cast_dtype(&v, val.dtype(), val.raw_ptr());
414
        m_summary = ssprintf("const<%.3g>", v);
415 416 417 418 419 420 421 422 423 424
        if (val.shape().ndim != 1) {
            m_summary += val.shape().to_string();
        }
    } else {
        m_summary = ssprintf("const%s", val.shape().to_string().c_str());
    }
}

DeviceTensorND& ImmutableTensor::Value::static_infer() {
    MGB_LOCK_GUARD(m_mtx);
425
    if (!m_static_infer.shape_valid()) {
426 427
        mgb_assert(m_dev->shape_valid());
        m_static_infer.comp_node(CompNode::default_cpu()).copy_from(*m_dev);
428 429 430 431
    }
    return m_static_infer;
}

M
Megvii Engine Team 已提交
432
class ImmutableTensor::DevValueCache final : public UserDataContainer::UserData {
433 434 435 436 437 438 439 440 441 442 443 444 445
    MGB_TYPEINFO_OBJ_DECL;
    CompNode m_comp_node;

    class TensorKey {
        struct Trait {
            size_t hash = 0, size_bytes = 0;
            TensorLayout layout;
        };
        Trait m_trait;
        std::vector<dt_byte> m_val;
        HostTensorND m_val_ref;

        const dt_byte* val_ptr() const {
446
            mgb_assert(m_trait.size_bytes);
447 448 449
            return m_val.empty() ? m_val_ref.raw_ptr() : m_val.data();
        }

M
Megvii Engine Team 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463
    public:
        TensorKey() = default;
        TensorKey(const HostTensorND& v) : m_val_ref{v} {
            mgb_assert(v.layout().is_contiguous() || v.layout().is_empty());
            m_trait.size_bytes = v.layout().span().high_byte;

            auto&& layout = m_trait.layout;
            // zero to enable byte-comparison
            memset(&layout, 0, sizeof(layout));
            layout.ndim = v.layout().ndim;
            layout.dtype = v.layout().dtype;
            for (size_t i = 0; i < layout.ndim; ++i) {
                layout.shape[i] = v.layout().shape[i];
                layout.stride[i] = v.layout().stride[i];
464
            }
M
Megvii Engine Team 已提交
465 466 467
            XXHash hasher;
            if (!v.empty()) {
                hasher.update(v.raw_ptr(), m_trait.size_bytes);
468
            }
M
Megvii Engine Team 已提交
469 470 471
            hasher.update(&m_trait.layout, sizeof(m_trait.layout));
            m_trait.hash = hasher.digest();
        }
472

M
Megvii Engine Team 已提交
473 474 475 476 477
        bool operator==(const TensorKey& rhs) const {
            return !memcmp(&m_trait, &rhs.m_trait, sizeof(Trait)) &&
                   ((m_trait.size_bytes == 0 && rhs.m_trait.size_bytes == 0) ||
                    !memcmp(val_ptr(), rhs.val_ptr(), m_trait.size_bytes));
        }
478

M
Megvii Engine Team 已提交
479 480 481 482 483 484 485 486 487 488 489 490
        size_t hash() const { return m_trait.hash; }

        //! copy from m_val_ref to m_val, to avoid refed value being
        //! modified
        void copy_val_permanent() {
            if (m_trait.size_bytes == 0)
                return;
            mgb_assert(m_val.empty());
            m_val.resize(m_trait.size_bytes);
            memcpy(m_val.data(), m_val_ref.raw_ptr(), m_trait.size_bytes);
            m_val_ref = {};
        }
491 492 493 494 495 496
    };
    struct ScalarKey {
        size_t hash = 0;
        DTypeScalar val;

        ScalarKey() = default;
M
Megvii Engine Team 已提交
497
        ScalarKey(const DTypeScalar& v) : val{v} {
498 499 500
            hash = PODHash<DTypeScalar>::perform(&val, 1);
        }

M
Megvii Engine Team 已提交
501
        bool operator==(const ScalarKey& rhs) const { return val == rhs.val; }
502 503
    };
    struct Hash {
M
Megvii Engine Team 已提交
504 505
        size_t operator()(const TensorKey& key) const { return key.hash(); }
        size_t operator()(const ScalarKey& key) const { return key.hash; }
506 507 508 509 510
    };

    std::unordered_map<TensorKey, Value, Hash> m_tensor2val;
    std::unordered_map<ScalarKey, Value, Hash> m_scalar2val;

511
    MGB_MUTEX m_mtx;
512

M
Megvii Engine Team 已提交
513
    void setup_value(Value& dest, const HostTensorND& val) {
514 515 516
        dest.setup(m_comp_node, val);
    }

M
Megvii Engine Team 已提交
517 518 519
public:
    //! max number of elements for a tensor to be stored in this cache
    static constexpr size_t MAX_SIZE = TensorLayout::MAX_NDIM * 4;
520

M
Megvii Engine Team 已提交
521
    struct VarNodeCache;
522

M
Megvii Engine Team 已提交
523
    DevValueCache(const CompNodeEnv& env) : m_comp_node{env.comp_node()} {}
524

M
Megvii Engine Team 已提交
525 526 527 528 529
    static DevValueCache& inst(CompNode cn) {
        auto&& env = CompNodeEnv::from_comp_node(cn);
        auto maker = [&]() { return std::make_shared<DevValueCache>(env); };
        return env.get_user_data<DevValueCache>(maker);
    }
530

M
Megvii Engine Team 已提交
531 532 533 534
    const Value& get(const HostTensorND& tensor) {
        if (tensor.shape().is_scalar()) {
            return get(DTypeScalar::make_from_raw(tensor.dtype(), tensor.raw_ptr()));
        }
535

M
Megvii Engine Team 已提交
536 537 538 539 540 541
        MGB_LOCK_GUARD(m_mtx);
        TensorKey key{tensor};
        Value& item = m_tensor2val[key];
        if (!item.initialized()) {
            setup_value(item, tensor);
            const_cast<TensorKey&>(m_tensor2val.find(key)->first).copy_val_permanent();
542
        }
M
Megvii Engine Team 已提交
543 544
        return item;
    }
545

M
Megvii Engine Team 已提交
546 547
    const Value& get(const DTypeScalar& scalar) {
        MGB_LOCK_GUARD(m_mtx);
548

M
Megvii Engine Team 已提交
549 550 551 552 553 554 555
        ScalarKey key{scalar};
        Value& item = m_scalar2val[key];
        if (!item.initialized()) {
            HostTensorND hv{m_comp_node, scalar.dtype()};
            hv.resize({1});
            memcpy(hv.raw_ptr(), scalar.storage(), scalar.dtype().size(1));
            setup_value(item, hv);
556
        }
M
Megvii Engine Team 已提交
557 558
        return item;
    }
559 560 561 562
};
MGB_TYPEINFO_OBJ_IMPL(ImmutableTensor::DevValueCache);
using ImmutableTensorDevValueCache = ImmutableTensor::DevValueCache;

M
Megvii Engine Team 已提交
563 564
struct ImmutableTensor::DevValueCache::VarNodeCache final
        : public UserDataContainer::UserData {
565 566 567 568 569 570
    ThinHashMap<const Value*, SymbolVar> val2var;

    MGB_TYPEINFO_OBJ_DECL;
};
MGB_TYPEINFO_OBJ_IMPL(ImmutableTensor::DevValueCache::VarNodeCache);

M
Megvii Engine Team 已提交
571 572 573
ImmutableTensor::ImmutableTensor(
        ComputingGraph& graph, const Value& value, const OperatorNodeConfig& config)
        : Super{&graph, config, value.summary(), {}}, m_value{value} {
574 575 576 577
    mgb_assert(value.initialized());

    add_output(value.dev().dtype());
    add_equivalence_component<ScalarHash<const void*>>(&value);
578
    output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
579 580 581 582
}

ImmutableTensor::~ImmutableTensor() noexcept = default;

M
Megvii Engine Team 已提交
583 584 585
SymbolVar ImmutableTensor::make(
        ComputingGraph& graph, const HostTensorND& val,
        const OperatorNodeConfig& config) {
586 587 588 589 590 591 592 593 594 595 596
    auto cn = val.comp_node();
    if (config.has_comp_node_set())
        cn = config.get_single_comp_node();

    if (val.shape().total_nr_elems() > DevValueCache::MAX_SIZE) {
        // tensor too large, do not dedup
        auto value = std::make_shared<Value>();
        value->setup(cn, val);
        return make_from_value(graph, *value, value, config);
    }

M
Megvii Engine Team 已提交
597
    auto&& cache = DevValueCache::inst(cn);
598 599 600
    return make_from_value(graph, cache.get(val), {}, config);
}

601 602 603 604 605 606 607 608 609 610 611 612 613
SymbolVar ImmutableTensor::make(
        ComputingGraph& graph, std::shared_ptr<DeviceTensorND> val,
        const OperatorNodeConfig& config) {
    auto cn = val->comp_node();
    if (config.has_comp_node_set())
        cn = config.get_single_comp_node();

    auto value = std::make_shared<Value>();
    value->setup(val);

    return make_from_value(graph, *value, value, config);
}

M
Megvii Engine Team 已提交
614 615 616 617 618
SymbolVar ImmutableTensor::make(
        ComputingGraph& graph, const DTypeScalar& val,
        const OperatorNodeConfig& config) {
    mgb_assert(
            config.has_comp_node_set(),
619 620 621 622
            "comp node must be set for constructing ImmutableTensor from "
            "DTypeScalar");

    auto cn = config.get_single_comp_node();
M
Megvii Engine Team 已提交
623
    auto&& cache = DevValueCache::inst(cn);
624 625 626 627 628 629
    return make_from_value(graph, cache.get(val), {}, config);
}

const DeviceTensorND& ImmutableTensor::value() const {
    return m_value.dev();
}
M
Megvii Engine Team 已提交
630
const DeviceTensorND& ImmutableTensor::host_value() {
631 632
    return const_cast<Value*>(&m_value)->static_infer();
}
633 634

SymbolVar ImmutableTensor::make_from_value(
M
Megvii Engine Team 已提交
635 636 637 638 639 640
        ComputingGraph& graph, const Value& val,
        const std::shared_ptr<Value>& val_refkeep, const OperatorNodeConfig& config) {
    auto ud = graph.options()
                      .user_data.get_user_data_or_create<DevValueCache::VarNodeCache>(
                              std::make_shared<DevValueCache::VarNodeCache>);
    SymbolVar& var = ud->val2var[&val];
641 642

    if (!var.node()) {
M
Megvii Engine Team 已提交
643 644
        var = graph.insert_opr(std::make_unique<ImmutableTensor>(graph, val, config))
                      ->output(0);
645
        if (val_refkeep) {
M
Megvii Engine Team 已提交
646 647
            auto&& opr = var.node()->owner_opr()->cast_final<ImmutableTensor>();
            mgb_assert(&opr.m_value == val_refkeep.get() && !opr.m_value_refkeep);
648 649 650 651 652 653 654 655 656
            opr.m_value_refkeep = val_refkeep;
        }
    }
#if !MGB_BUILD_SLIM_SERVING
    // FIXME: make() of immutable tensor would return immediately instead of
    // calling insert_opr() when hitting cache, so we need call it munually.
    // see MGE-81
    else {
        if (graph.options().eager_evaluation) {
M
Megvii Engine Team 已提交
657
            auto&& opr = var.node()->owner_opr();
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
            graph.insert_opr(std::unique_ptr<OperatorNodeBase>(opr));
        }
    }
#endif
    return var;
}

void ImmutableTensor::init_output_comp_node() {
    comp_node(m_value.dev().comp_node());
}

const TensorShape& ImmutableTensor::get_output_shape() {
    return m_value.dev().shape();
}

M
Megvii Engine Team 已提交
673
bool ImmutableTensor::fill_in_static_infer(DeviceTensorND* dest) {
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
    if (dest)
        *dest = const_cast<Value&>(m_value).static_infer();
    return true;
}

const DeviceTensorND& ImmutableTensor::get_dev_tensor() const {
    return m_value.dev();
}

cg::static_infer::SourceType ImmutableTensor::static_infer_src_type() const {
    return cg::static_infer::SourceType::CONSTANT;
}

/* ===================== Copy ===================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(Copy);

M
Megvii Engine Team 已提交
691 692
Copy::Copy(VarNode* inp, const OperatorNodeConfig& config)
        : Super{inp->owner_graph(), config, "copy", {inp}} {
693
    add_input({inp});
694
    add_output(None)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
695 696
}

M
Megvii Engine Team 已提交
697
SymbolVar Copy::make(SymbolVar inp, const OperatorNodeConfig& config) {
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
    return inp.insert_single_output_opr<Copy>(inp.node(), config);
}

void Copy::mem_plan_fwd_in2out_readonly() {
    if (owner_graph()->options().force_dynamic_alloc) {
        // copy on same CN in force_dynamic_alloc graphs usually used for
        // resolving dependency
        // TODO: add an option disable_auto_memfwd for Copy
        m_mem_fwd_success = false;
        return;
    }

    if (output(0)->comp_node().mem_node() == input(0)->comp_node().mem_node()) {
        m_mem_fwd_success = output(0)->set_fwd_in2out_readonly(
                input(0), SubTensorSpec::make_from_layout(input(0)->layout()));
    } else
        m_mem_fwd_success = false;
}

void Copy::init_output_comp_node() {
    Super::init_output_comp_node();
    if (output(0)->comp_node().mem_node() != input(0)->comp_node().mem_node()) {
        owner_graph()->seq_comp_node_optimizer().register_stream_var(
                output(0), {CompNode::Stream::COPY,
                            cg::SeqCompNodeOptimizer::StreamPropType::WEAK});
    }
}

void Copy::init_rt_force_dynamic_mem_alloc_imply_chain() {
    auto ivar = input(0), ovar = output(0);
    auto cn0 = ivar->comp_node(), cn1 = ovar->comp_node();
    if (cn0 != cn1 && cn0.mem_node() == cn1.mem_node()) {
        // make it possible to forward memory between comp nodes on the same mem
        // node
        ivar->add_rt_force_dynamic_mem_alloc_imply_chain(ovar);
        ovar->add_rt_force_dynamic_mem_alloc_imply_chain(ivar);
    }
}

void Copy::scn_do_execute() {
M
Megvii Engine Team 已提交
738
    auto &&od = output(0)->dev_tensor(), &&id = input(0)->dev_tensor();
739
    if (m_mem_fwd_success) {
M
Megvii Engine Team 已提交
740
        mgb_assert(od.raw_ptr() == id.raw_ptr() && od.layout().eq_layout(id.layout()));
741 742 743 744 745 746 747 748 749 750
    } else {
        od.copy_from_fixlayout(id);
    }
}

Copy::NodeProp* Copy::do_make_node_prop() const {
    auto rst = Super::do_make_node_prop();
    using F = NodeProp::Flag;
    rst->add_flag(F::CROSS_COMP_NODE_MEMORY);
    rst->add_flag(F::NO_AUTOMATIC_DUP);
M
Megvii Engine Team 已提交
751
    rst->add_dep_type_existing_var(input(0), NodeProp::DepType::VALUE_ALLOW_EMPTY);
752 753 754
    return rst;
}

755
#if MGB_ENABLE_GRAD
756 757
MGB_IMPL_OPR_GRAD(Copy) {
    mgb_assert(wrt_idx == 0);
M
Megvii Engine Team 已提交
758 759
    return Copy::make(out_grad[0], OperatorNodeConfig{}.follow_comp_node(opr.input(0)))
            .node();
760
}
761
#endif
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

void Copy::add_input_layout_constraint() {
    if (input(0)->comp_node() != output(0)->comp_node()) {
        auto check = [this](const TensorLayout& layout) {
            auto handle = intl::get_megdnn_handle(this->comp_node());
            return handle->check_cross_dev_copy_constraint(layout);
        };
        input(0)->add_layout_constraint(check);
    }
}

void Copy::init_output_static_infer_desc() {
    using namespace cg::static_infer;
    Super::init_output_static_infer_desc();
    owner_graph()->static_infer_manager().register_value_infer(
            output(0), ValueInferDesc::make_identity(input(0)));
}

/* ===================== MultipleDeviceTensorHolderBase ===================== */

class intl::MultipleDeviceTensorHolderBase::DevValuesExecDep final
        : public ExecDependency {
    SmallVector<DeviceTensorStorage> m_vals;

public:
M
Megvii Engine Team 已提交
787 788 789 790 791
    explicit DevValuesExecDep(
            const ValueArray& vals, MultipleDeviceTensorHolderBase* opr) {
        mgb_assert(
                vals.size() == opr->output().size(),
                "the output value size is diff from output var size");
792
        for (size_t index = 0; index < vals.size(); index++) {
M
Megvii Engine Team 已提交
793
            if (!opr->output(index)->contain_flag(VarNode::Flag::MEMORY_NO_NEED)) {
794 795
                m_vals.emplace_back(std::move(vals[index]->storage()));
            }
796 797 798 799 800
        }
    }
};

intl::MultipleDeviceTensorHolderBase::MultipleDeviceTensorHolderBase(
M
Megvii Engine Team 已提交
801
        ComputingGraph& graph, ValueArray values, const OperatorNodeConfig& config)
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
        : Super(&graph, config, "multi_dv", {}), m_values{std::move(values)} {
    mgb_assert(
            !config.has_comp_node_set(),
            "comp node should not be set for MultipleDeviceTensorHolderBase");
    for (size_t i = 0; i < m_values.size(); ++i) {
        dv_helper::add_output(*this, m_values[i]->dtype(), ssprintf("o%zu", i));
        add_equivalence_component<ScalarHash<void*>>(m_values[i].get());
    }
}

void intl::MultipleDeviceTensorHolderBase::do_execute(ExecEnv& env) {
    // only dispatch to first comp node since all device values should be ready
    // due to PERSISTENT_DEVICE_VALUE
    auto work = [this]() {
        auto&& out = output();
        for (size_t i = 0; i < m_values.size(); ++i) {
            dv_helper::check_in_exec(*m_values[i], out[i]);
        }
    };
    env.dispatch_on_comp_node(output(0)->comp_node(), work);

    // Send BeforeKernel/AfterKernel event on every different comp_node
    ThinHashSet<mgb::CompNode> st = cg::get_opr_comp_node_set(this);
    for (auto cn : st) {
        auto send_event = [this, cn]() {
M
Megvii Engine Team 已提交
827 828
            this->owner_graph()->event().signal_inplace<cg::event::BeforeKernel>(
                    this, cn);
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
            this->owner_graph()->event().signal_inplace<cg::event::AfterKernel>(
                    this, cn);
        };
        env.dispatch_on_comp_node(cn, send_event);
    }
}

void intl::MultipleDeviceTensorHolderBase::init_output_mem_plan(bool dynamic) {
    for (size_t i = 0; i < m_values.size(); ++i) {
        dv_helper::init_output_mem_plan(*m_values[i], *this, dynamic, i);
    }
}

void intl::MultipleDeviceTensorHolderBase::on_output_comp_node_stream_changed() {
    mgb_throw(SystemError, "comp node of device tensor should not change");
}

void intl::MultipleDeviceTensorHolderBase::init_output_comp_node() {
    for (size_t i = 0; i < m_values.size(); ++i) {
        output(i)->comp_node(m_values[i]->comp_node());
    }
}

void intl::MultipleDeviceTensorHolderBase::init_output_static_infer_desc() {
    using namespace cg::static_infer;
    auto&& mgr = owner_graph()->static_infer_manager();
    for (size_t i = 0; i < m_values.size(); ++i) {
M
Megvii Engine Team 已提交
856 857
        auto infer_shp = [p = m_values[i].get()](
                                 TensorShape& dest, const InpVal&) -> bool {
858 859 860
            dest = p->shape();
            return dest.ndim;
        };
M
Megvii Engine Team 已提交
861
        mgr.register_shape_infer(output(i), {SourceType::CONSTANT, {}, infer_shp});
862 863 864
    }
}

M
Megvii Engine Team 已提交
865 866
intl::MultipleDeviceTensorHolderBase::NodeProp* intl::MultipleDeviceTensorHolderBase::
        do_make_node_prop() const {
867 868 869 870 871 872 873
    auto ret = Super::do_make_node_prop();
    ret->add_flag(NodeProp::Flag::CROSS_COMP_NODE_MEMORY);
    return ret;
}

void intl::MultipleDeviceTensorHolderBase::record_execute_deps(
        ExecDependencyArray& deps) {
874
    deps.emplace_back(std::make_unique<DevValuesExecDep>(values(), this));
875 876 877 878 879 880 881
}

/* ===================== MultipleDeviceTensorHolder ===================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(MultipleDeviceTensorHolder);

SymbolVarArray MultipleDeviceTensorHolder::make(
M
Megvii Engine Team 已提交
882
        ComputingGraph& graph, ValueArray values, const OperatorNodeConfig& config) {
883
    return cg::to_symbol_var_array(
M
Megvii Engine Team 已提交
884 885
            graph.insert_opr(std::make_unique<MultipleDeviceTensorHolder>(
                                     graph, std::move(values), config))
886 887 888 889 890 891 892 893
                    ->output());
}

/* ================== MultipleDeviceTensorWithFormatHolder ================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(MultipleDeviceTensorWithFormatHolder);

SymbolVarArray MultipleDeviceTensorWithFormatHolder::make(
M
Megvii Engine Team 已提交
894
        ComputingGraph& graph, ValueArray values, const OperatorNodeConfig& config) {
895
    return cg::to_symbol_var_array(
M
Megvii Engine Team 已提交
896 897
            graph.insert_opr(std::make_unique<MultipleDeviceTensorWithFormatHolder>(
                                     graph, std::move(values), config))
898 899 900 901 902 903 904 905 906 907
                    ->output());
}

void MultipleDeviceTensorWithFormatHolder::init_output_format() {
    for (size_t i = 0; i < m_values.size(); ++i) {
        output(i)->format(m_values[i]->format());
    }
}

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