pool_mkldnn_op.cc 19.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

X
xiaoli.liu@intel.com 已提交
15
#include "paddle/fluid/framework/data_layout_transform.h"
16 17
#include "paddle/fluid/operators/pool_op.h"
#include "paddle/fluid/platform/mkldnn_helper.h"
18
#include "paddle/fluid/platform/mkldnn_reuse.h"
19 20 21 22

namespace paddle {
namespace operators {

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

// Generate keys for storing/retriving primitives for this operator
33 34 35 36 37 38
std::string CreateKey(const paddle::framework::ExecutionContext& ctx,
                      const memory::dims& input_dims,
                      const std::string& pooling_type,
                      const std::vector<int>& ksize,
                      const std::vector<int>& strides,
                      const std::vector<int>& paddings,
39 40
                      const memory::data_type& dt, const memory::format& fmt,
                      const std::string& suffix) {
41 42 43 44 45 46 47 48
  std::string key;
  key.reserve(platform::MKLDNNHandler::MaxKeyLength);
  platform::MKLDNNHandler::AppendKeyDims(&key, input_dims);
  platform::MKLDNNHandler::AppendKey(&key, pooling_type);
  platform::MKLDNNHandler::AppendKeyVec(&key, ksize);
  platform::MKLDNNHandler::AppendKeyVec(&key, strides);
  platform::MKLDNNHandler::AppendKeyVec(&key, paddings);
  platform::MKLDNNHandler::AppendKey(&key, std::to_string(dt));
49
  platform::MKLDNNHandler::AppendKey(&key, std::to_string(fmt));
50
  platform::MKLDNNHandler::AppendKey(&key, suffix);
51 52 53 54 55 56 57
  if (platform::get_cur_thread_id() != -1) {
    auto tid = std::this_thread::get_id();
    std::stringstream ss;
    ss << tid;
    platform::MKLDNNHandler::AppendKey(&key, "-t:");
    platform::MKLDNNHandler::AppendKey(&key, ss.str());
  }
58
  return key;
59 60
}

61 62
static inline int ComputeCeiledOutput(int input_size, int kernel_size,
                                      int padding, int stride) {
63 64 65
  return (input_size - kernel_size + 2 * padding) / stride + 1;
}

66 67 68 69 70 71
static inline void CorrectOutputSize(
    const std::vector<int>& src_tz, const std::vector<int>& dst_tz,
    const std::vector<int>& kernel_size, const std::vector<int>& paddings,
    const std::vector<int>& strides,
    std::vector<int>& right_bot_padding) {  // NOLINT
  for (size_t i = 0; i < right_bot_padding.size(); i++) {
72 73 74 75 76 77 78 79
    int desired_size = ComputeCeiledOutput(src_tz[i + 2], kernel_size[i],
                                           paddings[i], strides[i]);
    if (desired_size != dst_tz[i + 2]) {
      right_bot_padding[i] += strides[i];
    }
  }
}

80 81 82 83 84 85 86 87 88 89 90 91 92
template <typename T>
class PoolMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "It must use CPUPlace.");
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();

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

93 94 95
    PADDLE_ENFORCE(input->layout() == DataLayout::kMKLDNN &&
                       input->format() != memory::format::format_undef,
                   "Wrong layout/format set for Input tensor");
96 97 98 99 100

    std::string pooling_type = ctx.Attr<std::string>("pooling_type");
    std::vector<int> ksize = ctx.Attr<std::vector<int>>("ksize");
    std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
101
    bool is_test = ctx.Attr<bool>("is_test");
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    if (ctx.Attr<bool>("global_pooling")) {
      for (size_t i = 0; i < ksize.size(); ++i) {
        paddings[i] = 0;
        ksize[i] = static_cast<int>(input->dims()[i + 2]);
      }
    }

    // Only 2D pooling is supported now
    PADDLE_ENFORCE(ksize.size() == 2, "ksize must be 2D, i.e. 2D pooling");
    PADDLE_ENFORCE(pooling_type == "max" || pooling_type == "avg",
                   "pooling_type must be 'max' or 'avg'");
    PADDLE_ENFORCE(input->dims().size() == 4,
                   "Input dim must be with 4, i.e. NCHW");

