layer_norm_op.h 12.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
C
chengduoZH 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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

#pragma once
P
Pei Yang 已提交
16

17
#include <algorithm>
P
Pei Yang 已提交
18
#include <vector>
W
wanghuancoder 已提交
19

Y
Yi Wang 已提交
20 21
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
W
Wu Yi 已提交
22
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
Y
Yu Yang 已提交
23
#include "paddle/fluid/operators/math/blas.h"
24 25
#if !defined(PADDLE_WITH_CUDA) && !defined(_WIN32) && !defined(__APPLE__) && \
    !defined(__OSX__)
26
#include "paddle/fluid/operators/jit/kernels.h"
27
#endif
Y
Yi Wang 已提交
28
#include "paddle/fluid/operators/math/math_function.h"
C
chengduoZH 已提交
29

W
wanghuancoder 已提交
30 31 32 33 34 35 36 37
namespace paddle {
namespace platform {
class CPUDeviceContext;
class CUDADeviceContext;
class DeviceContext;
}  // namespace platform
}  // namespace paddle

C
chengduoZH 已提交
38 39 40
namespace paddle {
namespace operators {

X
Xin Pan 已提交
41 42 43 44 45 46 47 48 49 50 51 52
// Wrap RowwiseMean and ColwiseMean.
// Reuse the cpu codes and replace the gpu codes with cublas_gemv, which is
// significantly faster. Unlike the RowwiseMean and ColwiseMean, the
// implementation only considers 2D.
template <typename DeviceContext, typename T>
struct RowwiseMean2D {
  RowwiseMean2D(int left, int right, const platform::DeviceContext& dev_ctx);

  void operator()(const platform::DeviceContext& context,
                  const framework::Tensor& input, framework::Tensor* vec);
};

53
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
X
Xin Pan 已提交
54 55 56 57 58 59 60 61 62 63 64
template <typename T>
class RowwiseMean2D<platform::CUDADeviceContext, T> {
 public:
  RowwiseMean2D(int left, int right, const platform::DeviceContext& dev_ctx)
      : left_(left), right_(right) {
    framework::DDim ones_dim({right_});
    divisor_.mutable_data<T>(ones_dim, dev_ctx.GetPlace());
    math::set_constant(dev_ctx, &divisor_, 1.0 / right);
  }
  void operator()(const platform::CUDADeviceContext& context,
                  const framework::Tensor& input, framework::Tensor* out) {
Y
Yu Yang 已提交
65 66 67
    math::GetBlas<platform::CUDADeviceContext, T>(context).GEMV(
        false, left_, right_, 1., input.data<T>(), divisor_.data<T>(), 0.,
        out->data<T>());
X
Xin Pan 已提交
68 69 70 71 72 73 74
  }

 private:
  int left_;
  int right_;
  framework::Tensor divisor_;
};
X
Xin Pan 已提交
75
#endif
X
Xin Pan 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

template <typename T>
class RowwiseMean2D<platform::CPUDeviceContext, T> {
 public:
  RowwiseMean2D(int left, int right, const platform::DeviceContext& dev_ctx) {}

  void operator()(const platform::CPUDeviceContext& context,
                  const framework::Tensor& input, framework::Tensor* out) {
    row_mean_(context, input, out);
  }

 private:
  math::RowwiseMean<platform::CPUDeviceContext, T> row_mean_;
};

template <typename DeviceContext, typename T>
struct ColwiseSum2D {
  ColwiseSum2D(int left, int right, const platform::DeviceContext& dev_ctx);

  void operator()(const platform::DeviceContext& context,
                  const framework::Tensor& input, framework::Tensor* vec);
};

99
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
X
Xin Pan 已提交
100 101 102 103 104 105 106 107 108 109 110 111
template <typename T>
class ColwiseSum2D<platform::CUDADeviceContext, T> {
 public:
  ColwiseSum2D(int left, int right, const platform::DeviceContext& dev_ctx)
      : left_(left), right_(right) {
    framework::DDim ones_dim({left_});
    divisor_.mutable_data<T>(ones_dim, dev_ctx.GetPlace());
    math::set_constant(dev_ctx, &divisor_, 1.0);
  }

  void operator()(const platform::CUDADeviceContext& context,
                  const framework::Tensor& input, framework::Tensor* out) {
Y
Yu Yang 已提交
112 113 114
    math::GetBlas<platform::CUDADeviceContext, T>(context).GEMV(
        true, left_, right_, 1., input.data<T>(), divisor_.data<T>(), 0.,
        out->data<T>());
X
Xin Pan 已提交
115 116 117 118 119 120 121
  }

