layer_norm_op.cc 14.7 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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/operators/layer_norm_op.h"

namespace paddle {
namespace operators {

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

template <typename T>
using EigenMatrixMapRowMajor = Eigen::Map<
    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>;
template <typename T>
using ConstEigenMatrixMapRowMajor = Eigen::Map<
    const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>;

class LayerNormOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
C
chengduoZH 已提交
36 37 38 39 40 41 42 43
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of LayerNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Y"),
                   "Output(Y) of LayerNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Mean"),
                   "Output(Mean) of LayerNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Variance"),
                   "Output(Variance) of LayerNormOp should not be null.");
C
chengduoZH 已提交
44

C
chengduoZH 已提交
45 46 47
    auto x_dim = ctx->GetInputDim("X");
    auto begin_norm_axis = ctx->Attrs().Get<int>("begin_norm_axis");
    PADDLE_ENFORCE_LT(begin_norm_axis, x_dim.size(),
C
chengduoZH 已提交
48
                      "'begin_norm_axis' must be less than the rank of X.");
C
chengduoZH 已提交
49 50 51

    auto matrix_dim = framework::flatten_to_2d(x_dim, begin_norm_axis);
    int left = static_cast<int>(matrix_dim[0]);
C
chengduoZH 已提交
52
    int right = static_cast<int>(matrix_dim[1]);
C
chengduoZH 已提交
53 54 55 56 57 58 59 60
    if (ctx->HasInput("Scale")) {
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("Scale").size(), 1UL);
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("Scale")[0], right);
    }
    if (ctx->HasInput("Bias")) {
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("Bias").size(), 1UL);
      PADDLE_ENFORCE_EQ(ctx->GetInputDim("Bias")[0], right);
    }
C
chengduoZH 已提交
61

C
chengduoZH 已提交
62
    ctx->SetOutputDim("Y", ctx->GetInputDim("X"));
C
chengduoZH 已提交
63 64
    ctx->SetOutputDim("Mean", {left});
    ctx->SetOutputDim("Variance", {left});
C
chengduoZH 已提交
65 66 67 68 69 70 71 72
    ctx->ShareLoD("X", "Y");
  }
};

class LayerNormOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  LayerNormOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
C
chengduoZH 已提交
73
    AddInput("X", "(LoDTensor) The input tensor.");
C
chengduoZH 已提交
74
    AddInput("Scale",
C
chengduoZH 已提交
75 76 77 78
             "(Tensor, optional) Scale is a 1-dimensional tensor of size "
             "H(`begin_norm_axis` splits the tensor(`X`) to a matrix [N,H])."
             "It is applied to the output.")
        .AsDispensable();
C
chengduoZH 已提交
79
    AddInput("Bias",
C
chengduoZH 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92
             "(Tensor, optional) Bias is a 1-dimensional tensor of size "
             "H(`begin_norm_axis` splits the tensor(`X`) to a matrix [N,H])."
             "It is applied to the output.")
        .AsDispensable();
    AddOutput("Y", "(LoDTensor) Result after normalization.");
    AddOutput("Mean", "(Tensor) Mean of the current mini batch.")
        .AsIntermediate();
    AddOutput("Variance", "(Tensor) Variance of the current mini batch.")
        .AsIntermediate();

    AddAttr<float>("epsilon",
                   "(float, default 1e-5) Constant for "
                   "numerical stability")
C
chengduoZH 已提交
93 94 95 96 97
        .SetDefault(1e-5)
        .AddCustomChecker([](const float &epsilon) {
          PADDLE_ENFORCE(epsilon >= 0.0f && epsilon <= 0.001f,
                         "'epsilon' should be between 0.0 and 0.001.");
        });
C
chengduoZH 已提交
98 99
    AddAttr<int>("begin_norm_axis",
                 "(int default:1), the "
C
chengduoZH 已提交
100 101 102
                 "axis of `begin_norm_axis ... Rank(X) - 1` will be "
                 "normalized. `begin_norm_axis` splits the tensor(`X`) to a "
                 "matrix [N,H].")
