grad_override.cpp 28.1 KB
Newer Older
1 2
#include "./grad.h"
#include "megbrain/imperative/ops/autogen.h"
3
#include "megbrain/imperative/transformations/grad.h"
4 5

namespace mgb::imperative::python {
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 50 51 52 53 54 55

class CustomGradMaker {
    bool output_size_set = false, input_has_grad_initialized = false;
    CustomBackward& target;
    size_t nr_inputs;
    void init_input_has_grad() {
        if (!input_has_grad_initialized) {
            input_has_grad_initialized = true;
            target.m_input_has_grad.resize(nr_inputs, true);
        }
    }

public:
    CustomGradMaker(CustomBackward& target, size_t nr_inputs)
            : target(target), nr_inputs(nr_inputs) {}

    CustomGradMaker& backward(CustomBackward::BackwardFn f) {
        mgb_assert(!target.m_backward);
        target.m_backward = f;
        return *this;
    }
    // mandatory
    CustomGradMaker& output_size(size_t sz) {
        mgb_assert(!output_size_set);
        output_size_set = true;
        target.m_output_attrs.resize(sz);
        return *this;
    }
    // optional, defaults to all true
    CustomGradMaker& input_has_grad(size_t i, bool v) {
        init_input_has_grad();
        target.m_input_has_grad.at(i) = v;
        return *this;
    }
    // optional, defaults to all true
    CustomGradMaker& output_requires_grad(size_t i, bool v) {
        target.m_output_attrs.at(i).requires_grad = v;
        return *this;
    }
    // optional, defaults to all true
    CustomGradMaker& output_captured(size_t i, bool v) {
        target.m_output_attrs.at(i).captured = v;
        return *this;
    }
    void finalize() {
        mgb_assert(output_size_set);
        init_input_has_grad();
    }
};

56 57
namespace {

58
ValueRef get_shape(ValueRef x) {
59
    static auto op = GetVarShape::make();
60
    return imperative::apply(*op, x)[0];
61 62
}

63
ValueRef reduce_to(ValueRef x, ValueRef s) {
64
    static auto op = Reduce::make();
65
    return imperative::apply(*op, x, s)[0];
66 67
}

68
ValueRef reshape_to(ValueRef x, ValueRef s) {
69
    static auto op = Reshape::make();
70
    return imperative::apply(*op, x, s)[0];
71 72
}

73
ValueRef broadcast_to(ValueRef x, ValueRef s) {
74
    static auto op = Broadcast::make();
75
    return imperative::apply(*op, x, s)[0];
76 77
}

78 79 80 81 82 83 84 85 86
ValueRef make_empty_tensor(
        CompNodeValue::ref_t device, ValueRef shape, DTypeValue::ref_t dtype) {
    HostTensorStorage storage(*device);
    storage.ensure_size(dtype->size());
    std::memset(storage.ptr(), 0, dtype->size());
    auto t = imperative::apply(
            CreateTensor(CreateTensor::Unique, *device, *dtype, ValueShape()),
            HostStorage::make(storage))[0];
    auto res = broadcast_to(t, shape);
87 88 89
    return res;
}

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 163 164 165 166 167 168 169 170 171 172 173 174 175 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 211 212 213 214 215 216 217 218 219
std::optional<ValueRefList> matrix_mul_grad_rule(
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& matmul = op.cast_final_safe<MatrixMul>();
    size_t dimA = matmul.dimA;
    size_t dimB = matmul.dimB;
    auto&& param = matmul.param();
    auto&& policy = matmul.policy();
    mgb_assert(inputs.size() == 2);
    std::array<ValueRef, 2> inps, input_shapes;
    for (size_t i = 0; i < 2; ++i) {
        if (inputs_require_grad[i ^ 1]) {
            inps[i] = inputs[i];
            input_shapes[i] = get_shape(inputs[i]);
        }
    }
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([inps_ = std::move(inps), input_shapes_ = std::move(input_shapes),
                    param, policy, dimA, dimB](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
        SmallVector<ValueRef> ret(2);
        if (!grad) {
            return ret;
        }
        size_t dimG = std::max(dimA, dimB);
        if (inps_[1]) {
            if (param.transposeA) {
                // A^T(2) @ B(2) = G(2), A'(2) = B'(2) @ G'^T(2) -> MatrixMul
                auto&& grad_op = MatrixMul::make(
                        param.transposeB, true, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimB, dimG);
                ret[0] = imperative::apply(*grad_op, inps_[1], grad)[0];
            } else {
                // A(>=2) @ B(2) = G(>=2), A'(>=2) = G'(>=2) @ B(2) -> MatrixMul
                auto&& grad_op = MatrixMul::make(
                        false, !param.transposeB, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimG, dimB);
                ret[0] = imperative::apply(*grad_op, grad, inps_[1])[0];
            }
        }
        if (inps_[0]) {
            if (param.transposeB) {
                // A(>=2) @ B^T(2) = G(>=2), B'(2) = G'^T(>=2) @ A(>=2) -> MatrixMul
                // (specialized)
                auto&& grad_op = MatrixMul::make(
                        true, param.transposeA, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimG, dimA);
                ret[1] = imperative::apply(*grad_op, grad, inps_[0])[0];
            } else {
                // A(>=2) @ B(2) = G(>=2), B'(2) = G'(>=2) @ A(>=2) -> MatrixMul
                // (specialized)
                auto&& grad_op = MatrixMul::make(
                        !param.transposeA, false, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimA, dimG);
                ret[1] = imperative::apply(*grad_op, inps_[0], grad)[0];
            }
        }
        return ret;
    });
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
}

std::optional<ValueRefList> batched_matrix_mul_grad_rule(
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& bmm = op.cast_final_safe<BatchedMatrixMul>();
    size_t dimA = bmm.dimA;
    size_t dimB = bmm.dimB;
    auto&& param = bmm.param();
    auto&& policy = bmm.policy();
    mgb_assert(inputs.size() == 2);
    std::array<ValueRef, 2> inps, input_shapes;
    for (size_t i = 0; i < 2; ++i) {
        if (inputs_require_grad[i ^ 1]) {
            inps[i] = inputs[i];
            input_shapes[i] = get_shape(inputs[i]);
        }
    }
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([inps_ = std::move(inps), input_shapes_ = std::move(input_shapes),
                    param, policy, dimA, dimB](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
        SmallVector<ValueRef> ret(2);
        if (!grad) {
            return ret;
        }
        size_t dimG = std::max(dimA, dimB);
        if (inps_[1]) {
            if (param.transposeA) {
                auto&& grad_op = BatchedMatrixMul::make(
                        param.transposeB, true, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimB, dimG);
                ret[0] = imperative::apply(*grad_op, inps_[1], grad)[0];
            } else {
                auto&& grad_op = BatchedMatrixMul::make(
                        false, !param.transposeB, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimG, dimB);
                ret[0] = imperative::apply(*grad_op, grad, inps_[1])[0];
            }
            if (dimG != dimA) {
                ret[0] = reduce_to(ret[0], input_shapes_[0]);
            }
        }
        if (inps_[0]) {
            if (param.transposeB) {
                auto&& grad_op = BatchedMatrixMul::make(
                        true, param.transposeA, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimG, dimA);
                ret[1] = imperative::apply(*grad_op, grad, inps_[0])[0];
            } else {
                auto&& grad_op = BatchedMatrixMul::make(
                        !param.transposeA, false, param.compute_mode, param.format,
                        policy.strategy, policy.workspace_limit, dimA, dimG);
                ret[1] = imperative::apply(*grad_op, inps_[0], grad)[0];
            }
            if (dimG != dimB) {
                ret[1] = reduce_to(ret[1], input_shapes_[1]);
            }
        }
        return ret;
    });
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
}

220
std::optional<ValueRefList> elemwise_grad_rule(
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto& elemwise = op.cast_final_safe<Elemwise>();
    if (elemwise.mode != Elemwise::Mode::ADD) {
        return {};
    }
    mgb_assert(inputs.size() == 2);
    std::array<ValueRef, 2> input_shapes;
    for (size_t i = 0; i < 2; ++i) {
        if (inputs_require_grad[i]) {
            input_shapes[i] = get_shape(inputs[i]);
        }
    }
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([shapes = std::move(input_shapes)](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
239
        SmallVector<ValueRef> ret(2);
240 241 242
        if (!grad) {
            return ret;
        }
243
        for (size_t i = 0; i < 2; ++i) {
244 245
            if (shapes[i]) {
                ret[i] = reduce_to(grad, shapes[i]);
246 247
            }
        }
248 249 250 251
        return ret;
    });
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
252 253
}

254
std::optional<ValueRefList> reshape_grad_rule(
255 256
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
257 258
    mgb_assert(inputs.size() == 1 || inputs.size() == 2);
    size_t nr_inp = inputs.size();
259
    std::array<ValueRef, 2> input_shapes;
260
    for (size_t i = 0; i < nr_inp; ++i) {
261 262
        if (inputs_require_grad[i]) {
            input_shapes[i] = get_shape(inputs[i]);
263 264
        }
    }
265
    auto maker = CustomGradMaker(backward, inputs.size());
266
    maker.output_size(1).output_captured(0, false);
267
    maker.backward([shapes = std::move(input_shapes), nr_inp](Span<ValueRef> grads) {
268 269
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
270
        SmallVector<ValueRef> ret(nr_inp);
271 272 273
        if (!grad) {
            return ret;
        }
274
        for (size_t i = 0; i < nr_inp; ++i) {
275
            if (shapes[i]) {
276
                ret[i] = reshape_to(grad, shapes[i]);
277 278 279 280
            }
        }
        return ret;
    });
281 282
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
283 284
}

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
std::optional<ValueRefList> broadcast_grad_rule(
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    mgb_assert(inputs.size() == 1 || inputs.size() == 2);
    size_t nr_inp = inputs.size();
    std::array<ValueRef, 2> input_shapes;
    for (size_t i = 0; i < nr_inp; ++i) {
        if (inputs_require_grad[i]) {
            input_shapes[i] = get_shape(inputs[i]);
        }
    }
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([shapes = std::move(input_shapes), nr_inp](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
        SmallVector<ValueRef> ret(nr_inp);
        if (!grad) {
            return ret;
        }
        for (size_t i = 0; i < nr_inp; ++i) {
            if (shapes[i]) {
                ret[i] = reduce_to(grad, shapes[i]);
            }
        }
        return ret;
    });
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
}

316
std::optional<ValueRefList> subtensor_grad_rule(
317 318 319 320 321 322 323 324 325
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& subtensor = op.cast_final_safe<Subtensor>();
    auto&& grad_op = SetSubtensor::make(subtensor.items);
    SmallVector<ValueRef> inputs2;
    if (inputs_require_grad[0]) {
        inputs2.push_back(get_shape(inputs[0]));
        for (size_t i = 1; i < inputs.size(); ++i) {
            inputs2.push_back(inputs[i]);
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
    CompNodeValue::ref_t device = inputs[0].device();
    auto get_subtensor_index = [&](int idx) {
        HostTensorStorage storage(*device);
        storage.ensure_size(dtype::Int32().size());
        auto* ptr = reinterpret_cast<dt_int32*>(storage.ptr());
        ptr[0] = idx;
        return imperative::apply(
                CreateTensor(
                        CreateTensor::Unique, *device, dtype::Int32(), ValueShape({1})),
                HostStorage::make(storage))[0];
    };
    auto slice_items = subtensor.slice_items;
    auto items = subtensor.items;
    for (int i = 0; i < slice_items.size(); i++) {
        auto&& [axis, b_flag, e_flag, s_flag, idx_flag] = items[i];
        auto&& [b_val, e_val, s_val, ax_val] = slice_items[i];
        if (b_flag) {
            inputs2.push_back(get_subtensor_index(b_val));
        };
        if (e_flag) {
            inputs2.push_back(get_subtensor_index(e_val));
        };
        if (s_flag) {
            inputs2.push_back(get_subtensor_index(s_val));
        };
        if (idx_flag) {
            inputs2.push_back(get_subtensor_index(ax_val));
        };
    };
357
    auto maker = CustomGradMaker(backward, inputs.size());
358
    maker.output_size(1).output_captured(0, false);
359 360 361 362
    maker.backward([inputs = std::move(inputs2),
                    grad_op_ = std::move(grad_op)](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
363
        SmallVector<ValueRef> ret(1);
364
        if (grad && inputs[0]) {
365
            ValueRefList args_(inputs.size() + 1);
366 367
            auto&& zeros = make_empty_tensor(grad.device(), inputs[0], grad.dtype());
            args_[0] = zeros;
368 369
            args_[1] = grad;
            for (size_t i = 1; i < inputs.size(); ++i) {
370
                args_[i + 1] = inputs[i];
371
            }
372
            ret[0] = imperative::apply(ApplyOp(*grad_op_), args_)[0];
373 374 375
        }
        return ret;
    });
376 377
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
378 379
}

380
std::optional<ValueRefList> indexingMultiAxisVec_grad_rule(
381 382 383
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& indexingMultiAxisVec = op.cast_final_safe<IndexingMultiAxisVec>();
384
    auto&& grad_op = IndexingIncrMultiAxisVec::make(indexingMultiAxisVec.items);
385 386 387 388 389
    SmallVector<ValueRef> inputs2;
    if (inputs_require_grad[0]) {
        inputs2.push_back(get_shape(inputs[0]));
        for (size_t i = 1; i < inputs.size(); ++i) {
            inputs2.push_back(inputs[i]);
390 391
        }
    }
392
    auto maker = CustomGradMaker(backward, inputs.size());
393
    maker.output_size(1).output_captured(0, false);
394 395 396 397
    maker.backward([inputs = std::move(inputs2),
                    grad_op_ = std::move(grad_op)](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
398
        SmallVector<ValueRef> ret(1);
399
        if (grad && inputs[0]) {
400
            ValueRefList args_(inputs.size() + 1);
401 402
            auto&& zeros = make_empty_tensor(grad.device(), inputs[0], grad.dtype());
            args_[0] = zeros;
403 404
            args_[1] = grad;
            for (size_t i = 1; i < inputs.size(); ++i) {
405
                args_[i + 1] = inputs[i];
406
            }
407
            ret[0] = imperative::apply(ApplyOp(*grad_op_), args_)[0];
408 409 410
        }
        return ret;
    });
411 412
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
413 414
}

415
std::optional<ValueRefList> reduce_grad_rule(
416 417 418 419 420 421
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto& reduce = op.cast_final_safe<Reduce>();
    if (reduce.mode != Reduce::Mode::SUM) {
        return {};
    }
422 423
    auto axis = reduce.axis;
    if (inputs.size() != 1 || axis == INT_MAX) {
424 425 426 427 428
        return {};
    }
    std::array<ValueRef, 1> input_shapes;
    if (inputs_require_grad[0]) {
        input_shapes[0] = get_shape(inputs[0]);
429
    }
430 431 432
    if (axis < 0) {
        axis = (*inputs[0].shape()).ndim + axis;
    }
433
    auto maker = CustomGradMaker(backward, inputs.size());
434
    auto keepdim = reduce.keepdim || axis == INT_MAX;
435
    maker.output_size(1).output_captured(0, false);
436 437 438 439
    maker.backward(
            [shapes = std::move(input_shapes), axis, keepdim](Span<ValueRef> grads) {
                mgb_assert(grads.size() == 1);
                ValueRef grad = grads[0];
440
                if (!keepdim && grad) {
441 442 443 444 445 446 447 448 449
                    auto&& grad_op = AddAxis::make(std::vector<int32_t>({axis}));
                    grad = imperative::apply(*grad_op, grad)[0];
                }
                SmallVector<ValueRef> ret(1);
                if (grad && shapes[0]) {
                    ret[0] = broadcast_to(grad, shapes[0]);
                }
                return ret;
            });
450 451
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
452 453
}

454
std::optional<ValueRefList> addAxis_grad_rule(
455 456 457 458 459 460
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& addAxis = op.cast_final_safe<AddAxis>();
    mgb_assert(inputs.size() == 1);
    bool flag = inputs_require_grad[0];
    auto&& grad_op = RemoveAxis::make(addAxis.axis);
461
    std::sort(grad_op->axis.begin(), grad_op->axis.end(), std::greater<int32_t>());
462
    auto maker = CustomGradMaker(backward, inputs.size());
463
    maker.output_size(1).output_captured(0, false);
464 465 466
    maker.backward([grad_op_ = std::move(grad_op), flag_ = flag](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
467
        SmallVector<ValueRef> ret(1);
468
        if (grad && flag_) {
469
            ret[0] = imperative::apply(*grad_op_, grad)[0];
470
        }
471 472
        return ret;
    });
473 474
    maker.finalize();
    return imperative::apply(op, inputs);
475 476
}

477
std::optional<ValueRefList> removeAxis_grad_rule(
478 479 480 481 482 483
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& removeAxis = op.cast_final_safe<RemoveAxis>();
    mgb_assert(inputs.size() == 1);
    bool flag = inputs_require_grad[0];
    auto&& grad_op = AddAxis::make(removeAxis.axis);
484
    std::sort(grad_op->axis.begin(), grad_op->axis.end());
485
    auto maker = CustomGradMaker(backward, inputs.size());
486
    maker.output_size(1).output_captured(0, false);
487 488 489
    maker.backward([grad_op_ = std::move(grad_op), flag_ = flag](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
490
        SmallVector<ValueRef> ret(1);
491
        if (grad && flag_) {
492
            ret[0] = imperative::apply(*grad_op_, grad)[0];
493
        }
494 495
        return ret;
    });
496 497
    maker.finalize();
    return imperative::apply(op, inputs);
498 499
}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
std::optional<ValueRefList> pixelShuffle_grad_rule(
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& pixelShuffle = op.cast_final_safe<PixelShuffle>();
    mgb_assert(inputs.size() == 1);
    bool flag = inputs_require_grad[0];
    auto&& grad_op = PixelShuffleBackward::make(pixelShuffle.factor);
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([grad_op_ = std::move(grad_op), flag_ = flag](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
        SmallVector<ValueRef> ret(1);
        if (grad && flag_) {
            ret[0] = imperative::apply(*grad_op_, grad)[0];
        }
        return ret;
    });
    maker.finalize();
    return imperative::apply(op, inputs);
}

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
std::optional<ValueRefList> indexing_grad_rule(
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& indexing = op.cast_final_safe<IndexingOneHot>();
    mgb_assert(inputs.size() == 2);
    bool flag = inputs_require_grad[0];
    auto&& grad_op = IndexingSetOneHot::make(indexing.axis, indexing.ndim);
    SmallVector<ValueRef> inputs2;
    if (flag) {
        inputs2.push_back(get_shape(inputs[0]));
        for (size_t i = 1; i < inputs.size(); ++i) {
            inputs2.push_back(inputs[i]);
        }
    }
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([inputs = std::move(inputs2),
                    grad_op_ = std::move(grad_op)](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
        SmallVector<ValueRef> ret(1);
        if (grad && inputs[0]) {
            ValueRefList args_(inputs.size() + 1);
            auto&& zeros = make_empty_tensor(grad.device(), inputs[0], grad.dtype());
            args_[0] = zeros;
            args_[1] = inputs[1];
            args_[2] = grads[0];
            ret[0] = imperative::apply(*grad_op_, args_)[0];
        }
        return ret;
    });
    maker.finalize();
    return imperative::apply(op, inputs);
}

std::optional<ValueRefList> indexing_set_one_hot_grad_rule(
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& indexingSetOneHot = op.cast_final_safe<IndexingSetOneHot>();
    mgb_assert(inputs.size() == 3);
    SmallVector<ValueRef> inputs2;
    inputs2.push_back(get_shape(inputs[0]));
    inputs2.push_back(inputs[1]);
    inputs2.push_back(get_shape(inputs[2]));
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([inputs = std::move(inputs2),
                    &indexingSetOneHot](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
        SmallVector<ValueRef> ret(3);
        if (!grad) {
            return ret;
        }
        if (inputs[0]) {
            auto&& grad_op = IndexingSetOneHot::make(
                    indexingSetOneHot.axis, indexingSetOneHot.ndim);
            ValueRefList args_(inputs.size());
            auto&& zeros = make_empty_tensor(grad.device(), inputs[2], grad.dtype());
            args_[0] = grads[0];
            args_[1] = inputs[1];
            args_[2] = zeros;
            ret[0] = imperative::apply(*grad_op, args_)[0];
        }
        if (inputs[2]) {
            auto&& grad_op = IndexingOneHot::make(
                    indexingSetOneHot.axis, indexingSetOneHot.ndim);
            ValueRefList args_(inputs.size() - 1);
            args_[0] = grads[0];
            args_[1] = inputs[1];
            ret[2] = imperative::apply(*grad_op, args_)[0];
        }
        return ret;
    });
    maker.finalize();
    return imperative::apply(op, inputs);
}

600
std::optional<ValueRefList> fastpathcopy_grad_rule(
601 602 603 604
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    mgb_assert(inputs.size() == 1);
    auto maker = CustomGradMaker(backward, inputs.size());
605
    maker.output_size(1).output_captured(0, false);
606 607 608
    maker.backward([](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
609
        SmallVector<ValueRef> ret(1);
610
        if (grad) {
611
            ret[0] = grad;
612 613 614
        }
        return ret;
    });
615 616
    maker.finalize();
    return imperative::apply(op, inputs);
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 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
std::optional<ValueRefList> warp_affine_grad_rule(
        const OpDef& op, Span<ValueRef> inputs, Span<bool> inputs_require_grad,
        CustomBackward& backward) {
    auto&& warp_affine = op.cast_final_safe<WarpAffine>();
    auto&& param = warp_affine.param();
    mgb_assert(inputs.size() == 3);
    SmallVector<ValueRef> inps;
    if (inputs_require_grad[0] || inputs_require_grad[1]) {
        for (size_t i = 0; i < inputs.size(); ++i) {
            inps.push_back(inputs[i]);
        }
    }
    auto maker = CustomGradMaker(backward, inputs.size());
    maker.output_size(1).output_captured(0, false);
    maker.backward([inputs = std::move(inps), &warp_affine,
                    param](Span<ValueRef> grads) {
        mgb_assert(grads.size() == 1);
        ValueRef grad = grads[0];
        SmallVector<ValueRef> ret(2);
        if (!grad) {
            return ret;
        }

        CompNodeValue::ref_t device = inputs[0].device();
        DTypeValue::ref_t dtype = inputs[0].dtype();
        HostTensorStorage storage(*device);
        storage.ensure_size(3 * (dtype->size()));

        auto* ptr = reinterpret_cast<dt_float32*>(storage.ptr());
        ptr[0] = 0;
        ptr[1] = 0;
        ptr[2] = 1;
        auto t = imperative::apply(
                CreateTensor(
                        CreateTensor::Unique, *device, dtype::Float32(),
                        ValueShape({1, 1, 3})),
                HostStorage::make(storage))[0];
        auto mat = inputs[1];
        auto&& concat = Concat::make();
        concat->axis = 1;
        mat = imperative::apply(*concat, inputs[1], t)[0];
        if (inputs[0]) {
            auto&& grad_op = WarpPerspectiveBackwardData::make(
                    param.imode, param.border_mode, param.format, param.border_val);
            ValueRefList args_(inputs.size());
            args_[0] = mat;
            args_[1] = grads[0];
            args_[2] = inputs[0];
            ret[0] = imperative::apply(*grad_op, args_)[0];
        }
        if (inputs[1]) {
            auto&& grad_op = WarpPerspectiveBackwardMat::make(
                    param.imode, param.border_mode, param.format, param.border_val);
            ValueRefList args_(inputs.size());
            args_[0] = inputs[0];
            args_[1] = mat;
            args_[2] = grads[0];
            ret[1] = imperative::apply(*grad_op, args_)[0];

            std::vector<std::tuple<int8_t, bool, bool, bool, bool>> items;
679
            std::vector<std::tuple<int32_t, int32_t, int32_t, int32_t>> slice_items;
680
            items.push_back(std::make_tuple(1, true, true, false, false));
681
            auto&& subtensor = Subtensor::make(items, slice_items);
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

            CompNodeValue::ref_t device = inputs[0].device();
            DTypeValue::ref_t dtype = inputs[0].dtype();
            int start_idx = 0;
            int stop_idx = 2;
            auto get_subtensor_index = [&](int idx) {
                HostTensorStorage storage(*device);
                storage.ensure_size(dtype::Int32().size());
                auto* ptr = reinterpret_cast<dt_int32*>(storage.ptr());
                ptr[0] = idx;
                return imperative::apply(
                        CreateTensor(
                                CreateTensor::Unique, *device, dtype::Int32(),
                                ValueShape({1})),
                        HostStorage::make(storage))[0];
            };
            auto start = get_subtensor_index(start_idx);
            auto stop = get_subtensor_index(stop_idx);

            auto data = ret[1];
            mgb_assert(data);
            ret[1] = imperative::apply(*subtensor, data, start, stop)[0];
        }
        return ret;
    });
    maker.finalize();
    return imperative::apply(ApplyOp(op), inputs);
}

711 712
struct Init {
    Init() {
713 714
        CustomBackward::register_grad_rule(Elemwise::typeinfo(), elemwise_grad_rule);
        CustomBackward::register_grad_rule(Reshape::typeinfo(), reshape_grad_rule);
715
        CustomBackward::register_grad_rule(Broadcast::typeinfo(), broadcast_grad_rule);
716 717 718 719 720 721 722
        CustomBackward::register_grad_rule(Subtensor::typeinfo(), subtensor_grad_rule);
        CustomBackward::register_grad_rule(
                IndexingMultiAxisVec::typeinfo(), indexingMultiAxisVec_grad_rule);
        CustomBackward::register_grad_rule(Reduce::typeinfo(), reduce_grad_rule);
        CustomBackward::register_grad_rule(AddAxis::typeinfo(), addAxis_grad_rule);
        CustomBackward::register_grad_rule(
                RemoveAxis::typeinfo(), removeAxis_grad_rule);
723 724 725 726
        CustomBackward::register_grad_rule(
                IndexingOneHot::typeinfo(), indexing_grad_rule);
        CustomBackward::register_grad_rule(
                IndexingSetOneHot::typeinfo(), indexing_set_one_hot_grad_rule);
727 728
        CustomBackward::register_grad_rule(
                FastpathCopy::typeinfo(), fastpathcopy_grad_rule);
729 730
        CustomBackward::register_grad_rule(
                PixelShuffle::typeinfo(), pixelShuffle_grad_rule);
731 732 733
        CustomBackward::register_grad_rule(MatrixMul::typeinfo(), matrix_mul_grad_rule);
        CustomBackward::register_grad_rule(
                BatchedMatrixMul::typeinfo(), batched_matrix_mul_grad_rule);
734 735
        CustomBackward::register_grad_rule(
                WarpAffine::typeinfo(), warp_affine_grad_rule);
736 737 738
    }
} _;

M
Megvii Engine Team 已提交
739 740
}  // namespace
}  // namespace mgb::imperative::python