 private:
  int left_;
  int right_;
  framework::Tensor divisor_;
};
X
Xin Pan 已提交
122
#endif
X
Xin Pan 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

template <typename T>
class ColwiseSum2D<platform::CPUDeviceContext, T> {
 public:
  ColwiseSum2D(int left, int right, const platform::DeviceContext& dev_ctx) {}

  void operator()(const platform::CPUDeviceContext& context,
                  const framework::Tensor& input, framework::Tensor* out) {
    col_wise_(context, input, out);
  }

 private:
  math::ColwiseSum<platform::CPUDeviceContext, T> col_wise_;
};

C
chengduoZH 已提交
138 139 140 141 142 143 144 145 146
template <typename T>
struct SubAndSquareFunctor {
  inline HOSTDEVICE T operator()(T a, T b) const { return (a - b) * (a - b); }
};

template <typename T>
struct DivAndSqrtFunctor {
  explicit DivAndSqrtFunctor(T epsilon) { epsilon_ = epsilon; }
  inline HOSTDEVICE T operator()(T a, T b) const {
C
chengduoZH 已提交
147
    return a / (sqrt(b + epsilon_));
C
chengduoZH 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  }

 private:
  T epsilon_;
};

template <typename T>
struct MulInvVarFunctor {
  inline HOSTDEVICE T operator()(T a, T b) const {
    return a * std::sqrt(1.0 / b);
  }
};

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using DataLayout = framework::DataLayout;

165
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
P
Pei Yang 已提交
166 167 168
template <typename T>
class LayerNormDirectCUDAFunctor {
 public:
169
  void operator()(gpuStream_t stream, const T* input,
P
Pei Yang 已提交
170 171 172 173 174 175
                  std::vector<int> input_shape, const T* bias, const T* scale,
                  T* output, T* mean, T* variance, int begin_norm_axis,
                  float eps);
};
#endif

C
chengduoZH 已提交
176 177 178
template <typename DeviceContext, typename T>
class LayerNormKernel : public framework::OpKernel<T> {
 public:
X
Xin Pan 已提交
179
  void Compute(const framework::ExecutionContext& ctx) const override {
C
chengduoZH 已提交
180
    const float epsilon = ctx.Attr<float>("epsilon");
X
Xin Pan 已提交
181 182
    auto* scale = ctx.Input<Tensor>("Scale");
    auto* bias = ctx.Input<Tensor>("Bias");
C
chengduoZH 已提交
183 184
    auto x = *ctx.Input<Tensor>("X");

X
Xin Pan 已提交
185 186 187
    auto* y = ctx.Output<Tensor>("Y");
    auto* mean = ctx.Output<Tensor>("Mean");
    auto* var = ctx.Output<Tensor>("Variance");
C
chengduoZH 已提交
188 189
    const auto begin_norm_axis = ctx.Attr<int>("begin_norm_axis");

C
chengduoZH 已提交
190
    const auto x_dims = x.dims();
C
chengduoZH 已提交
191 192 193 194 195 196 197 198 199 200 201

    y->mutable_data<T>(ctx.GetPlace());
    mean->mutable_data<T>(ctx.GetPlace());
    var->mutable_data<T>(ctx.GetPlace());

    auto matrix_dim = framework::flatten_to_2d(x_dims, begin_norm_axis);
    int left = static_cast<int>(matrix_dim[0]);
    int right = static_cast<int>(matrix_dim[1]);
    framework::DDim matrix_shape({left, right});

    x.Resize(matrix_shape);
C
chengduoZH 已提交
202 203 204
    Tensor out;
    out.ShareDataWith(*y);
    out.Resize(matrix_shape);
C
chengduoZH 已提交
205

206 207
#if defined(PADDLE_WITH_CUDA) || defined(_WIN32) || defined(__APPLE__) || \
    defined(__OSX__)
X
Xin Pan 已提交
208 209
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    RowwiseMean2D<DeviceContext, T> row_mean(left, right, ctx.device_context());
C
chengduoZH 已提交
210

C
chengduoZH 已提交
211
    // get mean
C
chengduoZH 已提交
212 213
    row_mean(dev_ctx, x, mean);

C
chengduoZH 已提交
214
    // get variance
C
chengduoZH 已提交
215
    ElementwiseComputeEx<SubAndSquareFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
216 217
        ctx, &x, mean, /*axis*/ 0, SubAndSquareFunctor<T>(), &out);
    row_mean(dev_ctx, out, var);
C
chengduoZH 已提交
218

C
chengduoZH 已提交
219
    // get x_norm
C
chengduoZH 已提交
220
    ElementwiseComputeEx<SubFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
221
        ctx, &x, mean, /*axis*/ 0, SubFunctor<T>(), &out);
C
chengduoZH 已提交
222
    ElementwiseComputeEx<DivAndSqrtFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
223 224
        ctx, &out, var, /*axis*/ 0,
        DivAndSqrtFunctor<T>(static_cast<T>(epsilon)), &out);
C
chengduoZH 已提交
225 226 227

