infermeta_utils.h 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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

#include <string>
18 19
#include <typeindex>
#include <typeinfo>
20 21
#include <utility>

22
#include "paddle/phi/common/int_array.h"
23
#include "paddle/phi/common/scalar.h"
24
#include "paddle/phi/core/attribute.h"
25 26 27 28
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/macros.h"
#include "paddle/phi/core/meta_tensor.h"
#include "paddle/phi/core/type_defs.h"
29
#include "paddle/utils/any.h"
30
#include "paddle/utils/flat_hash_map.h"
31 32
#include "paddle/utils/small_vector.h"

33
namespace phi {
34 35 36 37 38 39 40

class InferMetaContext {
 public:
  InferMetaContext() = default;
  explicit InferMetaContext(MetaConfig config) : config_(config) {}

  void SetMetaConfig(MetaConfig config);
41 42 43 44
  const MetaConfig& GetMetaConfig() const;

  void EmplaceBackInput(MetaTensor input);
  void EmplaceBackOutput(MetaTensor output);
45
  void EmplaceBackAttr(Attribute attr);
46 47

  void EmplaceBackInputs(
C
Chen Weihang 已提交
48
      paddle::small_vector<MetaTensor, phi::kInputSmallVectorSize> inputs);
49
  void EmplaceBackOutputs(
C
Chen Weihang 已提交
50
      paddle::small_vector<MetaTensor, phi::kOutputSmallVectorSize> outputs);
51

52
  virtual const MetaTensor& InputAt(size_t idx) const;
53

54 55
  virtual std::vector<const MetaTensor*> InputsBetween(size_t start,
                                                       size_t end) const;
56
  virtual paddle::optional<std::vector<const MetaTensor*>>
57
  OptionalInputsBetween(size_t start, size_t end) const;
58

59 60 61
  virtual MetaTensor* MutableOutputAt(size_t idx);
  virtual std::vector<MetaTensor*> MutableOutputBetween(size_t start,
                                                        size_t end);
62 63

  template <typename AttrType>
64
  const AttrType& AttrAt(size_t idx) const;
65

H
hong 已提交
66 67
  const Attribute& AttrAt(size_t idx) const;

68 69 70 71 72 73
  const std::pair<int, int>& InputRangeAt(size_t idx) const;
  const std::pair<int, int>& OutputRangeAt(size_t idx) const;

  virtual ~InferMetaContext() = default;

 protected:
74 75
  MetaConfig config_;

C
Chen Weihang 已提交
76
  paddle::small_vector<Attribute, kAttrSmallVectorSize> attrs_;
77

C
Chen Weihang 已提交
78
  paddle::small_vector<std::pair<int, int>, phi::kInputSmallVectorSize>
79
      input_range_;
C
Chen Weihang 已提交
80
  paddle::small_vector<std::pair<int, int>, phi::kOutputSmallVectorSize>
81
      output_range_;
82

83
 private:
C
Chen Weihang 已提交
84 85
  paddle::small_vector<MetaTensor, phi::kInputSmallVectorSize> inputs_;
  paddle::small_vector<MetaTensor, phi::kOutputSmallVectorSize> outputs_;
86 87
};

88
#define PD_INFER_META(...) \
89
  ::phi::InferMetaFnImpl<decltype(&__VA_ARGS__), &__VA_ARGS__>::Call
90

91
#define PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(attr_type)           \
92 93 94 95 96 97 98 99
  template <typename... Tail>                                                  \
  struct InferMetaFnCallHelper<attr_type, Tail...> {                           \
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs> \
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {          \
      static_assert(out_idx == 0,                                              \
                    "InferMeta's Attributes should appear before Outputs.");   \
      attr_type arg = ctx->AttrAt<attr_type>(attr_idx);                        \
      InferMetaFnCallHelper<                                                   \
100 101
          Tail...>::template Call<in_idx, attr_idx + 1, out_idx>(ctx,          \
                                                                 pargs...,     \
102 103 104 105
                                                                 arg);         \
    }                                                                          \
  }

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
#define PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(attr_type) \
  template <typename... Tail>                                                  \
  struct InferMetaFnCallHelper<const attr_type&, Tail...> {                    \
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs> \
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {          \
      static_assert(out_idx == 0,                                              \
                    "InferMeta's Attributes should appear before Outputs.");   \
      const attr_type& arg = ctx->AttrAt<attr_type>(attr_idx);                 \
      InferMetaFnCallHelper<                                                   \
          Tail...>::template Call<in_idx, attr_idx + 1, out_idx>(ctx,          \
                                                                 pargs...,     \
                                                                 arg);         \
    }                                                                          \
  }

121
#define PD_SPECIALIZE_InferMetaFnCallHelper_FOR_TENSOR_SCALAR(attr_type)       \
H
hong 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  template <typename... Tail>                                                  \
  struct InferMetaFnCallHelper<const attr_type&, Tail...> {                    \
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs> \
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {          \
      static_assert(out_idx == 0,                                              \
                    "InferMeta's Attributes should appear before Outputs.");   \
      const Attribute& t = ctx->AttrAt(attr_idx);                              \
      static Attribute cmp_t = phi::TensorRef(nullptr);                        \
      attr_type attr1;                                                         \
      if (cmp_t.index() == t.index()) {                                        \
        attr1 = attr_type((*paddle::get<phi::TensorRef>(t).Get()));            \
      } else {                                                                 \
        attr1 = paddle::get<attr_type>(t);                                     \
      }                                                                        \
      InferMetaFnCallHelper<                                                   \
          Tail...>::template Call<in_idx, attr_idx + 1, out_idx>(ctx,          \
                                                                 pargs...,     \
                                                                 attr1);       \
    }                                                                          \
  }

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
#define PD_SPECIALIZE_InferMetaFnCallHelper_FOR_TENSOR_INTARRAY(attr_type)     \
  template <typename... Tail>                                                  \
  struct InferMetaFnCallHelper<const attr_type&, Tail...> {                    \
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs> \
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {          \
      static_assert(out_idx == 0,                                              \
                    "InferMeta's Attributes should appear before Outputs.");   \
      const Attribute& t = ctx->AttrAt(attr_idx);                              \
      static Attribute cmp_t = phi::TensorRef(nullptr);                        \
      static Attribute vec_ref =                                               \
          std::vector<phi::TensorRef>({phi::TensorRef(nullptr)});              \
      attr_type attr1;                                                         \
      if (cmp_t.index() == t.index()) {                                        \
        attr1 = attr_type((*paddle::get<phi::TensorRef>(t).Get()));            \
      } else if (vec_ref.index() == t.index()) {                               \
        attr1 = attr_type(paddle::get<std::vector<phi::TensorRef>>(t));        \
      } else {                                                                 \
        attr1 = paddle::get<attr_type>(t);                                     \
      }                                                                        \
      InferMetaFnCallHelper<                                                   \
          Tail...>::template Call<in_idx, attr_idx + 1, out_idx>(ctx,          \
                                                                 pargs...,     \
                                                                 attr1);       \
    }                                                                          \
  }

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
template <typename T>
struct InferMetaTypeTag {};

template <typename Fn, Fn fn>
struct InferMetaFnImpl;

template <typename Return, typename... Args, Return (*infer_meta_fn)(Args...)>
struct InferMetaFnImpl<Return (*)(Args...), infer_meta_fn> {
  static void Call(InferMetaContext* ctx) {
    InferMetaFnCallHelper<Args...,
                          InferMetaTypeTag<int>>::template Call<0, 0, 0>(ctx);
  }

