indexing.cpp 24.5 KB
Newer Older
1 2 3 4
/**
 * \file src/opr/impl/indexing.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11 12
 *
 * 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/opr/indexing.h"
M
Megvii Engine Team 已提交
13
#include "megbrain/graph/grad_impl.h"
14 15 16 17 18 19 20 21 22
#include "megbrain/opr/basic_arith.h"
#include "megbrain/opr/utility.h"

#include "./internal/megdnn_opr_wrapper.inl"

using namespace mgb;
using namespace opr;

namespace {
M
Megvii Engine Team 已提交
23 24 25 26 27 28 29 30 31 32 33
void check_index_dtype(std::initializer_list<SymbolVar*>& inputs) {
    mgb_assert(inputs.size() >= 2);
    auto iter = inputs.begin();
    ++iter;
    SymbolVar& index = **iter;
    if (index.dtype() != dtype::Int32()) {
        mgb_log_warn(
                "dtype of index in IndexingOneHot must be Int32, "
                "got %s for variable %s; convert to Int32 implicitly",
                index.dtype().name(), index.node()->cname());
        index = opr::TypeCvt::make(index, dtype::Int32());
34
    }
M
Megvii Engine Team 已提交
35
}
36

M
Megvii Engine Team 已提交
37
enum IndexingModifyType { SET, INCR };
38

M
Megvii Engine Team 已提交
39 40
template <typename Opr>
struct IndexingModifyTypeGetter {};
41

M
Megvii Engine Team 已提交
42 43 44
#define REG(op, type)                                                         \
    template <>                                                               \
    struct IndexingModifyTypeGetter<megdnn::op> {                             \
45 46 47 48 49 50 51 52 53 54
        static constexpr IndexingModifyType value = IndexingModifyType::type; \
    };
REG(IndexingIncrMultiAxisVec, INCR)
REG(IncrMeshIndexing, INCR)
REG(BatchedIncrMeshIndexing, INCR)
REG(IndexingSetMultiAxisVec, SET)
REG(SetMeshIndexing, SET)
REG(BatchedSetMeshIndexing, SET)
#undef REG

M
Megvii Engine Team 已提交
55
}  // namespace
56 57 58 59 60

namespace mgb {
namespace opr {
namespace intl {

M
Megvii Engine Team 已提交
61 62 63 64 65 66 67 68 69
template <>
struct MegDNNOprInitInputsModifier<IndexingOneHot> {
    static void apply(
            const IndexingOneHot::Param& param,
            std::initializer_list<SymbolVar*> inputs) {
        MGB_MARK_USED_VAR(param);
        check_index_dtype(inputs);
    }
};
70

M
Megvii Engine Team 已提交
71 72 73 74 75 76
template <>
struct MegDNNOprInitInputsModifier<IndexingSetOneHot>
        : public MegDNNOprInitInputsModifier<IndexingOneHot> {};
}  // namespace intl
}  // namespace opr
}  // namespace mgb
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 156 157 158 159 160 161 162
/* ==================== Diag ==================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(Diag);
MEGDNN_OPR_INIT1(Diag, "diag")

#if MGB_ENABLE_GRAD
MGB_IMPL_OPR_GRAD(Diag) {
    if (wrt_idx == 0) {
        SymbolVar data_sym{opr.input(0)};
        return DiagBackward::make(data_sym.symshape(), out_grad[0], opr.param()).node();
    }
    return InvalidGrad::make(opr, wrt_idx);
}
#endif

/* ==================== DiagBackward ==================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(DiagBackward);

DiagBackward::DiagBackward(
        VarNode* shape, VarNode* value, const Param& param,
        const OperatorNodeConfig& config)
        : Super{shape->owner_graph(), config, "diag_backward", {shape, value}},
          m_param{param} {
    add_input({shape, value});
    add_output(None)->dtype(value->dtype());
    add_equivalence_component<PODHash<Param>>(&m_param);
}

SymbolVar DiagBackward::make(
        SymbolVar shape, SymbolVar value, const Param& param,
        const OperatorNodeConfig& config) {
    return shape.insert_single_output_opr<DiagBackward>(
            shape.node(), value.node(), param, config);
}

cg::OperatorNodeBase::NodeProp* DiagBackward::do_make_node_prop() const {
    auto prop = Super::do_make_node_prop();
    using D = NodeProp::DepType;
    prop->add_dep_type(input(0), D::HOST_VALUE);
    return prop;
}

void DiagBackward::scn_do_execute() {
    auto&& dest = output(0)->dev_tensor();
    auto&& val = input(1)->dev_tensor();
    auto&& layout = dest.layout();
    mgb_assert(layout.ndim == 1 || layout.ndim == 2);
    if (layout.ndim == 2) {
        dev_tensor_memset(dest, 0);
        size_t offset = (m_param.k >= 0) ? (m_param.k * layout.stride[1])
                                         : (-m_param.k * layout.stride[0]);
        auto dest_sub = dest.sub(SubTensorSpec::make_from_offset_elem(
                {val.shape(), {layout.stride[0] + layout.stride[1]}, val.dtype()},
                offset));
        dest_sub.copy_from_fixlayout(val);
    } else {
        auto&& opr = m_dnn_opr;
        if (!opr) {
            opr = intl::create_megdnn_opr<megdnn::Diag>(comp_node());
            opr->param() = m_param;
        }
        opr->exec(val.as_megdnn(), dest.as_megdnn(), {});
    }
}

void DiagBackward::record_execute_deps(ExecDependencyArray& deps) {
    deps.emplace_back(std::make_unique<intl::MegDNNGraphDep>(std::move(m_dnn_opr)));
}

void DiagBackward::init_output_static_infer_desc() {
    using namespace cg::static_infer;
    auto&& mgr = owner_graph()->static_infer_manager();
    auto infer_shape = [](TensorShape& dest, const InpVal& inp) {
        cg::copy_tensor_value_to_shape(dest, inp.val.at(0).value());
        return true;
    };
    mgr.register_shape_infer(
            output(0), {SourceType::DEP, {{input(0), DepType::VALUE}}, infer_shape});
}

#if MGB_ENABLE_GRAD
MGB_IMPL_OPR_GRAD(DiagBackward) {
    return InvalidGrad::make(opr, wrt_idx);
}
#endif

163 164 165 166 167 168 169 170
/* ==================== IndexingOneHot ==================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(IndexingOneHot);
MEGDNN_OPR_INIT2(IndexingOneHot, "indexing_one_hot")

void IndexingOneHot::init_output_dtype() {
    output(0)->dtype(input(0)->dtype());
}

171
#if MGB_ENABLE_GRAD
172 173 174
MGB_IMPL_OPR_GRAD(IndexingOneHot) {
    if (wrt_idx == 0) {
        return IndexingSetOneHot::make(
M
Megvii Engine Team 已提交
175 176 177
                       SymbolVar{opr.input(0)}.fill_retain_dtype(0), opr.input(1),
                       out_grad[0], opr.param())
                .node();
178 179 180
    }
    return InvalidGrad::make(opr, wrt_idx);
}
181
#endif
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

/* ==================== IndexingSetOneHot ==================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(IndexingSetOneHot);
MEGDNN_OPR_INIT3(IndexingSetOneHot, "indexing_set_one_hot")

void IndexingSetOneHot::init_output_dtype() {
    output(0)->dtype(input(0)->dtype());
}

void IndexingSetOneHot::add_input_layout_constraint() {
    mixin::megdnn_utils::add_input_layout_constraint_contig(*this);
}

void IndexingSetOneHot::mem_plan_fwd_in2out_writable() {
    cg::request_fwd_in2out_writable_if_no_mem_ovelap(this, 0, 0);
}

void IndexingSetOneHot::init_output_static_infer_desc() {
    using namespace cg::static_infer;
M
Megvii Engine Team 已提交
202 203
    auto&& mgr = owner_graph()->static_infer_manager();
    mgr.register_shape_infer(output(0), ShapeInferDesc::make_identity(input(0)));
204 205 206 207 208 209 210 211 212 213 214 215 216 217
    init_output_static_infer_desc_workspace(false);
}

void IndexingSetOneHot::scn_do_execute() {
    auto &&idata = input(0)->dev_tensor(), &&index = input(1)->dev_tensor(),
         &&odata = output(0)->dev_tensor();

    if (idata.raw_ptr() != odata.raw_ptr()) {
        odata.copy_from_fixlayout(idata);
    } else {
        mgb_assert(odata.layout().eq_layout(idata.layout()));
    }
    mgb_assert(odata.layout().is_contiguous());

M
Megvii Engine Team 已提交
218 219
    megdnn_opr()->exec(
            odata.as_megdnn(), index.as_megdnn(), input(2)->dev_tensor().as_megdnn(),
220 221 222
            intl::get_megdnn_workspace_from_var(output(1)));
}

223
#if MGB_ENABLE_GRAD
224 225 226
MGB_IMPL_OPR_GRAD(IndexingSetOneHot) {
    SymbolVar index{opr.input(1)}, sub{opr.input(2)}, og{out_grad.at(0)};
    if (wrt_idx == 0) {
M
Megvii Engine Team 已提交
227 228
        return IndexingSetOneHot::make(og, index, sub.fill_retain_dtype(0), opr.param())
                .node();
229 230 231 232 233 234
    }
    if (wrt_idx == 2) {
        return IndexingOneHot::make(og, index, opr.param()).node();
    }
    return InvalidGrad::make(opr, wrt_idx);
}
235
#endif
236 237

size_t IndexingSetOneHot::get_workspace_size_bytes(
M
Megvii Engine Team 已提交
238 239
        const TensorShapeArray& input_shapes,
        const TensorShapeArray& output_shapes) const {
240
    return megdnn_opr()->get_workspace_in_bytes(
M
Megvii Engine Team 已提交
241 242
            {input_shapes[0], input(0)->dtype()}, {input_shapes[1], input(1)->dtype()},
            {input_shapes[2], input(2)->dtype()});
243 244 245 246 247 248 249
}

/* ==================== IndexingRemap ==================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(IndexingRemap);
MEGDNN_OPR_INIT2(IndexingRemap, "indexing_remap")

void IndexingRemap::init_output_dtype() {
M
Megvii Engine Team 已提交
250 251
    mgb_throw_if(
            input(1)->dtype() != dtype::Int32(), GraphError,
252 253 254 255
            "IndexingRemap requires map input to be int32");
    output(0)->dtype(input(0)->dtype());
}

256
#if MGB_ENABLE_GRAD
257 258 259 260 261
MGB_IMPL_OPR_GRAD(IndexingRemap) {
    if (wrt_idx == 1)
        return InvalidGrad::make(opr, wrt_idx);
    mgb_assert(wrt_idx == 0 && out_grad[0]);
    return IndexingRemapBackward::make(
M
Megvii Engine Team 已提交
262 263
                   out_grad[0], opr.input(1), opr.input(0), opr.param())
            .node();
264
}
265
#endif
266 267 268 269 270

MGB_DYN_TYPE_OBJ_FINAL_IMPL(IndexingRemapBackward);
MEGDNN_OPR_INIT3(IndexingRemapBackward, "indexing_remap_bwd", 2, false);

/* ================= IndexingMultiAxisVecMegDNNOprHolder ================= */
M
Megvii Engine Team 已提交
271
template <class Opr>
272 273 274
Opr& mixin::IndexingMultiAxisVecMegDNNOprHolder<Opr>::megdnn_opr(
        cg::SingleCNOperatorNodeBase& self) {
    auto comp_node = self.comp_node();
275 276
    if (!m_dnn_opr || m_dnn_opr.comp_node() != comp_node) {
        m_dnn_opr = intl::create_megdnn_opr<Opr>(comp_node);
M
Megvii Engine Team 已提交
277
        m_dnn_opr->set_error_tracker(static_cast<cg::OperatorNodeBase*>(&self));
278
    }
279
    return *m_dnn_opr;
280 281
}

