mkldnn_helper.h 23.0 KB
Newer Older
1
/* Copyright (c) 2017 PaddlePaddle Authors. All Rights Reserved.
T
tensor-tang 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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. */
#pragma once

16
#include <algorithm>
J
Jacek Czaja 已提交
17
#include <iostream>
P
Physher 已提交
18
#include <memory>
J
Jacek Czaja 已提交
19
#include <sstream>
G
gongweibao 已提交
20
#include <string>
21
#include <utility>
22
#include <vector>
23

24
#include "dnnl.hpp"  // NOLINT
25
#include "paddle/fluid/framework/operator.h"
M
mozga-intel 已提交
26
#include "paddle/fluid/platform/place.h"
C
chenjian 已提交
27
#include "paddle/fluid/platform/profiler/event_tracing.h"
T
tensor-tang 已提交
28
namespace paddle {
29
#ifdef PADDLE_WITH_MKLDNN
30
using MKLDNNMemoryFormat = dnnl::memory::format_tag;
31
#endif
T
tensor-tang 已提交
32 33
namespace platform {

34 35 36 37 38 39
using MKLDNNStream = dnnl::stream;
using MKLDNNEngine = dnnl::engine;
using MKLDNNMemory = dnnl::memory;
using MKLDNNMemoryDescriptor = dnnl::memory::desc;
using MKLDNNPrimitive = dnnl::primitive;
using MKLDNNPrimitiveDesc = dnnl::handle<dnnl_primitive_desc_t>;
T
tensor-tang 已提交
40

41 42 43 44 45
typedef std::unique_ptr<MKLDNNStream> MKLDNNStreamPtr;
typedef std::unique_ptr<MKLDNNEngine> MKLDNNEnginePtr;
typedef std::unique_ptr<MKLDNNMemory> MKLDNNMemoryPtr;
typedef std::unique_ptr<MKLDNNPrimitive> MKLDNNPrimitivePtr;
typedef std::unique_ptr<MKLDNNPrimitiveDesc> MKLDNNPrimitiveDescPtr;
T
tensor-tang 已提交
46

47 48 49 50 51
template <typename Type>
void* to_void_cast(const Type* t) {
  return static_cast<void*>(const_cast<Type*>(t));
}

K
Krzysztof Binias 已提交
52 53 54 55 56
template <typename Type>
void* to_void_reinterpret_cast(const Type* t) {
  return reinterpret_cast<void*>(const_cast<Type*>(t));
}

57 58 59 60 61 62 63 64 65
template <class Type>
using tf_desc = typename Type::desc;

template <class Type>
using tf_pd = typename Type::primitive_desc;

template <typename Type, typename Engine, typename... Args>
std::shared_ptr<tf_pd<Type>> MKLDNNFwdPrimitiveDesc(const Engine& e,
                                                    Args&&... args) {
66
  auto desc = tf_desc<Type>(dnnl::prop_kind::forward, (args)...);
67 68 69 70 71
  auto pd = new tf_pd<Type>(desc, e);
  return std::shared_ptr<tf_pd<Type>>(pd);
}

template <typename Type, typename Engine, typename Primitive, typename... Args>
72 73
tf_pd<Type> MKLDNNBwdPrimitiveDesc(const Engine& e,
                                   const Primitive& p,
74 75 76 77 78
                                   Args&&... args) {
  auto desc = tf_desc<Type>(args...);
  return tf_pd<Type>(desc, e, p);
}

79
inline void MatchShapeToLayout(phi::DenseTensor* tensor_in,
80 81
                               framework::DataLayout from,
                               framework::DataLayout to) {
J
Jacek Czaja 已提交
82 83 84 85 86 87
  auto print_dims = [](const std::vector<int>& dims) {
    std::ostringstream oss;

    if (!dims.empty()) {
      oss << "[";
      // Convert all but the last element to avoid a trailing ","
88 89
      std::copy(
          dims.begin(), dims.end() - 1, std::ostream_iterator<int>(oss, ","));
J
Jacek Czaja 已提交
90 91 92 93 94 95 96 97

      // Now add the last element with no delimiter
      oss << dims.back() << "]";
    }

    return oss.str();
  };

98 99 100 101 102 103 104 105 106
  // In these data layouts, channel dimension is either on 2nd position: nChw or
  // at last nhwC, so for dim==2 these layouts are the same and nothing should
  // be done. Similarly for dim==1 when you have just one possible combination.
  if (tensor_in->dims().size() < 3) {
    VLOG(3) << "Keeping kMKLDNN/kNHWC/kNDHWC output_shape"
            << print_dims(phi::vectorize<int>(tensor_in->dims()));
    return;
  }

107 108
  switch (from) {
    case framework::DataLayout::kMKLDNN:
109 110
      if ((to == framework::DataLayout::kNHWC) ||
          (to == framework::DataLayout::kNDHWC)) {
111
        auto dims = phi::vectorize<int>(tensor_in->dims());
112
        std::rotate(dims.begin() + 1, dims.begin() + 2, dims.end());
113
        tensor_in->Resize(phi::make_ddim(dims));
114
        VLOG(3) << "Rotating Shape from: kMKLDNN to: kNHWC/kNDHWC output_shape"
J
Jacek Czaja 已提交
115
                << print_dims(dims);
116 117 118
      }
      break;
    case framework::DataLayout::kNHWC:
119
    case framework::DataLayout::kNDHWC:
120
      if (to == framework::DataLayout::kMKLDNN) {
121
        auto dims = phi::vectorize<int>(tensor_in->dims());
122
        std::rotate(dims.begin() + 1, dims.end() - 1, dims.end());
123
        tensor_in->Resize(phi::make_ddim(dims));
124
        VLOG(3) << "Rotating Shape from: kNHWC/kNDHWC to: kMKLDNN output_shape"
J
Jacek Czaja 已提交
125
                << print_dims(dims);
126 127 128 129 130 131 132
      }
      break;
    default:
      break;
  }
}

133 134 135 136 137
struct mkldnn_dummy_primitive {
  struct primitive_desc {};
  struct desc {};
};

138 139 140 141
inline dnnl::memory::desc MKLDNNMemDesc(const std::vector<int64_t>& dims,
                                        dnnl::memory::data_type data_type,
                                        MKLDNNMemoryFormat format) {
  return dnnl::memory::desc({dims}, data_type, format);
142 143
}

144 145
inline void ClearMKLDNNCache(const platform::Place& place,
                             void* ptr = nullptr) {
146 147 148 149 150
  // Clear mkl-dnn cache,
  if (platform::is_cpu_place(place)) {
    platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
    platform::MKLDNNDeviceContext* dev_ctx =
        (platform::MKLDNNDeviceContext*)pool.Get(place);
151
    dev_ctx->ResetBlobMap(ptr);
152 153 154
  }
}

155 156 157 158 159 160 161 162 163 164
inline void DontClearMKLDNNCache(const platform::Place& place) {
  // Clear mkl-dnn cache,
  if (platform::is_cpu_place(place)) {
    platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
    platform::MKLDNNDeviceContext* dev_ctx =
        (platform::MKLDNNDeviceContext*)pool.Get(place);
    dev_ctx->BlockNextCacheClearing();
  }
}

165
template <typename Type>
166 167
dnnl::memory::data_type MKLDNNGetDataType() {
  return dnnl::memory::data_type::undef;
168 169 170
}

template <>
171 172
inline dnnl::memory::data_type MKLDNNGetDataType<float>() {
  return dnnl::memory::data_type::f32;
173 174
}
template <>
175 176
inline dnnl::memory::data_type MKLDNNGetDataType<int32_t>() {
  return dnnl::memory::data_type::s32;
177
}
P
Physher 已提交
178
template <>
179 180
inline dnnl::memory::data_type MKLDNNGetDataType<int8_t>() {
  return dnnl::memory::data_type::s8;
P
Physher 已提交
181 182
}
template <>
183 184
inline dnnl::memory::data_type MKLDNNGetDataType<uint8_t>() {
  return dnnl::memory::data_type::u8;
P
Physher 已提交
185 186
}

187
template <>
188 189
inline dnnl::memory::data_type MKLDNNGetDataType<paddle::platform::bfloat16>() {
  return dnnl::memory::data_type::bf16;
190 191
}

192 193
inline void Reorder(dnnl::memory src,
                    dnnl::memory dst,
194 195
                    const dnnl::engine& engine) {
  auto reorder_prim = dnnl::reorder(src, dst);
196
  auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
197
  platform::RecordEvent record_reorder("int_reorder",
C
chenjian 已提交
198
                                       platform::TracerEventType::UserDefined,
199 200
                                       2,
                                       platform::EventRole::kUniqueOp);
A
Adam 已提交
201 202
  reorder_prim.execute(astream, src, dst);
  astream.wait();
M
mozga-intel 已提交
203 204
}

205
inline dnnl::memory::format_tag GetMKLDNNFormat(dnnl::memory::desc mem_desc) {
A
Adam 已提交
206 207 208 209 210 211 212
  auto ndims = mem_desc.data.ndims;
  auto strides = mem_desc.data.format_desc.blocking.strides;
  auto inner_nblks = mem_desc.data.format_desc.blocking.inner_nblks;
  auto inner_blks = mem_desc.data.format_desc.blocking.inner_blks;
  auto inner_idxs = mem_desc.data.format_desc.blocking.inner_idxs;

  if (ndims == 1) {
213
    return dnnl::memory::format_tag::x;
A
Adam 已提交
214 215 216
  } else if (ndims == 2) {
    if (inner_nblks == 0) {
      if (strides[0] >= strides[1]) {
217
        return dnnl::memory::format_tag::nc;
A
Adam 已提交
218
      } else {
219
        return dnnl::memory::format_tag::cn;
A
Adam 已提交
220 221 222 223 224
      }
    }
  } else if (ndims == 3) {
    if (inner_nblks == 0) {
      if (strides[0] >= strides[1] && strides[1] >= strides[2]) {
225
        return dnnl::memory::format_tag::ncw;
A
Adam 已提交
226
      } else if (strides[1] >= strides[0] && strides[0] >= strides[2]) {
227
        return dnnl::memory::format_tag::ntc;
A
Adam 已提交
228
      } else {
229
        return dnnl::memory::format_tag::nwc;
A
Adam 已提交
230 231 232 233 234 235
      }
    }
  } else if (ndims == 4) {
    if (inner_nblks == 0) {
      if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
          strides[2] >= strides[3]) {
236 237 238 239 240 241 242 243 244 245
        return dnnl::memory::format_tag::abcd;
      } else if (strides[2] >= strides[3] && strides[3] >= strides[1] &&
                 strides[1] >= strides[0]) {
        return dnnl::memory::format_tag::cdba;
      } else if (strides[0] >= strides[2] && strides[2] >= strides[3] &&
                 strides[3] >= strides[1]) {
        return dnnl::memory::format_tag::acdb;
      } else if (strides[0] >= strides[1] && strides[1] >= strides[3] &&
                 strides[3] >= strides[2]) {
        return dnnl::memory::format_tag::abdc;
246 247
      } else if (strides[2] >= strides[3] && strides[3] >= strides[1] &&
                 strides[1] >= strides[0]) {
248
        return dnnl::memory::format_tag::cdba;
A
Adam 已提交
249
      } else {
250
        return dnnl::memory::format_tag::dcab;
A
Adam 已提交
251 252 253
      }
    } else if (inner_nblks == 1) {
      if (inner_blks[0] == 16 && inner_idxs[0] == 1) {
254
        return dnnl::memory::format_tag::nChw16c;
A
Adam 已提交
255
      } else if (inner_blks[0] == 8 && inner_idxs[0] == 1) {
256
        return dnnl::memory::format_tag::nChw8c;
A
Adam 已提交
257 258 259
      } else if (inner_blks[0] == 8 && inner_idxs[0] == 0) {
        if (strides[0] >= strides[2] && strides[2] >= strides[3] &&
            strides[3] >= strides[1]) {
260
          return dnnl::memory::format_tag::Acdb8a;
A
Adam 已提交
261 262
        }
      } else if (inner_blks[0] == 4 && inner_idxs[0] == 1) {
263
        return dnnl::memory::format_tag::nChw4c;
A
Adam 已提交
264 265 266
      } else if (inner_blks[0] == 16 && inner_idxs[0] == 0) {
        if (strides[0] >= strides[2] && strides[2] >= strides[3] &&
            strides[3] >= strides[1]) {
267
          return dnnl::memory::format_tag::Acdb16a;
A
Adam 已提交
268 269 270 271 272
        }
      }
    } else if (inner_nblks == 2) {
      if (inner_blks[0] == 16 && inner_blks[1] == 16) {
        if (inner_idxs[0] == 1 && inner_idxs[1] == 0) {
273
          return dnnl::memory::format_tag::OIhw16i16o;
A
Adam 已提交
274 275 276
        }
      } else if (inner_blks[0] == 8 && inner_blks[1] == 8) {
        if (inner_idxs[0] == 1 && inner_idxs[1] == 0) {
277
          return dnnl::memory::format_tag::OIhw8i8o;
A
Adam 已提交
278 279 280 281 282 283 284
        }
      }
    }
  } else if (ndims == 5) {
    if (inner_nblks == 0) {
      if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
          strides[2] >= strides[3] && strides[3] >= strides[4]) {
285 286 287 288 289 290 291
        return dnnl::memory::format_tag::abcde;
      } else if (strides[0] >= strides[2] && strides[2] >= strides[1] &&
                 strides[1] >= strides[3] && strides[3] >= strides[4]) {
        return dnnl::memory::format_tag::acbde;
      } else if (strides[0] >= strides[2] && strides[2] >= strides[3] &&
                 strides[3] >= strides[4] && strides[4] >= strides[1]) {
        return dnnl::memory::format_tag::acdeb;
A
Adam 已提交
292 293
      }
    } else if (inner_nblks == 1) {
294 295 296 297 298 299
      if (inner_blks[0] == 4 && inner_idxs[0] == 1) {
        if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
            strides[2] >= strides[3] && strides[3] >= strides[4]) {
          return dnnl::memory::format_tag::aBcde4b;
        }
      } else if (inner_blks[0] == 8 && inner_idxs[0] == 0) {
A
Adam 已提交
300 301
        if (strides[0] >= strides[2] && strides[2] >= strides[3] &&
            strides[3] >= strides[4] && strides[4] >= strides[1]) {
302
          return dnnl::memory::format_tag::Acdeb8a;
A
Adam 已提交
303
        }
304 305
        if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
            strides[2] >= strides[3] && strides[3] >= strides[4]) {
306
          return dnnl::memory::format_tag::Abcde8a;
307
        }
A
Adam 已提交
308 309 310
      } else if (inner_blks[0] == 8 && inner_idxs[0] == 1) {
        if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
            strides[2] >= strides[3] && strides[3] >= strides[4]) {
311
          return dnnl::memory::format_tag::aBcde8b;
A
Adam 已提交
312 313 314 315
        }
      } else if (inner_blks[0] == 16 && inner_idxs[0] == 0) {
        if (strides[0] >= strides[2] && strides[2] >= strides[3] &&
            strides[3] >= strides[4] && strides[4] >= strides[1]) {
316
          return dnnl::memory::format_tag::Acdeb16a;
A
Adam 已提交
317
        }
318 319
        if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
            strides[2] >= strides[3] && strides[3] >= strides[4]) {
320
          return dnnl::memory::format_tag::Abcde16a;
321
        }