    if (scale) {
      ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
228
          ctx, &out, scale, /*axis*/ 1, MulFunctor<T>(), &out);
C
chengduoZH 已提交
229 230 231
    }
    if (bias) {
      ElementwiseComputeEx<AddFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
232
          ctx, &out, bias, /*axis*/ 1, AddFunctor<T>(), &out);
C
chengduoZH 已提交
233
    }
234
#else
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    PADDLE_ENFORCE_EQ(mean->numel(), left,
                      platform::errors::InvalidArgument(
                          "mean's length (%d) is not equal with expected (%d).",
                          mean->numel(), left));
    PADDLE_ENFORCE_EQ(var->numel(), left,
                      platform::errors::InvalidArgument(
                          "var's length (%d) is not equal with expected (%d).",
                          var->numel(), left));
    if (scale) {
      PADDLE_ENFORCE_EQ(
          scale->numel(), right,
          platform::errors::InvalidArgument(
              "scale's length (%d) is not equal with expected (%d).",
              scale->numel(), right));
    }
    if (bias) {
      PADDLE_ENFORCE_EQ(
          bias->numel(), right,
          platform::errors::InvalidArgument(
              "bias's length (%d) is not equal with expected (%d).",
              bias->numel(), right));
    }
257

258 259 260
    auto ker =
        jit::KernelFuncs<jit::LayerNormTuple<T>, platform::CPUPlace>::Cache()
            .At(right);
261
    ker(x.data<T>(), out.data<T>(), mean->data<T>(), var->data<T>(),
262 263
        scale ? scale->data<T>() : nullptr, bias ? bias->data<T>() : nullptr,
        static_cast<int>(left), static_cast<const float>(epsilon), right);
264
#endif
C
chengduoZH 已提交
265
  }
C
chengduoZH 已提交
266 267 268 269 270
};

template <typename DeviceContext, typename T>
class LayerNormGradKernel : public framework::OpKernel<T> {
 public:
X
Xin Pan 已提交
271
  void Compute(const framework::ExecutionContext& ctx) const override {
C
chengduoZH 已提交
272 273
    const float epsilon = ctx.Attr<float>("epsilon");
    auto x = *ctx.Input<Tensor>("X");
X
Xin Pan 已提交
274 275 276
    auto* mean = ctx.Input<Tensor>("Mean");
    auto* var = ctx.Input<Tensor>("Variance");
    auto* scale = ctx.Input<Tensor>("Scale");
C
chengduoZH 已提交
277 278 279 280
    auto d_y = *ctx.Input<Tensor>(framework::GradVarName("Y"));
    const auto begin_norm_axis = ctx.Attr<int>("begin_norm_axis");

    // init output
X
Xin Pan 已提交
281 282 283
    auto* d_x = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* d_scale = ctx.Output<Tensor>(framework::GradVarName("Scale"));
    auto* d_bias = ctx.Output<Tensor>(framework::GradVarName("Bias"));
C
chengduoZH 已提交
284

X
Xin Pan 已提交
285
    const auto& x_dims = x.dims();
C
chengduoZH 已提交
286 287 288 289 290 291
    auto matrix_dim = framework::flatten_to_2d(x_dims, begin_norm_axis);
    int left = static_cast<int>(matrix_dim[0]);
    int right = static_cast<int>(matrix_dim[1]);
    framework::DDim matrix_shape({left, right});

    d_y.Resize(matrix_shape);
X
Xin Pan 已提交
292 293 294
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    ColwiseSum2D<DeviceContext, T> colwise_sum(left, right,
                                               ctx.device_context());
C
chengduoZH 已提交
295 296 297 298 299 300 301

    Tensor temp;
    Tensor temp_norm;
    if (d_scale || d_x) {
      x.Resize(matrix_shape);
      temp.mutable_data<T>(matrix_shape, ctx.GetPlace());

S
sneaxiy 已提交
302 303 304 305 306 307 308
      temp_norm.mutable_data<T>(matrix_shape, ctx.GetPlace());
      // get x_norm
      ElementwiseComputeEx<SubFunctor<T>, DeviceContext, T>(
          ctx, &x, mean, /*axis*/ 0, SubFunctor<T>(), &temp_norm);
      ElementwiseComputeEx<DivAndSqrtFunctor<T>, DeviceContext, T>(
          ctx, &temp_norm, var, /*axis*/ 0,
          DivAndSqrtFunctor<T>(static_cast<T>(epsilon)), &temp_norm);
C
chengduoZH 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    }

    if (d_bias) {
      d_bias->mutable_data<T>(ctx.GetPlace());
      colwise_sum(dev_ctx, d_y, d_bias);
    }
    if (d_scale) {
      d_scale->mutable_data<T>(ctx.GetPlace());
      ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
          ctx, &temp_norm, &d_y, /*axis*/ 0, MulFunctor<T>(), &temp);
      colwise_sum(dev_ctx, temp, d_scale);
    }

