lrn_mkldnn_op.cc 5.8 KB
Newer Older
T
Tomasz Patejko 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 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/fluid/framework/tensor.h"
#include "paddle/fluid/operators/lrn_op.h"
17
#include "paddle/fluid/platform/mkldnn_reuse.h"
T
Tomasz Patejko 已提交
18 19 20 21 22 23 24 25 26 27 28

namespace paddle {
namespace operators {

using paddle::framework::Tensor;
using paddle::platform::MKLDNNDeviceContext;

template <typename T>
class LRNMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
M
minqiyang 已提交
29
    const bool is_float_type = std::is_same<T, float>::value;
M
minqiyang 已提交
30
    PADDLE_ENFORCE(is_float_type, "MKLDNN LRN must use float data.");
T
Tomasz Patejko 已提交
31 32 33 34 35 36 37 38 39 40
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "MKLDNN LRN must use CPUPlace.");

    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

    auto x = ctx.Input<Tensor>("X");
    auto out = ctx.Output<Tensor>("Out");
    auto mid = ctx.Output<Tensor>("MidOut");

    const int n = ctx.Attr<int>("n");
41 42 43 44 45 46
    // MKL-DNN implements LRN in a caffe way:
    // http://caffe.berkeleyvision.org/tutorial/layers/lrn.html
    // Where sum of squares is divided by size of normalization window
    // this is not the case for PaddlePaddle LRN.
    // Hence we need to compensate for this diffrence by
    // multipliing alpha by size of window(n)
47
    const float alpha = ctx.Attr<float>("alpha") * static_cast<float>(n);
T
Tomasz Patejko 已提交
48 49
    const float beta = ctx.Attr<float>("beta");
    const float k = ctx.Attr<float>("k");
J
Jacek Czaja 已提交
50
    bool is_test = ctx.Attr<bool>("is_test");
T
Tomasz Patejko 已提交
51

52
    auto dims = paddle::framework::vectorize<int>(x->dims());
53

J
Jacek Czaja 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    platform::LRNMKLDNNHandler<T> handler(dims, n, alpha, beta, k, x->format(),
                                          is_test, dev_ctx, ctx.GetPlace(),
                                          ctx.op().Output("Out"));

    auto src_memory = handler.AcquireSrcMemory(x);
    auto dst_memory = handler.AcquireDstMemory(out);

    std::shared_ptr<mkldnn::memory> workspace_memory;
    std::shared_ptr<mkldnn::lrn_forward> lrn_p;
    if (is_test == false) {
      workspace_memory = handler.AcquireWorkspaceMemory(mid);
      lrn_p = handler.AcquireForwardPrimitive(*src_memory, *workspace_memory,
                                              *dst_memory);
    } else {
      // mid has to be allocated and filled
      // k to pass LRN unit tests
      // TODO(jczaja): Disable checking mid in unit tests (Require API change)
      mid->mutable_data<T>(ctx.GetPlace());
      auto e_mid = framework::EigenTensor<T, 4>::From(*mid);
      e_mid = e_mid.constant(k);
      lrn_p = handler.AcquireForwardPrimitive(*src_memory, *dst_memory);
    }
76 77 78 79 80 81 82 83 84 85 86

    std::vector<mkldnn::primitive> pipeline = {*lrn_p};
    mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();

    auto output_format =
        (mkldnn::memory::format)dst_memory->get_primitive_desc()
            .desc()
            .data.format;

    out->set_layout(framework::DataLayout::kMKLDNN);
    out->set_format(output_format);
T
Tomasz Patejko 已提交
87 88 89 90 91 92 93
  }
};

template <typename T>
class LRNMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
M
minqiyang 已提交
94 95
    const bool is_float_type = std::is_same<T, float>::value;
    PADDLE_ENFORCE(is_float_type, "MKLDNN LRN must use float data.");
T
Tomasz Patejko 已提交
96 97
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "MKLDNN LRN must use CPUPlace.");
98 99 100
    PADDLE_ENFORCE(
        !ctx.Attr<bool>("is_test"),
        "is_test attribute should be set to False in training phase.");
T
Tomasz Patejko 已提交
101 102

    auto x = ctx.Input<Tensor>("X");
J
Jacek Czaja 已提交
103
    auto mid = ctx.Input<Tensor>("MidOut");
T
Tomasz Patejko 已提交
104 105 106 107 108

    auto out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto x_grad = ctx.Output<Tensor>(framework::GradVarName("X"));

    const int n = ctx.Attr<int>("n");
109
    const float alpha = ctx.Attr<float>("alpha") * static_cast<float>(n);
T
Tomasz Patejko 已提交
110 111 112 113 114
    const float beta = ctx.Attr<float>("beta");
    const float k = ctx.Attr<float>("k");

    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();

115
    auto dims = paddle::framework::vectorize<int>(x->dims());
T
Tomasz Patejko 已提交
116

J
Jacek Czaja 已提交
117 118 119
    platform::LRNMKLDNNHandler<T> handler(
        dims, n, alpha, beta, k, x->format(), out_grad->format(), dev_ctx,
        ctx.GetPlace(), ctx.op().Input("Out"));
T
Tomasz Patejko 已提交
120

J
Jacek Czaja 已提交
121 122 123 124
    auto src_memory = handler.AcquireSrcMemory(x);
    auto workspace = handler.AcquireBackwardWorkspaceMemory(mid);
    auto diff_dst_memory = handler.AcquireDiffDstMemory(out_grad);
    auto diff_src_memory = handler.AcquireDiffSrcMemory(x_grad);
T
Tomasz Patejko 已提交
125

J
Jacek Czaja 已提交
126 127
    auto lrn_bwd = handler.AcquireBackwardPrimitive(
        *src_memory, *diff_dst_memory, *workspace, *diff_src_memory);
T
Tomasz Patejko 已提交
128

129
    std::vector<mkldnn::primitive> pipeline = {*lrn_bwd};
T
Tomasz Patejko 已提交
130
    mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();
131 132 133 134 135 136 137 138

    auto output_format =
        (mkldnn::memory::format)diff_src_memory->get_primitive_desc()
            .desc()
            .data.format;

    x_grad->set_layout(framework::DataLayout::kMKLDNN);
    x_grad->set_format(output_format);
T
Tomasz Patejko 已提交
139 140 141 142 143 144 145 146 147 148 149
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_KERNEL(lrn, MKLDNN, paddle::platform::CPUPlace,
                   ops::LRNMKLDNNOpKernel<float>);
REGISTER_OP_KERNEL(lrn_grad, MKLDNN, paddle::platform::CPUPlace,
                   ops::LRNMKLDNNGradOpKernel<float>);