p_norm_op.cu 11.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2020 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.
Indicesou 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 <algorithm>
16
#ifdef __NVCC__
17
#include "cub/cub.cuh"
18 19 20 21 22
#endif
#ifdef __HIPCC__
#include <hipcub/hipcub.hpp>
namespace cub = hipcub;
#endif
G
Guoxia Wang 已提交
23
#include "paddle/fluid/operators/amp/fp16_type_traits.h"
24
#include "paddle/fluid/operators/elementwise/elementwise_op_impl.cu.h"
25
#include "paddle/fluid/operators/p_norm_op.h"
26 27
#include "paddle/fluid/operators/reduce_ops/reduce_op.cu.h"
#include "paddle/fluid/operators/reduce_ops/reduce_op.h"
G
Guoxia Wang 已提交
28
#include "paddle/fluid/platform/float16.h"
29 30 31 32 33 34 35 36 37

namespace paddle {
namespace operators {

template <typename T>
__device__ __forceinline__ int sgn(T val) {
  return (T(0) < val) - (val < T(0));
}

G
Guoxia Wang 已提交
38 39 40
__device__ __forceinline__ platform::float16 inline_abs(platform::float16 x) {
  return static_cast<platform::float16>(abs(static_cast<float>(x)));
}
41 42 43
__device__ __forceinline__ float inline_abs(float x) { return abs(x); }
__device__ __forceinline__ double inline_abs(double x) { return abs(x); }

G
Guoxia Wang 已提交
44 45 46
__device__ __forceinline__ int inline_sign(platform::float16 x) {
  return sgn<platform::float16>(x);
}
47 48 49
__device__ __forceinline__ int inline_sign(float x) { return sgn<float>(x); }
__device__ __forceinline__ int inline_sign(double x) { return sgn<double>(x); }

G
Guoxia Wang 已提交
50 51 52 53 54
__device__ __forceinline__ platform::float16 inline_pow(
    platform::float16 base, platform::float16 exponent) {
  return static_cast<platform::float16>(
      pow(static_cast<float>(base), static_cast<float>(exponent)));
}
55 56 57 58 59 60 61
__device__ __forceinline__ float inline_pow(float base, float exponent) {
  return pow(base, exponent);
}
__device__ __forceinline__ double inline_pow(double base, double exponent) {
  return pow(base, exponent);
}

62 63 64 65 66 67
struct IdentityFunctor {
  HOSTDEVICE explicit inline IdentityFunctor() {}
  HOSTDEVICE explicit inline IdentityFunctor(int n) {}
  template <typename T>
  HOSTDEVICE inline T operator()(const T& x) const {
    return static_cast<T>(x);
68
  }
69
};
70

71 72 73 74 75 76
struct NonzeroFunctor {
  HOSTDEVICE explicit inline NonzeroFunctor() {}
  HOSTDEVICE explicit inline NonzeroFunctor(int n) {}
  template <typename T>
  HOSTDEVICE inline T operator()(const T& x) const {
    return static_cast<T>(static_cast<double>(x) != 0);
77
  }
78
};
79

80 81 82 83 84 85
struct AbsFunctor {
  HOSTDEVICE explicit inline AbsFunctor() {}
  HOSTDEVICE explicit inline AbsFunctor(int n) {}
  template <typename T>
  HOSTDEVICE inline T operator()(const T& x) const {
    return static_cast<T>(inline_abs(x));
86
  }
87
};
88

89 90 91 92
template <typename Tx, typename Ty = Tx>
struct UnsignedPowFunctor {
  HOSTDEVICE explicit inline UnsignedPowFunctor(float porder) {
    this->porder = porder;
93
  }
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
  HOSTDEVICE inline Ty operator()(const Tx& x) const {
    return static_cast<Ty>(inline_pow(inline_abs(x), static_cast<Tx>(porder)));
  }
  float porder;
};

template <typename Tx, typename Ty = Tx>
struct PowFunctor {
  HOSTDEVICE explicit inline PowFunctor(float porder) { this->porder = porder; }
  HOSTDEVICE inline Ty operator()(const Tx& x) const {
    return static_cast<Ty>(inline_pow(x, static_cast<Tx>(porder)));
  }
  float porder;
};

template <typename Tx, typename Ty = Tx>
struct AbsAndMin {
  using Transformer = AbsFunctor;
  using MT = typename details::MPTypeTrait<Ty>::Type;
  inline Ty initial() {
    return static_cast<Ty>(std::numeric_limits<MT>::infinity());
  }
  __device__ __forceinline__ Ty operator()(const Ty& a, const Ty& b) const {
    return (a < b) ? a : b;
  }
};

template <typename Tx, typename Ty = Tx>
struct AbsAndMax {
  using Transformer = AbsFunctor;
  using MT = typename details::MPTypeTrait<Ty>::Type;
  inline Ty initial() {
    return static_cast<Ty>(-std::numeric_limits<MT>::infinity());
  }
  __device__ __forceinline__ Ty operator()(const Ty& a, const Ty& b) const {
    return (a > b) ? a : b;
  }
};

template <typename Tx, typename Ty = Tx>
struct NonzeroAndSum {
  using Transformer = NonzeroFunctor;
  inline Ty initial() { return static_cast<Ty>(0.0f); }
  __device__ __forceinline__ Ty operator()(const Ty& a, const Ty& b) const {
    return b + a;
  }
};

template <typename Tx, typename Ty = Tx>
struct IdentityAndSum {
  using Transformer = IdentityFunctor;
  inline Ty initial() { return static_cast<Ty>(0.0f); }
  __device__ __forceinline__ Ty operator()(const Ty& a, const Ty& b) const {
    return b + a;
  }
};
150 151 152 153 154 155 156 157 158 159 160 161 162 163

template <typename DeviceContext, typename T>
class PnormCUDAKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in_x = ctx.Input<framework::Tensor>("X");
    auto* out_norm = ctx.Output<framework::Tensor>("Out");
    const T* x = in_x->data<T>();
    T* norm = out_norm->mutable_data<T>(ctx.GetPlace());
    auto xdim = in_x->dims();
    auto ndim = out_norm->dims();
    float porder = ctx.Attr<float>("porder");
    int axis = ctx.Attr<int>("axis");
    if (axis < 0) axis = xdim.size() + axis;
164
    std::vector<int> reduce_axis = {axis};
165

166
    auto stream = ctx.cuda_device_context().stream();
167

168
    using MT = typename details::MPTypeTrait<T>::Type;
169
    if (porder == 0) {
170 171
      TensorReduceFunctorImpl<T, T, NonzeroAndSum>(*in_x, out_norm, reduce_axis,
                                                   stream);
172
    } else if (porder == INFINITY) {
173 174
      TensorReduceFunctorImpl<T, T, AbsAndMax>(*in_x, out_norm, reduce_axis,
                                               stream);
175
    } else if (porder == -INFINITY) {
176 177
      TensorReduceFunctorImpl<T, T, AbsAndMin>(*in_x, out_norm, reduce_axis,
                                               stream);
178
    } else {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
      framework::Tensor tmp_x;
      tmp_x.mutable_data<T>(xdim, ctx.GetPlace());
      std::vector<const framework::Tensor*> ins = {in_x};
      std::vector<framework::Tensor*> outs = {&tmp_x};
      auto func = UnsignedPowFunctor<MT, T>(porder);
      const auto& cuda_ctx =
          ctx.template device_context<platform::CUDADeviceContext>();

      LaunchSameDimsElementwiseCudaKernel<ElementwiseType::kUnary, MT, T,
                                          UnsignedPowFunctor<MT, T>>(
          cuda_ctx, ins, &outs, func);
      framework::Tensor tmp_y;
      tmp_y.mutable_data<T>(ndim, ctx.GetPlace());
      TensorReduceFunctorImpl<T, T, IdentityAndSum>(tmp_x, &tmp_y, reduce_axis,
                                                    stream);
      const framework::Tensor* tmp_norm = &tmp_y;
      ins = {tmp_norm};
      outs = {out_norm};
      auto func_inverse = UnsignedPowFunctor<MT, T>(1. / porder);

      LaunchSameDimsElementwiseCudaKernel<ElementwiseType::kUnary, MT, T,
                                          UnsignedPowFunctor<MT, T>>(
          cuda_ctx, ins, &outs, func_inverse);
202
    }
203 204 205
  }
};