A
Adam 已提交
322 323 324
      } else if (inner_blks[0] == 16 && inner_idxs[0] == 1) {
        if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
            strides[2] >= strides[3] && strides[3] >= strides[4]) {
325
          return dnnl::memory::format_tag::aBcde16b;
A
Adam 已提交
326 327 328 329 330 331 332 333
        }
      }
    }
  } else if (ndims == 6) {
    if (inner_nblks == 0) {
      if (strides[0] >= strides[1] && strides[1] >= strides[2] &&
          strides[2] >= strides[3] && strides[3] >= strides[4] &&
          strides[4] >= strides[5]) {
334
        return dnnl::memory::format_tag::abcdef;
335 336 337 338
      } else if (strides[0] >= strides[2] && strides[2] >= strides[1] &&
                 strides[1] >= strides[3] && strides[3] >= strides[4] &&
                 strides[4] >= strides[5]) {
        return dnnl::memory::format_tag::acbdef;
A
Adam 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
      }
    }
  }
  // DEBUG CODE - KEEP UNTILL TENSOR.MEMORY_DESC IMPLEMENTED
  // std::cout<<"@@@@@@@@@@ UNDEFINED FORMAT @@@@@@@@@@@@@@@@@@@"<<std::endl;
  // std::cout<<"NDIMS: "<<ndims<<std::endl;
  // std::cout<<"INNER_NBLKS: "<<inner_nblks<<std::endl;
  // for (int i=0;i<ndims;++i) {
  //   std::cout<<"STRIDE["<<i<<"]: "<<strides[i]<<std::endl;
  // }
  // for (int i=0;i<inner_nblks;++i) {
  //   std::cout<<"INNER_BLKS["<<i<<"]: "<<inner_blks[i]<<std::endl;
  // }
  // for (int i=0;i<inner_nblks;++i) {
  //   std::cout<<"INNER_IDXS["<<i<<"]: "<<inner_idxs[i]<<std::endl;
  // }