M
Megvii Engine Team 已提交
282
template <class Opr>
283
void mixin::IndexingMultiAxisVecMegDNNOprHolder<Opr>::register_workspace_infer(
M
Megvii Engine Team 已提交
284
        const indexing::IndexDesc& index_desc, cg::SingleCNOperatorNodeBase& opr,
285
        VarNode* data, VarNode* value, VarNodeArray idx_arr) {
286
    using namespace cg::static_infer;
287 288 289 290 291 292 293
    DepVal deps = {{data, DepType::SHAPE}, {value, DepType::SHAPE}};

    for (auto&& idx : idx_arr) {
        deps.push_back({idx, DepType::SHAPE});
    }
    auto infer_shape = [this, &index_desc, &opr, nr_idx = idx_arr.size()](
                               TensorShape& dest, const InpVal& inp) {
294 295
        size_t axes[TensorShape::MAX_NDIM], nr_axes = 0;
        auto ndim = inp.val[0].shape().ndim;
M
Megvii Engine Team 已提交
296
        for (auto&& i : reverse_adaptor(index_desc)) {
297
            if (i.idx.node()) {
M
Megvii Engine Team 已提交
298
                axes[nr_axes++] = i.axis.get(ndim);
299 300
            }
        }
301
        mgb_assert(nr_axes == nr_idx);
302 303 304
        if (!nr_axes) {
            dest = {0};
        } else {
305 306 307 308 309
            size_t idx_ndim = 0;
            for (size_t i = 0; i < nr_idx; ++i) {
                idx_ndim = std::max(idx_ndim, inp.val[2 + i].shape().ndim);
            }
            mgb_assert(idx_ndim > 0);
310
            dest = {megdnn_opr(opr).get_workspace_in_bytes(
311
                    inp.val[1].shape(), axes, nr_axes, idx_ndim)};
312 313 314 315
        }
        return true;
    };
    opr.owner_graph()->static_infer_manager().register_shape_infer(
316
            opr.output(1), {SourceType::DEP, deps, infer_shape});
317 318 319 320 321
}