C
chengduoZH 已提交
103 104 105 106 107
        .SetDefault(1)
        .AddCustomChecker([](const int &begin_norm_axis) {
          PADDLE_ENFORCE_GT(begin_norm_axis, 0,
                            "'begin_norm_axis' should be greater than zero.");
        });
C
chengduoZH 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

    AddComment(R"DOC(
Layer Normalization.

Layer Norm has been implemented as discussed in the paper:
https://arxiv.org/abs/1607.06450
...
)DOC");
  }
};

template <typename T>
class LayerNormKernel<platform::CPUDeviceContext, T>
    : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const float epsilon = ctx.Attr<float>("epsilon");
    const auto *scale = ctx.Input<Tensor>("Scale");
    const auto *bias = ctx.Input<Tensor>("Bias");
    const auto *x = ctx.Input<Tensor>("X");
    const auto &x_dims = x->dims();
C
chengduoZH 已提交
129
    const auto begin_norm_axis = ctx.Attr<int>("begin_norm_axis");
C
chengduoZH 已提交
130 131 132 133 134 135 136 137

    auto *output = ctx.Output<Tensor>("Y");
    auto *mean = ctx.Output<Tensor>("Mean");
    auto *var = ctx.Output<Tensor>("Variance");
    output->mutable_data<T>(ctx.GetPlace());
    mean->mutable_data<T>(ctx.GetPlace());
    var->mutable_data<T>(ctx.GetPlace());

C
chengduoZH 已提交
138 139 140
    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]);
C
chengduoZH 已提交
141

C
chengduoZH 已提交
142
    auto input_map = ConstEigenMatrixMapRowMajor<T>(x->data<T>(), left, right);
C
chengduoZH 已提交
143

C
chengduoZH 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157
    auto mean_map = EigenMatrixMapRowMajor<T>(mean->data<T>(), left, 1);
    auto var_map = EigenMatrixMapRowMajor<T>(var->data<T>(), left, 1);
    auto output_map = EigenMatrixMapRowMajor<T>(output->data<T>(), left, right);

    auto squre = [](T ele) { return ele * ele; };
    auto add_epslion = [epsilon](T ele) { return ele + epsilon; };

    mean_map = input_map.rowwise().mean();
    var_map = (input_map - mean_map.replicate(1, right))
                  .unaryExpr(squre)
                  .rowwise()
                  .mean()
                  .unaryExpr(add_epslion);

C
chengduoZH 已提交
158
    auto inv_std_func = [](T ele) { return std::sqrt(1 / ele); };
C
chengduoZH 已提交
159 160
    // TODO(zcd): Some thinking about output_map, is it appropriate that
    // `output_map` and `input_map` point to the same memory.
C
chengduoZH 已提交
161
    auto inv_std = var_map.unaryExpr(inv_std_func);
C
chengduoZH 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    if (scale && bias) {
      auto scale_map =
          ConstEigenMatrixMapRowMajor<T>(scale->data<T>(), 1, right);
      auto bias_map = ConstEigenMatrixMapRowMajor<T>(bias->data<T>(), 1, right);
      output_map = (input_map - mean_map.replicate(1, right))
                       .cwiseProduct(inv_std.replicate(1, right))
                       .cwiseProduct(scale_map.replicate(left, 1)) +
                   bias_map.replicate(left, 1);
    } else if (scale) {
      auto scale_map =
          ConstEigenMatrixMapRowMajor<T>(scale->data<T>(), 1, right);
      output_map = (input_map - mean_map.replicate(1, right))
                       .cwiseProduct(inv_std.replicate(1, right))
                       .cwiseProduct(scale_map.replicate(left, 1));
    } else if (bias) {
      auto bias_map = ConstEigenMatrixMapRowMajor<T>(bias->data<T>(), 1, right);
      output_map = (input_map - mean_map.replicate(1, right))
                       .cwiseProduct(inv_std.replicate(1, right)) +
                   bias_map.replicate(left, 1);
    } else {
      output_map = (input_map - mean_map.replicate(1, right))
                       .cwiseProduct(inv_std.replicate(1, right));
    }
