gather_op.cc 6.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zchen0211 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

S
sneaxiy 已提交
15 16 17
#include <memory>
#include <string>
#include <vector>
C
Chen Weihang 已提交
18 19

#include "paddle/fluid/framework/infershape_utils.h"
20
#include "paddle/fluid/framework/op_registry.h"
21
#include "paddle/fluid/framework/op_version_registry.h"
J
Jiabin Yang 已提交
22 23
#include "paddle/fluid/prim/api/composite_backward/composite_backward_api.h"
#include "paddle/fluid/prim/utils/static/composite_grad_desc_maker.h"
24
#include "paddle/phi/core/ddim.h"
C
Chen Weihang 已提交
25 26 27
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/backward.h"
#include "paddle/phi/infermeta/binary.h"
28

Z
zchen0211 已提交
29 30 31 32
namespace paddle {
namespace operators {

class GatherOp : public framework::OperatorWithKernel {
Z
zchen0211 已提交
33 34 35
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

36
 protected:
37
  phi::KernelKey GetExpectedKernelType(
Y
Yu Yang 已提交
38
      const framework::ExecutionContext& ctx) const override {
39 40
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                          ctx.device_context().GetPlace());
Y
Yu Yang 已提交
41
  }
42
  phi::KernelKey GetKernelTypeForVar(
43
      const std::string& var_name,
44
      const phi::DenseTensor& tensor,
45
      const phi::KernelKey& expected_kernel_type) const override {
46
    if (var_name == "Axis") {
47 48 49
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
50
    }
51 52
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
53
  }
Z
zchen0211 已提交
54 55 56 57 58 59
};

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

60
 protected:
61
  phi::KernelKey GetExpectedKernelType(
Y
Yu Yang 已提交
62
      const framework::ExecutionContext& ctx) const override {
63 64 65
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(
                              ctx, framework::GradVarName("Out")),
                          ctx.device_context().GetPlace());
Y
Yu Yang 已提交
66
  }
67
  phi::KernelKey GetKernelTypeForVar(
68
      const std::string& var_name,
69
      const phi::DenseTensor& tensor,
70
      const phi::KernelKey& expected_kernel_type) const override {
71
    if (var_name == "Axis") {
72 73 74
      return phi::KernelKey(phi::Backend::ALL_BACKEND,
                            expected_kernel_type.layout(),
                            expected_kernel_type.dtype());
75
    }
76 77
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
78
  }
Z
zchen0211 已提交
79 80 81 82
};

class GatherOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
83
  void Make() override {
Z
zchen0211 已提交
84 85
    AddInput("X", "The source input of gather op");
    AddInput("Index", "The index input of gather op");
86 87 88
    AddInput("Axis",
             "The Tensor which contains the axis that we do gather operation.")
        .AsDispensable();
K
kexinzhao 已提交
89
    AddOutput("Out", "The output of gather op");
90 91 92 93
    AddAttr<int>(
        "axis",
        "The Tensor which contains the axis that we do gather operation.")
        .SetDefault(0);
Z
zchen0211 已提交
94
    AddComment(R"DOC(
K
kexinzhao 已提交
95 96 97 98
Gather Operator.

$Out = X[Index]$

Y
Yibing Liu 已提交
99
Out is obtained by gathering entries of the outer-most dimension
K
kexinzhao 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113
of X indexed by Index and concatenate them together.

Example:

X = [[1, 2],
     [3, 4],
     [5, 6]]

Index = [[1, 2]]

Then:

Out = [[3, 4],
       [5, 6]]
Z
zchen0211 已提交
114 115 116 117

)DOC");
  }
};
S
sneaxiy 已提交
118

H
hong 已提交
119 120
template <typename T>
class GatherGradOpMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
121
 public:
H
hong 已提交
122
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
123 124

 protected:
125
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
126
    op->SetType("gather_grad");
H
hong 已提交
127
    op->SetInput("Index", this->Input("Index"));
128 129
    op->SetInput("Axis", this->Input("Axis"));

H
hong 已提交
130 131 132 133
    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());
S
sneaxiy 已提交
134 135 136
  }
};

J
Jiabin Yang 已提交
137 138 139 140 141 142
class GatherCompositeGradOpMaker : public prim::CompositeGradOpMakerBase {
 public:
  using prim::CompositeGradOpMakerBase::CompositeGradOpMakerBase;

 protected:
  void Apply() override {
143 144
    paddle::Tensor index = this->GetSingleForwardInput("Index");
    paddle::optional<paddle::Tensor> tensor_axis =
J
Jiabin Yang 已提交
145
        this->GetOptionalSingleForwardInput("Axis");
146 147 148
    paddle::Tensor x = this->GetSingleForwardInput("X");
    paddle::Tensor dout = this->GetSingleOutputGrad("Out");
    paddle::Tensor dx = this->GetSingleInputGrad("X");
J
Jiabin Yang 已提交
149 150 151 152 153 154 155 156 157
    auto* dx_ptr = this->GetOutputPtr(&dx);
    std::string dx_name = this->GetOutputName(*dx_ptr);
    int axis = static_cast<int>(this->Attr<int>("axis"));
    VLOG(3) << "Runing gather_grad composite func";
    if (tensor_axis.is_initialized()) {
      PADDLE_THROW(platform::errors::Unimplemented(
          "We don't support dynamic index from tensor for gather composite "
          "grad for now. "));
    } else {
158
      prim::gather_grad<prim::DescTensor>(x, index, dout, axis, dx_ptr);
J
Jiabin Yang 已提交
159 160 161 162 163
    }
    this->RecoverOutputName(dx, dx_name);
  }
};

164
DECLARE_NO_NEED_BUFFER_VARS_INFERER(GatherGradNoNeedBufferVarInferer, "X");
S
sneaxiy 已提交
165

Z
zchen0211 已提交
166 167 168 169
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
170 171
DECLARE_INFER_SHAPE_FUNCTOR(gather,
                            GatherInferShapeFunctor,
C
Chen Weihang 已提交
172
                            PD_INFER_META(phi::GatherInferMeta));
173 174 175
REGISTER_OPERATOR(gather,
                  ops::GatherOp,
                  ops::GatherOpMaker,
H
hong 已提交
176
                  ops::GatherGradOpMaker<paddle::framework::OpDesc>,
C
Chen Weihang 已提交
177
                  ops::GatherGradOpMaker<paddle::imperative::OpBase>,
J
Jiabin Yang 已提交
178
                  ops::GatherCompositeGradOpMaker,
C
Chen Weihang 已提交
179
                  GatherInferShapeFunctor);
180 181
DECLARE_INFER_SHAPE_FUNCTOR(gather_grad,
                            GatherGradInferShapeFunctor,
C
Chen Weihang 已提交
182
                            PD_INFER_META(phi::GeneralUnaryGradInferMeta));
183 184
REGISTER_OPERATOR(gather_grad,
                  ops::GatherGradOp,
C
Chen Weihang 已提交
185 186
                  ops::GatherGradNoNeedBufferVarInferer,
                  GatherGradInferShapeFunctor);
187

188 189 190 191
REGISTER_OP_VERSION(gather).AddCheckpoint(
    R"ROC(upgrad gather, add a new input [Axis])ROC",
    paddle::framework::compatible::OpVersionDesc().NewInput(
        "Axis", "Specify the axis of gather operation."));