template <class Opr>
void mixin::IndexingMultiAxisVecMegDNNOprHolder<Opr>::record_megdnn_opr(
        mgb::cg::GraphExecutable::ExecDependencyArray& deps) {
M
Megvii Engine Team 已提交
322
    deps.emplace_back(std::make_unique<intl::MegDNNGraphDep>(std::move(m_dnn_opr)));
323 324 325
}

/* ==================== MultiAxisVecFancyIndexingHelper ==================== */
M
Megvii Engine Team 已提交
326 327 328 329
std::pair<const megdnn::IndexingMultiAxisVec::IndexDesc&, bool> intl::
        MultiAxisVecFancyIndexingHelper::make_megdnn_index_desc(
                size_t inp_ndim, bool warn_all_scalar) {
    auto&& index = m_megdnn_index_cache;
330
    index.clear();
331
    bool is_empty_shape = false;
M
Megvii Engine Team 已提交
332
    for (auto i : reverse_adaptor(m_input2idxonly_axis_indexer)) {
333
        if (i) {
M
Megvii Engine Team 已提交
334 335
            index.push_back(
                    {i->axis.get(inp_ndim), i->idx.node()->dev_tensor().as_megdnn()});
336
            is_empty_shape |= index.back().vec.layout.is_empty();
337 338 339
        }
    }

340 341
    if (!m_scalar_idx_warn_printed && warn_all_scalar &&
        !this->owner_graph()->options().imperative_proxy_graph) {
342
        bool all_scalar = true;
M
Megvii Engine Team 已提交
343
        for (auto&& i : index) {
344 345 346 347 348 349
            if (!i.vec.layout.is_scalar()) {
                all_scalar = false;
                break;
            }
        }
        if (all_scalar) {
350 351 352
#if MGB_ENABLE_GETENV
            mgb_log_warn(
                    "%s{%s}: no vector indexer; consider using Subtensor "
353 354 355 356
                    "family for better performance; you can set "
                    "MGB_THROW_ON_SCALAR_IDX to throw an exception to help "
                    "tracking the related operator",
                    cname(), dyn_typeinfo()->name);
357 358 359 360 361 362 363
#else
            mgb_log_warn(
                    "%s{%s}: no vector indexer; consider using Subtensor "
                    "family for better performance",
                    cname(), dyn_typeinfo()->name);
#endif
#if MGB_ENABLE_GETENV
M
Megvii Engine Team 已提交
364 365 366 367
            mgb_throw_if(
                    MGB_GETENV("MGB_THROW_ON_SCALAR_IDX"), MegBrainError,
                    "vector-indexing operator used with all "
                    "scalar indices");
368
#endif
369 370 371 372 373 374 375
        }

        // always set m_scalar_idx_warn_printed to be true, so we do not print
        // this warning in the future
        m_scalar_idx_warn_printed = true;
    }

376
    return {index, is_empty_shape};
377 378 379
}

