pool_mkldnn_op.cc 7.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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/operators/pool_op.h"
#include "paddle/fluid/platform/mkldnn_helper.h"
17
#include "paddle/fluid/platform/mkldnn_reuse.h"
18 19 20 21

namespace paddle {
namespace operators {

22 23
using framework::DataLayout;
using mkldnn::memory;
24
using mkldnn::pooling_backward;
25 26 27 28 29
using mkldnn::pooling_forward;
using mkldnn::primitive;
using mkldnn::reorder;
using mkldnn::stream;
using platform::to_void_cast;
30

31 32 33 34
template <typename T>
class PoolMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
35 36 37
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL Pool must use CPUPlace"));
38 39
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
40
    const auto& mkldnn_engine = dev_ctx.GetEngine();
41 42 43 44

    const Tensor* input = ctx.Input<Tensor>("X");
    Tensor* output = ctx.Output<Tensor>("Out");

45 46 47
    platform::PoolingMKLDNNHandler<T> handler(ctx, dev_ctx, mkldnn_engine,
                                              ctx.GetPlace(), input, output,
                                              ctx.OutputName("Out"));
48 49 50 51

    auto src_memory = handler.AcquireSrcMemory(input);
    auto dst_memory = handler.AcquireDstMemory(output);

A
Adam 已提交
52
    auto pool_p = handler.AcquireForwardPrimitive();
53

A
Adam 已提交
54
    mkldnn::stream astream(dev_ctx.GetEngine());
55 56
    if ((ctx.Attr<bool>("is_test") == false) &&
        (ctx.Attr<std::string>("pooling_type") == "max")) {
57
      // Training
A
Adam 已提交
58 59 60 61
      auto workspace_memory = handler.AcquireWorkspaceMemory();
      pool_p->execute(astream, {{MKLDNN_ARG_SRC, *src_memory},
                                {MKLDNN_ARG_DST, *dst_memory},
                                {MKLDNN_ARG_WORKSPACE, *workspace_memory}});
62 63
    } else {
      // Inference
A
Adam 已提交
64 65
      pool_p->execute(astream, {{MKLDNN_ARG_SRC, *src_memory},
                                {MKLDNN_ARG_DST, *dst_memory}});
66
    }
A
Adam 已提交
67
    astream.wait();
68 69

    output->set_layout(DataLayout::kMKLDNN);
A
Adam 已提交
70
    output->set_format(platform::GetMKLDNNFormat(*dst_memory));
71 72 73 74 75 76 77
  }
};

template <typename T>
class PoolMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
78 79 80
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL PoolGrad must use CPUPlace"));
81 82 83 84
    const Tensor* in_x = ctx.Input<Tensor>("X");
    const Tensor* out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
    Tensor* in_x_grad = ctx.Output<Tensor>(framework::GradVarName("X"));

85 86 87 88 89 90
    PADDLE_ENFORCE_EQ(
        in_x->layout(), DataLayout::kMKLDNN,
        platform::errors::InvalidArgument("Wrong layout set for Input tensor"));
    PADDLE_ENFORCE_NE(
        in_x->format(), MKLDNNMemoryFormat::undef,
        platform::errors::InvalidArgument("Wrong format set for Input tensor"));
91

92
    PADDLE_ENFORCE_EQ(out_grad->layout(), DataLayout::kMKLDNN,
93 94
                      platform::errors::InvalidArgument(
                          "Wrong layout set for Input output_grad tensor"));
A
Adam 已提交
95
    PADDLE_ENFORCE_NE(out_grad->format(), MKLDNNMemoryFormat::undef,
96 97
                      platform::errors::InvalidArgument(
                          "Wrong format set for Input output_grad tensor"));
98 99 100

    PADDLE_ENFORCE_EQ(
        ctx.Attr<bool>("is_test"), false,
101 102
        platform::errors::InvalidArgument(
            "is_test attribute should be set to False in training phase."));
103

104
    std::string pooling_type = ctx.Attr<std::string>("pooling_type");
A
Adam 已提交
105 106 107 108 109 110 111 112 113 114

    std::vector<int> ksize_temp = ctx.Attr<std::vector<int>>("ksize");
    std::vector<int64_t> ksize(begin(ksize_temp), end(ksize_temp));

    std::vector<int> strides_temp = ctx.Attr<std::vector<int>>("strides");
    std::vector<int64_t> strides(begin(strides_temp), end(strides_temp));

    std::vector<int> paddings_temp = ctx.Attr<std::vector<int>>("paddings");
    std::vector<int64_t> paddings(begin(paddings_temp), end(paddings_temp));

