indexing.cpp 20.8 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 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 *
 * 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"
#include "megbrain/opr/basic_arith.h"
#include "megbrain/opr/utility.h"
#include "megbrain/graph/grad_impl.h"

#include "./internal/megdnn_opr_wrapper.inl"

using namespace mgb;
using namespace opr;

namespace {
    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());
        }
    }
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

    enum IndexingModifyType {
        SET, INCR
    };

    template<typename Opr>
    struct IndexingModifyTypeGetter {};

#define REG(op, type) \
    template<> \
    struct IndexingModifyTypeGetter<megdnn::op> { \
        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

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
}

namespace mgb {
namespace opr {
namespace intl {

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

    template<>
    struct MegDNNOprInitInputsModifier<IndexingSetOneHot>:
    public MegDNNOprInitInputsModifier<IndexingOneHot> {};
}
}
}

/* ==================== 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());
}

86
#if MGB_ENABLE_GRAD
87 88 89 90 91 92 93 94
MGB_IMPL_OPR_GRAD(IndexingOneHot) {
    if (wrt_idx == 0) {
        return IndexingSetOneHot::make(
                SymbolVar{opr.input(0)}.fill_retain_dtype(0),
                opr.input(1), out_grad[0], opr.param()).node();
    }
    return InvalidGrad::make(opr, wrt_idx);
}
95
#endif
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

/* ==================== 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;
    auto &&mgr = owner_graph()->static_infer_manager();
    mgr.register_shape_infer(output(0),
            ShapeInferDesc::make_identity(input(0)));
    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());

    megdnn_opr()->exec(odata.as_megdnn(), index.as_megdnn(),
            input(2)->dev_tensor().as_megdnn(),
            intl::get_megdnn_workspace_from_var(output(1)));
}

138
#if MGB_ENABLE_GRAD
139 140 141 142 143 144 145 146 147 148 149
MGB_IMPL_OPR_GRAD(IndexingSetOneHot) {
    SymbolVar index{opr.input(1)}, sub{opr.input(2)}, og{out_grad.at(0)};
    if (wrt_idx == 0) {
        return IndexingSetOneHot::make(og, index, sub.fill_retain_dtype(0),
                opr.param()).node();
    }
    if (wrt_idx == 2) {
        return IndexingOneHot::make(og, index, opr.param()).node();
    }
    return InvalidGrad::make(opr, wrt_idx);
}
150
#endif
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

size_t IndexingSetOneHot::get_workspace_size_bytes(
        const TensorShapeArray &input_shapes,
        const TensorShapeArray &output_shapes) const {
    return megdnn_opr()->get_workspace_in_bytes(
            {input_shapes[0], input(0)->dtype()},
            {input_shapes[1], input(1)->dtype()},
            {input_shapes[2], input(2)->dtype()}
            );
}

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

void IndexingRemap::init_output_dtype() {
    mgb_throw_if(input(1)->dtype() != dtype::Int32(), GraphError,
            "IndexingRemap requires map input to be int32");
    output(0)->dtype(input(0)->dtype());
}

172
#if MGB_ENABLE_GRAD
173 174 175 176 177 178 179
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(
            out_grad[0], opr.input(1), opr.input(0), opr.param()).node();
}
180
#endif
181 182 183 184 185 186 187 188 189

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

/* ================= IndexingMultiAxisVecMegDNNOprHolder ================= */
template<class Opr>
Opr& mixin::IndexingMultiAxisVecMegDNNOprHolder<Opr>::megdnn_opr(
        cg::SingleCNOperatorNodeBase& self) {
    auto comp_node = self.comp_node();
190 191 192
    if (!m_dnn_opr || m_dnn_opr.comp_node() != comp_node) {
        m_dnn_opr = intl::create_megdnn_opr<Opr>(comp_node);
        m_dnn_opr->set_error_tracker(
193 194
                static_cast<cg::OperatorNodeBase*>(&self));
    }
195
    return *m_dnn_opr;
196 197 198 199 200 201 202 203 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
}