/* ==================== IndexingMultiAxisVecBase ==================== */
M
Megvii Engine Team 已提交
380 381 382
template <class Opr>
cg::OperatorNodeBase::NodeProp* IndexingMultiAxisVecBase<Opr>::do_make_node_prop()
        const {
383
    auto prop = Super::do_make_node_prop();
384 385
    using DT = NodeProp::DepType;
    prop->add_dep_type_existing_var(input(0), DT::VALUE_ALLOW_EMPTY);
M
Megvii Engine Team 已提交
386
    for (auto i : m_input2idxonly_axis_indexer) {
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        if (i) {
            prop->add_dep_type_existing_var(
                    i->idx.node(), NodeProp::DepType::VALUE_ALLOW_EMPTY);
        }
    }
    return prop;
}

template <class Opr>
void IndexingMultiAxisVecBase<Opr>::init_output_static_infer_desc() {
    using namespace cg::static_infer;
    DepVal deps;

    // shape inference only needs slices
    deps.push_back({input(0), DepType::SHAPE});
    // loop in reverse order because megdnn opr needs ascending axes
M
Megvii Engine Team 已提交
403
    for (size_t i = m_input2idxonly_axis_indexer.size() - 1; i; --i) {
404 405 406 407 408
        if (m_input2idxonly_axis_indexer[i]) {
            deps.push_back({input(i), DepType::SHAPE});
        }
    }
    size_t inp_interval_start = deps.size();
M
Megvii Engine Team 已提交
409
    for (size_t i = 1; i < m_input2idxonly_axis_indexer.size(); ++i) {
410 411 412 413 414
        if (!m_input2idxonly_axis_indexer[i]) {
            deps.push_back({input(i), DepType::VALUE});
        }
    }
    auto infer_shape = [this, inp_interval_start](
M
Megvii Engine Team 已提交
415 416
                               TensorShape& dest, const InpVal& inp) {
        auto&& ishp = inp.val[0].shape();
417 418 419 420 421
        auto subspec = fancy_indexing_make_sub_spec(
                {ishp, input(0)->dtype()}, inp, inp_interval_start);
        dest = subspec.layout();
        typename Opr::IndexDescLayoutOnly index_layout;
        size_t indexer_pos = 1;
M
Megvii Engine Team 已提交
422
        for (auto i : reverse_adaptor(m_input2idxonly_axis_indexer)) {
423
            if (i) {
M
Megvii Engine Team 已提交
424 425 426
                index_layout.push_back(
                        {i->axis.get(dest.ndim),
                         {inp.val.at(indexer_pos++).shape(), dtype::Int32()}});
427 428 429 430 431 432
            }
        }
        mgb_assert(indexer_pos == inp_interval_start);
        if (!index_layout.empty()) {
            // index_layout is empty if all indices are intervals
            TensorLayout tmp;
M
Megvii Engine Team 已提交
433
            Opr::deduce_layout({dest, input(0)->dtype()}, index_layout, tmp);
434 435 436 437 438 439
            dest = tmp;
        }
        return true;
    };
    owner_graph()->static_infer_manager().register_shape_infer(
            output(0), {SourceType::DEP, deps, infer_shape});
440 441 442 443 444 445 446
    VarNodeArray idx_arr;
    for (size_t i = 1; i < m_input2idxonly_axis_indexer.size(); ++i) {
        if (m_input2idxonly_axis_indexer[i]) {
            idx_arr.push_back(input(i));
        }
    }
    this->register_workspace_infer(index_desc(), *this, input(0), output(0), idx_arr);
447 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
}

