reduce_op.h 10.3 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 15 16

#pragma once

W
whs 已提交
17
#include <vector>
D
Dong Zhihong 已提交
18
#include "glog/logging.h"
Y
Yi Wang 已提交
19 20
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
G
guosheng 已提交
21 22 23 24 25 26 27 28 29

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using DDim = framework::DDim;
template <typename T, size_t D, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>;
D
Dong Zhihong 已提交
30 31 32
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenScalar = framework::EigenScalar<T, MajorType, IndexType>;
33 34 35
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;
D
Dong Zhihong 已提交
36

G
guosheng 已提交
37
struct SumFunctor {
Q
QI JUN 已提交
38
  template <typename DeviceContext, typename X, typename Y, typename Dim>
39 40
  void operator()(const DeviceContext& place, X* x, Y* y, const Dim& dim) {
    y->device(place) = x->sum(dim);
G
guosheng 已提交
41 42 43 44
  }
};

struct SumGradFunctor {
Q
QI JUN 已提交
45 46
  template <typename DeviceContext, typename X, typename Y, typename DX,
            typename DY, typename Dim>
47
  void operator()(const DeviceContext& place, X* x, Y* y, DX* dx, DY* dy,
G
guosheng 已提交
48
                  const Dim& dim, int size) {
49
    dx->device(place) = dy->broadcast(dim);
G
guosheng 已提交
50 51 52 53
  }
};

struct MeanFunctor {
Q
QI JUN 已提交
54
  template <typename DeviceContext, typename X, typename Y, typename Dim>
55 56
  void operator()(const DeviceContext& place, X* x, Y* y, const Dim& dim) {
    y->device(place) = x->mean(dim);
G
guosheng 已提交
57 58 59 60
  }
};

struct MeanGradFunctor {
Q
QI JUN 已提交
61 62
  template <typename DeviceContext, typename X, typename Y, typename DX,
            typename DY, typename Dim>
63
  void operator()(const DeviceContext& place, X* x, Y* y, DX* dx, DY* dy,
G
guosheng 已提交
64
                  const Dim& dim, int size) {
65
    dx->device(place) = dy->broadcast(dim) / dx->constant(size);
G
guosheng 已提交
66 67 68 69
  }
};

struct MaxFunctor {
Q
QI JUN 已提交
70
  template <typename DeviceContext, typename X, typename Y, typename Dim>
71 72
  void operator()(const DeviceContext& place, X* x, Y* y, const Dim& dim) {
    y->device(place) = x->maximum(dim);
G
guosheng 已提交
73 74 75 76
  }
};

struct MinFunctor {
Q
QI JUN 已提交
77
  template <typename DeviceContext, typename X, typename Y, typename Dim>
78 79
  void operator()(const DeviceContext& place, X* x, Y* y, const Dim& dim) {
    y->device(place) = x->minimum(dim);
G
guosheng 已提交
80 81 82 83
  }
};

struct MaxOrMinGradFunctor {
Q
QI JUN 已提交
84 85
  template <typename DeviceContext, typename X, typename Y, typename DX,
            typename DY, typename Dim>
86
  void operator()(const DeviceContext& place, X* x, Y* y, DX* dx, DY* dy,
G
guosheng 已提交
87
                  const Dim& dim, int size) {
88 89 90
    auto equals = (*x) == y->broadcast(dim);
    auto ones = dx->constant(1);
    auto zeros = dx->constant(0);
91 92
    // If there are multiple minimum or maximum elements, the subgradient of
    // each is the set [0, 1], and we pass gradient to all of them here.
93
    dx->device(place) = dy->broadcast(dim) * equals.select(ones, zeros);
G
guosheng 已提交
94 95 96
  }
};

97 98
struct ProdFunctor {
  template <typename DeviceContext, typename X, typename Y, typename Dim>
99 100
  void operator()(const DeviceContext& place, X* x, Y* y, const Dim& dim) {
    y->device(place) = x->prod(dim);
101 102 103 104 105 106
  }
};

struct ProdGradFunctor {
  template <typename DeviceContext, typename X, typename Y, typename DX,
            typename DY, typename Dim>
107
  void operator()(const DeviceContext& place, X* x, Y* y, DX* dx, DY* dy,
108
                  const Dim& dim, int size) {
109
    dx->device(place) = dy->broadcast(dim) * y->broadcast(dim) * x->inverse();
110 111 112
  }
};