355
  return dnnl::memory::format_tag::undef;
M
mozga-intel 已提交
356 357
}

358
inline dnnl::memory::format_tag GetMKLDNNFormat(const dnnl::memory memory) {
A
Adam 已提交
359 360
  auto mem_desc = memory.get_desc();
  return GetMKLDNNFormat(mem_desc);
361 362
}

363
inline dnnl::memory::format_tag GetPlainMKLDNNFormat(int tensor_rank) {
364 365
  switch (tensor_rank) {
    case 1:
366
      return dnnl::memory::format_tag::a;
367
    case 2:
368
      return dnnl::memory::format_tag::ab;
369
    case 3:
370
      return dnnl::memory::format_tag::abc;
371
    case 4:
372
      return dnnl::memory::format_tag::abcd;
373
    case 5:
374
      return dnnl::memory::format_tag::abcde;
375
    case 6:
376
      return dnnl::memory::format_tag::abcdef;
377
    case 7:
378
      return dnnl::memory::format_tag::abcdefg;
379
    case 8:
380
      return dnnl::memory::format_tag::abcdefgh;
381
    case 9:
382
      return dnnl::memory::format_tag::abcdefghi;
383 384 385 386 387 388 389 390
    default:
      PADDLE_THROW(platform::errors::Unimplemented(
          "Paddle support tensors with rank in range <1, 9>, but received "
          "tensor with rank: %d",
          tensor_rank));
  }
}