template <class Opr>
void IndexingMultiAxisVecBase<Opr>::record_execute_deps(
        mgb::cg::GraphExecutable::ExecDependencyArray& deps) {
    this->record_megdnn_opr(deps);
}

namespace {
template <class Opr>
struct ShouldWarnOnScalarIndexer {
    static constexpr bool val = false;
};

#define WARN(opr)                                   \
    template <>                                     \
    struct ShouldWarnOnScalarIndexer<megdnn::opr> { \
        static constexpr bool val = true;           \
    }
WARN(IndexingMultiAxisVec);
WARN(IndexingSetMultiAxisVec);
WARN(IndexingIncrMultiAxisVec);
#undef WARN
}  // anonymous namespace

template <class Opr>
void IndexingMultiAxisVecBase<Opr>::scn_do_execute() {
474 475 476
    if (output(0)->layout().is_empty()) {
        return;
    }
477 478
    auto inp = input(0)->dev_tensor();
    inp = inp.sub(fancy_indexing_make_sub_spec(inp.layout()));
M
Megvii Engine Team 已提交
479
    auto&& index_desc = make_megdnn_index_desc(
480
            inp.layout().ndim, ShouldWarnOnScalarIndexer<Opr>::val);
M
Megvii Engine Team 已提交
481
    auto&& odev = output(0)->dev_tensor();
482
    if (index_desc.first.empty()) {
483 484
        odev.copy_from_fixlayout(inp);
    } else {
485
        if (!index_desc.second) {
486 487
            // only call megdnn exec if result is not empty
            this->megdnn_opr(*this).exec(
488
                    inp.as_megdnn(), index_desc.first, odev.as_megdnn(),
489 490 491 492 493 494 495 496 497
                    intl::get_megdnn_workspace_from_var(output(1)));
        } else {
            mgb_assert(odev.empty());
        }
    }
}

