gather_nd_op.cc 6.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 29
/* 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/gather_nd_op.h"
#include <memory>
#include <string>
#include <vector>
#include "paddle/fluid/framework/ddim.h"

namespace paddle {
namespace operators {

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

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

    auto x_dims = ctx->GetInputDim("X");
    auto x_dims_size = x_dims.size();
    auto index_dims = ctx->GetInputDim("Index");
    auto index_dims_size = index_dims.size();

44 45
    PADDLE_ENFORCE_LE(
        index_dims[index_dims_size - 1], x_dims_size,
46 47
        platform::errors::InvalidArgument(
            "Input(Index).shape[-1] should be no greater than Input(X).rank"));
48
    PADDLE_ENFORCE_GE(index_dims_size, 2UL,
49 50
                      platform::errors::InvalidArgument(
                          "The rank of Input(Index) should be greater than 1"));
51 52 53 54 55 56 57 58 59 60 61 62

    std::vector<int64_t> result_dims;
    // The result dims is
    //   Index.shape[:-1] + X.shape[Index.shape[-1]:]
    for (int i = 0; i < index_dims_size - 1; ++i) {
      result_dims.emplace_back(index_dims[i]);
    }
    for (int i = index_dims[index_dims_size - 1]; i < x_dims_size; ++i) {
      result_dims.emplace_back(x_dims[i]);
    }

    ctx->SetOutputDim("Out", framework::make_ddim(result_dims));
63
    ctx->ShareLoD("X", /*->*/ "Out");
64 65 66 67 68
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
G
Guo Sheng 已提交
69
    auto* x = ctx.Input<Tensor>("X");
70
    const auto& x_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
G
Guo Sheng 已提交
71 72 73 74 75
    return framework::OpKernelType(
        x_type,
        x_type == framework::proto::VarType::BOOL
            ? x->place()  // to be consistent with compare and logical ops
            : ctx.device_context().GetPlace());
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
    ctx->ShareLoD("X", /*-->*/ framework::GradVarName("X"));
  }

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

class GatherNdOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "The source input of gather_nd op");
    AddInput("Index", "The index input of gather_nd op");
    AddOutput("Out", "The output of gather_nd op");
    AddComment(R"DOC(
    Gather_Nd Operator.

    This function is actually a high-dimensional extension of gather 
    and supports for simultaneous indexing by multiple axes. Out is 
    obtained by gathering slices from X into a tensor with shape 
    Index.shape[:-1] + X.shape[Index.shape[-1]:].

    Example:
   
    Given:
         X = [[[ 0,  1,  2,  3],
               [ 4,  5,  6,  7],
               [ 8,  9, 10, 11]],
              [[12, 13, 14, 15],
               [16, 17, 18, 19],
               [20, 21, 22, 23]]]
       
         X.shape = (2, 3, 4)

   *Case 1:

       Index = [[1]]

    we get:
       Out = 
            [[12, 13, 14, 15],
             [16, 17, 18, 19],
             [20, 21, 22, 23]]

   *Case 2:

       Index = [[0,2]]

    we get:
        
       Out =  [8, 9, 10, 11]

   *Case 3:

       Index = [[1, 2, 3]]

    we get:

       Out = [23]

)DOC");
  }
};

H
hong 已提交
153 154
template <typename T>
class GatherNdGradOpMaker : 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("gather_nd_grad");
H
hong 已提交
161 162 163 164 165
    op->SetInput("Index", this->Input("Index"));
    op->SetInput("X", this->Input("X"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
166 167 168
  }
};

169
DECLARE_NO_NEED_BUFFER_VARS_INFERER(GatherNdGradNoNeedBufferVarInference, "X");
170 171 172 173 174 175 176

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(gather_nd, ops::GatherNdOp, ops::GatherNdOpMaker,
H
hong 已提交
177 178
                  ops::GatherNdGradOpMaker<paddle::framework::OpDesc>,
                  ops::GatherNdGradOpMaker<paddle::imperative::OpBase>);
179 180 181 182 183 184 185

REGISTER_OPERATOR(gather_nd_grad, ops::GatherNdGradOp,
                  ops::GatherNdGradNoNeedBufferVarInference);

REGISTER_OP_CPU_KERNEL(gather_nd, ops::GatherNdOpKernel<float>,
                       ops::GatherNdOpKernel<double>,
                       ops::GatherNdOpKernel<int64_t>,
G
Guo Sheng 已提交
186
                       ops::GatherNdOpKernel<int>, ops::GatherNdOpKernel<bool>,
187 188 189 190 191 192 193
                       ops::GatherNdOpKernel<uint8_t>);

REGISTER_OP_CPU_KERNEL(gather_nd_grad, ops::GatherNdGradOpKernel<float>,
                       ops::GatherNdGradOpKernel<double>,
                       ops::GatherNdGradOpKernel<int64_t>,
                       ops::GatherNdGradOpKernel<int>,
                       ops::GatherNdGradOpKernel<uint8_t>);