391 392
inline MKLDNNMemoryFormat MKLDNNFormatForSize(size_t dims_size,
                                              MKLDNNMemoryFormat data_format) {
393
  if (dims_size == 1) {
394
    return MKLDNNMemoryFormat::x;
395
  } else if (dims_size == 2) {
396
    return MKLDNNMemoryFormat::nc;
397
  } else if (dims_size == 3) {
398 399 400 401
    if (data_format == MKLDNNMemoryFormat::nchw) {
      return MKLDNNMemoryFormat::ncw;
    } else if (data_format == MKLDNNMemoryFormat::nhwc) {
      return MKLDNNMemoryFormat::nwc;
402
    }
403
  } else if (dims_size == 4) {
404 405
    if (data_format == MKLDNNMemoryFormat::goihw) {
      return MKLDNNMemoryFormat::oihw;
406
    }
407
  } else if (dims_size == 5) {
408 409
    if (data_format == MKLDNNMemoryFormat::goidhw) {
      return MKLDNNMemoryFormat::oidhw;
410
    }
411 412 413 414
    if (data_format == MKLDNNMemoryFormat::nchw) {
      return MKLDNNMemoryFormat::ncdhw;
    } else if (data_format == MKLDNNMemoryFormat::nhwc) {
      return MKLDNNMemoryFormat::ndhwc;
415
    }
416
  } else if (dims_size == 6) {
417 418 419
    if (data_format == MKLDNNMemoryFormat::nchw) {
      return MKLDNNMemoryFormat::abcdef;
    }
420 421 422 423
  }
  return data_format;
}

