norm_op.h 8.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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.
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. */

#pragma once
Y
Yi Wang 已提交
16 17
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/math/math_function.h"
18 19 20 21

namespace paddle {
namespace operators {

S
sweetsky0901 已提交
22
template <typename DeviceContext, typename T, typename AttrType = T>
23 24 25 26 27 28
class NormKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    const framework::Tensor* in_x = context.Input<framework::Tensor>("X");
    const framework::Tensor* scale = context.Input<framework::Tensor>("Scale");
    auto* out = context.Output<framework::Tensor>("Out");
S
sweetsky0901 已提交
29
    auto epsilon = static_cast<T>(context.Attr<AttrType>("epsilon"));
30 31 32 33 34 35 36 37
    out->mutable_data<T>(context.GetPlace());
    int batch_size = in_x->dims()[0];
    int channels = in_x->dims()[1];
    int height = in_x->dims()[2];
    int width = in_x->dims()[3];
    int fea_len = height * width;
    auto* place =
        context.template device_context<DeviceContext>().eigen_device();
S
sweetsky0901 已提交
38 39 40
    auto x =
        framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
            *in_x, framework::make_ddim({batch_size, fea_len * channels}));
41 42 43
    // get square
    framework::Tensor x_square;
    x_square.mutable_data<T>(in_x->dims(), context.GetPlace());
S
sweetsky0901 已提交
44 45 46
    auto x_square_eigen =
        framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
            x_square, framework::make_ddim({batch_size, fea_len * channels}));
47
    x_square_eigen.device(*place) = x.square();
S
sweetsky0901 已提交
48 49 50
    auto scale_eigen =
        framework::EigenVector<T, Eigen::RowMajor, Eigen::DenseIndex>::Flatten(
            *scale);
51 52
    for (int n = 0; n < batch_size; ++n) {
      framework::Tensor in_x_batch = in_x->Slice(n, n + 1);
S
sweetsky0901 已提交
53 54 55
      auto in_x_batch_eigen =
          framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
              in_x_batch, framework::make_ddim({channels, fea_len}));
56
      framework::Tensor x_square_batch = x_square.Slice(n, n + 1);
S
sweetsky0901 已提交
57 58 59
      auto x_square_batch_eigen =
          framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
              x_square_batch, framework::make_ddim({channels, fea_len}));
60
      framework::Tensor out_batch = out->Slice(n, n + 1);
S
sweetsky0901 已提交
61 62 63
      auto out_batch_eigen =
          framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
              out_batch, framework::make_ddim({channels, fea_len}));
64 65 66
      framework::Tensor tmp_tensor;
      tmp_tensor.mutable_data<T>(framework::make_ddim({1, fea_len}),
                                 context.GetPlace());
S
sweetsky0901 已提交
67 68
      auto tmp = framework::EigenVector<T, Eigen::RowMajor,
                                        Eigen::DenseIndex>::Flatten(tmp_tensor);
X
xuwei06 已提交
69
      // get colsum and sqrt , inverse
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
      auto dim = Eigen::array<int, 1>({{0}});
      tmp.device(*place) = x_square_batch_eigen.sum(dim);
      tmp.device(*place) = (tmp + epsilon).sqrt().inverse();
      Eigen::array<int, 2> broadcast_dim_col;
      broadcast_dim_col[1] = 1;
      broadcast_dim_col[0] = channels;
      out_batch_eigen.device(*place) =
          in_x_batch_eigen * (tmp.broadcast(broadcast_dim_col));
      Eigen::array<int, 2> broadcast_dim_row;
      broadcast_dim_row[1] = fea_len;
      broadcast_dim_row[0] = 1;
      out_batch_eigen.device(*place) =
          out_batch_eigen * (scale_eigen.broadcast(broadcast_dim_row));
    }
  }
};
S
sweetsky0901 已提交
86
template <typename DeviceContext, typename T, typename AttrType = T>
87 88 89 90 91 92 93
class NormGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    const framework::Tensor* in_x = context.Input<framework::Tensor>("X");
    const framework::Tensor* scale = context.Input<framework::Tensor>("Scale");
    const framework::Tensor* out_grad =
        context.Input<framework::Tensor>(framework::GradVarName("Out"));
S
sweetsky0901 已提交
94
    auto epsilon = static_cast<T>(context.Attr<AttrType>("epsilon"));