C
chengduoZH 已提交
185 186 187 188 189 190 191 192 193
  }
};

class LayerNormGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
    // check input
C
chengduoZH 已提交
194 195 196 197 198 199 200 201 202 203
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of LayerNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Scale"),
                   "Input(Scale) of LayerNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Mean"),
                   "Input(Mean) of LayerNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Variance"),
                   "Input(Variance) of LayerNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Y")),
                   "Input(Y@GRAD) of LayerNormOp should not be null.");
C
chengduoZH 已提交
204 205 206

    // check output
    if (ctx->HasOutput(framework::GradVarName("X"))) {
C
chengduoZH 已提交
207
      ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
C
chengduoZH 已提交
208 209
    }
    if (ctx->HasOutput(framework::GradVarName("Scale"))) {
C
chengduoZH 已提交
210 211
      ctx->SetOutputDim(framework::GradVarName("Scale"),
                        ctx->GetInputDim("Scale"));
C
chengduoZH 已提交
212 213
    }
    if (ctx->HasOutput(framework::GradVarName("Bias"))) {
C
chengduoZH 已提交
214 215
      ctx->SetOutputDim(framework::GradVarName("Bias"),
                        ctx->GetInputDim("Bias"));
C
chengduoZH 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    const auto *var = ctx.InputVar(framework::GradVarName("Y"));
    if (var == nullptr) {
      PADDLE_THROW("can't find Y@GRAD");
    }
    const Tensor *t = nullptr;
    if (var->IsType<Tensor>()) {
      t = &var->Get<Tensor>();
    } else if (var->IsType<LoDTensor>()) {
      t = &var->Get<LoDTensor>();
    }
    if (t == nullptr) {
      PADDLE_THROW("can't find Y@GRAD");
    }
    return framework::OpKernelType(framework::ToDataType(t->type()),
                                   ctx.GetPlace());
  }
};

template <typename T>
class LayerNormGradKernel<platform::CPUDeviceContext, T>
    : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const auto *x = ctx.Input<Tensor>("X");
    const auto *mean = ctx.Input<Tensor>("Mean");
    const auto *var = ctx.Input<Tensor>("Variance");
    const auto *scale = ctx.Input<Tensor>("Scale");
    const auto *d_y = ctx.Input<Tensor>(framework::GradVarName("Y"));

    const auto &x_dims = x->dims();

C
chengduoZH 已提交
253 254
    const auto begin_norm_axis = ctx.Attr<int>("begin_norm_axis");
    auto matrix_dim = framework::flatten_to_2d(x_dims, begin_norm_axis);
C
chengduoZH 已提交
255 256
    int left = static_cast<int>(matrix_dim[0]);
    int right = static_cast<int>(matrix_dim[1]);