    const T* input_data = input->data<T>();
    T* output_data = output->mutable_data<T>(ctx.GetPlace());

    std::vector<int> src_tz = paddle::framework::vectorize2int(input->dims());
    std::vector<int> dst_tz = paddle::framework::vectorize2int(output->dims());

122 123 124
    auto input_format = input->format();
    memory::format output_format{memory::format::format_undef};

125 126
    mkldnn::memory::data_type dt =
        paddle::framework::ToMKLDNNDataType(input->type());
127 128 129 130
    auto fmt = input->format();
    const std::string key =
        CreateKey(ctx, src_tz, pooling_type, ksize, strides, paddings, dt, fmt,
                  ctx.op().Output("Out"));
131 132 133 134 135 136
    const std::string key_pool_p = key + "@pool_p";
    const std::string key_pool_pd = key + "@pool_pd";
    const std::string key_pool_src_mem_p = key + "@pool_src_mem_p";
    const std::string key_pool_dst_mem_p = key + "@pool_dst_mem_p";
    const std::string key_pool_workspace_memory =
        key + "@pool_workspace_memory";
137

138 139 140 141
    std::shared_ptr<mkldnn::memory> src_memory, dst_memory;
    std::shared_ptr<mkldnn::pooling_forward::primitive_desc> pool_pd;
    std::shared_ptr<mkldnn::memory> pool_src_memory_p, pool_dst_memory_p;

142 143 144
    auto pool_p =
        std::static_pointer_cast<pooling_forward>(dev_ctx.GetBlob(key_pool_p));
    if (pool_p == nullptr) {
145 146 147 148 149 150 151
      const std::vector<int>& padding_left_top(paddings);
      std::vector<int> padding_right_bottom(paddings);
      bool ceil_mode = ctx.Attr<bool>("ceil_mode");
      if (ceil_mode) {
        CorrectOutputSize(src_tz, dst_tz, ksize, paddings, strides,
                          padding_right_bottom);
      }
X
xiaoli.liu@intel.com 已提交
152 153

      auto src_md = platform::MKLDNNMemDesc(src_tz, dt, input_format);
154

155 156 157 158
      /* create memory descriptor for pooling without specified format
       * ('any') which lets a primitive (pooling in this case) choose
       * the memory format preferred for best performance
       */
X
xiaoli.liu@intel.com 已提交
159 160 161 162 163
      auto dst_md =
          platform::MKLDNNMemDesc(dst_tz, dt, mkldnn::memory::format::any);
      auto propagation = src_md.data.data_type == mkldnn_f32
                             ? mkldnn::prop_kind::forward_training
                             : mkldnn::prop_kind::forward_scoring;
164
      std::shared_ptr<mkldnn::pooling_forward::primitive_desc> pool_pd =
X
xiaoli.liu@intel.com 已提交
165 166 167
          CreatePrimitiveDesc(src_md, dst_md, propagation, strides,
                              padding_left_top, padding_right_bottom, ksize,
                              pooling_type, mkldnn_engine, ceil_mode, is_test);
168 169

      // save pool_pd into global device context to be referred in backward path
170
      if (!is_test) dev_ctx.SetBlob(key_pool_pd, pool_pd);
171

172 173 174
      src_memory = std::make_shared<memory>(pool_pd->src_primitive_desc(),
                                            to_void_cast<T>(input_data));
      dst_memory =
175
          std::make_shared<memory>(pool_pd->dst_primitive_desc(), output_data);
176

177 178 179
      dev_ctx.SetBlob(key_pool_src_mem_p, src_memory);
      dev_ctx.SetBlob(key_pool_dst_mem_p, dst_memory);

180 181 182 183 184 185 186 187 188 189 190 191 192
      if (is_test) {
        pool_p = std::make_shared<pooling_forward>(*pool_pd, *src_memory,
                                                   *dst_memory);
      } else {
        std::shared_ptr<mkldnn::memory> workspace_memory =
            CreateWorkspaceMemory(pool_pd, pooling_type, mkldnn_engine);

        // save pool_workspace_memory to be referred in backward path
        dev_ctx.SetBlob(key_pool_workspace_memory, workspace_memory);

        pool_p = std::make_shared<pooling_forward>(
            *pool_pd, *src_memory, *dst_memory, *workspace_memory);
      }
193 194

      dev_ctx.SetBlob(key_pool_p, pool_p);
195 196 197

      output_format =
          (memory::format)dst_memory->get_primitive_desc().desc().data.format;
198 199
    } else {
      // Primitives already exist
200
      pool_src_memory_p =
201 202 203
          std::static_pointer_cast<memory>(dev_ctx.GetBlob(key_pool_src_mem_p));
      PADDLE_ENFORCE(pool_src_memory_p != nullptr,
                     "Fail to find pooling src mem_p in device context");
204
      pool_dst_memory_p =
205 206 207
          std::static_pointer_cast<memory>(dev_ctx.GetBlob(key_pool_dst_mem_p));
      PADDLE_ENFORCE(pool_dst_memory_p != nullptr,
                     "Fail to find pooling dst mem_p in device context");
208
      pool_src_memory_p->set_data_handle(to_void_cast<T>(input_data));
209
      pool_dst_memory_p->set_data_handle(output_data);
210 211 212 213

      output_format = (memory::format)pool_dst_memory_p->get_primitive_desc()
                          .desc()
                          .data.format;
214
    }
215 216

