lrn_mkldnn_op.cc 7.9 KB
Newer Older
T
Tomasz Patejko 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

15
#include "paddle/fluid/platform/mkldnn_reuse.h"
T
Tomasz Patejko 已提交
16 17 18 19 20 21 22

namespace paddle {
namespace operators {

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

23
template <typename T>
24
class LRNMKLDNNHandler
25 26
    : public platform::MKLDNNHandlerNoCachingT<T, dnnl::lrn_forward,
                                               dnnl::lrn_backward> {
27 28
 public:
  LRNMKLDNNHandler(const framework::ExecutionContext& ctx,
29 30
                   const dnnl::engine mkldnn_engine, platform::Place cpu_place,
                   const Tensor* input)
31

32 33 34
      : platform::MKLDNNHandlerNoCachingT<T, dnnl::lrn_forward,
                                          dnnl::lrn_backward>(mkldnn_engine,
                                                              cpu_place) {
35 36 37 38 39 40 41 42 43 44 45 46 47
    const int n = ctx.Attr<int>("n");
    // 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)
    const float alpha = ctx.Attr<float>("alpha") * static_cast<float>(n);
    const float beta = ctx.Attr<float>("beta");
    const float k = ctx.Attr<float>("k");
    bool is_test = ctx.Attr<bool>("is_test");

    this->AcquireForwardPrimitiveDescriptor(
48 49
        is_test ? dnnl::prop_kind::forward_inference
                : dnnl::prop_kind::forward_training,
50 51
        dnnl::algorithm::lrn_across_channels, input->mem_desc(), n, alpha, beta,
        k);
52 53 54
  }

  LRNMKLDNNHandler(const framework::ExecutionContext& ctx,
55 56 57 58 59 60
                   const dnnl::engine mkldnn_engine, platform::Place cpu_place,
                   const Tensor* in_x, const Tensor* out_grad,
                   Tensor* in_x_grad)
      : platform::MKLDNNHandlerNoCachingT<T, dnnl::lrn_forward,
                                          dnnl::lrn_backward>(mkldnn_engine,
                                                              cpu_place) {
61 62 63 64 65 66 67 68 69 70 71
    PADDLE_ENFORCE_EQ(
        ctx.Attr<bool>("is_test"), false,
        platform::errors::PreconditionNotMet(
            "is_test attribute should be set to False in training phase."));

    const int n = ctx.Attr<int>("n");
    const float alpha = ctx.Attr<float>("alpha") * static_cast<float>(n);
    const float beta = ctx.Attr<float>("beta");
    const float k = ctx.Attr<float>("k");

    this->AcquireForwardPrimitiveDescriptor(
72
        dnnl::prop_kind::forward_training, dnnl::algorithm::lrn_across_channels,
73
        in_x->mem_desc(), n, alpha, beta, k);
74 75

    this->AcquireBackwardPrimitiveDescriptor(
76 77
        dnnl::algorithm::lrn_across_channels, in_x->mem_desc(),
        out_grad->mem_desc(), n, alpha, beta, k);
78 79
  }

80
  std::shared_ptr<dnnl::memory> AcquireWorkspaceMemory(Tensor* workspace) {
81 82 83
    T* ptr = workspace->mutable_data<T>(
        this->place_, this->fwd_pd_->workspace_desc().get_size());
    return this->AcquireMemoryFromPrimitive(this->fwd_pd_->workspace_desc(),
84
                                            ptr);
85 86
  }

87
  std::shared_ptr<dnnl::memory> AcquireBackwardWorkspaceMemory(
88 89 90 91
      const Tensor* workspace) {
    const T* workspace_data = workspace->data<T>();
    return this->AcquireMemoryFromPrimitive(
        this->fwd_pd_->workspace_desc(),
92
        platform::to_void_cast<T>(workspace_data));
93 94 95
  }
};

T
Tomasz Patejko 已提交
96 97 98 99
template <typename T>
class LRNMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
M
minqiyang 已提交
100
    const bool is_float_type = std::is_same<T, float>::value;
101 102 103 104 105 106
    PADDLE_ENFORCE_EQ(
        is_float_type, true,
        platform::errors::PreconditionNotMet("DNNL LRN must use float data."));
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL LRN must use CPUPlace"));
107 108 109
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();
T
Tomasz Patejko 已提交
110 111 112 113 114

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

115
    LRNMKLDNNHandler<T> handler(ctx, mkldnn_engine, ctx.GetPlace(), x);
J
Jacek Czaja 已提交
116 117 118 119

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

A
Adam 已提交
120 121 122 123 124
    auto lrn_p = handler.AcquireForwardPrimitive();

