lrn_op.cc 14.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
G
gongweibao 已提交
2

L
Luo Tao 已提交
3 4 5
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
G
gongweibao 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
G
gongweibao 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
G
gongweibao 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/lrn_op.h"
16

17
#include <memory>
18
#include <string>
19
#include <vector>
20

21 22
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/math_function.h"
T
Tomasz Patejko 已提交
23 24 25
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
G
gongweibao 已提交
26 27 28 29

namespace paddle {
namespace operators {

30
using DataLayout = phi::DataLayout;
G
gongweibao 已提交
31

32
template <typename T>
L
Leo Chen 已提交
33
struct LRNFunctor<phi::CPUContext, T> {
34
  void operator()(const framework::ExecutionContext& ctx,
35 36 37
                  const phi::DenseTensor& input,
                  phi::DenseTensor* out,
                  phi::DenseTensor* mid,
38 39 40 41 42 43 44 45 46
                  int N,
                  int C,
                  int H,
                  int W,
                  int n,
                  T k,
                  T alpha,
                  T beta,
                  const DataLayout data_layout) {
47
    auto place = ctx.GetPlace();
48
    auto& dev_ctx = ctx.template device_context<phi::CPUContext>();
49 50
    auto blas = phi::funcs::GetBlas<phi::CPUContext, T>(dev_ctx);
    phi::funcs::Transpose<phi::CPUContext, T, 4> transpose;
51
    phi::DenseTensor in_transpose, mid_transpose, out_transpose;
52 53 54 55 56
    // if channel_last, transpose to channel_first
    if (data_layout == DataLayout::kNHWC) {
      auto in_dims = input.dims();
      std::vector<int64_t> shape(
          {in_dims[0], in_dims[3], in_dims[1], in_dims[2]});
57 58 59
      in_transpose.mutable_data<T>(phi::make_ddim(shape), place);
      mid_transpose.mutable_data<T>(phi::make_ddim(shape), place);
      out_transpose.mutable_data<T>(phi::make_ddim(shape), place);
60 61 62 63 64 65 66 67 68 69 70 71 72 73
      std::vector<int> axis = {0, 3, 1, 2};
      transpose(dev_ctx, input, &in_transpose, axis);
    } else {
      in_transpose = input;
      mid_transpose = *mid;
      out_transpose = *out;
      mid_transpose.mutable_data<T>(mid->dims(), place);
      out_transpose.mutable_data<T>(out->dims(), place);
    }

    const T* idata = in_transpose.data<T>();
    T* odata = out_transpose.data<T>();
    T* mdata = mid_transpose.data<T>();

74
    phi::DenseTensor squared;
75 76 77 78 79 80 81 82 83 84
    T* sdata = squared.mutable_data<T>({1, C + n - 1, H, W}, place);
    std::memset(sdata, 0, sizeof(T) * squared.numel());
    for (int i = 0; i < mid->numel(); ++i) {
      mdata[i] = k;
    }
    int img_size = H * W;
    int fea_size = C * img_size;
    int pre_pad = (n - 1) / 2;
    // compute batches one by one
    for (int i = 0; i < N; ++i) {
T
tensor-tang 已提交
85
      blas.VSQUARE(fea_size, idata + i * fea_size, sdata + pre_pad * img_size);
86 87 88 89 90 91 92
      // init the first channel of mid
      for (int c = 0; c < n; ++c) {
        blas.AXPY(img_size, alpha, sdata + c * img_size, mdata + i * fea_size);
      }
      for (int c = 1; c < C; ++c) {
        // copy previous scale
        int mid_offset = i * fea_size + c * img_size;
93 94
        std::memcpy(mdata + mid_offset,
                    mdata + mid_offset - img_size,
95 96
                    img_size * sizeof(T));
        // add last
97 98 99
        blas.AXPY(img_size,
                  alpha,
                  sdata + (c + n - 1) * img_size,
100 101
                  mdata + mid_offset);
        // sub rest
102 103
        blas.AXPY(
            img_size, -alpha, sdata + (c - 1) * img_size, mdata + mid_offset);
104 105
      }
    }
106 107 108
    // compute the final output
    blas.VPOW(mid->numel(), mdata, -beta, odata);
    blas.VMUL(mid->numel(), odata, idata, odata);
109 110 111 112 113 114 115

    // if channel_last, transpose the output(NCHW) to channel_last
    if (data_layout == DataLayout::kNHWC) {
      std::vector<int> axis = {0, 2, 3, 1};
      transpose(dev_ctx, mid_transpose, mid, axis);
      transpose(dev_ctx, out_transpose, out, axis);
    }
116 117
  }
};
L
Leo Chen 已提交
118 119
template struct LRNFunctor<phi::CPUContext, float>;
template struct LRNFunctor<phi::CPUContext, double>;
120 121

template <typename T>
L
Leo Chen 已提交
122
struct LRNGradFunctor<phi::CPUContext, T> {
123
  void operator()(const framework::ExecutionContext& ctx,
124 125 126 127 128
                  const phi::DenseTensor& x,
                  const phi::DenseTensor& out,
                  const phi::DenseTensor& mid,
                  phi::DenseTensor* x_g,
                  const phi::DenseTensor& out_g,
129 130 131 132 133 134 135 136
                  int N,
                  int C,
                  int H,
                  int W,
                  int n,
                  T alpha,
                  T beta,
                  const DataLayout data_layout) {
137 138 139 140 141 142 143 144 145 146 147 148 149 150
    T ratio = -2 * alpha * beta;
    auto x_g_e = framework::EigenVector<T>::Flatten(*x_g);
    x_g_e = x_g_e.constant(0.0);

    auto e_x = framework::EigenTensor<T, 4>::From(x);
    auto e_x_g = framework::EigenTensor<T, 4>::From(*x_g);
    auto e_out = framework::EigenTensor<T, 4>::From(out);
    auto e_out_g = framework::EigenTensor<T, 4>::From(out_g);
    auto e_mid = framework::EigenTensor<T, 4>::From(mid);

    const int start = -(n - 1) / 2;
    const int end = start + n;
    for (int m = 0; m < N; m++) {
      for (int i = 0; i < C; i++) {
151 152 153 154 155 156
        auto offsets = Eigen::array<int, 4>({{m, i, 0, 0}});
        auto extents = Eigen::array<int, 4>({{1, 1, H, W}});
        if (data_layout == DataLayout::kNHWC) {
          offsets = Eigen::array<int, 4>({{m, 0, 0, i}});
          extents = Eigen::array<int, 4>({{1, H, W, 1}});
        }
157

158 159 160 161
        auto i_x = e_x.slice(offsets, extents);
        auto i_x_g = e_x_g.slice(offsets, extents);
        auto i_out_g = e_out_g.slice(offsets, extents);
        auto i_mid = e_mid.slice(offsets, extents);
162 163

        i_x_g = i_mid.pow(-beta) * i_out_g;
Q
qingqing01 已提交
164
        for (int c = start; c < end; c++) {
165 166 167 168 169
          int ch = i + c;
          if (ch < 0 || ch >= C) {
            continue;
          }

170 171 172 173 174 175 176 177
          if (data_layout != DataLayout::kNHWC) {
            offsets = Eigen::array<int, 4>({{m, ch, 0, 0}});
          } else {
            offsets = Eigen::array<int, 4>({{m, 0, 0, ch}});
          }
          auto c_out = e_out.slice(offsets, extents);
          auto c_mid = e_mid.slice(offsets, extents);
          auto c_out_g = e_out_g.slice(offsets, extents);
178 179 180 181 182 183 184

          i_x_g += ratio * c_out_g * c_out * i_x / c_mid;
        }
      }
    }
  }
};
L
Leo Chen 已提交
185 186
template struct LRNGradFunctor<phi::CPUContext, float>;
template struct LRNGradFunctor<phi::CPUContext, double>;
187

G
gongweibao 已提交
188 189 190 191 192 193
class LRNOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
194 195 196
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "LRN");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "LRN");
    OP_INOUT_CHECK(ctx->HasOutput("MidOut"), "Output", "MidOut", "LRN");