template<class Opr>
void mixin::IndexingMultiAxisVecMegDNNOprHolder<Opr>::register_workspace_infer(
        const indexing::IndexDesc &index_desc,
        cg::SingleCNOperatorNodeBase &opr, VarNode *data, VarNode *value) {
    using namespace cg::static_infer;
    auto infer_shape = [this, &index_desc, &opr](
            TensorShape &dest, const InpVal &inp) {
        size_t axes[TensorShape::MAX_NDIM], nr_axes = 0;
        auto ndim = inp.val[0].shape().ndim;
        for (auto &&i: reverse_adaptor(index_desc)) {
            if (i.idx.node()) {
                axes[nr_axes ++] = i.axis.get(ndim);
            }
        }
        if (!nr_axes) {
            dest = {0};
        } else {
            dest = {megdnn_opr(opr).get_workspace_in_bytes(
                    inp.val[1].shape(), axes, nr_axes)};
        }
        return true;
    };
    opr.owner_graph()->static_infer_manager().register_shape_infer(
            opr.output(1),
            {SourceType::DEP,
            {{data, DepType::SHAPE}, {value, DepType::SHAPE}},
            infer_shape});
}

template <class Opr>
void mixin::IndexingMultiAxisVecMegDNNOprHolder<Opr>::record_megdnn_opr(
        mgb::cg::GraphExecutable::ExecDependencyArray& deps) {
    deps.emplace_back(
231
            std::make_unique<intl::MegDNNGraphDep>(std::move(m_dnn_opr)));
232 233 234
}

