kernel_factory.h 8.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
//   Copyright (c) 2021 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

#include <ostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>

23 24 25 26 27 28
#include "paddle/phi/common/backend.h"
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/common/layout.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/type_defs.h"
29 30 31
#include "paddle/utils/flat_hash_map.h"
#include "paddle/utils/small_vector.h"

32
namespace phi {
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 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 91 92 93 94 95 96 97

using DataType = paddle::experimental::DataType;
using DataLayout = paddle::experimental::DataLayout;

/**
 * [ Naming considerations ]
 *
 * The tensor operation library contains many kernels, and the computation
 * in each specific scenario is represented by an kernel.
 *
 * We directly named it `Kernel` instead of `Kernel`, the tensor operation
 * library here and fluid are independent, avoiding developers from
 * misunderstanding the relationship between the two concepts.
 */

class KernelContext;

class KernelKey {
 public:
  KernelKey() = default;

  KernelKey(Backend backend, DataLayout layout, DataType dtype)
      : backend_(backend), layout_(layout), dtype_(dtype) {}

  Backend backend() const { return backend_; }
  DataLayout layout() const { return layout_; }
  DataType dtype() const { return dtype_; }

  struct Hash {
    // Note: Now the number of bits we need does not exceed 32 bits, so there is
    // no need to use 64 bits. If needed in the future, it can be expanded,
    // but now we don’t over-design.
    uint32_t operator()(const KernelKey& key) const;
  };

  uint32_t hash_value() const { return Hash()(*this); }

  bool operator<(const KernelKey& key) const {
    return hash_value() < key.hash_value();
  }

  bool operator==(const KernelKey& key) const {
    return hash_value() == key.hash_value();
  }

  bool operator!=(const KernelKey& key) const {
    return hash_value() != key.hash_value();
  }

 private:
  // In total should be smaller than 32.
  constexpr static int kBackendBitLength = 8;
  constexpr static int kDataLayoutBitLength = 4;
  constexpr static int kDataTypeBitLength = 8;

  Backend backend_{Backend::UNDEFINED};
  DataLayout layout_{DataLayout::UNDEFINED};
  DataType dtype_{DataType::UNDEFINED};
};

// TODO(chenweihang): how deal with vector<Param>?
struct TensorArgDef {
  Backend backend;
  DataLayout layout;
  DataType dtype;
H
hong 已提交
98
  std::type_index type_index;
99

H
hong 已提交
100 101 102 103 104 105 106 107
  TensorArgDef(Backend in_backend,
               DataLayout in_layout,
               DataType in_dtype,
               std::type_index in_type_index)
      : backend(in_backend),
        layout(in_layout),
        dtype(in_dtype),
        type_index(in_type_index) {}
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

  TensorArgDef& SetBackend(Backend in_backend) {
    backend = in_backend;
    return *this;
  }

  TensorArgDef& SetDataLayout(DataLayout in_layout) {
    layout = in_layout;
    return *this;
  }

  TensorArgDef& SetDataType(DataType in_dtype) {
    dtype = in_dtype;
    return *this;
  }
};

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
// Align the original fluid Attribute type with lower overhead
enum class AttributeType {
  UNDEFINED = 0,
  BOOL,
  INT32,
  INT64,
  FLOAT32,
  FLOAT64,
  STRING,
  BOOLS,
  INT32S,
  INT64S,
  FLOAT32S,
  FLOAT64S,
  STRINGS,
  SCALAR,
  SCALARS,
  INT_ARRAY,
  DATA_TYPE,
  DATA_LAYOUT,
  PLACE,
};

148
struct AttributeArgDef {
149
  AttributeType type_index;
150

151
  explicit AttributeArgDef(AttributeType type_index) : type_index(type_index) {}
152 153 154 155 156 157
};

class KernelArgsDef {
 public:
  KernelArgsDef() = default;

H
hong 已提交
158 159 160 161 162
  void AppendInput(Backend backend,
                   DataLayout layout,
                   DataType dtype,
                   std::type_index type_index) {
    input_defs_.emplace_back(TensorArgDef(backend, layout, dtype, type_index));
163 164
  }

H
hong 已提交
165 166 167 168 169
  void AppendOutput(Backend backend,
                    DataLayout layout,
                    DataType dtype,
                    std::type_index type_index) {
    output_defs_.emplace_back(TensorArgDef(backend, layout, dtype, type_index));
170 171
  }

172
  void AppendAttribute(AttributeType type_index) {
173 174 175
    attribute_defs_.emplace_back(AttributeArgDef(type_index));
  }

C
Chen Weihang 已提交
176
  const paddle::small_vector<TensorArgDef, kInputSmallVectorSize>& input_defs()
177
      const {
178 179 180
    return input_defs_;
  }

C
Chen Weihang 已提交
181 182
  const paddle::small_vector<TensorArgDef, kOutputSmallVectorSize>&
  output_defs() const {
183 184 185
    return output_defs_;
  }

C
Chen Weihang 已提交
186
  const paddle::small_vector<AttributeArgDef, kAttrSmallVectorSize>&
187
  attribute_defs() const {
188 189 190
    return attribute_defs_;
  }

C
Chen Weihang 已提交
191
  paddle::small_vector<TensorArgDef, kInputSmallVectorSize>& input_defs() {
192 193
    return input_defs_;
  }
194

C
Chen Weihang 已提交
195
  paddle::small_vector<TensorArgDef, kOutputSmallVectorSize>& output_defs() {
196 197
    return output_defs_;
  }
198

C
Chen Weihang 已提交
199 200
  paddle::small_vector<AttributeArgDef, kAttrSmallVectorSize>&
  attribute_defs() {
201 202 203 204
    return attribute_defs_;
  }