G
gongweibao 已提交
197 198

    auto x_dim = ctx->GetInputDim("X");
199
    PADDLE_ENFORCE_EQ(
200 201
        x_dim.size(),
        4,
202 203 204
        platform::errors::InvalidArgument("Input(input) rank should be 4, "
                                          "but received input rank (%d) != 4",
                                          x_dim.size()));
G
gongweibao 已提交
205

206
    int n = ctx->Attrs().Get<int>("n");
207 208
    PADDLE_ENFORCE_GT(n,
                      0UL,
209 210 211 212
                      platform::errors::InvalidArgument(
                          "Argument(n) should be positive, "
                          "but received n(%d) not greater than 0",
                          n));
213 214
    PADDLE_ENFORCE_EQ(n % 2,
                      1UL,
215 216 217 218
                      platform::errors::InvalidArgument(
                          "Argument(n) should be odd value, "
                          "but received n(%d) is not an odd value",
                          n));
219

G
gongweibao 已提交
220 221
    ctx->SetOutputDim("Out", x_dim);
    ctx->ShareLoD("X", /*->*/ "Out");
222
    ctx->SetOutputDim("MidOut", x_dim);
G
gongweibao 已提交
223
  }
T
Tomasz Patejko 已提交
224

225
  phi::KernelKey GetExpectedKernelType(
226
      const framework::ExecutionContext& ctx) const override {
227
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
228
    return phi::KernelKey(data_type, ctx.GetPlace());
T
Tomasz Patejko 已提交
229
  }
