MCPcopy Create free account
hub / github.com/alibaba/MNN / onGrad

Method onGrad

tools/train/source/grad/ReduceGrad.cpp:16–86  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14class ReduceGrad : public OpGrad {
15public:
16 virtual std::vector<Express::VARP> onGrad(Express::EXPRP expr,
17 const std::vector<Express::VARP>& backwardOutput) override {
18 std::vector<Express::VARP> result;
19 auto inputs = expr->inputs();
20 result.resize(inputs.size());
21 std::unique_ptr<OpT> forwardOp(expr->get()->UnPack());
22 std::vector<int> reductionDims = forwardOp->main.AsReductionParam()->dim;
23 auto keepDim = forwardOp->main.AsReductionParam()->keepDims;
24 if (inputs.size() > 1) {
25 reductionDims.clear();
26 auto ptr = inputs[1]->readMap<int32_t>();
27 auto shape = inputs[1]->getInfo();
28 for (int i = 0; i < shape->size; ++i) {
29 reductionDims.emplace_back(ptr[i]);
30 }
31 }
32 if (reductionDims.empty()) {
33 auto shape = inputs[0]->getInfo();
34 for (int i = 0; i < shape->dim.size(); ++i) {
35 reductionDims.emplace_back(i);
36 }
37 }
38
39 VARP mask = _ZerosLike(inputs[0]) + _Scalar<float>(1.0f);
40 auto outputDiff = backwardOutput[0];
41
42 // implement other reduction op's grad below
43 if (forwardOp->main.AsReductionParam()->operation == ReductionType_SUM) {
44 // do not need to modify grads, just copy them, so, pass
45 }
46
47 if (forwardOp->main.AsReductionParam()->operation == ReductionType_MEAN) {
48 auto gradCount = _Size(outputDiff);
49 auto inputCount = _Size(inputs[0]);
50 outputDiff = _Multiply(outputDiff, _Cast<float>(gradCount) / _Cast<float>(inputCount));
51 }
52
53 if (forwardOp->main.AsReductionParam()->operation == ReductionType_MAXIMUM) {
54 auto output = Variable::create(expr);
55 if (!keepDim) {
56 output = _Unsqueeze(output, reductionDims);
57 }
58 mask = _Sign(inputs[0] - output) + _Scalar<float>(1.0f);
59 mask = mask / _ReduceSum(mask);
60 }
61
62 if (forwardOp->main.AsReductionParam()->operation == ReductionType_MINIMUM) {
63 auto output = Variable::create(expr);
64 if (!keepDim) {
65 output = _Unsqueeze(output, reductionDims);
66 }
67 mask = _Sign(output - inputs[0]) + _Scalar<float>(1.0f);
68 mask = mask / _ReduceSum(mask);
69 }
70
71 if (forwardOp->main.AsReductionParam()->operation == ReductionType_PROD) {
72 auto output = Variable::create(expr);
73 if (!keepDim) {

Callers

nothing calls this directly

Calls 15

_ZerosLikeFunction · 0.85
_SizeFunction · 0.85
_MultiplyFunction · 0.85
_UnsqueezeFunction · 0.85
_SignFunction · 0.85
_ReduceSumFunction · 0.85
AsReductionParamMethod · 0.80
createFunction · 0.50
resizeMethod · 0.45
sizeMethod · 0.45
UnPackMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected