scatter_nd_add_op.cc 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/operators/scatter_nd_add_op.h"
#include <memory>
#include <vector>
#include "paddle/fluid/framework/ddim.h"

namespace paddle {
namespace operators {

class ScatterNdAddOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
29 30 31 32 33 34 35 36 37 38
                      platform::errors::InvalidArgument(
                          "Input(X) of ScatterNdAddOp should not be null."));
    PADDLE_ENFORCE_EQ(
        ctx->HasInput("Index"), true,
        platform::errors::InvalidArgument(
            "Input(Index) of ScatterNdAddOp should not be null."));
    PADDLE_ENFORCE_EQ(
        ctx->HasInput("Updates"), true,
        platform::errors::InvalidArgument(
            "Input(Updates) of ScatterNdAddOp should not be null."));
39
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
40 41
                      platform::errors::InvalidArgument(
                          "Output(Out) of ScatterNdAddOp should not be null."));
42 43 44 45 46 47 48 49 50 51

    auto ref_dims = ctx->GetInputDim("X");
    auto ref_dims_size = ref_dims.size();
    auto index_dims = ctx->GetInputDim("Index");
    auto index_dims_size = index_dims.size();
    auto updates_dims = ctx->GetInputDim("Updates");
    auto updates_dims_size = updates_dims.size();

    PADDLE_ENFORCE_LE(
        index_dims[index_dims_size - 1], ref_dims_size,
52 53
        platform::errors::InvalidArgument(
            "Input(Index).shape[-1] should be no greater than Input(X).rank"));
54
    PADDLE_ENFORCE_GE(index_dims_size, 2UL,
55 56
                      platform::errors::InvalidArgument(
                          "The rank of Input(Index) should be greater than 1"));
57 58 59 60 61 62 63 64 65 66

    // update.shape = index.shape[:-1] + output.shape[index.shape[-1]:]
    std::vector<int64_t> r_updates_dims;
    for (int64_t i = 0; i < index_dims_size - 1; ++i) {
      r_updates_dims.emplace_back(index_dims[i]);
    }
    for (int64_t i = index_dims[index_dims_size - 1]; i < ref_dims_size; ++i) {
      r_updates_dims.emplace_back(ref_dims[i]);
    }

67 68 69
    PADDLE_ENFORCE_EQ(
        r_updates_dims.size(), updates_dims_size,
        platform::errors::InvalidArgument("Updates has wrong shape"));
70 71

    for (int64_t i = 0; i < updates_dims_size; ++i) {
72 73 74
      PADDLE_ENFORCE_EQ(
          r_updates_dims[i], updates_dims[i],
          platform::errors::InvalidArgument("Updates has wrong shape"));
75 76
    }
    ctx->SetOutputDim("Out", ref_dims);
77
    ctx->ShareLoD("X", /*->*/ "Out");
78 79 80 81 82
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
83 84
    PADDLE_ENFORCE_EQ(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                      OperatorWithKernel::IndicateVarDataType(ctx, "Updates"),
85 86
                      platform::errors::InvalidArgument(
                          "Ref and Updates must have same type"));
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    return framework::OpKernelType(ctx.Input<Tensor>("X")->type(),
                                   ctx.device_context());
  }
};

class ScatterNdAddGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    if (ctx->HasOutput(framework::GradVarName("Updates"))) {
      ctx->SetOutputDim(framework::GradVarName("Updates"),
                        ctx->GetInputDim("Updates"));
    }
    if (ctx->HasOutput(framework::GradVarName("X"))) {
      ctx->SetOutputDim(framework::GradVarName("X"),
                        ctx->GetInputDim(framework::GradVarName("Out")));
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
110 111 112
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
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
  }
};

class ScatterNdAddOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "The source input of scatter_nd_add op");
    AddInput("Index",
             "The index input of scatter_nd_add op where X will be updated");
    AddInput("Updates", "The updated value of scatter_nd_add op");
    AddOutput("Out", "The output of scatter_nd_add op");
    AddComment(R"DOC(
Scatter_nd_add Operator.

Output is obtained by applying sparse addition to a single value or slice in a Variable.

      Given:
        * Case 1:
            ref = [0, 1, 2, 3, 4, 5]
            index = [[1], [2], [3], [1]]
            updates = [9, 10, 11, 12]

          we get:

            output = [0, 22, 12, 14, 4, 5]

        * Case 2:
            ref = [[65, 17], [-14, -25]]
            index = [[], []]
            updates = [[[-1, -2], [1, 2]],
                       [[3, 4], [-3, -4]]]
            ref.shape = (2, 2)
            index.shape = (2, 0)
            updates.shape = (2, 2, 2)

          we get:

            output = [[67, 19], [-16, -27]]
)DOC");
  }
};

H
hong 已提交
155 156
template <typename T>
class ScatterNdAddGradMaker : public framework::SingleGradOpMaker<T> {
157
 public:
H
hong 已提交
158
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
159 160

 protected:
161
  void Apply(GradOpPtr<T> op) const override {
162
    op->SetType("scatter_nd_add_grad");
H
hong 已提交
163 164 165 166 167 168 169
    op->SetInput("Index", this->Input("Index"));
    op->SetInput("Updates", this->Input("Updates"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetOutput(framework::GradVarName("Updates"),
                  this->InputGrad("Updates"));
    op->SetAttrMap(this->Attrs());
170 171 172
  }
};

173
DECLARE_NO_NEED_BUFFER_VARS_INFERER(ScatterNdAddGradNoNeedBufferVarsInferer,
Z
Zeng Jinle 已提交
174
                                    "Updates");
175 176 177 178 179 180 181

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(scatter_nd_add, ops::ScatterNdAddOp, ops::ScatterNdAddOpMaker,
H
hong 已提交
182 183
                  ops::ScatterNdAddGradMaker<paddle::framework::OpDesc>,
                  ops::ScatterNdAddGradMaker<paddle::imperative::OpBase>);
184 185

REGISTER_OPERATOR(scatter_nd_add_grad, ops::ScatterNdAddGradOp,
186
                  ops::ScatterNdAddGradNoNeedBufferVarsInferer);
187 188 189 190 191 192 193 194 195 196 197 198 199

REGISTER_OP_CPU_KERNEL(scatter_nd_add, ops::ScatterNdAddOpKernel<float>,
                       ops::ScatterNdAddOpKernel<double>,
                       ops::ScatterNdAddOpKernel<int64_t>,
                       ops::ScatterNdAddOpKernel<int>,
                       ops::ScatterNdAddOpKernel<uint8_t>);

REGISTER_OP_CPU_KERNEL(scatter_nd_add_grad,
                       ops::ScatterNdAddGradientOpKernel<float>,
                       ops::ScatterNdAddGradientOpKernel<double>,
                       ops::ScatterNdAddGradientOpKernel<int64_t>,
                       ops::ScatterNdAddGradientOpKernel<int>,
                       ops::ScatterNdAddGradientOpKernel<uint8_t>);