424
inline MKLDNNMemoryFormat data_format_to_memory_format(
425 426 427
    const std::string& data_format) {
  switch (framework::StringToDataLayout(data_format)) {
    case framework::DataLayout::kNHWC:
428
      return MKLDNNMemoryFormat::nhwc;
429
    case framework::DataLayout::kNCHW:
430
      return MKLDNNMemoryFormat::nchw;
431
    default:
432
      return MKLDNNMemoryFormat::any;
433 434 435
  }
}

436
inline MKLDNNMemoryFormat StringToMKLDNNFormat(std::string* format) {
437 438 439
  std::transform(format->begin(), format->end(), format->begin(), ::tolower);

  if (!format->compare("nchw")) {
440
    return MKLDNNMemoryFormat::nchw;
441
  } else if (!format->compare("nchw16c")) {
442
    return MKLDNNMemoryFormat::nChw16c;
443
  } else if (!format->compare("nchw8c")) {
444
    return MKLDNNMemoryFormat::nChw8c;
445
  } else if (!format->compare("nhwc")) {
446
    return MKLDNNMemoryFormat::nhwc;
447
  } else {
448
    return MKLDNNMemoryFormat::any;
449 450 451
  }
}

A
Adam 已提交
452 453 454 455 456
inline std::string ThreadIDasStr(void) {
  return std::to_string(
      std::hash<std::thread::id>()(std::this_thread::get_id()));
}

