onednn_helper.h 9.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright (c) 2022 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.

#pragma once

17
#include <thread>
18 19 20 21 22 23 24 25 26 27 28
#include "dnnl.hpp"  // NOLINT
#include "glog/logging.h"

#include "paddle/phi/backends/onednn/onednn_context.h"
#include "paddle/phi/common/layout.h"
#include "paddle/phi/common/place.h"
#include "paddle/phi/core/dense_tensor.h"

namespace phi {
namespace funcs {

29 30
using OneDNNMemoryFormat = dnnl::memory::format_tag;
using OneDNNDataType = dnnl::memory::data_type;
31 32 33 34 35 36

template <typename Type>
void* to_void_cast(const Type* t) {
  return static_cast<void*>(const_cast<Type*>(t));
}

37 38
inline OneDNNMemoryFormat OneDNNFormatForSize(size_t dims_size,
                                              OneDNNMemoryFormat data_format) {
39 40 41
  if (dims_size == 0) {
    return OneDNNMemoryFormat::x;
  } else if (dims_size == 1) {
42
    return OneDNNMemoryFormat::x;
43
  } else if (dims_size == 2) {
44
    return OneDNNMemoryFormat::nc;
45
  } else if (dims_size == 3) {
46 47 48 49
    if (data_format == OneDNNMemoryFormat::nchw) {
      return OneDNNMemoryFormat::ncw;
    } else if (data_format == OneDNNMemoryFormat::nhwc) {
      return OneDNNMemoryFormat::nwc;
50 51
    }
  } else if (dims_size == 4) {
52 53
    if (data_format == OneDNNMemoryFormat::goihw) {
      return OneDNNMemoryFormat::oihw;
54 55
    }
  } else if (dims_size == 5) {
56 57
    if (data_format == OneDNNMemoryFormat::goidhw) {
      return OneDNNMemoryFormat::oidhw;
58
    }
59 60 61 62
    if (data_format == OneDNNMemoryFormat::nchw) {
      return OneDNNMemoryFormat::ncdhw;
    } else if (data_format == OneDNNMemoryFormat::nhwc) {
      return OneDNNMemoryFormat::ndhwc;
63 64
    }
  } else if (dims_size == 6) {
65 66
    if (data_format == OneDNNMemoryFormat::nchw) {
      return OneDNNMemoryFormat::abcdef;
67 68 69 70 71
    }
  }
  return data_format;
}

72 73
inline dnnl::memory::format_tag GetPlainOneDNNFormat(int tensor_rank) {
  switch (tensor_rank) {
74 75 76
    case 0:
      // use 1D to represent 0D
      return dnnl::memory::format_tag::a;
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    case 1:
      return dnnl::memory::format_tag::a;
    case 2:
      return dnnl::memory::format_tag::ab;
    case 3:
      return dnnl::memory::format_tag::abc;
    case 4:
      return dnnl::memory::format_tag::abcd;
    case 5:
      return dnnl::memory::format_tag::abcde;
    case 6:
      return dnnl::memory::format_tag::abcdef;
    case 7:
      return dnnl::memory::format_tag::abcdefg;
    case 8:
      return dnnl::memory::format_tag::abcdefgh;
    case 9:
      return dnnl::memory::format_tag::abcdefghi;
    default:
      PADDLE_THROW(phi::errors::Unimplemented(
          "Paddle support tensors with rank in range <1, 9>, but received "
          "tensor with rank: %d",
          tensor_rank));
  }
}

103
template <typename Type>
104
dnnl::memory::data_type OneDNNGetDataType() {
105 106 107 108
  return dnnl::memory::data_type::undef;
}

template <>
109
inline dnnl::memory::data_type OneDNNGetDataType<float>() {
110 111 112
  return dnnl::memory::data_type::f32;
}
template <>
113
inline dnnl::memory::data_type OneDNNGetDataType<int32_t>() {
114 115 116
  return dnnl::memory::data_type::s32;
}
template <>
117
inline dnnl::memory::data_type OneDNNGetDataType<int8_t>() {
118 119 120
  return dnnl::memory::data_type::s8;
}
template <>
121
inline dnnl::memory::data_type OneDNNGetDataType<uint8_t>() {
122 123 124 125
  return dnnl::memory::data_type::u8;
}

template <>
126
inline dnnl::memory::data_type OneDNNGetDataType<dtype::bfloat16>() {
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  return dnnl::memory::data_type::bf16;
}

inline std::vector<std::vector<int64_t>> ToOneDNNPadding(
    const std::vector<int64_t>& paddings) {
  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}};
  }
}

template <typename T>
inline void AppendKey(std::string* key, const T& num) {
  key->append(std::to_string(num));
}

157 158 159 160 161 162
template <>
inline void AppendKey(std::string* key,
                      const dnnl::memory::format_kind& format) {
  key->append(std::to_string(static_cast<int>(format)));
}

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
template <>
inline void AppendKey(std::string* key,
                      const dnnl::memory::format_tag& format) {
  key->append(std::to_string(static_cast<int>(format)));
}

