elementwise_div_op.h 11.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
G
gongweibao 已提交
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
gongweibao 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
G
gongweibao 已提交
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
gongweibao 已提交
14

F
fengjiayi 已提交
15 16
#pragma once

C
chentianyu03 已提交
17
#include <string>
18 19
#include <vector>
#include "paddle/fluid/operators/elementwise/elementwise_mul_op.h"
W
Wu Yi 已提交
20
#include "paddle/fluid/operators/elementwise/elementwise_op.h"
21
#include "paddle/fluid/operators/elementwise/elementwise_op_function.cu.h"
W
Wu Yi 已提交
22
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
23
#include "paddle/fluid/operators/elementwise/elementwise_sub_op.h"
24
#include "paddle/fluid/operators/math/blas.h"
25 26
#include "paddle/fluid/operators/reduce_ops/reduce_op.h"

G
gongweibao 已提交
27 28 29
namespace paddle {
namespace operators {

30 31 32 33 34
template <typename DeviceContext, typename T>
void default_elementwise_div(const framework::ExecutionContext& ctx,
                             const framework::Tensor* x,
                             const framework::Tensor* y, framework::Tensor* z) {
  int axis = ctx.Attr<int>("axis");
35 36 37
  auto x_dims = x->dims();
  auto y_dims = y->dims();
  if (x_dims.size() >= y_dims.size()) {
38 39 40 41 42 43
    ElementwiseComputeEx<DivFunctor<T>, DeviceContext, T>(ctx, x, y, axis,
                                                          DivFunctor<T>(), z);
  } else {
    ElementwiseComputeEx<InverseDivFunctor<T>, DeviceContext, T>(
        ctx, x, y, axis, InverseDivFunctor<T>(), z);
  }
44 45 46 47 48 49 50
}

template <typename DeviceContext, typename T, class Enable = void>
struct SameDimsElemwiseDiv {
  void operator()(const framework::ExecutionContext& ctx,
                  const framework::Tensor* x, const framework::Tensor* y,
                  framework::Tensor* z);
51 52
};

Q
QI JUN 已提交
53
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
54
class ElementwiseDivKernel : public framework::OpKernel<T> {
G
gongweibao 已提交
55 56
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
C
chengduo 已提交
57 58 59
    auto* x = ctx.Input<framework::LoDTensor>("X");
    auto* y = ctx.Input<framework::LoDTensor>("Y");
    auto* z = ctx.Output<framework::LoDTensor>("Out");
C
chengduoZH 已提交
60
    z->mutable_data<T>(ctx.GetPlace());
61 62 63 64 65 66 67 68