457 458 459
template <typename T>
inline void AppendKey(std::string* key, const T& num) {
  key->append(std::to_string(num));
A
Adam 已提交
460 461
}

A
Adam 已提交
462 463
template <>
inline void AppendKey(std::string* key,
464
                      const dnnl::memory::format_tag& format) {
A
Adam 已提交
465 466 467 468 469
  key->append(std::to_string(static_cast<int>(format)));
}

template <>
inline void AppendKey(std::string* key,
470
                      const dnnl::memory::data_type& data_type) {
A
Adam 已提交
471 472 473 474
  key->append(std::to_string(static_cast<int>(data_type)));
}

template <>
475
inline void AppendKey(std::string* key, const dnnl::algorithm& algorithm) {
A
Adam 已提交
476 477 478 479 480
  key->append(std::to_string(static_cast<int>(algorithm)));
}

template <>
inline void AppendKey(std::string* key,
481
                      const dnnl::normalization_flags& flags) {
A
Adam 已提交
482 483 484
  key->append(std::to_string(static_cast<int>(flags)));
}

485 486
inline void AppendKey(std::string* key, const std::string& str) {
  key->append(str);
A
Adam 已提交
487 488
}

489
inline void AppendKey(std::string* key, const char* str) { key->append(str); }
A
Adam 已提交
490

A
Adam 已提交
491 492
template <typename T>
inline void AppendKey(std::string* key, const std::vector<T>& dims) {
493
  for (size_t i = 0; i < dims.size(); i++) {
A
Adam 已提交
494 495 496 497
    AppendKey(key, std::to_string(dims[i]));
  }
}

498 499 500 501
// If MKLDNN build and CPU place then register suffix in DeviceContext
inline void AttachPointerHashToMKLDNNKey(void* ptr,
                                         const platform::Place& place) {
  if (platform::is_cpu_place(place)) {
J
Jacek Czaja 已提交
502 503 504 505 506 507 508 509 510 511 512 513 514
    // Static vars will remember first executor and its thread
    // so both of them need to be processed by the same thread within
    // critical section
    static std::mutex static_vars_barrier;
    static_vars_barrier.lock();
    static auto first_exec = ptr;
    static auto first_thread = ThreadIDasStr();
    static_vars_barrier.unlock();

    if (first_exec != ptr) {
      paddle::platform::MKLDNNDeviceContext::tls().set_key_suffix(
          "E" + std::to_string(reinterpret_cast<uintptr_t>(ptr)));
    }
515 516 517
    // Let's register adress of current executor
    paddle::platform::MKLDNNDeviceContext::tls().set_curr_exec(ptr);

J
Jacek Czaja 已提交
518 519 520 521
    // For first thread
    if (first_thread == ThreadIDasStr()) {
      paddle::platform::MKLDNNDeviceContext::tls().disable_tid_in_key();
    }
522 523 524
  }
}

525
template <typename... ArgTypes>
526 527
inline std::string CreateKey(const platform::MKLDNNDeviceContext& dev_ctx,
                             ArgTypes&&... args) {
528
  std::string key;
529
  key.reserve(64);
530
  using expand_type = int[];
531
  expand_type{0, (AppendKey(&key, std::forward<ArgTypes>(args)), 0)...};
J
Jacek Czaja 已提交
532
  key += paddle::platform::MKLDNNDeviceContext::tls().get_key_suffix();
533 534 535
  return key;
}

536 537
inline std::string ExtendKeyWithThreadInfoIfNeeded(
    const platform::MKLDNNDeviceContext& dev_ctx, const std::string& key) {
J
Jacek Czaja 已提交
538 539
  return (paddle::platform::MKLDNNDeviceContext::tls().is_tid_used_in_key() ==
          true)
540 541 542 543
             ? key + "-t:" + ThreadIDasStr()
             : key;
}