W
whs 已提交
113 114 115 116 117
#define HANDLE_DIM(NDIM, RDIM)          \
  if (ndim == NDIM && rdim == RDIM) {   \
    ReduceCompute<NDIM, RDIM>(context); \
  }

Q
QI JUN 已提交
118
template <typename DeviceContext, typename T, typename Functor>
Y
Yu Yang 已提交
119
class ReduceKernel : public framework::OpKernel<T> {
G
guosheng 已提交
120 121
 public:
  void Compute(const framework::ExecutionContext& context) const override {
122 123 124 125 126 127 128 129 130 131 132 133
    bool reduce_all = context.Attr<bool>("reduce_all");
    if (reduce_all) {
      // Flatten and reduce 1-D tensor
      auto* input = context.Input<Tensor>("X");
      auto* output = context.Output<Tensor>("Out");
      output->mutable_data<T>(context.GetPlace());
      auto x = EigenVector<T>::Flatten(*input);
      auto out = EigenScalar<T>::From(*output);
      auto& place =
          *context.template device_context<DeviceContext>().eigen_device();
      auto reduce_dim = Eigen::array<int, 1>({{0}});
      Functor functor;
134
      functor(place, &x, &out, reduce_dim);
135
    } else {
W
whs 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
      int ndim = context.Input<Tensor>("X")->dims().size();
      int rdim = context.Attr<std::vector<int>>("dim").size();
      HANDLE_DIM(6, 5);
      HANDLE_DIM(6, 4);
      HANDLE_DIM(6, 3);
      HANDLE_DIM(6, 2);
      HANDLE_DIM(6, 1);
      HANDLE_DIM(5, 4);
      HANDLE_DIM(5, 3);
      HANDLE_DIM(5, 2);
      HANDLE_DIM(5, 1);
      HANDLE_DIM(4, 3);
      HANDLE_DIM(4, 2);
      HANDLE_DIM(4, 1);
      HANDLE_DIM(3, 2);
      HANDLE_DIM(3, 1);
      HANDLE_DIM(2, 1);
      HANDLE_DIM(1, 1);
G
guosheng 已提交
154 155 156 157
    }
  }

 private:
W
whs 已提交
158
  template <size_t D, size_t R_D>
G
guosheng 已提交
159 160 161 162 163 164 165
  void ReduceCompute(const framework::ExecutionContext& context) const {
    auto* input = context.Input<Tensor>("X");
    auto* output = context.Output<Tensor>("Out");
    output->mutable_data<T>(context.GetPlace());

    auto x = EigenTensor<T, D>::From(*input);
    auto x_rank = static_cast<int>(x.dimensions().size());
W
whs 已提交
166 167 168 169 170 171
    auto dims = context.Attr<std::vector<int>>("dim");
    auto reduce_dim = Eigen::array<int, R_D>();
    for (size_t i = 0; i < dims.size(); ++i) {
      if (dims[i] < 0) dims[i] = x_rank + dims[i];
      reduce_dim[i] = dims[i];
    }
G
guosheng 已提交
172
    // construct the squeezed output tensor
G
guosheng 已提交
173
    bool keep_dim = context.Attr<bool>("keep_dim");
W
whs 已提交
174
    DDim out_dims = output->dims();
G
guosheng 已提交
175
    if (keep_dim && x_rank > 1) {
W
whs 已提交
176 177 178 179 180 181 182 183 184
      const int kDelFlag = -2;
      auto dims_vector = vectorize(out_dims);
      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());
      out_dims = framework::make_ddim(dims_vector);
G
guosheng 已提交
185
    }
Q
QI JUN 已提交
186 187
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
G
guosheng 已提交
188
    Functor functor;
D
Dong Zhihong 已提交
189 190 191

    if (D == 1) {
      auto out = EigenScalar<T>::From(*output);
192
      functor(place, &x, &out, reduce_dim);
D
Dong Zhihong 已提交
193
    } else {
W
whs 已提交
194
      auto out = EigenTensor<T, (D - R_D)>::From(*output, out_dims);
195
      functor(place, &x, &out, reduce_dim);
D
Dong Zhihong 已提交
196
    }
G
guosheng 已提交
197 198 199
  }
};