 private:
  template <typename... RemainingArgs>
  struct InferMetaFnCallHelper;

  template <typename... Tail>
  struct InferMetaFnCallHelper<const MetaTensor&, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {
      static_assert(attr_idx == 0,
                    "InferMeta's Input should appear before Attributes.");
      static_assert(out_idx == 0,
                    "InferMeta's Input should appear before Outputs.");
      const std::pair<int, int> range = ctx->InputRangeAt(in_idx);
      const MetaTensor& arg = ctx->InputAt(range.first);
      InferMetaFnCallHelper<
          Tail...>::template Call<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                 pargs...,
                                                                 arg);
    }
  };

203
  template <typename... Tail>
204
  struct InferMetaFnCallHelper<const std::vector<const MetaTensor*>&, Tail...> {
205 206 207 208 209 210 211
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {
      static_assert(attr_idx == 0,
                    "InferMeta's Input should appear before Attributes.");
      static_assert(out_idx == 0,
                    "InferMeta's Input should appear before Outputs.");
      const std::pair<int, int> range = ctx->InputRangeAt(in_idx);
212
      std::vector<const MetaTensor*> arg =
213 214 215 216 217 218 219 220
          ctx->InputsBetween(range.first, range.second);
      InferMetaFnCallHelper<
          Tail...>::template Call<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                 pargs...,
                                                                 arg);
    }
  };

221 222
  template <typename... Tail>
  struct InferMetaFnCallHelper<
223
      const paddle::optional<std::vector<const MetaTensor*>>&,
224 225 226 227 228 229 230 231
      Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {
      static_assert(attr_idx == 0,
                    "InferMeta's Input should appear before Attributes.");
      static_assert(out_idx == 0,
                    "InferMeta's Input should appear before Outputs.");
      const std::pair<int, int> range = ctx->InputRangeAt(in_idx);
232
      paddle::optional<std::vector<const MetaTensor*>> arg =
233 234 235 236 237 238 239 240
          ctx->OptionalInputsBetween(range.first, range.second);
      InferMetaFnCallHelper<
          Tail...>::template Call<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                 pargs...,
                                                                 arg);
    }
  };

241 242 243 244
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(bool);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(int);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(int64_t);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(float);
245
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(double);
246 247 248
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(DataType);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(Backend);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(DataLayout);
249
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(std::string);
250 251
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_TENSOR_SCALAR(Scalar);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_TENSOR_INTARRAY(IntArray);
252 253 254 255 256 257 258 259 260 261 262
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(
      std::vector<bool>);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector<int>);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(
      std::vector<int64_t>);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(
      std::vector<float>);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(
      std::vector<double>);
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(
      std::vector<std::string>);