template <>
inline void AppendKey(std::string* key,
                      const dnnl::memory::data_type& data_type) {
  key->append(std::to_string(static_cast<int>(data_type)));
}

template <>
inline void AppendKey(std::string* key, const dnnl::algorithm& algorithm) {
  key->append(std::to_string(static_cast<int>(algorithm)));
}

template <>
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
inline void AppendKey(std::string* key, const dnnl::memory::dims& dims) {
  for (size_t i = 0; i < dims.size(); i++) {
    AppendKey(key, static_cast<int64_t>(dims[i]));
  }
}

template <>
inline void AppendKey(std::string* key, const dnnl::memory::desc& md) {
  AppendKey(key, md.get_dims());
  AppendKey(key, md.get_data_type());
  AppendKey(key, md.get_format_kind());
  AppendKey(key, md.get_inner_blks());
  AppendKey(key, md.get_inner_idxs());
  AppendKey(key, md.get_inner_nblks());
  AppendKey(key, md.get_padded_dims());
  AppendKey(key, md.get_strides());
}

template <>
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
inline void AppendKey(std::string* key,
                      const dnnl::normalization_flags& flags) {
  key->append(std::to_string(static_cast<int>(flags)));
}

inline void AppendKey(std::string* key, const std::string& str) {
  key->append(str);
}

inline void AppendKey(std::string* key, const char* str) { key->append(str); }

template <typename T>
inline void AppendKey(std::string* key, const std::vector<T>& dims) {
  for (size_t i = 0; i < dims.size(); i++) {
    AppendKey(key, std::to_string(dims[i]));
  }
}

template <typename... ArgTypes>
219 220
inline std::string CreateKey(const OneDNNContext& dev_ctx UNUSED,
                             ArgTypes&&... args) {
221 222 223 224 225 226 227 228
  std::string key;
  key.reserve(64);
  using expand_type = int[];
  expand_type{0, (AppendKey(&key, std::forward<ArgTypes>(args)), 0)...};
  key += OneDNNContext::tls().get_key_suffix();
  return key;
}

229 230 231 232 233 234 235 236 237 238 239 240 241
// 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;
  }
}

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
inline void MatchShapeToLayout(DenseTensor* tensor_in,
                               DataLayout from,
                               DataLayout to) {
  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 ","
      std::copy(
          dims.begin(), dims.end() - 1, std::ostream_iterator<int>(oss, ","));

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

    return oss.str();
  };

  // 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) {
265
    VLOG(3) << "Keeping ONEDNN/NHWC/NDHWC output_shape"
266 267 268 269 270
            << print_dims(phi::vectorize<int>(tensor_in->dims()));
    return;
  }

  switch (from) {
271
    case DataLayout::ONEDNN:
272 273 274 275
      if ((to == DataLayout::NHWC) || (to == DataLayout::NDHWC)) {
        auto dims = phi::vectorize<int>(tensor_in->dims());
        std::rotate(dims.begin() + 1, dims.begin() + 2, dims.end());
        tensor_in->Resize(phi::make_ddim(dims));
276
        VLOG(3) << "Rotating Shape from: ONEDNN to: NHWC/NDHWC output_shape"
277 278 279 280 281
                << print_dims(dims);
      }
      break;
    case DataLayout::NHWC:
    case DataLayout::NDHWC:
282
      if (to == DataLayout::ONEDNN) {
283 284 285
        auto dims = phi::vectorize<int>(tensor_in->dims());
        std::rotate(dims.begin() + 1, dims.end() - 1, dims.end());
        tensor_in->Resize(phi::make_ddim(dims));
286
        VLOG(3) << "Rotating Shape from: NHWC/NDHWC to: ONEDNN output_shape"
287 288 289 290 291 292 293 294
                << print_dims(dims);
      }
      break;
    default:
      break;
  }
}

295
struct onednn_dummy_primitive {
296 297 298 299
  struct primitive_desc {};
  struct desc {};
};

300
inline dnnl::memory::desc OneDNNMemDesc(const std::vector<int64_t>& dims,
301
                                        dnnl::memory::data_type data_type,
302
                                        OneDNNMemoryFormat format) {
303 304 305
  return dnnl::memory::desc({dims}, data_type, format);
}

306 307 308 309 310
inline std::string ThreadIDasStr(void) {
  return std::to_string(
      std::hash<std::thread::id>()(std::this_thread::get_id()));
}

311 312
inline std::string ExtendKeyWithThreadInfoIfNeeded(
    const OneDNNContext& dev_ctx UNUSED, const std::string& key) {
313 314 315 316 317
  return (OneDNNContext::tls().is_tid_used_in_key() == true)
             ? key + "-t:" + ThreadIDasStr()
             : key;
}

318 319
enum class RNNReorderType { PP_NTC, PP_TNC, NTC_PP, TNC_PP };

320 321
}  // namespace funcs
}  // namespace phi