/* ==================== IndexingModifyMultiAxisVecHelper ==================== */

M
Megvii Engine Team 已提交
498 499
template <class Opr>
void intl::IndexingModifyMultiAxisVecHelper<Opr>::init_output_static_infer_desc() {
500 501 502 503
    using namespace cg::static_infer;
    this->owner_graph()->static_infer_manager().register_shape_infer(
            this->output(0), ShapeInferDesc::make_identity(this->input(0)));

504 505 506 507 508 509 510
    VarNodeArray idx_arr;
    for (size_t i = 1; i < m_input2idxonly_axis_indexer.size(); ++i) {
        if (m_input2idxonly_axis_indexer[i]) {
            idx_arr.push_back(input(i));
        }
    }
    this->register_workspace_infer(index_desc(), *this, input(0), input(1), idx_arr);
511 512
}

M
Megvii Engine Team 已提交
513
template <class Opr>
514 515 516 517
void intl::IndexingModifyMultiAxisVecHelper<Opr>::scn_do_execute() {
    auto inp = this->fancy_indexing_get_tensors_for_modify_in_scn_do_execute();
    auto index_desc = this->make_megdnn_index_desc(
            inp.first.layout().ndim, ShouldWarnOnScalarIndexer<Opr>::val);
M
Megvii Engine Team 已提交
518
    if (inp.first.shape().is_empty() || index_desc.second) {
519 520 521 522
        mgb_assert(inp.second.shape().is_empty());
        return;
    }
    if (index_desc.first.empty()) {
523
        using IMT = IndexingModifyType;
M
Megvii Engine Team 已提交
524
        static constexpr auto modify_type = IndexingModifyTypeGetter<Opr>::value;
525 526 527 528
        switch (modify_type) {
            case IMT::SET: {
                inp.first.copy_from_fixlayout(inp.second);
                break;
M
Megvii Engine Team 已提交
529 530 531 532
            }
            case IMT::INCR: {
                megdnn::AddUpdate* add_update =
                        intl::get_megdnn_global_opr<megdnn::AddUpdate>(comp_node());
533 534
                add_update->exec(inp.first.as_megdnn(), inp.second.as_megdnn());
                break;
M
Megvii Engine Team 已提交
535 536
            }
            default:
537
                mgb_throw(MegBrainError, "bad modify type");
538 539 540
        }
    } else {
        this->megdnn_opr(*this).exec(
M
Megvii Engine Team 已提交
541
                inp.first.as_megdnn(), inp.second.as_megdnn(), index_desc.first,
542 543 544 545
                intl::get_megdnn_workspace_from_var(output(1)));
    }
}