Q
QI JUN 已提交
200
template <typename DeviceContext, typename T, typename Functor>
Y
Yu Yang 已提交
201
class ReduceGradKernel : public framework::OpKernel<T> {
G
guosheng 已提交
202 203
 public:
  void Compute(const framework::ExecutionContext& context) const override {
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    bool reduce_all = context.Attr<bool>("reduce_all");
    if (reduce_all) {
      auto* input0 = context.Input<Tensor>("X");
      auto* input1 = context.Input<Tensor>("Out");
      auto* input2 = context.Input<Tensor>(framework::GradVarName("Out"));
      auto* output = context.Output<Tensor>(framework::GradVarName("X"));
      output->mutable_data<T>(context.GetPlace());
      auto x = EigenVector<T>::Flatten(*input0);
      auto x_reduce = EigenVector<T>::From(*input1);
      auto x_reduce_grad = EigenVector<T>::From(*input2);
      auto x_grad = EigenVector<T>::Flatten(*output);
      auto& place =
          *context.template device_context<DeviceContext>().eigen_device();
      auto broadcast_dim =
          Eigen::array<int, 1>({{static_cast<int>(input0->numel())}});
      Functor functor;
220
      functor(place, &x, &x_reduce, &x_grad, &x_reduce_grad, broadcast_dim,
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
              broadcast_dim[0]);
    } else {
      int rank = context.Input<Tensor>("X")->dims().size();
      switch (rank) {
        case 1:
          ReduceGradCompute<1>(context);
          break;
        case 2:
          ReduceGradCompute<2>(context);
          break;
        case 3:
          ReduceGradCompute<3>(context);
          break;
        case 4:
          ReduceGradCompute<4>(context);
          break;
        case 5:
          ReduceGradCompute<5>(context);
          break;
        case 6:
          ReduceGradCompute<6>(context);
          break;
      }
G
guosheng 已提交
244 245 246 247 248
    }
  }

 private:
  template <size_t D>
249
  void ReduceGradCompute(const framework::ExecutionContext& context) const {
G
guosheng 已提交
250 251 252 253 254
    auto* input0 = context.Input<Tensor>("X");
    auto* input1 = context.Input<Tensor>("Out");
    auto* input2 = context.Input<Tensor>(framework::GradVarName("Out"));
    auto* output = context.Output<Tensor>(framework::GradVarName("X"));

255 256 257 258
    output->mutable_data<T>(context.GetPlace());
    auto x = EigenTensor<T, D>::From(*input0);
    auto x_grad = EigenTensor<T, D>::From(*output);
    auto x_rank = static_cast<int>(x.dimensions().size());
W
whs 已提交
259 260 261
    auto dims = context.Attr<std::vector<int>>("dim");
    auto x_dims = input0->dims();
    auto reduced_dims_v = vectorize(x_dims);
D
Dong Zhihong 已提交
262 263
    Eigen::array<int, D> broadcast_dim;
    for (size_t i = 0; i < D; ++i) broadcast_dim[i] = 1;
W
whs 已提交
264 265 266 267 268 269 270 271 272 273 274 275

    int broad_cats_times = 1;
    for (size_t i = 0; i < dims.size(); ++i) {
      if (dims[i] < 0) dims[i] = x_rank + dims[i];
      reduced_dims_v[dims[i]] = 1;
      broadcast_dim[dims[i]] = x_dims[dims[i]];
      broad_cats_times *= x_dims[dims[i]];
    }
    auto reduced_dims = framework::make_ddim(reduced_dims_v);
    auto x_reduce = EigenTensor<T, D>::From(*input1, reduced_dims);
    auto x_reduce_grad = EigenTensor<T, D>::From(*input2, reduced_dims);

Q
QI JUN 已提交
276 277
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
W
whs 已提交
278

279
    Functor functor;
280
    functor(place, &x, &x_reduce, &x_grad, &x_reduce_grad, broadcast_dim,
W
whs 已提交
281
            broad_cats_times);
G
guosheng 已提交
282 283 284 285 286
  }
};

}  // namespace operators
}  // namespace paddle
287 288 289 290 291

#define FOR_EACH_KERNEL_FUNCTOR(__macro)                \
  __macro(reduce_sum, SumFunctor, SumGradFunctor);      \
  __macro(reduce_mean, MeanFunctor, MeanGradFunctor);   \
  __macro(reduce_max, MaxFunctor, MaxOrMinGradFunctor); \
292 293
  __macro(reduce_min, MinFunctor, MaxOrMinGradFunctor); \
  __macro(reduce_prod, ProdFunctor, ProdGradFunctor);