    // push primitive to stream and wait until it's executed
217
    std::vector<mkldnn::primitive> pipeline{*pool_p};
218 219 220 221
    stream(stream::kind::eager).submit(pipeline).wait();

    output->set_layout(DataLayout::kMKLDNN);
    output->set_format(output_format);
222 223 224 225 226
  }

 private:
  std::unique_ptr<mkldnn::pooling_forward::primitive_desc> CreatePrimitiveDesc(
      const mkldnn::memory::desc& src, const mkldnn::memory::desc& dst,
X
xiaoli.liu@intel.com 已提交
227 228
      const mkldnn::prop_kind& propagation, const std::vector<int>& stride,
      const std::vector<int>& padding_left_top,
229 230
      const std::vector<int>& padding_right_bot, const std::vector<int>& kernel,
      const std::string& pooling_type, const mkldnn::engine& engine,
231 232 233 234
      bool ceil_mode, bool is_test) const {
    auto mkldnn_forward_prop_kind = is_test
                                        ? mkldnn::prop_kind::forward_inference
                                        : mkldnn::prop_kind::forward_training;
235
    auto pool_desc = mkldnn::pooling_forward::desc(
236
        mkldnn_forward_prop_kind,
237 238
        pooling_type == "max" ? mkldnn::algorithm::pooling_max
                              : mkldnn::algorithm::pooling_avg,
239 240
        src, dst, stride, kernel, padding_left_top, padding_right_bot,
        mkldnn::padding_kind::zero);
241 242 243 244 245 246 247 248 249 250 251 252

    auto p_pool_pd =
        new mkldnn::pooling_forward::primitive_desc(pool_desc, engine);
    return std::unique_ptr<mkldnn::pooling_forward::primitive_desc>(p_pool_pd);
  }

  std::unique_ptr<mkldnn::memory> CreateWorkspaceMemory(
      std::shared_ptr<mkldnn::pooling_forward::primitive_desc> pool_pd,
      const std::string& pooling_type, const mkldnn::engine& engine) const {
    mkldnn::memory::primitive_desc workspace_md =
        pooling_type == "max"
            ? pool_pd->workspace_primitive_desc()
253 254 255 256
            : mkldnn::memory::primitive_desc({{},
                                              platform::MKLDNNGetDataType<T>(),
                                              mkldnn::memory::format::nchw},
                                             engine);
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

    auto p_workspace_memory = new mkldnn::memory(workspace_md);
    return std::unique_ptr<mkldnn::memory>(p_workspace_memory);
  }
};

template <typename T>
class PoolMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "It must use CPUPlace.");

    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"));

274 275 276 277 278 279 280
    PADDLE_ENFORCE(in_x->layout() == DataLayout::kMKLDNN &&
                       in_x->format() != memory::format::format_undef,
                   "Wrong layout/format set for Input X tensor");
    PADDLE_ENFORCE(out_grad->layout() == DataLayout::kMKLDNN &&
                       out_grad->format() != memory::format::format_undef,
                   "Wrong layout/format set for Input output_grad tensor");