 private:
C
Chen Weihang 已提交
205 206 207
  paddle::small_vector<TensorArgDef, kInputSmallVectorSize> input_defs_{{}};
  paddle::small_vector<TensorArgDef, kOutputSmallVectorSize> output_defs_{{}};
  paddle::small_vector<AttributeArgDef, kAttrSmallVectorSize> attribute_defs_{
208
      {}};
209 210 211 212 213 214 215
};

class Kernel {
 public:
  // for map element contruct
  Kernel() = default;

216 217
  explicit Kernel(KernelFn fn, void* variadic_fn)
      : fn_(fn), variadic_fn_(variadic_fn) {}
218 219 220

  void operator()(KernelContext* ctx) const { fn_(ctx); }

221 222 223 224 225 226
  template <typename Fn>
  Fn GetVariadicKernelFn() const {
    auto* func = reinterpret_cast<Fn>(variadic_fn_);
    return func;
  }

227 228 229 230
  KernelArgsDef* mutable_args_def() { return &args_def_; }

  const KernelArgsDef& args_def() const { return args_def_; }

231 232 233 234
  const TensorArgDef& InputAt(size_t idx) const {
    return args_def_.input_defs().at(idx);
  }

235 236
  TensorArgDef& InputAt(size_t idx) { return args_def_.input_defs().at(idx); }

237 238 239 240
  const TensorArgDef& OutputAt(size_t idx) const {
    return args_def_.output_defs().at(idx);
  }

241 242
  TensorArgDef& OutputAt(size_t idx) { return args_def_.output_defs().at(idx); }

243
  bool IsValid() const { return fn_ != nullptr; }
244 245 246

 private:
  KernelFn fn_{nullptr};
247
  void* variadic_fn_ = nullptr;
248 249 250
  KernelArgsDef args_def_;
};

251 252 253 254
using KernelKeyMap = paddle::flat_hash_map<KernelKey, Kernel, KernelKey::Hash>;

using KernelNameMap = paddle::flat_hash_map<std::string, KernelKeyMap>;

255 256 257 258 259 260 261 262 263 264
/**
 * Note: Each Computation need a basic kernel map that named by kernel_name.
 *       Such as for scale op, KernelMap contains a `scale` kernel map,
 *       if it still need other overload kernel, the op name can be
 *       `scale.***`.
 */
class KernelFactory {
 public:
  static KernelFactory& Instance();

265
  KernelNameMap& kernels() { return kernels_; }
266

267 268
  bool HasCompatiblePhiKernel(const std::string& op_type) const {
    return kernels_.find(TransToPhiKernelName(op_type)) != kernels_.end();
269 270
  }

Y
YuanRisheng 已提交
271
  const Kernel& SelectKernelOrThrowError(const std::string& kernel_name,
Z
zyfncg 已提交
272
                                         const KernelKey& kernel_key,
273
                                         bool use_gpudnn = false) const;
274

Y
YuanRisheng 已提交
275
  const Kernel& SelectKernelOrThrowError(const std::string& kernel_name,
276 277 278 279
                                         Backend backend,
                                         DataLayout layout,
                                         DataType dtype) const;

280 281
  bool HasKernel(const std::string& kernel_name,
                 const KernelKey& kernel_key) const;
282

283 284
  const Kernel& SelectKernel(const std::string& kernel_name,
                             const KernelKey& kernel_key) const;
285

286
  KernelKeyMap SelectKernelMap(const std::string& kernel_name) const;
287

288 289 290
  const KernelArgsDef& GetFirstKernelArgsDef(
      const std::string& kernel_name) const;

291 292 293
 private:
  KernelFactory() = default;

294
  KernelNameMap kernels_;
295 296 297 298 299 300 301 302
};

inline std::ostream& operator<<(std::ostream& os, const KernelKey& kernel_key) {
  os << "(" << kernel_key.backend() << ", " << kernel_key.layout() << ", "
     << kernel_key.dtype() << ")";
  return os;
}

303 304
std::ostream& operator<<(std::ostream& os, AttributeType attr_type);

305 306 307 308
std::ostream& operator<<(std::ostream& os, const Kernel& kernel);

std::ostream& operator<<(std::ostream& os, KernelFactory& kernel_factory);

309
}  // namespace phi