reduce_op.cc 7.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
G
guosheng 已提交
2

L
Luo Tao 已提交
3 4 5
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
G
guosheng 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
G
guosheng 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
G
guosheng 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/reduce_op.h"
G
guosheng 已提交
16

W
whs 已提交
17
#include <algorithm>
Y
Yang Yang 已提交
18 19 20
#include <string>
#include <vector>

G
guosheng 已提交
21 22 23 24 25 26 27 28 29
namespace paddle {
namespace operators {

using framework::Tensor;

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

30
  void InferShape(framework::InferShapeContext *ctx) const override {
31 32 33 34 35
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of ReduceOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of ReduceOp should not be null.");
    auto x_dims = ctx->GetInputDim("X");
G
guosheng 已提交
36
    auto x_rank = x_dims.size();
G
guosheng 已提交
37
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
W
whs 已提交
38 39 40 41 42 43 44 45
    auto dims = ctx->Attrs().Get<std::vector<int>>("dim");
    for (size_t i = 0; i < dims.size(); ++i) {
      if (dims[i] < 0) dims[i] = x_rank + dims[i];
      PADDLE_ENFORCE_LT(
          dims[i], x_rank,
          "The dim should be in the range [-rank(input), rank(input)).");
    }
    sort(dims.begin(), dims.end());
46
    bool reduce_all = ctx->Attrs().Get<bool>("reduce_all");
47
    bool keep_dim = ctx->Attrs().Get<bool>("keep_dim");
48
    if (reduce_all) {
49 50 51 52 53
      if (keep_dim)
        ctx->SetOutputDim(
            "Out", framework::make_ddim(std::vector<int64_t>(x_rank, 1)));
      else
        ctx->SetOutputDim("Out", {1});
G
guosheng 已提交
54
    } else {
55
      auto dims_vector = vectorize(x_dims);
W
whs 已提交
56 57 58 59
      if (keep_dim) {
        for (size_t i = 0; i < dims.size(); ++i) {
          dims_vector[dims[i]] = 1;
        }
60
      } else {
W
whs 已提交
61 62 63 64 65 66 67
        const int kDelFlag = -2;
        for (size_t i = 0; i < dims.size(); ++i) {
          dims_vector[dims[i]] = kDelFlag;
        }
        dims_vector.erase(
            remove(dims_vector.begin(), dims_vector.end(), kDelFlag),
            dims_vector.end());
68 69 70
      }
      auto out_dims = framework::make_ddim(dims_vector);
      ctx->SetOutputDim("Out", out_dims);
W
whs 已提交
71
      if (dims[0] != 0) {
72 73 74
        // Only pass LoD when not reducing on the first dim.
        ctx->ShareLoD("X", /*->*/ "Out");
      }
75
    }
G
guosheng 已提交
76 77 78 79 80 81 82
  }
};

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

83
  void InferShape(framework::InferShapeContext *ctx) const override {
84 85 86 87
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should not be null.");
    auto x_dims = ctx->GetInputDim("X");
G
guosheng 已提交
88
    auto x_rank = x_dims.size();
G
guosheng 已提交
89
    PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
W
whs 已提交
90 91 92 93 94 95 96 97
    auto dims = ctx->Attrs().Get<std::vector<int>>("dim");
    for (size_t i = 0; i < dims.size(); ++i) {
      if (dims[i] < 0) dims[i] = x_rank + dims[i];
      PADDLE_ENFORCE_LT(
          dims[i], x_rank,
          "The dim should be in the range [-rank(input), rank(input)).");
    }
    sort(dims.begin(), dims.end());
98 99 100
    auto x_grad_name = framework::GradVarName("X");
    if (ctx->HasOutput(x_grad_name)) {
      ctx->SetOutputDim(x_grad_name, x_dims);
101
      ctx->ShareLoD("X", /*->*/ x_grad_name);
102
    }
G
guosheng 已提交
103 104 105
  }
};

