sequence_scatter_op.cc 7.8 KB
Newer Older
Q
Qingsheng Li 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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. */

W
Wu Yi 已提交
15
#include "paddle/fluid/operators/sequence_ops/sequence_scatter_op.h"
16
#include <memory>
Q
Qingsheng Li 已提交
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/gather.h"
#include "paddle/fluid/operators/scatter.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;

class SequenceScatterOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor) The source input of sequence scatter op");
    AddInput("Ids",
             "(LoDTensor) The index input of sequence scatter op where X"
             " will be  updated, must be a LoDTensor");
    AddInput("Updates",
             "(LoDTensor) The values to scatter to the input tensor "
             "X, must be a LoDTensor with the same LoD information as Ids");
    AddOutput("Out",
              "(Tensor) The output tensor of sequence scatter op, which "
              "has the same dims as X");
    AddComment(R"DOC(
Sequence Scatter Operator.

This operator scatters the Updates tensor to the input X. It uses the LoD
information of Ids to select the rows to update, and use the values in Ids as
the columns to update in each row of X.

Following are cases to better explain how this works:

Example 1:
Given an all-ones Tensor input(X)
    X.data = [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
              [1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
              [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]]
    X.dims = [3, 6]
a LoDTensor input(Ids)
    Ids.data = [[0], [1], [2], [5], [4], [3], [2], [1], [3], [2], [5], [4]]
    Ids.lod =  [[0,        3,                       8,                 12]]
and a Tensor input(Updates)
    Updates.data = [[0.3], [0.3], [0.4], [0.1], [0.2], [0.3], [0.4], [0.0], [0.2], [0.3], [0.1], [0.4]]
    Updates.lod =  [[  0,            3,                                 8,                         12]]
then we get an output Tensor
    Out.data = [[1.3, 1.3, 1.4, 1.0, 1.0, 1.0],
                [1.0, 1.0, 1.4, 1.3, 1.2, 1.1],
                [1.0, 1.0, 1.3, 1.2, 1.4, 1.1]]
    Out.dims = X.dims = [3, 6]
)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    // Enforce has inputs and outputs
77 78 79 80 81
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "SequenceScatter");
    OP_INOUT_CHECK(ctx->HasInput("Ids"), "Input", "Ids", "SequenceScatter");
    OP_INOUT_CHECK(ctx->HasInput("Updates"), "Input", "Updates",
                   "SequenceScatter");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "SequenceScatter");
Q
Qingsheng Li 已提交
82 83 84 85 86 87

    // Set output dim the same as input
    auto ref_dims = ctx->GetInputDim("X");
    ctx->SetOutputDim("Out", ref_dims);

    // Enforce the Updates and Ids are the same shape
88 89 90 91 92 93 94 95
    auto updates_dim = ctx->GetInputDim("Updates");
    auto ids_dim = ctx->GetInputDim("Ids");
    PADDLE_ENFORCE_EQ(
        updates_dim[0], ids_dim[0],
        platform::errors::InvalidArgument(
            "The shape of SequenceScatter operator's input Updates and Ids do "
            "not match, receive Updates's shape is [%s], Ids's shape is [%s].",
            updates_dim, ids_dim));
Q
Qingsheng Li 已提交
96 97 98 99

    // Enforce LoD of ids and updates be the same
    if (ctx->IsRuntime()) {
      framework::Variable* ids_var =
100
          BOOST_GET(framework::Variable*, ctx->GetInputVarPtrs("Ids")[0]);
Q
Qingsheng Li 已提交
101
      framework::Variable* updates_var =
102
          BOOST_GET(framework::Variable*, ctx->GetInputVarPtrs("Updates")[0]);
Q
Qingsheng Li 已提交
103 104 105

      auto& ids_lod = ids_var->Get<LoDTensor>().lod();
      auto& updates_lod = updates_var->Get<LoDTensor>().lod();
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
      PADDLE_ENFORCE_EQ(
          ids_lod.size(), 1,
          platform::errors::InvalidArgument(
              "The SequenceScatter operator’s Input Ids holds wrong LoD "
              "information. Currently SequenceScatter operator can only deal "
              "with one level LoD for input Ids, but received LoD level is %d.",
              ids_lod.size()));
      PADDLE_ENFORCE_EQ(
          updates_lod.size(), 1,
          platform::errors::InvalidArgument(
              "The SequenceScatter operator’s Input Updates holds wrong LoD "
              "information. Currently SequenceScatter operator can only deal "
              "with one level LoD for input Updates, but received LoD level is "
              "%d.",
              ids_lod.size()));
Q
Qingsheng Li 已提交
121 122 123 124 125 126
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
127 128 129
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        platform::CPUPlace());
Q
Qingsheng Li 已提交
130 131 132 133 134 135 136 137 138 139
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    ctx->SetOutputDim(framework::GradVarName("Updates"),
                      ctx->GetInputDim("Updates"));
140 141
    ctx->SetOutputDim(framework::GradVarName("X"),
                      ctx->GetInputDim(framework::GradVarName("Out")));
Q
Qingsheng Li 已提交
142 143 144 145 146
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
147 148 149
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   platform::CPUPlace());
Q
Qingsheng Li 已提交
150 151 152
  }
};

H
hong 已提交
153 154
template <typename T>
class SequenceScatterGradMaker : public framework::SingleGradOpMaker<T> {
155
 public:
H
hong 已提交
156
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
157 158

 protected:
159
  void Apply(GradOpPtr<T> op) const override {
160
    op->SetType("sequence_scatter_grad");
H
hong 已提交
161 162 163 164 165 166 167
    op->SetInput("Ids", this->Input("Ids"));
    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());
168 169 170
  }
};

171 172
DECLARE_NO_NEED_BUFFER_VARS_INFERER(SequenceScatterGradNoNeedBufferVarsInferer,
                                    "Updates");
173

Q
Qingsheng Li 已提交
174 175 176 177 178 179
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(sequence_scatter, ops::SequenceScatterOp,
                  ops::SequenceScatterOpMaker,
H
hong 已提交
180 181
                  ops::SequenceScatterGradMaker<paddle::framework::OpDesc>,
                  ops::SequenceScatterGradMaker<paddle::imperative::OpBase>);
182
REGISTER_OPERATOR(sequence_scatter_grad, ops::SequenceScatterGradOp,
183
                  ops::SequenceScatterGradNoNeedBufferVarsInferer);
Q
Qingsheng Li 已提交
184 185 186 187 188 189 190 191 192
REGISTER_OP_CPU_KERNEL(sequence_scatter, ops::SequenceScatterOpKernel<float>,
                       ops::SequenceScatterOpKernel<double>,
                       ops::SequenceScatterOpKernel<int>,
                       ops::SequenceScatterOpKernel<int64_t>);
REGISTER_OP_CPU_KERNEL(sequence_scatter_grad,
                       ops::SequenceScatterGradientOpKernel<float>,
                       ops::SequenceScatterGradientOpKernel<double>,
                       ops::SequenceScatterGradientOpKernel<int>,
                       ops::SequenceScatterGradientOpKernel<int64_t>);