281 282 283 284
    PADDLE_ENFORCE(
        !ctx.Attr<bool>("is_test"),
        "is_test attribute should be set to False in training phase.");

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    std::string pooling_type = ctx.Attr<std::string>("pooling_type");
    std::vector<int> ksize = ctx.Attr<std::vector<int>>("ksize");
    std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");

    if (ctx.Attr<bool>("global_pooling")) {
      for (size_t i = 0; i < ksize.size(); ++i) {
        paddings[i] = 0;
        ksize[i] = static_cast<int>(in_x->dims()[i + 2]);
      }
    }

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

    const T* out_grad_data = out_grad->data<T>();
    T* in_x_grad_data = in_x_grad->mutable_data<T>(ctx.GetPlace());
303
    memory::format in_x_grad_format{memory::format::format_undef};
304 305 306 307 308 309

    std::vector<int> diff_src_tz =
        paddle::framework::vectorize2int(in_x_grad->dims());
    std::vector<int> diff_dst_tz =
        paddle::framework::vectorize2int(out_grad->dims());

310 311
    // Get an unique name from "argument" name of "Out" variable
    // This name will be used as key when referring info from device context
312 313 314
    const std::string key = CreateKey(ctx, diff_src_tz, pooling_type, ksize,
                                      strides, paddings, memory::data_type::f32,
                                      in_x->format(), ctx.op().Input("Out"));
315 316 317
    const std::string key_pool_bwd_p = key + "@pool_bwd_p";
    const std::string key_pool_diff_src_mem_p = key + "@pool_diff_src_mem_p";
    const std::string key_pool_diff_dst_mem_p = key + "@pool_diff_dst_mem_p";
318 319
    const std::string key_pool_src_mem_p = key + "@pool_src_mem_p";
    const std::string key_pool_dst_mem_p = key + "@pool_dst_mem_p";
320 321 322
    const std::string key_pool_pd = key + "@pool_pd";
    const std::string key_pool_workspace_memory =
        key + "@pool_workspace_memory";
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337
    auto user_diff_dst_memory =
        memory({{{diff_dst_tz}, memory::data_type::f32, out_grad->format()},
                mkldnn_engine},
               to_void_cast<T>(out_grad_data));

    std::shared_ptr<memory> diff_src_memory;
    std::shared_ptr<memory> diff_dst_memory;
    auto dst_memory =
        std::static_pointer_cast<memory>(dev_ctx.GetBlob(key_pool_dst_mem_p));
    PADDLE_ENFORCE(dst_memory != nullptr,
                   "Fail to find dst_memory in device context");

    primitive reorder_diff_dst;
    bool is_diff_dst_reordered = false;