95 96 97 98 99 100 101 102 103 104 105
    framework::Tensor* in_x_grad =
        context.Output<framework::Tensor>(framework::GradVarName("X"));
    in_x_grad->mutable_data<T>(context.GetPlace());
    int batch_size = in_x->dims()[0];
    int channels = in_x->dims()[1];
    int height = in_x->dims()[2];
    int width = in_x->dims()[3];
    int fea_len = height * width;
    auto* place =
        context.template device_context<DeviceContext>().eigen_device();

S
sweetsky0901 已提交
106 107 108 109 110 111
    auto scale_eigen =
        framework::EigenVector<T, Eigen::RowMajor, Eigen::DenseIndex>::Flatten(
            *scale);
    auto x =
        framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
            *in_x, framework::make_ddim({batch_size, fea_len * channels}));
112 113 114
    // get square
    framework::Tensor x_square;
    x_square.mutable_data<T>(in_x->dims(), context.GetPlace());
S
sweetsky0901 已提交
115 116 117
    auto x_square_eigen =
        framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
            x_square, framework::make_ddim({batch_size, fea_len * channels}));
118 119 120 121
    x_square_eigen.device(*place) = x.square();

    for (int n = 0; n < batch_size; ++n) {
      framework::Tensor in_x_batch = in_x->Slice(n, n + 1);
S
sweetsky0901 已提交
122 123 124
      auto in_x_batch_eigen =
          framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
              in_x_batch, framework::make_ddim({channels, fea_len}));
125
      framework::Tensor in_g_batch = in_x_grad->Slice(n, n + 1);
S
sweetsky0901 已提交
126 127 128
      auto in_g_batch_eigen =
          framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
              in_g_batch, framework::make_ddim({channels, fea_len}));
129
      framework::Tensor x_square_batch = x_square.Slice(n, n + 1);
S
sweetsky0901 已提交
130 131 132
      auto x_square_batch_eigen =
          framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
              x_square_batch, framework::make_ddim({channels, fea_len}));
133
      framework::Tensor outg_batch = out_grad->Slice(n, n + 1);
S
sweetsky0901 已提交
134 135 136
      auto outg_batch_eigen =
          framework::EigenMatrix<T, Eigen::RowMajor, Eigen::DenseIndex>::From(
              outg_batch, framework::make_ddim({channels, fea_len}));
137 138 139 140

      framework::Tensor tmp_tensor;
      tmp_tensor.mutable_data<T>(framework::make_ddim({1, fea_len}),
                                 context.GetPlace());
S
sweetsky0901 已提交
141 142 143
      auto tmp_eigen =
          framework::EigenVector<T, Eigen::RowMajor,
                                 Eigen::DenseIndex>::Flatten(tmp_tensor);
144 145 146 147 148
      auto dim = Eigen::array<int, 1>({{0}});
      tmp_eigen.device(*place) = (in_x_batch_eigen * outg_batch_eigen).sum(dim);
      framework::Tensor norm_tmp_tensor;
      norm_tmp_tensor.mutable_data<T>(framework::make_ddim({1, fea_len}),
                                      context.GetPlace());
S
sweetsky0901 已提交
149 150 151
      auto norm_tmp_eigen =
          framework::EigenVector<T, Eigen::RowMajor,
                                 Eigen::DenseIndex>::Flatten(norm_tmp_tensor);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
      norm_tmp_eigen.device(*place) =
          (x_square_batch_eigen.sum(dim) + epsilon).sqrt();
      Eigen::array<int, 2> broadcast_dim_col;
      broadcast_dim_col[1] = 1;
      broadcast_dim_col[0] = channels;
      in_g_batch_eigen.device(*place) =
          in_x_batch_eigen * tmp_eigen.broadcast(broadcast_dim_col);
      in_g_batch_eigen.device(*place) =
          in_g_batch_eigen /
          (norm_tmp_eigen * norm_tmp_eigen).broadcast(broadcast_dim_col);
      in_g_batch_eigen.device(*place) = outg_batch_eigen - in_g_batch_eigen;
      // outg_batch_eigen + (in_g_batch_eigen * -1);
      in_g_batch_eigen.device(*place) =
          in_g_batch_eigen / norm_tmp_eigen.broadcast(broadcast_dim_col);
      Eigen::array<int, 2> broadcast_dim_row;
      broadcast_dim_row[1] = fea_len;
      broadcast_dim_row[0] = 1;
      in_g_batch_eigen.device(*place) =
          in_g_batch_eigen * (scale_eigen.broadcast(broadcast_dim_row));
    }
  }
};
}  // namespace operators
}  // namespace paddle