M
Megvii Engine Team 已提交
546 547 548
template <class Opr>
cg::OperatorNodeBase::NodeProp* intl::IndexingModifyMultiAxisVecHelper<
        Opr>::do_make_node_prop() const {
549 550 551 552 553
    auto prop = Super::do_make_node_prop();
    using DT = NodeProp::DepType;
    // TODO: should also allow input shape is empty if any
    // indexer's shape is empty
    prop->add_dep_type_existing_var(input(1), DT::VALUE_ALLOW_EMPTY);
M
Megvii Engine Team 已提交
554
    for (auto i : m_input2idxonly_axis_indexer) {
555
        if (i) {
M
Megvii Engine Team 已提交
556
            prop->add_dep_type_existing_var(i->idx.node(), DT::VALUE_ALLOW_EMPTY);
557 558 559 560 561
        }
    }
    return prop;
}

M
Megvii Engine Team 已提交
562 563 564
template <class Opr>
void intl::IndexingModifyMultiAxisVecHelper<Opr>::add_input_layout_constraint() {
    auto check_cont1 = [](const TensorLayout& ly) {
565 566 567 568 569 570 571
        return ly.collapse_contiguous().ndim == 1;
    };
    this->input(1)->add_layout_constraint(check_cont1);
}

/* ==================== MultiAxisVec misc ==================== */

M
Megvii Engine Team 已提交
572 573
MGB_IMPL_FANCY_INDEXING_OPR_GET(IndexingMultiAxisVec, "indexing_multi_axis_vec", false,
                                output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE););
574
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(
575
        IndexingSetMultiAxisVec, "indexing_set_multi_axis_vec", false,
M
Megvii Engine Team 已提交
576
        output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE););
577 578 579
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(
        IndexingIncrMultiAxisVec, "indexing_incr_multi_axis_vec", false);

580 581
IndexingSetMultiAxisVec::NodeProp* IndexingSetMultiAxisVec::do_make_node_prop() const {
    auto prop = Super::do_make_node_prop();
M
Megvii Engine Team 已提交
582
    prop->add_dep_type_existing_var(input(0), NodeProp::DepType::VALUE_ALLOW_EMPTY);
583 584 585
    return prop;
}

586
#if MGB_ENABLE_GRAD
587 588 589 590 591
MGB_IMPL_OPR_GRAD(IndexingMultiAxisVec) {
    if (wrt_idx)
        return InvalidGrad::make(opr, wrt_idx);

    return IndexingIncrMultiAxisVec::make(
M
Megvii Engine Team 已提交
592 593 594
                   SymbolVar{opr.input(0)}.fill_retain_dtype(0), out_grad.at(0),
                   opr.index_desc())
            .node();
595
}
596
#endif
597

598
#if MGB_ENABLE_GRAD
599 600 601 602
MGB_IMPL_OPR_GRAD(IndexingSetMultiAxisVec) {
    if (wrt_idx >= 2)
        return InvalidGrad::make(opr, wrt_idx);
    if (wrt_idx == 0) {
M
Megvii Engine Team 已提交
603 604 605 606
        return IndexingSetMultiAxisVec::make(
                       out_grad.at(0), SymbolVar{opr.input(1)}.fill_retain_dtype(0),
                       opr.index_desc())
                .node();
607 608 609
    }
    return IndexingMultiAxisVec::make(out_grad.at(0), opr.index_desc()).node();
}
610
#endif
611

612
#if MGB_ENABLE_GRAD
613 614 615 616 617 618 619 620
MGB_IMPL_OPR_GRAD(IndexingIncrMultiAxisVec) {
    if (wrt_idx >= 2)
        return InvalidGrad::make(opr, wrt_idx);
    if (wrt_idx == 0) {
        return out_grad.at(0);
    }
    return IndexingMultiAxisVec::make(out_grad.at(0), opr.index_desc()).node();
}
621
#endif
622 623 624

/* ============================= Mesh Indexing ============================ */

M
Megvii Engine Team 已提交
625 626 627 628
MGB_IMPL_FANCY_INDEXING_OPR_GET(MeshIndexing, "mesh_indexing", false,
                                output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE););