/* ==================== MultiAxisVecFancyIndexingHelper ==================== */
235
std::pair<const megdnn::IndexingMultiAxisVec::IndexDesc&, bool>
236 237 238 239 240
intl::MultiAxisVecFancyIndexingHelper::make_megdnn_index_desc(
        size_t inp_ndim, bool warn_all_scalar) {

    auto &&index = m_megdnn_index_cache;
    index.clear();
241
    bool is_empty_shape = false;
242 243 244 245 246
    for (auto i: reverse_adaptor(m_input2idxonly_axis_indexer)) {
        if (i) {
            index.push_back({
                    i->axis.get(inp_ndim),
                    i->idx.node()->dev_tensor().as_megdnn()});
247
            is_empty_shape |= index.back().vec.layout.is_empty();
248 249 250
        }
    }

251 252
    if (!m_scalar_idx_warn_printed && warn_all_scalar &&
        !this->owner_graph()->options().imperative_proxy_graph) {
253 254 255 256 257 258 259 260
        bool all_scalar = true;
        for (auto &&i: index) {
            if (!i.vec.layout.is_scalar()) {
                all_scalar = false;
                break;
            }
        }
        if (all_scalar) {
261 262 263
#if MGB_ENABLE_GETENV
            mgb_log_warn(
                    "%s{%s}: no vector indexer; consider using Subtensor "
264 265 266 267
                    "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);
268 269 270 271 272 273 274 275 276 277 278
#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
            mgb_throw_if(MGB_GETENV("MGB_THROW_ON_SCALAR_IDX"), MegBrainError,
                         "vector-indexing operator used with all "
                         "scalar indices");
#endif
279 280 281 282 283 284 285
        }

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

286
    return {index, is_empty_shape};
287 288 289 290 291 292 293
}

/* ==================== IndexingMultiAxisVecBase ==================== */
template<class Opr>
cg::OperatorNodeBase::NodeProp*
IndexingMultiAxisVecBase<Opr>::do_make_node_prop() const {
    auto prop = Super::do_make_node_prop();
294
    using DT = NodeProp::DepType;
295 296
    // TODO: should also allow input shape is empty if any
    // indexer's shape is empty
297
    prop->add_dep_type_existing_var(input(0), DT::VALUE_ALLOW_EMPTY);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    for (auto i: m_input2idxonly_axis_indexer) {
        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
    for (size_t i = m_input2idxonly_axis_indexer.size() - 1; i; -- i) {
        if (m_input2idxonly_axis_indexer[i]) {
            deps.push_back({input(i), DepType::SHAPE});
        }
    }
    size_t inp_interval_start = deps.size();
    for (size_t i = 1; i < m_input2idxonly_axis_indexer.size(); ++ i) {
        if (!m_input2idxonly_axis_indexer[i]) {
            deps.push_back({input(i), DepType::VALUE});
        }
    }
    auto infer_shape = [this, inp_interval_start](
            TensorShape &dest, const InpVal &inp) {
        auto &&ishp = inp.val[0].shape();
        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;
        for (auto i: reverse_adaptor(m_input2idxonly_axis_indexer)) {
            if (i) {
                index_layout.push_back({i->axis.get(dest.ndim),
                        {inp.val.at(indexer_pos ++).shape(), dtype::Int32()}});
            }
        }
        mgb_assert(indexer_pos == inp_interval_start);
        if (!index_layout.empty()) {
            // index_layout is empty if all indices are intervals
            TensorLayout tmp;
            Opr::deduce_layout(
                    {dest, input(0)->dtype()}, index_layout, tmp);
            dest = tmp;
        }
        return true;
    };
    owner_graph()->static_infer_manager().register_shape_infer(
            output(0), {SourceType::DEP, deps, infer_shape});

    this->register_workspace_infer(index_desc(), *this, input(0), output(0));
}

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() {
381 382 383
    if (output(0)->layout().is_empty()) {
        return;
    }
384 385 386 387 388
    auto inp = input(0)->dev_tensor();
    inp = inp.sub(fancy_indexing_make_sub_spec(inp.layout()));
    auto &&index_desc = make_megdnn_index_desc(
            inp.layout().ndim, ShouldWarnOnScalarIndexer<Opr>::val);
    auto &&odev = output(0)->dev_tensor();
389
    if (index_desc.first.empty()) {
390 391
        odev.copy_from_fixlayout(inp);
    } else {
392
        if (!index_desc.second) {
393 394
            // only call megdnn exec if result is not empty
            this->megdnn_opr(*this).exec(
395
                    inp.as_megdnn(), index_desc.first, odev.as_megdnn(),
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
                    intl::get_megdnn_workspace_from_var(output(1)));
        } else {
            mgb_assert(odev.empty());
        }
    }
}

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

template<class Opr>
void intl::IndexingModifyMultiAxisVecHelper<Opr>::
init_output_static_infer_desc() {
    using namespace cg::static_infer;
    this->owner_graph()->static_infer_manager().register_shape_infer(
            this->output(0), ShapeInferDesc::make_identity(this->input(0)));

    this->register_workspace_infer(index_desc(), *this, input(0), input(1));
}

template<class Opr>
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);
420
    if (inp.first.shape().is_empty() || index_desc.second){
421 422 423 424
        mgb_assert(inp.second.shape().is_empty());
        return;
    }
    if (index_desc.first.empty()) {
425 426 427 428 429 430 431 432 433 434 435 436 437 438
        using IMT = IndexingModifyType;
        static constexpr auto modify_type =
                IndexingModifyTypeGetter<Opr>::value;
        switch (modify_type) {
            case IMT::SET: {
                inp.first.copy_from_fixlayout(inp.second);
                break;
            } case IMT::INCR: {
                megdnn::AddUpdate* add_update = intl::get_megdnn_global_opr<
                    megdnn::AddUpdate>(comp_node());
                add_update->exec(inp.first.as_megdnn(), inp.second.as_megdnn());
                break;
            } default:
                mgb_throw(MegBrainError, "bad modify type");
439 440 441 442
        }
    } else {
        this->megdnn_opr(*this).exec(
                inp.first.as_megdnn(), inp.second.as_megdnn(),
443
                index_desc.first,
444 445 446 447
                intl::get_megdnn_workspace_from_var(output(1)));
    }
}

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
template<class Opr>
cg::OperatorNodeBase::NodeProp*
intl::IndexingModifyMultiAxisVecHelper<Opr>::do_make_node_prop() const {
    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);
    for (auto i: m_input2idxonly_axis_indexer) {
        if (i) {
            prop->add_dep_type_existing_var(
                    i->idx.node(), DT::VALUE_ALLOW_EMPTY);
        }
    }
    return prop;
}

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
template<class Opr>
void intl::IndexingModifyMultiAxisVecHelper<Opr>::
add_input_layout_constraint() {
    auto check_cont1 = [](const TensorLayout &ly) {
        return ly.collapse_contiguous().ndim == 1;
    };
    this->input(1)->add_layout_constraint(check_cont1);
}

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

MGB_IMPL_FANCY_INDEXING_OPR_GET(
        IndexingMultiAxisVec, "indexing_multi_axis_vec", false,
        output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
        );
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(
481 482 483
        IndexingSetMultiAxisVec, "indexing_set_multi_axis_vec", false,
        output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
        );