206 207 208 209 210 211 212 213 214 215 216 217 218
template <typename T>
struct AbsMaxAndMinGradFunctor {
  template <typename DeviceContext, typename X, typename Y, typename DX,
            typename DY, typename Dim>
  void operator()(const DeviceContext& place, X* x, Y* y, DX* dx, DY* dy,
                  const Dim& dim, int size) {
    auto equals = ((*x).abs() == y->broadcast(dim));
    auto ones = dx->constant(static_cast<T>(1.));
    auto negs = dx->constant(static_cast<T>(-1.));
    auto zeros = dx->constant(static_cast<T>(0.));
    auto positives = (*x) > zeros;
    dx->device(place) = dy->broadcast(dim) * equals.select(ones, zeros) *
                        positives.select(ones, negs);
219
  }
220
};
221

222 223 224 225 226 227 228 229 230 231 232 233
template <typename T>
struct PNormPostGradFunctor {
  template <typename DeviceContext, typename X, typename Y, typename DX,
            typename DY, typename Dim>
  void operator()(const DeviceContext& place, X* x, Y* y, DX* dx, DY* dy,
                  const Dim& dim, int size) {
    auto ones = dx->constant(static_cast<T>(1.));
    auto negs = dx->constant(static_cast<T>(-1.));
    auto zeros = dx->constant(static_cast<T>(0.));
    auto positives = (*x) > zeros;
    dx->device(place) = (*dx) * dy->broadcast(dim) * y->broadcast(dim) *
                        positives.select(ones, negs);
234
  }
235
};
236