C
chengduoZH 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269

    // init output
    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"));

    auto x_map = ConstEigenMatrixMapRowMajor<T>(x->data<T>(), left, right);
    auto d_y_map = ConstEigenMatrixMapRowMajor<T>(d_y->data<T>(), left, right);
    auto mean_map = ConstEigenMatrixMapRowMajor<T>(mean->data<T>(), left, 1);
    auto var_map = ConstEigenMatrixMapRowMajor<T>(var->data<T>(), left, 1);

    if (d_bias) {
      d_bias->mutable_data<T>(ctx.GetPlace());
C
chengduoZH 已提交
270
      auto d_bias_map = EigenMatrixMapRowMajor<T>(d_bias->data<T>(), 1, right);
C
chengduoZH 已提交
271
      d_bias_map = d_y_map.colwise().sum();
C
chengduoZH 已提交
272 273 274
    }
    if (d_scale) {
      d_scale->mutable_data<T>(ctx.GetPlace());
C
chengduoZH 已提交
275 276
      auto d_scale_map =
          EigenMatrixMapRowMajor<T>(d_scale->data<T>(), 1, right);
C
chengduoZH 已提交
277
      auto inv_std_func = [](T ele) { return std::sqrt(1 / ele); };
C
chengduoZH 已提交
278 279
      // There are two equation to compute d_scale. One uses "Y" and the other
      // does not use "Y"
C
chengduoZH 已提交
280
      d_scale_map =
C
chengduoZH 已提交
281
          ((x_map - mean_map.replicate(1, right))
C
chengduoZH 已提交
282 283
               .cwiseProduct(
                   var_map.unaryExpr(inv_std_func).replicate(1, right))
C
chengduoZH 已提交
284
               .cwiseProduct(d_y_map))
C
chengduoZH 已提交
285
              .colwise()
C
chengduoZH 已提交
286
              .sum();
C
chengduoZH 已提交
287 288 289 290 291
    }

    if (d_x) {
      d_x->mutable_data<T>(ctx.GetPlace());
      auto d_x_map = EigenMatrixMapRowMajor<T>(d_x->data<T>(), left, right);
C
chengduoZH 已提交
292 293
      auto triple_product_func = [](T ele) { return ele * ele * ele; };
      auto inv_std_func = [](T ele) { return std::sqrt(1 / ele); };
C
chengduoZH 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
      // TODO(zcd): these code can be refined
      if (d_scale) {
        auto scale_map =
            ConstEigenMatrixMapRowMajor<T>(scale->data<T>(), 1, right);
        // dy_dx
        auto dx_end = var_map.unaryExpr(inv_std_func)
                          .replicate(1, right)
                          .cwiseProduct(d_y_map)
                          .cwiseProduct(scale_map.replicate(left, 1));
        // dy_dmean_dx
        auto dx_mean = (T(-1.0) / right) *
                       var_map.unaryExpr(inv_std_func)
                           .replicate(1, right)
                           .cwiseProduct(d_y_map)
                           .cwiseProduct(scale_map.replicate(left, 1))
                           .rowwise()
                           .sum()
                           .replicate(1, right);
        // dy_var_dx
        auto dvar_end_part = (x_map - mean_map.replicate(1, right))
                                 .cwiseProduct(scale_map.replicate(left, 1))
                                 .cwiseProduct(d_y_map)
                                 .rowwise()
                                 .sum();
        auto dvar_end = var_map.unaryExpr(inv_std_func)
                            .unaryExpr(triple_product_func)
                            .cwiseProduct(dvar_end_part)
                            .replicate(1, right);
        auto dx_var =
            (T(-1.0) / right) *
            (x_map - mean_map.replicate(1, right)).cwiseProduct(dvar_end);

        d_x_map = dx_end + dx_mean + dx_var;
      } else {
        // dy_dx
        auto dx_end = var_map.unaryExpr(inv_std_func)
                          .replicate(1, right)
                          .cwiseProduct(d_y_map);
        // dy_dmean_dx
        auto dx_mean = (T(-1.0) / right) *
                       var_map.unaryExpr(inv_std_func)
                           .replicate(1, right)
                           .cwiseProduct(d_y_map)
                           .rowwise()
                           .sum()
                           .replicate(1, right);
        // dy_var_dx
        auto dvar_end_part = (x_map - mean_map.replicate(1, right))
                                 .cwiseProduct(d_y_map)
                                 .rowwise()
                                 .sum();
        auto dvar_end = var_map.unaryExpr(inv_std_func)
                            .unaryExpr(triple_product_func)
                            .cwiseProduct(dvar_end_part)
                            .replicate(1, right);
        auto dx_var =
            (T(-1.0) / right) *
            (x_map - mean_map.replicate(1, right)).cwiseProduct(dvar_end);

        d_x_map = dx_end + dx_mean + dx_var;
      }
C
chengduoZH 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP(layer_norm, ops::LayerNormOp, ops::LayerNormOpMaker,
            layer_norm_grad, ops::LayerNormGradOp);
REGISTER_OP_CPU_KERNEL(
    layer_norm,
    ops::LayerNormKernel<paddle::platform::CPUDeviceContext, float>);
REGISTER_OP_CPU_KERNEL(
    layer_norm_grad,
    ops::LayerNormGradKernel<paddle::platform::CPUDeviceContext, float>);