484 485 486
MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(
        IndexingIncrMultiAxisVec, "indexing_incr_multi_axis_vec", false);

487 488 489 490 491 492 493
IndexingSetMultiAxisVec::NodeProp* IndexingSetMultiAxisVec::do_make_node_prop() const {
    auto prop = Super::do_make_node_prop();
    prop->add_dep_type_existing_var(input(0),
            NodeProp::DepType::VALUE_ALLOW_EMPTY);
    return prop;
}

494
#if MGB_ENABLE_GRAD
495 496 497 498 499 500 501 502
MGB_IMPL_OPR_GRAD(IndexingMultiAxisVec) {
    if (wrt_idx)
        return InvalidGrad::make(opr, wrt_idx);

    return IndexingIncrMultiAxisVec::make(
            SymbolVar{opr.input(0)}.fill_retain_dtype(0),
            out_grad.at(0), opr.index_desc()).node();
}
503
#endif
504

505
#if MGB_ENABLE_GRAD
506 507 508 509 510 511 512 513 514 515
MGB_IMPL_OPR_GRAD(IndexingSetMultiAxisVec) {
    if (wrt_idx >= 2)
        return InvalidGrad::make(opr, wrt_idx);
    if (wrt_idx == 0) {
        return IndexingSetMultiAxisVec::make(out_grad.at(0),
                SymbolVar{opr.input(1)}.fill_retain_dtype(0),
                opr.index_desc()).node();
    }
    return IndexingMultiAxisVec::make(out_grad.at(0), opr.index_desc()).node();
}
516
#endif
517

518
#if MGB_ENABLE_GRAD
519 520 521 522 523 524 525 526
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();
}
527
#endif
528 529 530 531 532

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

MGB_IMPL_FANCY_INDEXING_OPR_GET(
        MeshIndexing, "mesh_indexing", false,
533
        output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE););
534 535
MGB_IMPL_FANCY_INDEXING_OPR_GET(
        BatchedMeshIndexing, "batched_mesh_indexing", false,
536
        output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE););
537

538
#if MGB_ENABLE_GRAD
539 540 541 542 543 544 545 546 547
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();
}
548 549
#endif

550
#if MGB_ENABLE_GRAD
551 552 553 554 555 556 557 558 559
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();
}
560
#endif
561 562 563 564 565

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

MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(IncrMeshIndexing, "incr_mesh_indexing",
                                   false);
566

567
#if MGB_ENABLE_GRAD
568 569 570 571 572 573 574 575 576
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();
}
577
#endif
578 579 580

MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(BatchedIncrMeshIndexing,
                                   "batched_incr_mesh_indexing", false);
581
#if MGB_ENABLE_GRAD
582 583 584 585 586 587 588 589 590
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();
}
591
#endif
592 593 594 595

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

596
#if MGB_ENABLE_GRAD
597 598 599 600 601 602 603 604 605 606 607 608 609 610
MGB_IMPL_OPR_GRAD(SetMeshIndexing) {
    if (wrt_idx >= 2) {
        return opr::InvalidGrad::make(opr, wrt_idx);
    }
    if (wrt_idx == 0) {
        return SetMeshIndexing::make(
                       out_grad.at(0),
                    SymbolVar{opr.input(1)}.fill_retain_dtype(0),
                       opr.index_desc())
                .node();
    } else {
        return MeshIndexing::make(out_grad.at(0), opr.index_desc()).node();
    }
}
611
#endif
612 613 614

MGB_IMPL_FANCY_INDEXING_OPR_MODIFY(BatchedSetMeshIndexing,
                                   "batched_set_mesh_indexing", false);
615
#if MGB_ENABLE_GRAD
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
MGB_IMPL_OPR_GRAD(BatchedSetMeshIndexing) {
    if (wrt_idx > 2) {
        return opr::InvalidGrad::make(opr, wrt_idx);
    }
    if (wrt_idx == 0) {
        return BatchedSetMeshIndexing::make(
                       out_grad.at(0),
                       SymbolVar{opr.input(1)}.fill_retain_dtype(0),
                       opr.index_desc())
                .node();
    } else {
        return BatchedMeshIndexing::make(out_grad.at(0), opr.index_desc())
                .node();
    }
}
631
#endif
632 633

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