263 264
  PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(
      std::vector<Scalar>);
265 266 267 268 269 270 271 272 273 274 275 276 277 278

  template <typename... Tail>
  struct InferMetaFnCallHelper<MetaTensor*, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {
      const std::pair<int, int> range = ctx->OutputRangeAt(out_idx);
      MetaTensor* arg = ctx->MutableOutputAt(range.first);
      InferMetaFnCallHelper<
          Tail...>::template Call<in_idx, attr_idx, out_idx + 1>(ctx,
                                                                 pargs...,
                                                                 arg);
    }
  };

279
  template <typename... Tail>
280
  struct InferMetaFnCallHelper<std::vector<MetaTensor*>, Tail...> {
281 282 283
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {
      const std::pair<int, int> range = ctx->OutputRangeAt(out_idx);
284
      std::vector<MetaTensor*> arg =
285 286 287 288 289 290 291
          ctx->MutableOutputBetween(range.first, range.second);
      InferMetaFnCallHelper<
          Tail...>::template Call<in_idx, attr_idx, out_idx + 1>(ctx,
                                                                 pargs...,
                                                                 arg);
    }
  };
292 293 294 295 296

  template <typename... Tail>
  struct InferMetaFnCallHelper<MetaConfig, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) {
297
      MetaConfig arg = ctx->GetMetaConfig();
298 299 300 301 302 303 304 305 306
      InferMetaFnCallHelper<Tail...>::template Call<in_idx, attr_idx, out_idx>(
          ctx, pargs..., arg);
    }
  };

  /* End case */
  template <typename T>
  struct InferMetaFnCallHelper<InferMetaTypeTag<T>> {
    template <int in_idx, int attr_idx, int out_idx>
307
    static void Call(InferMetaContext* ctx UNUSED, Args&... args) {
308 309 310 311 312
      return infer_meta_fn(args...);
    }
  };
};

C
Chen Weihang 已提交
313
class MetaFnFactory {
314
 public:
C
Chen Weihang 已提交
315
  static MetaFnFactory& Instance();
316 317 318 319 320 321 322 323 324

  bool Contains(const std::string& kernel_name_prefix) const {
    return meta_fn_map_.count(kernel_name_prefix) > 0;
  }

  void Insert(std::string kernel_name_prefix, InferMetaFn infer_meta_fn) {
    PADDLE_ENFORCE_NE(
        Contains(kernel_name_prefix),
        true,
325
        phi::errors::AlreadyExists(
326 327 328 329 330 331 332 333 334 335 336
            "`%s`'s Series Kernel's InferMetaFn has been registered.",
            kernel_name_prefix));
    meta_fn_map_.insert(
        {std::move(kernel_name_prefix), std::move(infer_meta_fn)});
  }

  const InferMetaFn& Get(const std::string& kernel_name_prefix) const {
    auto it = meta_fn_map_.find(kernel_name_prefix);
    PADDLE_ENFORCE_NE(
        it,
        meta_fn_map_.end(),
337
        phi::errors::NotFound(
338 339 340 341 342 343
            "`%s`'s Series Kernel's InferMetaFn is not registered.",
            kernel_name_prefix));
    return it->second;
  }

 private:
C
Chen Weihang 已提交
344
  MetaFnFactory() = default;
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361

  /**
   * [ Why use kernel name prefix? ]
   *
   * one op -> a matrix of kernels
   *
   * such as, scale op, it may correspond to the following kernels:
   *
   * - scale, scale_sr, scale_dnnl
   * - scale_raw, scale_raw_sr, scale_raw_dnnl
   *
   * All the kernels in each row correspond to the same infershape function,
   * the number of kernel arguments in the same row is the same, and only
   * the tensor types in the arguments are different.
   */
  paddle::flat_hash_map<std::string, InferMetaFn> meta_fn_map_;

C
Chen Weihang 已提交
362
  DISABLE_COPY_AND_ASSIGN(MetaFnFactory);
363 364 365 366 367
};

struct InferMetaFnRegistrar {
  InferMetaFnRegistrar(const char* kernel_name_prefix,
                       InferMetaFn infer_meta_fn) {
C
Chen Weihang 已提交
368 369
    MetaFnFactory::Instance().Insert(kernel_name_prefix,
                                     std::move(infer_meta_fn));
370 371 372
  }
};

373
#define PD_REGISTER_INFER_META_FN(kernel_name_prefix, variadic_infer_meta_fn) \
374
  PD_STATIC_ASSERT_GLOBAL_NAMESPACE(                                          \
375 376
      PD_REGISTER_infer_meta_fn_ns_check_##kernel_name_prefix,                \
      "PD_REGISTER_INFER_META_FN must be called in global namespace.");       \
377
  static const ::phi::InferMetaFnRegistrar                                    \
378
      __registrar_arg_map_fn_for_##kernel_name_prefix(                        \
379
          #kernel_name_prefix, PD_INFER_META(variadic_infer_meta_fn))
380

381
}  // namespace phi