MGB_IMPL_FANCY_INDEXING_OPR_GET(BatchedMeshIndexing, "batched_mesh_indexing", false,
                                output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE););
629

630
#if MGB_ENABLE_GRAD
631 632 633 634 635 636 637 638 639
MGB_IMPL_OPR_GRAD(MeshIndexing) {
    if (wrt_idx != 0) {
        return InvalidGrad::make(opr, wrt_idx);
    }
    return IncrMeshIndexing::make(
                   SymbolVar{opr.input(0)}.fill_retain_dtype(0), out_grad.at(0),
                   opr.index_desc())
            .node();
}
640 641
#endif

642
#if MGB_ENABLE_GRAD
643 644 645 646 647 648 649 650 651
MGB_IMPL_OPR_GRAD(BatchedMeshIndexing) {
    if (wrt_idx != 0) {
        return InvalidGrad::make(opr, wrt_idx);
    }
    return BatchedIncrMeshIndexing::make(
                   SymbolVar{opr.input(0)}.fill_retain_dtype(0), out_grad.at(0),
                   opr.index_desc())
            .node();
}
652
#endif
653 654 655

/* ========================= IncrMeshIndexing ========================= */

M
Megvii Engine Team 已提交
656
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(IncrMeshIndexing, "incr_mesh_indexing", false);
657

658
#if MGB_ENABLE_GRAD
659 660 661 662 663 664 665 666 667
MGB_IMPL_OPR_GRAD(IncrMeshIndexing) {
    if (wrt_idx > 2) {
        return opr::InvalidGrad::make(opr, wrt_idx);
    }
    if (wrt_idx == 0) {
        return out_grad.at(0);
    }
    return MeshIndexing::make(out_grad.at(0), opr.index_desc()).node();
}
668
#endif
669

M
Megvii Engine Team 已提交
670 671
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(
        BatchedIncrMeshIndexing, "batched_incr_mesh_indexing", false);
672
#if MGB_ENABLE_GRAD
673 674 675 676 677 678 679 680 681
MGB_IMPL_OPR_GRAD(BatchedIncrMeshIndexing) {
    if (wrt_idx > 2) {
        return opr::InvalidGrad::make(opr, wrt_idx);
    }
    if (wrt_idx == 0) {
        return out_grad.at(0);
    }
    return BatchedMeshIndexing::make(out_grad.at(0), opr.index_desc()).node();
}
682
#endif
683 684 685 686

/* ======================== SetMeshIndexing =========================== */
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(SetMeshIndexing, "set_mesh_indexing", false);

687
#if MGB_ENABLE_GRAD
688 689 690 691 692 693
MGB_IMPL_OPR_GRAD(SetMeshIndexing) {
    if (wrt_idx >= 2) {
        return opr::InvalidGrad::make(opr, wrt_idx);
    }
    if (wrt_idx == 0) {
        return SetMeshIndexing::make(
M
Megvii Engine Team 已提交
694
                       out_grad.at(0), SymbolVar{opr.input(1)}.fill_retain_dtype(0),
695 696 697 698 699 700
                       opr.index_desc())
                .node();
    } else {
        return MeshIndexing::make(out_grad.at(0), opr.index_desc()).node();
    }
}
701
#endif
702

M
Megvii Engine Team 已提交
703 704
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(
        BatchedSetMeshIndexing, "batched_set_mesh_indexing", false);
705
#if MGB_ENABLE_GRAD
706 707 708 709 710 711
MGB_IMPL_OPR_GRAD(BatchedSetMeshIndexing) {
    if (wrt_idx > 2) {
        return opr::InvalidGrad::make(opr, wrt_idx);
    }
    if (wrt_idx == 0) {
        return BatchedSetMeshIndexing::make(
M
Megvii Engine Team 已提交
712
                       out_grad.at(0), SymbolVar{opr.input(1)}.fill_retain_dtype(0),
713 714 715
                       opr.index_desc())
                .node();
    } else {
M
Megvii Engine Team 已提交
716
        return BatchedMeshIndexing::make(out_grad.at(0), opr.index_desc()).node();
717 718
    }
}
719
#endif
720 721

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