    auto dims_equal = x->dims() == y->dims();
    if (dims_equal) {
      SameDimsElemwiseDiv<DeviceContext, T> same_dims_div;
      same_dims_div(ctx, x, y, z);
    } else {
      default_elementwise_div<DeviceContext, T>(ctx, x, y, z);
    }
G
gongweibao 已提交
69 70 71 72
  }
};

template <typename T>
C
chengduoZH 已提交
73 74
struct DivGradDX {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const { return dout / y; }
G
gongweibao 已提交
75 76
};

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
template <>
struct DivGradDX<paddle::platform::complex64> {
  HOSTDEVICE paddle::platform::complex64 operator()(
      paddle::platform::complex64 x, paddle::platform::complex64 y,
      paddle::platform::complex64 out, paddle::platform::complex64 dout) const {
    paddle::platform::complex64 y_conj(y.real, -y.imag);
    return dout / y_conj;
  }
};

template <>
struct DivGradDX<paddle::platform::complex128> {
  HOSTDEVICE paddle::platform::complex128 operator()(
      paddle::platform::complex128 x, paddle::platform::complex128 y,
      paddle::platform::complex128 out,
      paddle::platform::complex128 dout) const {
    paddle::platform::complex128 y_conj(y.real, -y.imag);
    return dout / y_conj;
  }
};

G
gongweibao 已提交
98
template <typename T>
C
chengduoZH 已提交
99 100
struct DivGradDY {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
101
    return -dout * out / y;
G
gongweibao 已提交
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
template <>
struct DivGradDY<paddle::platform::complex64> {
  HOSTDEVICE paddle::platform::complex64 operator()(
      paddle::platform::complex64 x, paddle::platform::complex64 y,
      paddle::platform::complex64 out, paddle::platform::complex64 dout) const {
    paddle::platform::complex64 out_div_y_conj((out / y).real, -(out / y).imag);
    return -dout * out_div_y_conj;
  }
};

template <>
struct DivGradDY<paddle::platform::complex128> {
  HOSTDEVICE paddle::platform::complex128 operator()(
      paddle::platform::complex128 x, paddle::platform::complex128 y,
      paddle::platform::complex128 out,
      paddle::platform::complex128 dout) const {
    paddle::platform::complex128 out_div_y_conj((out / y).real,
                                                -(out / y).imag);
    return -dout * out_div_y_conj;
  }
};

127 128 129 130 131 132 133
template <typename T>
struct DivDoubleDY {
  HOSTDEVICE T operator()(T x, T y, T out, T dout) const {
    return y * out * dout - x * dout;
  }
};

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
template <typename DeviceContext, typename T>
typename std::enable_if<
    std::is_same<DeviceContext, platform::CPUDeviceContext>::value>::type
elementwise_div_grad(const framework::ExecutionContext& ctx,
                     const framework::Tensor* x, const framework::Tensor* y,
                     const framework::Tensor* out,
                     const framework::Tensor* dout, framework::Tensor* dx,
                     framework::Tensor* dy) {
  int axis = ctx.Attr<int>("axis");
  ElemwiseGradCompute<DeviceContext, T, DivGradDX<T>, DivGradDY<T>>(
      ctx, *x, *y, *out, *dout, axis, dx, dy, DivGradDX<T>(), DivGradDY<T>());
}

#ifdef PADDLE_WITH_CUDA
// cuda definition
template <typename DeviceContext, typename T>
typename std::enable_if<
    std::is_same<DeviceContext, platform::CUDADeviceContext>::value>::type
elementwise_div_grad(const framework::ExecutionContext& ctx,
                     const framework::Tensor* x, const framework::Tensor* y,
                     const framework::Tensor* out,
                     const framework::Tensor* dout, framework::Tensor* dx,
                     framework::Tensor* dy);
#endif

Q
QI JUN 已提交
159
template <typename DeviceContext, typename T>
160
class ElementwiseDivGradKernel : public ElemwiseGradKernel<T> {
G
gongweibao 已提交
161 162
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
163
    ElemwiseGradKernel<T>::Compute(ctx);
C
chengduoZH 已提交
164 165
    using Tensor = framework::Tensor;

166
    auto* x = ctx.Input<Tensor>("X");
C
chengduoZH 已提交
167 168 169 170 171 172
    auto* y = ctx.Input<Tensor>("Y");
    auto* out = ctx.Input<Tensor>("Out");
    auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* dy = ctx.Output<Tensor>(framework::GradVarName("Y"));
    int axis = ctx.Attr<int>("axis");
173

174 175 176 177 178 179 180
    if (dx != nullptr && dy != nullptr && (dx->dims() == dy->dims())) {
      elementwise_div_grad<DeviceContext, T>(ctx, x, y, out, dout, dx, dy);
    } else {
      ElemwiseGradCompute<DeviceContext, T, DivGradDX<T>, DivGradDY<T>>(
          ctx, *x, *y, *out, *dout, axis, dx, dy, DivGradDX<T>(),
          DivGradDY<T>());
    }
G
gongweibao 已提交
181 182 183
  }
};

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
class ElementwiseDivOpDoubleGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  using Tensor = framework::Tensor;

  void InferShape(framework::InferShapeContext* ctx) const override {
    auto y_grad_name = framework::GradVarName("Y");
    if (ctx->HasOutput("DOut")) {
      ctx->ShareDim("DX", "DOut");
      ctx->ShareLoD("DX", "DOut");
    }
    if (ctx->HasOutput(y_grad_name)) {
      ctx->ShareDim("Y", y_grad_name);
      ctx->ShareLoD("Y", y_grad_name);
    }
    if (ctx->HasOutput("DDOut")) {
      ctx->ShareDim("DX", "DDOut");
      ctx->ShareLoD("DX", "DDOut");
    }
  }

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
C
chentianyu03 已提交
207
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "Out");
208 209

#ifdef PADDLE_WITH_MKLDNN
210
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
211 212 213 214 215 216 217
      return framework::OpKernelType(input_data_type, ctx.GetPlace(),
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN);
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
  }