A
Adam 已提交
544 545
inline std::vector<std::vector<int64_t>> ToMkldnnPadding(
    const std::vector<int64_t>& paddings) {
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
  if (paddings.size() == 6) {
    int padding_front = paddings[0];
    int padding_back = paddings[1];
    int padding_top = paddings[2];
    int padding_bottom = paddings[3];
    int padding_left = paddings[4];
    int padding_right = paddings[5];

    return {{padding_front, padding_top, padding_left},
            {padding_back, padding_bottom, padding_right}};
  } else {
    int padding_top = paddings[0];
    int padding_bottom = paddings[1];
    int padding_left = paddings[2];
    int padding_right = paddings[3];

    return {{padding_top, padding_left}, {padding_bottom, padding_right}};
  }
}

566 567 568 569 570 571 572 573 574 575 576 577 578
// The function adjusts the vector of weight dimensions for group convolutions
inline void GetGroupConvWeightsTz(std::vector<int64_t>& weights_tz,  // NOLINT
                                  const int groups) {
  if (groups > 1) {
    // if (is_conv3d) [o, i, d, h, w]->[g, o/g, i, d, h, w]
    // else [o, i, h, w] -> [g, o/g, i, h, w]
    weights_tz.push_back(0);
    std::rotate(weights_tz.begin(), weights_tz.end() - 1, weights_tz.end());
    weights_tz[0] = groups;
    weights_tz[1] = weights_tz[1] / groups;
  }
}

J
Jacek Czaja 已提交
579
inline void RegisterModelLayout(
580
    std::vector<std::unique_ptr<framework::OperatorBase>>& ops,  // NOLINT
J
Jacek Czaja 已提交
581 582
    const platform::Place& place) {
  if (platform::is_cpu_place(place)) {
583 584 585 586 587 588
    // If there is already registered NHWC then quit this call
    // not to overwrite setting with analysis of internal "while" op block
    if (platform::MKLDNNDeviceContext::tls().get_cur_paddle_data_layout() ==
        framework::DataLayout::kNHWC)
      return;

L
Leo Chen 已提交
589
    VLOG(4) << "RegisterModelLayout for mkldnn";
J
Jacek Czaja 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    auto check_attrib = [](std::unique_ptr<framework::OperatorBase>& op,
                           const std::string& attrib_name) -> bool {
      if (op->HasAttr(attrib_name)) {
        auto data_format = op->Attr<std::string>(attrib_name);
        platform::MKLDNNDeviceContext::tls().set_cur_paddle_data_layout(
            data_format.compare("NHWC") == 0 ? framework::DataLayout::kNHWC
                                             : framework::DataLayout::kNCHW);
        return true;
      } else {
        return false;
      }
    };

    for (auto& op : ops) {
      if (check_attrib(op, std::string("data_format"))) {
        return;
      }
      if (check_attrib(op, std::string("data_layout"))) {
        return;
      }
    }
  }
}

614 615 616 617 618
inline bool HasOpINT8DataType(const paddle::framework::OpDesc* op) {
  return (op->GetAttrIfExists<std::string>("mkldnn_data_type") == "int8" ||
          op->GetAttrIfExists<bool>("use_quantizer"));
}

619 620 621 622 623 624 625
inline bool HasOpBFLOAT16DataType(const paddle::framework::OpDesc* op) {
  return op->GetAttrIfExists<std::string>("mkldnn_data_type") == "bfloat16";
}

inline bool HasOpFLOAT32DataType(const paddle::framework::OpDesc* op) {
  return op->GetAttrIfExists<std::string>("mkldnn_data_type") == "float32";
}
A
Adam Osewski 已提交
626

A
Adam 已提交
627 628
enum class RNNReorderType { PP_NTC, PP_TNC, NTC_PP, TNC_PP };

A
Adam Osewski 已提交
629 630 631 632 633
template <typename T>
bool constexpr is_int8() {
  return std::is_same<T, int8_t>::value || std::is_same<T, uint8_t>::value;
}

T
tensor-tang 已提交
634
}  // namespace platform
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

inline std::string FindInputNameByVarName(framework::OpDesc* op,
                                          const std::string& searched_name) {
  std::string ret;
  for (const auto& name : op->InputNames())
    for (const auto& input_name : op->Input(name))
      if (input_name == searched_name) ret = name;
  return ret;
}

inline std::string FindOutputNameByVarName(framework::OpDesc* op,
                                           const std::string& searched_name) {
  std::string ret;
  for (const auto& name : op->OutputNames())
    for (const auto& output_name : op->Output(name))
      if (output_name == searched_name) ret = name;
  return ret;
}
T
tensor-tang 已提交
653
}  // namespace paddle