230

231
  phi::KernelKey GetKernelTypeForVar(
232
      const std::string& var_name,
233
      const phi::DenseTensor& tensor,
234
      const phi::KernelKey& expected_kernel_type) const override {
235
#ifdef PADDLE_WITH_MKLDNN
236
    if ((expected_kernel_type.layout() == phi::DataLayout::ONEDNN) &&
237
        (tensor.layout() != phi::DataLayout::ONEDNN)) {
238 239 240
      auto attrs = Attrs();
      auto ar = paddle::framework::AttrReader(attrs);
      const std::string data_format = ar.Get<std::string>("data_format");
241
      auto dl = phi::StringToDataLayout(data_format);
J
Jacek Czaja 已提交
242
      // Some models may have intentionally set "AnyLayout" for lrn
243
      // op. Treat this as NCHW (default data_format value)
244
      if (dl != phi::DataLayout::kAnyLayout) {
245
        return phi::KernelKey(tensor.place(), dl, expected_kernel_type.dtype());
246 247 248
      }
    }
#endif
249 250
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
251
  }
G
gongweibao 已提交
252 253 254 255 256
};

template <typename T>
class LRNOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
257
  void Make() override {
K
kexinzhao 已提交
258 259 260
    AddInput("X",
             "(Tensor) The input of LRN operator. "
             "It must be a 4D tenor with NCHW format.");
G
gongweibao 已提交
261 262 263
    AddOutput("Out",
              "(Tensor) The output of LRN operator, which is also the 4D "
              "tensor with NCHW format.");
K
kexinzhao 已提交
264 265 266 267 268 269 270 271
    AddOutput("MidOut",
              "(Tensor) Middle result of LRN operator. It's computed in "
              "forward process and also used in backward process.");

    AddAttr<int>("n",
                 "(int default 5) "
                 "n is the \"adjacent\" kernel that maps "
                 "at the same spatial position.")
G
gongweibao 已提交
272 273 274
        .SetDefault(5)
        .GreaterThan(0);

K
kexinzhao 已提交
275 276 277
    AddAttr<T>("k",
               "(float, default 2.0) "
               "k is the bias.")
G
gongweibao 已提交
278 279 280
        .SetDefault(2.0)
        .GreaterThan(0.0);

K
kexinzhao 已提交
281 282 283
    AddAttr<T>("alpha",
               "(float, default 0.0001) "
               "alpha is the scale number.")
G
gongweibao 已提交
284 285 286
        .SetDefault(0.0001)
        .GreaterThan(0.0);

K
kexinzhao 已提交
287 288 289
    AddAttr<T>("beta",
               "(float, default 0.75) "
               "beta is the power number.")
G
gongweibao 已提交
290 291
        .SetDefault(0.75)
        .GreaterThan(0.0);
T
Tomasz Patejko 已提交
292 293 294 295 296 297 298
    AddAttr<std::string>(
        "data_format",
        "(string, default NCHW) Only used in "
        "An optional string from: \"NHWC\", \"NCHW\". "
        "Defaults to \"NHWC\". Specify the data format of the output data, "
        "the input will be transformed automatically. ")
        .SetDefault("AnyLayout");
G
gongweibao 已提交
299
    AddComment(R"DOC(
K
kexinzhao 已提交
300
Local Response Normalization Operator.
G
gongweibao 已提交
301

302 303
This operator comes from the paper:
<<ImageNet Classification with Deep Convolutional Neural Networks>>.
G
gongweibao 已提交
304

K
kexinzhao 已提交
305
The original formula is:
G
gongweibao 已提交
306

K
kexinzhao 已提交
307 308
$$
Output(i, x, y) = Input(i, x, y) / \left(
X
xiaoting 已提交
309
k + \alpha \sum\limits^{\min(C-1, i + n/2)}_{j = \max(0, i - n/2)}
K
kexinzhao 已提交
310 311 312
(Input(j, x, y))^2
\right)^{\beta}
$$
G
gongweibao 已提交
313

K
kexinzhao 已提交
314
Function implementation:
G
gongweibao 已提交
315

T
tianshuo78520a 已提交
316
Inputs and outputs are in NCHW or NHWC format, while input.shape.ndims() equals 4.
317
If NCHW, the dimensions 0 ~ 3 represent batch size, feature maps, rows,
K
kexinzhao 已提交
318
and columns, respectively.
G
gongweibao 已提交
319

K
kexinzhao 已提交
320 321
Input and Output in the formula above is for each map(i) of one image, and
Input(i, x, y), Output(i, x, y) represents an element in an image.
G
gongweibao 已提交
322

K
kexinzhao 已提交
323 324 325
C is the number of feature maps of one image. n is a hyper-parameter
configured when operator is initialized. The sum in the denominator
is the sum of the same positions in the neighboring maps.
Q
QI JUN 已提交
326

K
kexinzhao 已提交
327
)DOC");
G
gongweibao 已提交
328 329 330 331 332 333 334 335 336
  }
};

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

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
337 338
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "LRNGrad");
    OP_INOUT_CHECK(ctx->HasInput("MidOut"), "Input", "MidOu", "LRNGrad");