C
chentianyu03 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const framework::Tensor& tensor,
      const framework::OpKernelType& expected_kernel_type) const {
    if (framework::IsComplexType(expected_kernel_type.data_type_)) {
      // only promote inputs’s types when contains complex input
      return framework::OpKernelType(tensor.type(), tensor.place(),
                                     tensor.layout());
    } else {
      return framework::OpKernelType(expected_kernel_type.data_type_,
                                     tensor.place(), tensor.layout());
    }
  }
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
};

template <typename DeviceContext, typename T>
class ElementwiseDivDoubleGradKernel : public framework::OpKernel<T> {
  using Tensor = framework::Tensor;

 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* Y = ctx.Input<Tensor>("Y");
    auto* Out = ctx.Input<Tensor>("Out");
    auto* ddX = ctx.Input<Tensor>("DDX");
    auto* ddY = ctx.Input<Tensor>("DDY");
    auto* dX = ctx.Input<Tensor>("DX");

    auto* dY = ctx.Output<Tensor>(framework::GradVarName("Y"));
    auto* dOut = ctx.Output<Tensor>("DOut");
    auto* ddOut = ctx.Output<Tensor>("DDOut");

    int axis = ctx.Attr<int>("axis");

    if (dY) dY->mutable_data<T>(Y->dims(), ctx.GetPlace());
    if (dOut) dOut->mutable_data<T>(Out->dims(), ctx.GetPlace());
    if (ddOut) ddOut->mutable_data<T>(Out->dims(), ctx.GetPlace());

    // ddX_safe == null ? 0 : ddX
    // ddY_safe == null ? 0 : ddY
    Tensor ddX_safe, ddY_safe;
258
    GetDoubleGradSafeTensor<DeviceContext, T>(ctx, dX, ddX, &ddX_safe);
259 260
    GetDoubleGradSafeTensor<DeviceContext, T>(ctx, Y, ddY, &ddY_safe);

261 262 263 264 265 266
    // ddOut = ddX / Y - Out * ddY / Y = (ddX - Out * ddY) / Y
    // dY = Out * dX * ddY / Y - dX * ddX / Y
    // dOut = - dX * ddY
    // To save memory, (1) dout can be used as 'tmp' tensor, (2) ddout can
    // inplace ddx
    Tensor tmp;
267
    if (dOut) {
268 269 270 271
      tmp = *dOut;
    } else {
      auto& dev_ctx = ctx.template device_context<DeviceContext>();
      tmp = ctx.AllocateTmpTensor<T, DeviceContext>(Out->dims(), dev_ctx);
272 273 274
    }
    if (dY) {
      // dX_div_Y = dX / Y;
275
      Tensor dX_div_Y = tmp;
276
      default_elementwise_div<DeviceContext, T>(ctx, dX, Y, &dX_div_Y);
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

      // NOTE(dengkaipeng): in the following ElemwiseGradCompute, for the
      // first output tensor is nullptr, the branch to calculate first
      // output tensor will not be activated, DivGradDx function will not
      // be called and can be ignored, the first branch has little effect
      // on running speed.

      // dY = Out * dX * ddY / Y - dX * ddX / Y
      ElemwiseGradCompute<DeviceContext, T, DivGradDX<T>, DivDoubleDY<T>>(
          ctx, ddX_safe, ddY_safe, *Out, dX_div_Y, axis, nullptr, dY,
          DivGradDX<T>(), DivDoubleDY<T>());
    }

    if (ddOut) {
      // ddOut = ddX / Y - Out * ddY / Y = (ddX - Out * ddY) / Y
292
      default_elementwise_mul<DeviceContext, T>(ctx, Out, &ddY_safe, &tmp);
293 294
      default_elementwise_sub<DeviceContext, T>(ctx, &ddX_safe, &tmp, &tmp);
      default_elementwise_div<DeviceContext, T>(ctx, &tmp, Y, ddOut);
295 296 297 298 299 300 301 302 303
    }

    if (dOut) {
      // dOut = - dX * ddY
      default_elementwise_mul<DeviceContext, T>(ctx, dX, &ddY_safe, dOut);
      auto& place =
          *ctx.template device_context<DeviceContext>().eigen_device();
      auto dout = framework::EigenVector<T>::Flatten(*dOut);
      dout.device(place) = static_cast<T>(-1) * dout;
304 305 306 307
    }
  }
};

G
gongweibao 已提交
308 309
}  // namespace operators
}  // namespace paddle