338 339 340
    auto pool_bwd_p = std::static_pointer_cast<pooling_backward>(
        dev_ctx.GetBlob(key_pool_bwd_p));
    if (pool_bwd_p == nullptr) {
341 342 343 344 345
      // Retrieve src_memory/dst_memory saved in forward pass
      auto src_memory =
          std::static_pointer_cast<memory>(dev_ctx.GetBlob(key_pool_src_mem_p));
      PADDLE_ENFORCE(src_memory != nullptr,
                     "Fail to find src_memory in device context");
346 347 348 349 350 351
      // Retrieve pool_pd/pool_workspace_memory from device context
      auto pool_pd =
          std::static_pointer_cast<mkldnn::pooling_forward::primitive_desc>(
              dev_ctx.GetBlob(key_pool_pd));
      PADDLE_ENFORCE(pool_pd != nullptr,
                     "Fail to find pool_pd in device context");
352
      auto workspace_memory = std::static_pointer_cast<memory>(
353 354 355 356
          dev_ctx.GetBlob(key_pool_workspace_memory));
      PADDLE_ENFORCE(workspace_memory != nullptr,
                     "Fail to find workspace_memory in device context");

357 358 359
      // create memory descriptors for pooling
      auto diff_src_md = src_memory.get()->get_primitive_desc().desc();
      auto diff_dst_md = dst_memory.get()->get_primitive_desc().desc();
360 361 362 363 364 365 366 367 368

      auto pool_bwd_desc = mkldnn::pooling_backward::desc(
          pooling_type == "max" ? mkldnn::algorithm::pooling_max
                                : mkldnn::algorithm::pooling_avg,
          diff_src_md, diff_dst_md, strides, ksize, paddings, paddings,
          mkldnn::padding_kind::zero);
      auto pool_bwd_pd = mkldnn::pooling_backward::primitive_desc(
          pool_bwd_desc, mkldnn_engine, *pool_pd);

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
      // reorder between user_diff_dst and pool diff_dst if needed
      diff_dst_memory = std::make_shared<memory>(user_diff_dst_memory);
      if (memory::primitive_desc(dst_memory->get_primitive_desc()) !=
          user_diff_dst_memory.get_primitive_desc()) {
        diff_dst_memory =
            std::make_shared<memory>(dst_memory.get()->get_primitive_desc());
        reorder_diff_dst = reorder(user_diff_dst_memory, *diff_dst_memory);
        is_diff_dst_reordered = true;
      }

      diff_src_memory = std::make_shared<memory>(
          pool_bwd_pd.diff_src_primitive_desc(), in_x_grad_data);

      dev_ctx.SetBlob(key_pool_diff_src_mem_p, diff_src_memory);
      dev_ctx.SetBlob(key_pool_diff_dst_mem_p, diff_dst_memory);

385
      pool_bwd_p = std::make_shared<pooling_backward>(
386
          pool_bwd_pd, *diff_dst_memory, *workspace_memory, *diff_src_memory);
387
      dev_ctx.SetBlob(key_pool_bwd_p, pool_bwd_p);
388

389 390
    } else {
      // Primitives already exist
391
      diff_src_memory = std::static_pointer_cast<memory>(
392
          dev_ctx.GetBlob(key_pool_diff_src_mem_p));
393
      PADDLE_ENFORCE(diff_src_memory != nullptr,
394
                     "Fail to find pooling src mem_p in device context");
395
      diff_dst_memory = std::static_pointer_cast<memory>(
396
          dev_ctx.GetBlob(key_pool_diff_dst_mem_p));
397
      PADDLE_ENFORCE(diff_dst_memory != nullptr,
398
                     "Fail to find pooling dst mem_p in device context");
399 400 401 402 403 404 405 406 407 408 409 410

      diff_src_memory->set_data_handle(reinterpret_cast<void*>(in_x_grad_data));
      diff_dst_memory->set_data_handle(const_cast<T*>(out_grad_data));

      // reorder between user_diff_dst and pool diff_dst if needed
      if (memory::primitive_desc(dst_memory->get_primitive_desc()) !=
          user_diff_dst_memory.get_primitive_desc()) {
        diff_dst_memory =
            std::make_shared<memory>(dst_memory.get()->get_primitive_desc());
        reorder_diff_dst = reorder(user_diff_dst_memory, *diff_dst_memory);
        is_diff_dst_reordered = true;
      }
411
    }
412

413 414 415 416
    in_x_grad_format = (memory::format)diff_src_memory->get_primitive_desc()
                           .desc()
                           .data.format;

417
    // push primitive to stream and wait until it's executed
418 419 420 421
    std::vector<mkldnn::primitive> pipeline;
    if (is_diff_dst_reordered) {
      pipeline.push_back(reorder_diff_dst);
    }
422
    pipeline.push_back(*pool_bwd_p);
423
    mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();
424 425 426

    in_x_grad->set_layout(DataLayout::kMKLDNN);
    in_x_grad->set_format(in_x_grad_format);
427 428 429 430 431 432
  }  // Compute()
};

}  // namespace operators
}  // namespace paddle

433 434
namespace ops = paddle::operators;

435
REGISTER_OP_KERNEL(pool2d, MKLDNN, ::paddle::platform::CPUPlace,
X
xiaoli.liu@intel.com 已提交
436 437 438 439
                   ops::PoolMKLDNNOpKernel<float>,
                   ops::PoolMKLDNNOpKernel<int8_t>,
                   ops::PoolMKLDNNOpKernel<uint8_t>);

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