115 116
    bool global_pooling = ctx.Attr<bool>("global_pooling");
    std::string padding_algorithm = ctx.Attr<std::string>("padding_algorithm");
117

118 119 120 121 122 123
    auto in_x_dims = in_x->dims();
    framework::DDim data_dims =
        framework::slice_ddim(in_x_dims, 2, in_x_dims.size());

    if (global_pooling) {
      UpdateKsize(&ksize, data_dims);
124 125
    }

126 127 128
    UpdatePadding(&paddings, global_pooling, 0, padding_algorithm, data_dims,
                  strides, ksize);

129 130 131
    platform::PoolingMKLDNNHandler<T>::ComputeAdaptivePoolParameters(
        ctx, paddle::framework::vectorize(in_x->dims()), ksize, strides);

132 133 134
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();

135 136
    std::vector<mkldnn::primitive> pipeline;

A
Adam 已提交
137 138
    auto diff_src_tz = paddle::framework::vectorize<int64_t>(in_x_grad->dims());
    auto diff_dst_tz = paddle::framework::vectorize<int64_t>(out_grad->dims());
139

140 141
    // Get an unique name from "argument" name of "Out" variable
    // This name will be used as key when referring info from device context
142
    const std::string key = platform::CreateKey(
143
        dev_ctx, diff_src_tz, pooling_type, ksize, strides, paddings,
H
hong 已提交
144
        memory::data_type::f32, in_x->format(), ctx.InputName("Out"));
145

146 147 148 149
    platform::PoolingMKLDNNHandler<T> handler(
        diff_dst_tz, diff_src_tz, ksize, strides, paddings, pooling_type,
        ctx.Attr<bool>("ceil_mode"), in_x->format(), out_grad->format(),
        paddle::framework::ToMKLDNNDataType(out_grad->type()), dev_ctx,
H
hong 已提交
150
        ctx.GetPlace(), ctx.InputName("Out"), ctx.Attr<bool>("exclusive"));
151 152 153 154

    auto diff_dst_memory = handler.AcquireDiffDstMemory(out_grad);
    auto diff_src_memory = handler.AcquireDiffSrcMemory(in_x_grad);

A
Adam 已提交
155
    auto pool_bwd_p = handler.AcquireBackwardPrimitive();
156

A
Adam 已提交
157
    mkldnn::stream astream(dev_ctx.GetEngine());
158 159
    if (pooling_type == "max") {
      // Max - pooling needs Workspace
A
Adam 已提交
160 161 162 163
      auto workspace_memory = handler.AcquireWorkspaceMemory();
      pool_bwd_p->execute(astream, {{MKLDNN_ARG_DIFF_SRC, *diff_src_memory},
                                    {MKLDNN_ARG_DIFF_DST, *diff_dst_memory},
                                    {MKLDNN_ARG_WORKSPACE, *workspace_memory}});
164 165
    } else {
      // Average Pooling
A
Adam 已提交
166 167
      pool_bwd_p->execute(astream, {{MKLDNN_ARG_DIFF_SRC, *diff_src_memory},
                                    {MKLDNN_ARG_DIFF_DST, *diff_dst_memory}});
168
    }
A
Adam 已提交
169
    astream.wait();
170 171

    in_x_grad->set_layout(DataLayout::kMKLDNN);
A
Adam 已提交
172
    in_x_grad->set_format(platform::GetMKLDNNFormat(*diff_src_memory));
173 174 175 176 177 178
  }  // Compute()
};

}  // namespace operators
}  // namespace paddle

179 180
namespace ops = paddle::operators;

181
REGISTER_OP_KERNEL(pool2d, MKLDNN, ::paddle::platform::CPUPlace,
X
xiaoli.liu@intel.com 已提交
182 183
                   ops::PoolMKLDNNOpKernel<float>,
                   ops::PoolMKLDNNOpKernel<int8_t>,
184 185
                   ops::PoolMKLDNNOpKernel<uint8_t>,
                   ops::PoolMKLDNNOpKernel<paddle::platform::bfloat16>);
X
xiaoli.liu@intel.com 已提交
186

187
REGISTER_OP_KERNEL(pool2d_grad, MKLDNN, ::paddle::platform::CPUPlace,
188
                   ops::PoolMKLDNNGradOpKernel<float>);