lrn_mkldnn_op.cc 8.8 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 24 25 26 27 28 29 30 31 32 33 34 35 36
template <typename T>
class LRNMKLDNNHandler : public platform::MKLDNNHandlerT<T, mkldnn::lrn_forward,
                                                         mkldnn::lrn_backward> {
 public:
  LRNMKLDNNHandler(const framework::ExecutionContext& ctx,
                   const MKLDNNDeviceContext& dev_ctx,
                   const mkldnn::engine mkldnn_engine,
                   platform::Place cpu_place, const Tensor* input,
                   const std::string& unique_name)

      : platform::MKLDNNHandlerT<T, mkldnn::lrn_forward, mkldnn::lrn_backward>(
            dev_ctx, mkldnn_engine, cpu_place,
            platform::CreateKey(dev_ctx, framework::vectorize(input->dims()),
                                unique_name)) {
37
    if (!this->isCached()) {
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
      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");

      auto dims = framework::vectorize(input->dims());

      auto src_md = mkldnn::memory::desc(dims, platform::MKLDNNGetDataType<T>(),
                                         input->format());

55
      this->AcquireForwardPrimitiveDescriptor(
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
          is_test ? mkldnn::prop_kind::forward_inference
                  : mkldnn::prop_kind::forward_training,
          mkldnn::algorithm::lrn_across_channels, src_md, n, alpha, beta, k);
    }
  }

  LRNMKLDNNHandler(const framework::ExecutionContext& ctx,
                   const MKLDNNDeviceContext& dev_ctx,
                   platform::Place cpu_place, const Tensor* in_x,
                   const Tensor* out_grad, Tensor* in_x_grad,
                   const std::string& unique_name)
      : platform::MKLDNNHandlerT<T, mkldnn::lrn_forward, mkldnn::lrn_backward>(
            dev_ctx, dev_ctx.GetEngine(), cpu_place,
            platform::CreateKey(dev_ctx, framework::vectorize(in_x->dims()),
                                unique_name)) {
    if (!this->isBwdCached()) {
      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");

      auto dims = framework::vectorize<int64_t>(in_x->dims());

      auto src_md = mkldnn::memory::desc(dims, platform::MKLDNNGetDataType<T>(),
                                         in_x->format());
      auto diff_md = mkldnn::memory::desc(
          dims, platform::MKLDNNGetDataType<T>(), out_grad->format());

89
      this->AcquireForwardPrimitiveDescriptor(
90 91 92
          mkldnn::prop_kind::forward_training,
          mkldnn::algorithm::lrn_across_channels, src_md, n, alpha, beta, k);

93
      this->AcquireBackwardPrimitiveDescriptor(
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
          mkldnn::algorithm::lrn_across_channels, src_md, diff_md, n, alpha,
          beta, k);
    }
  }

  std::shared_ptr<mkldnn::memory> AcquireWorkspaceMemory(Tensor* workspace) {
    T* ptr = workspace->mutable_data<T>(
        this->place_, this->fwd_pd_->workspace_desc().get_size());
    return this->AcquireMemoryFromPrimitive(this->fwd_pd_->workspace_desc(),
                                            ptr, "@wrk_mem_p");
  }

  std::shared_ptr<mkldnn::memory> AcquireBackwardWorkspaceMemory(
      const Tensor* workspace) {
    const T* workspace_data = workspace->data<T>();
    return this->AcquireMemoryFromPrimitive(
        this->fwd_pd_->workspace_desc(),
        platform::to_void_cast<T>(workspace_data), "@bwd-wrk_mem_p");
  }
};

T
Tomasz Patejko 已提交
115 116 117 118
template <typename T>
class LRNMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
M
minqiyang 已提交
119
    const bool is_float_type = std::is_same<T, float>::value;
120 121 122 123 124 125
    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"));
126 127 128
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();
T
Tomasz Patejko 已提交
129 130 131 132 133

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

134 135
    LRNMKLDNNHandler<T> handler(ctx, dev_ctx, mkldnn_engine, ctx.GetPlace(), x,
                                ctx.OutputName("Out"));
J
Jacek Czaja 已提交
136 137 138 139

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

A
Adam 已提交
140 141 142 143 144
    auto lrn_p = handler.AcquireForwardPrimitive();

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

145
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
146
    if (!workspace_memory->get_desc().is_zero()) {
147
      mid->set_format(platform::GetMKLDNNFormat(*workspace_memory));
A
Adam 已提交
148 149 150
      lrn_p->execute(astream, {{MKLDNN_ARG_SRC, *src_memory},
                               {MKLDNN_ARG_DST, *dst_memory},
                               {MKLDNN_ARG_WORKSPACE, *workspace_memory}});
J
Jacek Czaja 已提交
151
    } else {
A
Adam 已提交
152 153 154 155
      lrn_p->execute(astream, {{MKLDNN_ARG_SRC, *src_memory},
                               {MKLDNN_ARG_DST, *dst_memory}});
    }
    astream.wait();
156 157

    out->set_layout(framework::DataLayout::kMKLDNN);
A
Adam 已提交
158
    out->set_format(platform::GetMKLDNNFormat(*dst_memory));
T
Tomasz Patejko 已提交
159 160 161 162 163 164 165
  }
};

template <typename T>
class LRNMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
M
minqiyang 已提交
166
    const bool is_float_type = std::is_same<T, float>::value;
167 168
    PADDLE_ENFORCE_EQ(is_float_type, true,
                      platform::errors::PreconditionNotMet(
J
Jacek Czaja 已提交
169
                          "DNNL LRN GradOpKernel must use float data."));
170 171 172
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL LRNGrad must use CPUPlace"));
T
Tomasz Patejko 已提交
173

174
    auto in_x = ctx.Input<Tensor>("X");
J
Jacek Czaja 已提交
175
    auto mid = ctx.Input<Tensor>("MidOut");
T
Tomasz Patejko 已提交
176 177

    auto out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
178
    auto in_x_grad = ctx.Output<Tensor>(framework::GradVarName("X"));
T
Tomasz Patejko 已提交
179 180 181

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

182 183
    LRNMKLDNNHandler<T> handler(ctx, dev_ctx, ctx.GetPlace(), in_x, out_grad,
                                in_x_grad, ctx.InputName("Out"));
T
Tomasz Patejko 已提交
184

185
    auto src_memory = handler.AcquireSrcMemory(in_x);
J
Jacek Czaja 已提交
186 187
    auto workspace = handler.AcquireBackwardWorkspaceMemory(mid);
    auto diff_dst_memory = handler.AcquireDiffDstMemory(out_grad);
188
    auto diff_src_memory = handler.AcquireDiffSrcMemory(in_x_grad);
T
Tomasz Patejko 已提交
189

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

192
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
193 194 195 196 197
    lrn_bwd->execute(astream, {{MKLDNN_ARG_SRC, *src_memory},
                               {MKLDNN_ARG_DIFF_DST, *diff_dst_memory},
                               {MKLDNN_ARG_DIFF_SRC, *diff_src_memory},
                               {MKLDNN_ARG_WORKSPACE, *workspace}});
    astream.wait();
198

199 200
    in_x_grad->set_layout(framework::DataLayout::kMKLDNN);
    in_x_grad->set_format(platform::GetMKLDNNFormat(*diff_src_memory));
T
Tomasz Patejko 已提交
201 202 203 204 205 206 207 208 209 210 211
  }
};
}  // 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>);