237 238 239 240 241 242 243 244 245 246 247 248 249 250
template <typename DeviceContext, typename T, typename AttrType = T>
class PnormGradCUDAKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in_x = ctx.Input<framework::Tensor>("X");
    auto* in_norm = ctx.Input<framework::Tensor>("Out");
    auto* in_norm_dy =
        ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
    auto* out_dx = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
    T* dx = out_dx->mutable_data<T>(ctx.GetPlace());

    auto xdim = in_x->dims();
    float porder = ctx.Attr<float>("porder");
    int axis = ctx.Attr<int>("axis");
251
    bool reduce_all = ((axis < 0) || (in_norm->numel() == 1));
252
    if (axis < 0) axis = xdim.size() + axis;
253
    const std::vector<int> dims = {axis};
254

255
    auto& cuda_ctx = ctx.template device_context<DeviceContext>();
256

257 258
    if (porder == 0) {
      math::SetConstant<DeviceContext, T> set_zero;
259
      set_zero(cuda_ctx, out_dx, static_cast<T>(0));
260
    } else if (porder == INFINITY || porder == -INFINITY) {
261 262
      LaunchReduceGradKernel<DeviceContext, T, AbsMaxAndMinGradFunctor<T>>(
          ctx, in_x, in_norm, in_norm_dy, out_dx, dims, reduce_all);
263
    } else {
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
      framework::Tensor tmp_norm;
      tmp_norm.mutable_data<T>(in_norm->dims(), ctx.GetPlace());
      std::vector<const framework::Tensor*> ins = {in_norm};
      std::vector<framework::Tensor*> outs = {&tmp_norm};
      auto pow_functor = PowFunctor<T>(1. - porder);
      LaunchSameDimsElementwiseCudaKernel<ElementwiseType::kUnary, T, T,
                                          PowFunctor<T>>(cuda_ctx, ins, &outs,
                                                         pow_functor);
      ins = {in_x};
      outs = {out_dx};
      auto unsigned_pow = UnsignedPowFunctor<T>(porder - 1.);
      LaunchSameDimsElementwiseCudaKernel<ElementwiseType::kUnary, T, T,
                                          UnsignedPowFunctor<T>>(
          cuda_ctx, ins, &outs, unsigned_pow);
      const framework::Tensor* tmp_norm_const = &tmp_norm;
      LaunchReduceGradKernel<DeviceContext, T, PNormPostGradFunctor<T>>(
          ctx, in_x, tmp_norm_const, in_norm_dy, out_dx, dims, reduce_all);
281
    }
282 283 284 285 286 287 288 289 290
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
using CUDA = paddle::platform::CUDADeviceContext;

G
Guoxia Wang 已提交
291 292 293
REGISTER_OP_CUDA_KERNEL(p_norm,
                        ops::PnormCUDAKernel<CUDA, paddle::platform::float16>,
                        ops::PnormCUDAKernel<CUDA, float>,
294
                        ops::PnormCUDAKernel<CUDA, double>);
G
Guoxia Wang 已提交
295 296 297 298
REGISTER_OP_CUDA_KERNEL(
    p_norm_grad, ops::PnormGradCUDAKernel<CUDA, paddle::platform::float16>,
    ops::PnormGradCUDAKernel<CUDA, float>,
    ops::PnormGradCUDAKernel<CUDA, double>);