lrn_mkldnn_op.cc 6.6 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 41 42 43 44 45
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "MKLDNN LRN must use CPUPlace.");

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

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

    auto input_data = x->data<T>();
    auto output_data = out->mutable_data<T>(ctx.GetPlace());
    mid->mutable_data<T>(ctx.GetPlace());

    const int n = ctx.Attr<int>("n");
46 47 48 49 50 51
    // 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)
52
    const float alpha = ctx.Attr<float>("alpha") * static_cast<float>(n);
T
Tomasz Patejko 已提交
53 54 55 56 57 58
    const float beta = ctx.Attr<float>("beta");
    const float k = ctx.Attr<float>("k");

    auto e_mid = framework::EigenTensor<T, 4>::From(*mid);
    e_mid = e_mid.constant(k);

59
    auto dims = paddle::framework::vectorize<int>(x->dims());
60

61 62 63 64
    // Format and dims are assumed to be the same for dst and src
    auto md = paddle::platform::MKLDNNMemDesc(
        dims, platform::MKLDNNGetDataType<T>(), x->format());

65
    const std::string key = platform::CreateKey(
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        dims, n, alpha, beta, k, x->format(), ctx.op().Output("Out"));

    platform::LRNMKLDNNHandler handler(ctx.Attr<bool>("is_test"), dev_ctx,
                                       mkldnn_engine, key);
    auto src_memory =
        handler.AcquireSrcMemory(md, platform::to_void_cast<T>(input_data));

    // TODO(jczaja): Hide getting PD inside of handler for all Acquire API
    handler.AcquireLRNPrimitiveDescriptor(md, n, alpha, beta, k);

    auto dst_memory =
        handler.AcquireDstMemory(md, platform::to_void_cast<T>(output_data));

    auto lrn_p = handler.AcquireLRN(dst_memory, src_memory);

    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 已提交
91 92 93 94 95 96 97
  }
};

template <typename T>
class LRNMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
M
minqiyang 已提交
98 99
    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 已提交
100 101
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "MKLDNN LRN must use CPUPlace.");
102 103 104
    PADDLE_ENFORCE(
        !ctx.Attr<bool>("is_test"),
        "is_test attribute should be set to False in training phase.");
T
Tomasz Patejko 已提交
105 106 107 108 109 110 111

    auto x = ctx.Input<Tensor>("X");

    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");
112
    const float alpha = ctx.Attr<float>("alpha") * static_cast<float>(n);
T
Tomasz Patejko 已提交
113 114 115 116 117 118 119 120 121
    const float beta = ctx.Attr<float>("beta");
    const float k = ctx.Attr<float>("k");

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

    auto x_grad_data = x_grad->mutable_data<T>(ctx.GetPlace());
    auto out_grad_data = out_grad->data<T>();

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

124
    const std::string key = platform::CreateKey(
125
        dims, n, alpha, beta, k, x->format(), ctx.op().Input("Out"));
T
Tomasz Patejko 已提交
126

127
    platform::LRNMKLDNNHandler handler(false, dev_ctx, mkldnn_engine, key);
T
Tomasz Patejko 已提交
128

129 130
    auto src_md = paddle::platform::MKLDNNMemDesc(
        dims, platform::MKLDNNGetDataType<T>(), x->format());
T
Tomasz Patejko 已提交
131

132 133 134
    // diff_dst and diff_src layouts are assumed to be the same
    auto diff_md = paddle::platform::MKLDNNMemDesc(
        dims, platform::MKLDNNGetDataType<T>(), out_grad->format());
T
Tomasz Patejko 已提交
135

136
    auto workspace = handler.AcquireWorkspaceMemory();
T
Tomasz Patejko 已提交
137

138 139
    auto diff_dst_memory = handler.AcquireDiffDstMemory(
        diff_md, platform::to_void_cast<T>(out_grad_data));
T
Tomasz Patejko 已提交
140

141 142
    auto diff_src_memory = handler.AcquireDiffSrcMemory(
        diff_md, platform::to_void_cast<T>(x_grad_data));
T
Tomasz Patejko 已提交
143

144 145
    auto src_memory = handler.AcquireSrcMemory(
        src_md, platform::to_void_cast<T>(x->data<T>()));
T
Tomasz Patejko 已提交
146

147 148 149
    // TODO(jczaja): Hide this call inside Handler
    handler.AcquireLRNBackwardPrimitiveDescriptor(src_md, diff_md, n, alpha,
                                                  beta, k);
T
Tomasz Patejko 已提交
150

151 152
    auto lrn_bwd = handler.AcquireLRNBackward(src_memory, diff_dst_memory,
                                              workspace, diff_src_memory);
T
Tomasz Patejko 已提交
153

154
    std::vector<mkldnn::primitive> pipeline = {*lrn_bwd};
T
Tomasz Patejko 已提交
155
    mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();
156 157 158 159 160 161 162 163

    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 已提交
164 165 166 167 168 169 170 171 172 173 174
  }
};
}  // 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>);