G
guosheng 已提交
106
class ReduceOpMaker : public framework::OpProtoAndCheckerMaker {
G
guosheng 已提交
107
 public:
Y
Yu Yang 已提交
108
  void Make() final {
K
kexinzhao 已提交
109 110 111
    AddInput("X",
             "(Tensor) The input tensor. Tensors with rank at most 6 are "
             "supported.");
G
guosheng 已提交
112
    AddOutput("Out", "(Tensor) The result tensor.");
W
whs 已提交
113
    AddAttr<std::vector<int>>(
114
        "dim",
W
whs 已提交
115
        "(list<int>, default {0}) The dimensions to reduce. "
116
        "Must be in the range [-rank(input), rank(input)). "
W
whs 已提交
117
        "If `dim[i] < 0`, the dims[i] to reduce is `rank + dims[i]`. "
K
kexinzhao 已提交
118
        "Note that reducing on the first dim will make the LoD info lost.")
W
whs 已提交
119
        .SetDefault({0});
G
guosheng 已提交
120 121 122 123
    AddAttr<bool>("keep_dim",
                  "(bool, default false) "
                  "If true, retain the reduced dimension with length 1.")
        .SetDefault(false);
124 125 126 127
    AddAttr<bool>("reduce_all",
                  "(bool, default false) "
                  "If true, output a scalar reduced along all dimensions.")
        .SetDefault(false);
Y
Yu Yang 已提交
128 129
    AddComment(string::Sprintf(R"DOC(
%s Operator.
K
kexinzhao 已提交
130

Y
Yu Yang 已提交
131
This operator computes the %s of input tensor along the given dimension.
K
kexinzhao 已提交
132
The result tensor has 1 fewer dimension than the input unless keep_dim is true.
133
If reduce_all is true, just reduce along all dimensions and output a scalar.
K
kexinzhao 已提交
134

Y
Yu Yang 已提交
135 136
)DOC",
                               GetOpType(), GetName()));
G
guosheng 已提交
137 138 139
  }

 protected:
Y
Yu Yang 已提交
140 141
  virtual std::string GetName() const = 0;
  virtual std::string GetOpType() const = 0;
142 143
};

G
guosheng 已提交
144 145 146 147 148
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

Y
Yu Yang 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
#define REGISTER_REDUCE_OP(op_name)                                        \
  class __##op_name##Maker__ : public ops::ReduceOpMaker {                 \
   protected:                                                              \
    virtual std::string GetName() const { return #op_name; }               \
    virtual std::string GetOpType() const { return "Reduce " #op_name; }   \
  };                                                                       \
  REGISTER_OPERATOR(reduce_##op_name, ops::ReduceOp, __##op_name##Maker__, \
                    paddle::framework::DefaultGradOpDescMaker<true>);      \
  REGISTER_OPERATOR(reduce_##op_name##_grad, ops::ReduceGradOp)

REGISTER_REDUCE_OP(sum);
REGISTER_REDUCE_OP(mean);
REGISTER_REDUCE_OP(max);
REGISTER_REDUCE_OP(min);
REGISTER_REDUCE_OP(prod);
164

Q
QI JUN 已提交
165 166 167
#define REGISTER_REDUCE_CPU_KERNEL(reduce_type, functor, grad_functor)         \
  REGISTER_OP_CPU_KERNEL(reduce_type,                                          \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
168 169 170 171 172 173 174
                                           float, ops::functor>,               \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
                                           double, ops::functor>,              \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
                                           int, ops::functor>,                 \
                         ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
                                           int64_t, ops::functor>);            \
Q
QI JUN 已提交
175 176 177
  REGISTER_OP_CPU_KERNEL(                                                      \
      reduce_type##_grad,                                                      \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, float,         \
178 179 180 181 182 183
                            ops::grad_functor>,                                \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, double,        \
                            ops::grad_functor>,                                \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, int,           \
                            ops::grad_functor>,                                \
      ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, int64_t,       \
Q
QI JUN 已提交
184
                            ops::grad_functor>);
185 186

FOR_EACH_KERNEL_FUNCTOR(REGISTER_REDUCE_CPU_KERNEL);