339 340 341 342
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   "Out@GRAD",
                   "LRNGrad");
G
gongweibao 已提交
343 344 345 346 347

    auto x_dims = ctx->GetInputDim("X");
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
  }

348
  phi::KernelKey GetExpectedKernelType(
349
      const framework::ExecutionContext& ctx) const override {
350
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
351
    return phi::KernelKey(data_type, ctx.GetPlace());
T
Tomasz Patejko 已提交
352
  }
353

354
  phi::KernelKey GetKernelTypeForVar(
355
      const std::string& var_name,
356
      const phi::DenseTensor& tensor,
357
      const phi::KernelKey& expected_kernel_type) const override {
358
#ifdef PADDLE_WITH_MKLDNN
359
    if ((expected_kernel_type.layout() == phi::DataLayout::ONEDNN) &&
360
        (tensor.layout() != phi::DataLayout::ONEDNN)) {
361 362 363
      auto attrs = Attrs();
      auto ar = paddle::framework::AttrReader(attrs);
      const std::string data_format = ar.Get<std::string>("data_format");
364
      auto dl = phi::StringToDataLayout(data_format);
365 366
      // Some models may have intentionally set "AnyLayout" for lrn
      // op. Treat this as NCHW (default data_format value)
367
      if (dl != phi::DataLayout::kAnyLayout) {
368
        return phi::KernelKey(tensor.place(), dl, expected_kernel_type.dtype());
369 370 371
      }
    }
#endif
372 373
    return phi::KernelKey(
        tensor.place(), tensor.layout(), expected_kernel_type.dtype());
374
  }
T
Tomasz Patejko 已提交
375
};
376 377 378 379 380

template <typename T>
class LRNGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
381
  void Apply(GradOpPtr<T> op) const override {
382 383 384 385 386 387 388 389 390 391
    op->SetType(this->ForwardOpType() + "_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput("Out", this->Output("Out"));
    op->SetInput("MidOut", this->Output("MidOut"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
  }
};

G
gongweibao 已提交
392 393 394 395
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
396 397 398
REGISTER_OPERATOR(lrn,
                  ops::LRNOp,
                  ops::LRNOpMaker<float>,
399 400
                  ops::LRNGradOpMaker<paddle::framework::OpDesc>,
                  ops::LRNGradOpMaker<paddle::imperative::OpBase>);
H
hong 已提交
401

402
REGISTER_OPERATOR(lrn_grad, ops::LRNOpGrad);
H
huangjiyi 已提交
403 404 405 406

PD_REGISTER_STRUCT_KERNEL(lrn, CPU, ALL_LAYOUT, ops::LRNKernel, float) {}
PD_REGISTER_STRUCT_KERNEL(
    lrn_grad, CPU, ALL_LAYOUT, ops::LRNGradKernel, float) {}