    auto workspace_memory = handler.AcquireWorkspaceMemory(mid);
    mid->set_layout(framework::DataLayout::kMKLDNN);

125
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
126
    if (!workspace_memory->get_desc().is_zero()) {
127
      mid->set_format(platform::GetMKLDNNFormat(*workspace_memory));
128 129 130
      lrn_p->execute(astream, {{DNNL_ARG_SRC, *src_memory},
                               {DNNL_ARG_DST, *dst_memory},
                               {DNNL_ARG_WORKSPACE, *workspace_memory}});
J
Jacek Czaja 已提交
131
    } else {
132 133
      lrn_p->execute(
          astream, {{DNNL_ARG_SRC, *src_memory}, {DNNL_ARG_DST, *dst_memory}});
A
Adam 已提交
134 135
    }
    astream.wait();
136 137

    out->set_layout(framework::DataLayout::kMKLDNN);
A
Adam 已提交
138
    out->set_format(platform::GetMKLDNNFormat(*dst_memory));
T
Tomasz Patejko 已提交
139 140 141 142 143 144 145
  }
};

template <typename T>
class LRNMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
M
minqiyang 已提交
146
    const bool is_float_type = std::is_same<T, float>::value;
147 148
    PADDLE_ENFORCE_EQ(is_float_type, true,
                      platform::errors::PreconditionNotMet(
J
Jacek Czaja 已提交
149
                          "DNNL LRN GradOpKernel must use float data."));
150 151 152
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL LRNGrad must use CPUPlace"));
T
Tomasz Patejko 已提交
153

154
    auto in_x = ctx.Input<Tensor>("X");
J
Jacek Czaja 已提交
155
    auto mid = ctx.Input<Tensor>("MidOut");
T
Tomasz Patejko 已提交
156 157

    auto out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
158
    auto in_x_grad = ctx.Output<Tensor>(framework::GradVarName("X"));
T
Tomasz Patejko 已提交
159 160

    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
161
    const auto& mkldnn_engine = dev_ctx.GetEngine();
T
Tomasz Patejko 已提交
162

163 164
    LRNMKLDNNHandler<T> handler(ctx, mkldnn_engine, ctx.GetPlace(), in_x,
                                out_grad, in_x_grad);
T
Tomasz Patejko 已提交
165

166
    auto src_memory = handler.AcquireSrcMemory(in_x);
J
Jacek Czaja 已提交
167 168
    auto workspace = handler.AcquireBackwardWorkspaceMemory(mid);
    auto diff_dst_memory = handler.AcquireDiffDstMemory(out_grad);
169
    auto diff_src_memory = handler.AcquireDiffSrcMemory(in_x_grad);
T
Tomasz Patejko 已提交
170

A
Adam 已提交
171
    auto lrn_bwd = handler.AcquireBackwardPrimitive();
T
Tomasz Patejko 已提交
172

173
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
174 175 176 177
    lrn_bwd->execute(astream, {{DNNL_ARG_SRC, *src_memory},
                               {DNNL_ARG_DIFF_DST, *diff_dst_memory},
                               {DNNL_ARG_DIFF_SRC, *diff_src_memory},
                               {DNNL_ARG_WORKSPACE, *workspace}});
A
Adam 已提交
178
    astream.wait();
179

180 181
    in_x_grad->set_layout(framework::DataLayout::kMKLDNN);
    in_x_grad->set_format(platform::GetMKLDNNFormat(*diff_src_memory));
T
Tomasz Patejko 已提交
182 183 184 185 186 187 188 189 190 191 192
  }
};
}  // 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>);