layer_norm_grad_kernel.cc 5.3 KB
Newer Older
H
hong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2022 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.
// 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.

#include "paddle/phi/kernels/layer_norm_grad_kernel.h"
16

H
hong 已提交
17 18
#include "paddle/phi/backends/cpu/cpu_context.h"
#include "paddle/phi/core/kernel_registry.h"
19
#include "paddle/phi/core/tensor_utils.h"
20
#include "paddle/phi/kernels/cpu/elementwise.h"
H
hong 已提交
21 22 23
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/elementwise_base.h"
#include "paddle/phi/kernels/funcs/elementwise_functor.h"
24
#include "paddle/phi/kernels/funcs/layer_norm_util.h"
H
hong 已提交
25 26 27 28 29 30 31
#include "paddle/phi/kernels/funcs/math_function.h"

namespace phi {

template <typename T, typename Context>
void LayerNormGradKernel(const Context& dev_ctx,
                         const DenseTensor& x,
32 33
                         const paddle::optional<DenseTensor>& scale_opt,
                         const paddle::optional<DenseTensor>& bias_opt,
H
hong 已提交
34 35
                         const DenseTensor& mean,
                         const DenseTensor& variance,
H
hong 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
                         const DenseTensor& out_grad,
                         float epsilon,
                         int begin_norm_axis,
                         DenseTensor* x_grad,
                         DenseTensor* scale_grad,
                         DenseTensor* bias_grad) {
  auto* scale = scale_opt.get_ptr();
  auto d_y = out_grad;

  // init output
  auto* d_x = x_grad;
  auto* d_scale = scale_grad;
  auto* d_bias = bias_grad;

  const auto& x_dims = x.dims();
  auto matrix_dim = phi::flatten_to_2d(x_dims, begin_norm_axis);
  int left = static_cast<int>(matrix_dim[0]);
  int right = static_cast<int>(matrix_dim[1]);
  DDim matrix_shape({left, right});

  d_y.Resize(matrix_shape);

  funcs::ColwiseSum2D<phi::CPUContext, T> colwise_sum(left, right, dev_ctx);
  DenseTensor x_tmp = x;

  DenseTensor temp;
  DenseTensor temp_norm;
  if (d_scale || d_x) {
    x_tmp.Resize(matrix_shape);
    temp.Resize(matrix_shape);
    dev_ctx.template Alloc<T>(&temp);

    temp_norm.Resize(matrix_shape);
    dev_ctx.template Alloc<T>(&temp_norm);
    // get x_norm
71 72 73
    phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T>(
        dev_ctx, x_tmp, mean, funcs::SubtractFunctor<T>(), &temp_norm, 0);
    phi::funcs::ElementwiseCompute<funcs::DivAndSqrtFunctor<T>, T>(
H
hong 已提交
74 75 76 77
        dev_ctx,
        temp_norm,
        variance,
        funcs::DivAndSqrtFunctor<T>(static_cast<T>(epsilon)),
78 79
        &temp_norm,
        0);
H
hong 已提交
80 81 82 83 84 85 86 87
  }

  if (d_bias) {
    dev_ctx.template Alloc<T>(d_bias);
    colwise_sum(dev_ctx, d_y, d_bias);
  }
  if (d_scale) {
    dev_ctx.template Alloc<T>(d_scale);
88 89
    phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T>(
        dev_ctx, temp_norm, d_y, funcs::MultiplyFunctor<T>(), &temp, 0);
H
hong 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    colwise_sum(dev_ctx, temp, d_scale);
  }

  if (d_x) {
    DDim vec_shape({left});
    dev_ctx.template Alloc<T>(d_x);
    auto dx_dim = d_x->dims();
    DenseTensor temp_vec;
    temp_vec.Resize(vec_shape);
    dev_ctx.template Alloc<T>(&temp_vec);

    funcs::RowwiseMean2D<phi::CPUContext, T> row_mean(left, right, dev_ctx);

    if (d_scale) {
      // dy_dx
105 106
      phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T>(
          dev_ctx, d_y, *scale, funcs::MultiplyFunctor<T>(), &temp, 1);
H
hong 已提交
107 108 109 110
      phi::Copy<Context>(dev_ctx, temp, dev_ctx.GetPlace(), false, d_x);

      // dy_dmean_dx
      row_mean(dev_ctx, temp, &temp_vec);
111 112
      phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T>(
          dev_ctx, *d_x, temp_vec, funcs::SubtractFunctor<T>(), d_x, 0);
H
hong 已提交
113 114

      // dy_var_dx
115 116
      phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T>(
          dev_ctx, temp, temp_norm, funcs::MultiplyFunctor<T>(), &temp, 0);
H
hong 已提交
117 118 119 120 121 122
    } else {
      // dy_dx
      phi::Copy<Context>(dev_ctx, d_y, dev_ctx.GetPlace(), false, d_x);

      // dy_dmean_dx
      row_mean(dev_ctx, d_y, &temp_vec);
123 124
      phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T>(
          dev_ctx, *d_x, temp_vec, funcs::SubtractFunctor<T>(), d_x, 0);
H
hong 已提交
125 126

      // dy_var_dx
127 128
      phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T>(
          dev_ctx, d_y, temp_norm, funcs::MultiplyFunctor<T>(), &temp, 0);
H
hong 已提交
129 130 131
    }
    // dy_var_dx
    row_mean(dev_ctx, temp, &temp_vec);
132 133 134 135 136 137
    phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T>(
        dev_ctx, temp_norm, temp_vec, funcs::MultiplyFunctor<T>(), &temp, 0);
    phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T>(
        dev_ctx, *d_x, temp, funcs::SubtractFunctor<T>(), d_x, 0);

    phi::funcs::ElementwiseCompute<funcs::DivAndSqrtFunctor<T>, T>(
H
hong 已提交
138 139 140 141
        dev_ctx,
        *d_x,
        variance,
        funcs::DivAndSqrtFunctor<T>(static_cast<T>(epsilon)),
142 143
        d_x,
        0);
H
hong 已提交
144 145 146 147 148 149 150 151 152
    d_x->Resize(dx_dim);
  }
}

}  // namespace phi

PD_REGISTER_KERNEL(
    layer_norm_grad, CPU, ALL_LAYOUT, phi::LayerNormGradKernel, float, double) {
}