sequence_scatter_op.cc 7.7 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
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.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
75 76 77 78 79
    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 已提交
80 81 82 83 84 85

    // 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
86 87 88 89 90 91 92 93
    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 已提交
94 95 96 97

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

      auto& ids_lod = ids_var->Get<LoDTensor>().lod();
      auto& updates_lod = updates_var->Get<LoDTensor>().lod();
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
      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 已提交
119 120 121 122 123 124
    }
  }

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

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"));
138 139
    ctx->SetOutputDim(framework::GradVarName("X"),
                      ctx->GetInputDim(framework::GradVarName("Out")));
Q
Qingsheng Li 已提交
140 141 142 143 144
  }

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

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

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

169 170
DECLARE_NO_NEED_BUFFER_VARS_INFERER(SequenceScatterGradNoNeedBufferVarsInferer,
                                    "Updates");
171

Q
Qingsheng Li 已提交
172 173 174 175 176 177
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(sequence_scatter, ops::SequenceScatterOp,
                  ops::SequenceScatterOpMaker,
H
hong 已提交
178 179
                  ops::SequenceScatterGradMaker<paddle::framework::OpDesc>,
                  ops::SequenceScatterGradMaker<paddle::imperative::OpBase>);
180
REGISTER_OPERATOR(sequence_scatter_grad, ops::SequenceScatterGradOp,
181
                  ops::SequenceScatterGradNoNeedBufferVarsInferer);
Q
Qingsheng Li 已提交
182 183 184 185 186 187 188 189 190
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>);