    if (d_x) {
      framework::DDim vec_shape({left});
      d_x->mutable_data<T>(ctx.GetPlace());
C
chengduoZH 已提交
325
      auto dx_dim = d_x->dims();
C
chengduoZH 已提交
326 327 328
      Tensor temp_vec;
      temp_vec.mutable_data<T>(vec_shape, ctx.GetPlace());

X
Xin Pan 已提交
329 330
      RowwiseMean2D<DeviceContext, T> row_mean(left, right,
                                               ctx.device_context());
C
chengduoZH 已提交
331 332 333 334

      if (d_scale) {
        // dy_dx
        ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
335
            ctx, &d_y, scale, /*axis*/ 1, MulFunctor<T>(), &temp);
Y
Yi Wang 已提交
336
        framework::TensorCopy(temp, ctx.GetPlace(), ctx.device_context(), d_x);
C
chengduoZH 已提交
337 338 339 340 341 342 343 344 345 346 347

        // dy_dmean_dx
        row_mean(dev_ctx, temp, &temp_vec);
        ElementwiseComputeEx<SubFunctor<T>, DeviceContext, T>(
            ctx, d_x, &temp_vec, /*axis*/ 0, SubFunctor<T>(), d_x);

        // dy_var_dx
        ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
            ctx, &temp, &temp_norm, /*axis*/ 0, MulFunctor<T>(), &temp);
      } else {
        // dy_dx
Y
Yi Wang 已提交
348
        framework::TensorCopy(d_y, ctx.GetPlace(), ctx.device_context(), d_x);
C
chengduoZH 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361

        // dy_dmean_dx
        row_mean(dev_ctx, d_y, &temp_vec);
        ElementwiseComputeEx<SubFunctor<T>, DeviceContext, T>(
            ctx, d_x, &temp_vec, /*axis*/ 0, SubFunctor<T>(), d_x);

        // dy_var_dx
        ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
            ctx, &d_y, &temp_norm, /*axis*/ 0, MulFunctor<T>(), &temp);
      }
      // dy_var_dx
      row_mean(dev_ctx, temp, &temp_vec);
      ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
362
          ctx, &temp_norm, &temp_vec, /*axis*/ 0, MulFunctor<T>(), &temp);
C
chengduoZH 已提交
363
      ElementwiseComputeEx<SubFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
364
          ctx, d_x, &temp, /*axis*/ 0, SubFunctor<T>(), d_x);
C
chengduoZH 已提交
365 366

      ElementwiseComputeEx<DivAndSqrtFunctor<T>, DeviceContext, T>(
C
chengduoZH 已提交
367
          ctx, d_x, var, /*axis*/ 0,
C
chengduoZH 已提交
368
          DivAndSqrtFunctor<T>(static_cast<T>(epsilon)), d_x);
C
chengduoZH 已提交
369
      d_x->Resize(dx_dim);
C
chengduoZH 已提交
370 371
    }
  }
C
chengduoZH 已提交
372 373 374 375
};

}  // namespace operators
}  // namespace paddle