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

17
#include <iostream>
18 19
#include <string>
#include <unordered_map>
20
#include <utility>
21 22
#include <vector>

23
#include "paddle/phi/api/ext/exception.h"
24
#include "paddle/phi/api/include/dll_decl.h"
25
#include "paddle/phi/api/include/tensor.h"
26
#include "paddle/utils/any.h"
27 28
#include "paddle/utils/none.h"
#include "paddle/utils/optional.h"
29 30 31 32 33 34 35 36 37 38

/**
 * Op Meta Info Related Define.
 *
 * Used to maintain operator core information.
 *
 */

namespace paddle {

39
class PADDLE_API OpMetaInfoHelper;
40
using Tensor = paddle::Tensor;
41

42 43
///////////////// Util Marco Define ////////////////

44 45 46 47 48 49 50
#define PD_DISABLE_COPY_AND_ASSIGN(classname)      \
 private:                                          \
  classname(const classname&) = delete;            \
  classname(classname&&) = delete;                 \
  classname& operator=(const classname&) = delete; \
  classname& operator=(classname&&) = delete

51 52 53 54 55 56
#define STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg)                        \
  struct __test_global_namespace_##uniq_name##__ {};                          \
  static_assert(std::is_same<::__test_global_namespace_##uniq_name##__,       \
                             __test_global_namespace_##uniq_name##__>::value, \
                msg)

57 58
///////////////// Util Define and Function ////////////////

59 60
constexpr char kGradTensorSuffix[] = "@GRAD";
constexpr char kTensorVectorSuffix[] = "@VECTOR";
61
constexpr char kDoubleGradNewOutSuffix[] = "@NEW";
62
constexpr char kOptionalSuffix[] = "@OPTIONAL";
63 64 65 66 67 68 69 70 71 72 73 74

// Used for Construct Grad Tensor name
inline std::string Grad(const std::string& t_name) {
  std::string result;
  result.reserve(t_name.size() + 5U);
  result += t_name;
  result += kGradTensorSuffix;
  return result;
}

// Used for Construct std::vector<Tensor> name
inline std::string Vec(const std::string& t_name) {
75
  std::string result;
76 77 78
  result.reserve(t_name.size() + 7U);
  result += t_name;
  result += kTensorVectorSuffix;
79 80 81
  return result;
}

82 83 84 85 86 87 88 89 90
// Used for Construct double grad output name
inline std::string New(const std::string& t_name) {
  std::string result;
  result.reserve(t_name.size() + 4U);
  result += t_name;
  result += kDoubleGradNewOutSuffix;
  return result;
}

91 92 93 94 95 96 97 98 99
// Used for Construct paddle::optional name
inline std::string Optional(const std::string& t_name) {
  std::string result;
  result.reserve(t_name.size() + 9U);
  result += t_name;
  result += kOptionalSuffix;
  return result;
}

100 101
std::vector<std::string> ParseAttrStr(const std::string& attr);

102 103 104 105 106 107 108 109 110
PADDLE_API void AssignTensorImpl(const Tensor& src, Tensor* dst);

////////////////////// Kernel Context ////////////////////////

class PADDLE_API CustomOpKernelContext {
 public:
  CustomOpKernelContext() = default;

  void EmplaceBackInput(Tensor&& input);
111
  void EmplaceBackInputs(const std::vector<Tensor>& inputs);
112
  void EmplaceBackOutput(Tensor&& output);
113
  void EmplaceBackOutputs(const std::vector<Tensor>& outputs);
114
  void EmplaceBackAttr(paddle::any attr);
115
  void EmplaceBackAttrs(const std::vector<paddle::any>& attrs);
116 117 118 119 120
  const std::pair<size_t, size_t>& InputRangeAt(size_t idx) const;
  const std::pair<size_t, size_t>& OutputRangeAt(size_t idx) const;

  const Tensor& InputAt(size_t idx) const;
  std::vector<Tensor> InputsBetween(size_t start, size_t end) const;
121
  Tensor& MutableInputAt(size_t idx);
122
  std::vector<Tensor>* AllMutableInput();
123
  paddle::optional<Tensor> OptionalInputAt(size_t idx);
124 125
  paddle::optional<std::vector<Tensor>> OptionalInputsBetween(size_t start,
                                                              size_t end);
126 127 128
  const std::vector<paddle::any>& Attrs() const;
  const std::vector<std::pair<size_t, size_t>>& InputRange();
  const std::vector<std::pair<size_t, size_t>>& OutputRange();
129
  Tensor* MutableOutputAt(size_t idx);
C
co63oc 已提交
130 131
  std::vector<Tensor*> MutableOutputBetween(size_t start, size_t end);
  std::vector<Tensor> OutputsBetween(size_t start, size_t end);
132 133 134 135 136 137 138 139 140 141 142
  std::vector<Tensor>* AllMutableOutput();

  template <typename AttrType>
  AttrType AttrAt(size_t idx) const {
    try {
      return paddle::any_cast<AttrType>(attrs_.at(idx));
    } catch (paddle::bad_any_cast&) {
      PD_THROW("Attribute cast error in Custom Op Kernel Context.");
    }
  }

143
  // handle inplace map
144 145 146 147 148
  void ConstructInplaceIndex(
      const std::vector<std::string>& inputs,
      const std::vector<std::string>& outputs,
      const std::unordered_map<std::string, std::string>& inplace_map);
  void UpdatePlainOutputs(
149 150 151 152 153
      const std::vector<std::string>& inputs,
      const std::vector<std::string>& outputs,
      const std::unordered_map<std::string, std::string>& inplace_map);
  void AssignInplaceOutputs();
  std::vector<Tensor*>* AllMutablePlainOutput();
154 155
  std::unordered_map<size_t, size_t> GetInplaceIndexMap();
  std::unordered_map<size_t, size_t> GetInplaceReverseIndexMap();
156

157 158 159 160 161
 private:
  // TODO(chenweihang): replaced be SmallVector
  std::vector<Tensor> inputs_;
  std::vector<Tensor> outputs_;
  std::vector<paddle::any> attrs_;
162
  // handle inplace map
163
  std::vector<Tensor*> plain_outputs_;
164 165 166 167
  // {input: output}
  std::unordered_map<size_t, size_t> inplace_idx_map_;
  // {output: input}
  std::unordered_map<size_t, size_t> inplace_reverse_idx_map_;
168 169 170 171 172

  std::vector<std::pair<size_t, size_t>> input_range_;
  std::vector<std::pair<size_t, size_t>> output_range_;
};

173 174 175
////////////////////// Kernel Function (PD_KERNEL) ////////////////////////

// Record Op kernel core function
176 177 178 179 180 181
using KernelFunc = void (*)(CustomOpKernelContext*);

#define PD_SPECIALIZE_ComputeCallHelper(attr_type)                             \
  template <typename... Tail>                                                  \
  struct ComputeCallHelper<attr_type, Tail...> {                               \
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs> \
182
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {  \
183 184 185 186 187 188
      attr_type arg = ctx->AttrAt<attr_type>(attr_idx);                        \
      ComputeCallHelper<                                                       \
          Tail...>::template Compute<in_idx, attr_idx + 1, out_idx>(ctx,       \
                                                                    pargs...,  \
                                                                    arg);      \
    }                                                                          \
189 190
  }

191 192 193 194 195 196 197 198
template <typename T>
struct TypeTag {};

template <typename F, F f>
struct KernelFuncImpl;

template <typename Return, typename... Args, Return (*impl_fn)(Args...)>
struct KernelFuncImpl<Return (*)(Args...), impl_fn> {
199 200
  static void Compute(CustomOpKernelContext* ctx) {
    ComputeCallHelper<Args..., TypeTag<int>>::template Compute<0, 0, 0>(ctx);
201 202 203 204 205 206
  }

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

207
  // Handle args for general Tensor input case
208 209
  template <typename... Tail>
  struct ComputeCallHelper<const Tensor&, Tail...> {
210
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
211
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
212
      auto& range = ctx->InputRangeAt(in_idx);
213
      auto& arg = ctx->MutableInputAt(range.first);
214 215 216 217
      ComputeCallHelper<
          Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                    pargs...,
                                                                    arg);
218 219 220
    }
  };

221
  // Handle args for optional Tensor input case
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
  template <typename... Tail>
  struct ComputeCallHelper<const paddle::optional<paddle::Tensor>&, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
      auto& range = ctx->InputRangeAt(in_idx);
      auto& arg = ctx->InputAt(range.first);
      if (!arg.is_initialized()) {
        ComputeCallHelper<Tail...>::
            template Compute<in_idx + 1, attr_idx, out_idx>(
                ctx, pargs..., paddle::none);
      } else {
        ComputeCallHelper<
            Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                      pargs...,
                                                                      arg);
      }
    }
  };

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
  // Handle args for inplace Tensor case
  template <typename... Tail>
  struct ComputeCallHelper<Tensor&, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
      auto& range = ctx->InputRangeAt(in_idx);
      auto& arg = ctx->MutableInputAt(range.first);
      ComputeCallHelper<
          Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                    pargs...,
                                                                    arg);
    }
  };

  // Handle args for optional inplace Tensor input case
  template <typename... Tail>
  struct ComputeCallHelper<paddle::optional<paddle::Tensor>&, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
      auto& range = ctx->InputRangeAt(in_idx);
      auto arg = ctx->OptionalInputAt(range.first);
      ComputeCallHelper<
          Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                    pargs...,
                                                                    arg);
    }
  };

269
  // Handle args for general vector<Tensor> input case
270 271
  template <typename... Tail>
  struct ComputeCallHelper<const std::vector<Tensor>&, Tail...> {
272
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
273
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
274 275 276 277 278 279
      auto& range = ctx->InputRangeAt(in_idx);
      auto arg = ctx->InputsBetween(range.first, range.second);
      ComputeCallHelper<
          Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                    pargs...,
                                                                    arg);
280 281 282
    }
  };

283
  // Handle args for optional vector<Tensor> input case
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
  template <typename... Tail>
  struct ComputeCallHelper<const paddle::optional<std::vector<paddle::Tensor>>&,
                           Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
      auto& range = ctx->InputRangeAt(in_idx);
      auto arg = ctx->InputsBetween(range.first, range.second);
      if (arg.empty() || !arg[0].is_initialized()) {
        ComputeCallHelper<Tail...>::
            template Compute<in_idx + 1, attr_idx, out_idx>(
                ctx, pargs..., paddle::none);
      } else {
        ComputeCallHelper<
            Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                      pargs...,
                                                                      arg);
      }
    }
  };

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
  // Handle args for inplace vector<Tensor> case
  template <typename... Tail>
  struct ComputeCallHelper<std::vector<Tensor>&, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
      auto& range = ctx->InputRangeAt(in_idx);
      auto arg = ctx->InputsBetween(range.first, range.second);
      ComputeCallHelper<
          Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                    pargs...,
                                                                    arg);
    }
  };

  // Handle args for optional inplace vector<Tensor> case
  template <typename... Tail>
  struct ComputeCallHelper<paddle::optional<std::vector<Tensor>>&, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
      auto& range = ctx->InputRangeAt(in_idx);
      auto arg = ctx->OptionalInputsBetween(range.first, range.second);
      ComputeCallHelper<
          Tail...>::template Compute<in_idx + 1, attr_idx, out_idx>(ctx,
                                                                    pargs...,
                                                                    arg);
    }
  };

332 333 334 335
  PD_SPECIALIZE_ComputeCallHelper(bool);
  PD_SPECIALIZE_ComputeCallHelper(int);
  PD_SPECIALIZE_ComputeCallHelper(float);
  PD_SPECIALIZE_ComputeCallHelper(int64_t);
336 337 338 339 340 341 342
  PD_SPECIALIZE_ComputeCallHelper(const std::string&);
  PD_SPECIALIZE_ComputeCallHelper(const std::vector<int>&);
  PD_SPECIALIZE_ComputeCallHelper(const std::vector<float>&);
  PD_SPECIALIZE_ComputeCallHelper(const std::vector<int64_t>&);
  PD_SPECIALIZE_ComputeCallHelper(const std::vector<std::string>&);
  // TODO(chenweihang): support other attribute type if needed.
  // Why not support other attribute type here?
R
Ruibiao Chen 已提交
343
  // - paddle::blank, std::vector<bool> and std::vector<double>
344 345 346 347 348
  //   are not used in op
  // - BlockDesc* and std::vector<BlockDesc*> are used in framework

  // NOTE(chenweihang): Used to be compatible with the 2.0.1 released
  // interface, and will be deprecated in the future
349 350 351 352
  PD_SPECIALIZE_ComputeCallHelper(const bool&);
  PD_SPECIALIZE_ComputeCallHelper(const int&);
  PD_SPECIALIZE_ComputeCallHelper(const float&);
  PD_SPECIALIZE_ComputeCallHelper(const int64_t&);
353

C
Chen Weihang 已提交
354 355 356 357 358 359 360 361
  // NOTE(chenweihang): Used to be compatible with the 2.1 released
  // interface, but not recommended
  PD_SPECIALIZE_ComputeCallHelper(std::string);
  PD_SPECIALIZE_ComputeCallHelper(std::vector<int>);
  PD_SPECIALIZE_ComputeCallHelper(std::vector<float>);
  PD_SPECIALIZE_ComputeCallHelper(std::vector<int64_t>);
  PD_SPECIALIZE_ComputeCallHelper(std::vector<std::string>);

362 363
  // Used to be compatible with 2.3 released internal inplace interface, not
  // recommended
364
  // Handle args for compatible inplace case
365 366 367
  template <typename... Tail>
  struct ComputeCallHelper<Tensor*, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
368
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
369 370 371 372 373 374 375 376 377
      auto& range = ctx->OutputRangeAt(out_idx);
      auto* arg = ctx->MutableOutputAt(range.first);
      ComputeCallHelper<
          Tail...>::template Compute<in_idx, attr_idx, out_idx + 1>(ctx,
                                                                    pargs...,
                                                                    arg);
    }
  };

378 379
  // Used to be compatible with 2.3 released internal inplace interface, not
  // recommended
380 381
  // TODO(chenweihang): What is the appropriate output form?
  // std::vector<Tensor>*? or std::vector<Tensor*>? or std::vector<Tensor*>*
382
  // Handle args for compatible inplace case
383 384 385
  template <typename... Tail>
  struct ComputeCallHelper<std::vector<Tensor*>, Tail...> {
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
386
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
387
      auto& range = ctx->OutputRangeAt(out_idx);
C
co63oc 已提交
388
      auto arg = ctx->MutableOutputBetween(range.first, range.second);
389 390 391 392 393 394 395 396 397 398 399 400 401
      ComputeCallHelper<
          Tail...>::template Compute<in_idx, attr_idx, out_idx + 1>(ctx,
                                                                    pargs...,
                                                                    arg);
    }
  };

  template <int out_idx, typename T>
  struct ComputeReturnHelper;

  // For compatibility with the original custom op form
  template <int out_idx>
  struct ComputeReturnHelper<out_idx, std::vector<Tensor>> {
402
    static void Compute(CustomOpKernelContext* ctx, Args&... args) {
403 404
      static_assert(out_idx == 0,
                    "If return std::vector<Tensor> in Custom OpKernel, "
H
HongyuJia 已提交
405
                    "you cannot pass output by kernel function argument.");
406
      auto outs = impl_fn(args...);
407
      auto* orig_outs = ctx->AllMutablePlainOutput();
408 409 410 411 412 413 414 415
      PD_CHECK(orig_outs->size() == outs.size(),
               "The number of element in custom operator outputs is wrong, "
               "expected contains ",
               orig_outs->size(),
               " Tensors, but actually contains ",
               outs.size(),
               " Tensors.");
      for (size_t i = 0; i < outs.size(); ++i) {
416
        AssignTensorImpl(outs.at(i), orig_outs->at(i));
417 418 419 420 421 422
      }
    }
  };

  template <int out_idx>
  struct ComputeReturnHelper<out_idx, void> {
423
    static void Compute(CustomOpKernelContext* ctx, Args&... args) {
424 425 426 427
      impl_fn(args...);
    }
  };

428 429 430
  // end: base template
  template <typename T>
  struct ComputeCallHelper<TypeTag<T>> {
431
    template <int in_idx, int attr_idx, int out_idx, typename... PreviousArgs>
432
    static void Compute(CustomOpKernelContext* ctx, PreviousArgs&... pargs) {
433
      ComputeReturnHelper<out_idx, Return>::Compute(ctx, pargs...);
434 435 436 437 438 439 440 441 442 443 444
    }
  };
};

#define PD_KERNEL(...) \
  ::paddle::KernelFuncImpl<decltype(&__VA_ARGS__), &__VA_ARGS__>::Compute

/////////////// InferShape Function (PD_INFER_SHAPE) ///////////////

// Record Op infershape core function
using InferShapeFunc = std::vector<std::vector<int64_t>> (*)(
445
    const std::vector<std::vector<int64_t>>& input_shapes,
446
    const std::vector<std::vector<std::vector<int64_t>>>& vec_input_shapes,
447 448
    const std::vector<paddle::any>& attrs);

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
#define PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPE(input_type)     \
  template <typename... Tail>                                        \
  struct InferShapeCallHelper<input_type, Tail...> {                 \
    template <int in_idx,                                            \
              int vec_in_idx,                                        \
              int attr_idx,                                          \
              typename... PreviousArgs>                              \
    static Return InferShape(                                        \
        const std::vector<std::vector<int64_t>>& input_shapes,       \
        const std::vector<std::vector<std::vector<int64_t>>>&        \
            vec_input_shapes,                                        \
        const std::vector<paddle::any>& attrs,                       \
        const PreviousArgs&... pargs) {                              \
      input_type arg = input_shapes[in_idx];                         \
      return InferShapeCallHelper<Tail...>::                         \
          template InferShape<in_idx + 1, vec_in_idx, attr_idx>(     \
              input_shapes, vec_input_shapes, attrs, pargs..., arg); \
    }                                                                \
467 468
  }

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
#define PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPES(input_type)    \
  template <typename... Tail>                                        \
  struct InferShapeCallHelper<input_type, Tail...> {                 \
    template <int in_idx,                                            \
              int vec_in_idx,                                        \
              int attr_idx,                                          \
              typename... PreviousArgs>                              \
    static Return InferShape(                                        \
        const std::vector<std::vector<int64_t>>& input_shapes,       \
        const std::vector<std::vector<std::vector<int64_t>>>&        \
            vec_input_shapes,                                        \
        const std::vector<paddle::any>& attrs,                       \
        const PreviousArgs&... pargs) {                              \
      input_type arg = vec_input_shapes[vec_in_idx];                 \
      return InferShapeCallHelper<Tail...>::                         \
          template InferShape<in_idx, vec_in_idx + 1, attr_idx>(     \
              input_shapes, vec_input_shapes, attrs, pargs..., arg); \
    }                                                                \
487 488
  }

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
#define PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(attr_type)               \
  template <typename... Tail>                                                \
  struct InferShapeCallHelper<attr_type, Tail...> {                          \
    template <int in_idx,                                                    \
              int vec_in_idx,                                                \
              int attr_idx,                                                  \
              typename... PreviousArgs>                                      \
    static Return InferShape(                                                \
        const std::vector<std::vector<int64_t>>& input_shapes,               \
        const std::vector<std::vector<std::vector<int64_t>>>&                \
            vec_input_shapes,                                                \
        const std::vector<paddle::any>& attrs,                               \
        const PreviousArgs&... pargs) {                                      \
      try {                                                                  \
        attr_type arg = paddle::any_cast<attr_type>(attrs[attr_idx]);        \
        return InferShapeCallHelper<Tail...>::                               \
            template InferShape<in_idx, vec_in_idx, attr_idx + 1>(           \
                input_shapes, vec_input_shapes, attrs, pargs..., arg);       \
      } catch (paddle::bad_any_cast&) {                                      \
        PD_THROW(                                                            \
            "Attribute cast error in custom operator InferShapeFn. "         \
            "Expected " #attr_type                                           \
            " value. InferShapeFn's attribute list must be exactly same as " \
            "Forward "                                                       \
            "KernelFn's attribute list except std::vector<int64_t> "         \
            "attribute.");                                                   \
      }                                                                      \
    }                                                                        \
517
  }
518 519 520 521 522 523

template <typename F, F f>
struct InferShapeFuncImpl;

template <typename Return, typename... Args, Return (*impl_fn)(Args...)>
struct InferShapeFuncImpl<Return (*)(Args...), impl_fn> {
524
  static Return InferShape(
525
      const std::vector<std::vector<int64_t>>& input_shapes,
526
      const std::vector<std::vector<std::vector<int64_t>>>& vec_input_shapes,
527
      const std::vector<paddle::any>& attrs) {
528 529
    return InferShapeCallHelper<Args..., TypeTag<int>>::
        template InferShape<0, 0, 0>(input_shapes, vec_input_shapes, attrs);
530 531 532 533 534 535
  }

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

536 537 538
  PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPE(const std::vector<int64_t>&);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPES(
      const std::vector<std::vector<int64_t>>&);
539

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
  template <typename... Tail>
  struct InferShapeCallHelper<const paddle::optional<std::vector<int64_t>>&,
                              Tail...> {
    template <int in_idx,
              int vec_in_idx,
              int attr_idx,
              typename... PreviousArgs>
    static Return InferShape(
        const std::vector<std::vector<int64_t>>& input_shapes,
        const std::vector<std::vector<std::vector<int64_t>>>& vec_input_shapes,
        const std::vector<paddle::any>& attrs,
        const PreviousArgs&... pargs) {
      const std::vector<int64_t>& arg = input_shapes[in_idx];
      if (arg.empty()) {
        return InferShapeCallHelper<Tail...>::
            template InferShape<in_idx + 1, vec_in_idx, attr_idx>(
                input_shapes, vec_input_shapes, attrs, pargs..., paddle::none);
      } else {
        return InferShapeCallHelper<Tail...>::
            template InferShape<in_idx + 1, vec_in_idx, attr_idx>(
                input_shapes, vec_input_shapes, attrs, pargs..., arg);
      }
    }
  };

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  template <typename... Tail>
  struct InferShapeCallHelper<
      const paddle::optional<std::vector<std::vector<int64_t>>>&,
      Tail...> {
    template <int in_idx,
              int vec_in_idx,
              int attr_idx,
              typename... PreviousArgs>
    static Return InferShape(
        const std::vector<std::vector<int64_t>>& input_shapes,
        const std::vector<std::vector<std::vector<int64_t>>>& vec_input_shapes,
        const std::vector<paddle::any>& attrs,
        const PreviousArgs&... pargs) {
      const std::vector<std::vector<int64_t>>& arg =
          vec_input_shapes[vec_in_idx];
      if (arg.empty()) {
        return InferShapeCallHelper<Tail...>::
            template InferShape<in_idx, vec_in_idx + 1, attr_idx>(
                input_shapes, vec_input_shapes, attrs, pargs..., paddle::none);
      } else {
        return InferShapeCallHelper<Tail...>::
            template InferShape<in_idx, vec_in_idx + 1, attr_idx>(
                input_shapes, vec_input_shapes, attrs, pargs..., arg);
      }
    }
  };

592 593 594 595 596
  // NOTE(chenweihang): Used to be compatible with the 2.0.1 released
  // interface, and will be deprecated in the future
  PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPE(std::vector<int64_t>);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPES(
      std::vector<std::vector<int64_t>>);
597

598 599 600 601
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(bool);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(int);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(float);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(int64_t);
602 603 604 605 606 607 608 609
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::string&);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::vector<int>&);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::vector<float>&);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::vector<std::string>&);
  // NOTE(chenweihang): InferShape can't support std::vector<int64_t> attr type,
  // because the input type is std::vector<int64_t>, only can use one rule to
  // parse std::vector<int64_t> parameter

610 611 612 613 614 615 616
  // NOTE(chenweihang): Used to be compatible with the 2.0.1 released
  // interface, and will be deprecated in the future
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const bool&);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const int&);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const float&);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const int64_t&);

C
Chen Weihang 已提交
617 618 619 620 621 622 623
  // NOTE(chenweihang): Used to be compatible with the 2.1 released
  // interface, but not recommended
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::string);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::vector<int>);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::vector<float>);
  PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::vector<std::string>);

624 625 626
  // end: base template
  template <typename T>
  struct InferShapeCallHelper<TypeTag<T>> {
627
    template <int in_idx, int vec_in_idx, int attr_idx>
628
    static Return InferShape(
629 630
        const std::vector<std::vector<int64_t>>& input_shapes,
        const std::vector<std::vector<std::vector<int64_t>>>& vec_input_shapes,
631 632
        const std::vector<paddle::any>& attrs,
        const Args&... args) {
633 634 635 636 637 638 639 640 641 642 643
      return impl_fn(args...);
    }
  };
};

#define PD_INFER_SHAPE(...) \
  ::paddle::InferShapeFuncImpl<decltype(&__VA_ARGS__), &__VA_ARGS__>::InferShape

/////////////// InferDataType Function (PD_INFER_DTYPE) ///////////////

// Record Op Infer dtype core function
644
using InferDtypeFunc = std::vector<DataType> (*)(
645
    const std::vector<DataType>& input_dtypes,
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    const std::vector<std::vector<DataType>>& vec_input_dtypes,
    const std::vector<paddle::any>& attrs);

#define PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPE(input_type)     \
  template <typename... Tail>                                        \
  struct InferDtypeCallHelper<input_type, Tail...> {                 \
    template <int in_idx,                                            \
              int vec_in_idx,                                        \
              int attr_idx,                                          \
              typename... PreviousArgs>                              \
    static Return InferDtype(                                        \
        const std::vector<DataType>& input_dtypes,                   \
        const std::vector<std::vector<DataType>>& vec_input_dtypes,  \
        const std::vector<paddle::any>& attrs,                       \
        const PreviousArgs&... pargs) {                              \
      input_type arg = input_dtypes[in_idx];                         \
      return InferDtypeCallHelper<Tail...>::                         \
          template InferDtype<in_idx + 1, vec_in_idx, attr_idx>(     \
              input_dtypes, vec_input_dtypes, attrs, pargs..., arg); \
    }                                                                \
  }
667

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
#define PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPES(input_type)    \
  template <typename... Tail>                                        \
  struct InferDtypeCallHelper<input_type, Tail...> {                 \
    template <int in_idx,                                            \
              int vec_in_idx,                                        \
              int attr_idx,                                          \
              typename... PreviousArgs>                              \
    static Return InferDtype(                                        \
        const std::vector<DataType>& input_dtypes,                   \
        const std::vector<std::vector<DataType>>& vec_input_dtypes,  \
        const std::vector<paddle::any>& attrs,                       \
        const PreviousArgs&... pargs) {                              \
      input_type arg = vec_input_dtypes[vec_in_idx];                 \
      return InferDtypeCallHelper<Tail...>::                         \
          template InferDtype<in_idx, vec_in_idx + 1, attr_idx>(     \
              input_dtypes, vec_input_dtypes, attrs, pargs..., arg); \
    }                                                                \
  }

#define PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(attr_type)               \
688
  template <typename... Tail>                                                \
689 690 691 692 693
  struct InferDtypeCallHelper<attr_type, Tail...> {                          \
    template <int in_idx,                                                    \
              int vec_in_idx,                                                \
              int attr_idx,                                                  \
              typename... PreviousArgs>                                      \
694 695 696
    static Return InferDtype(                                                \
        const std::vector<DataType>& input_dtypes,                           \
        const std::vector<std::vector<DataType>>& vec_input_dtypes,          \
697
        const std::vector<paddle::any>& attrs,                               \
698
        const PreviousArgs&... pargs) {                                      \
699 700 701 702 703 704 705 706 707 708 709 710
      try {                                                                  \
        attr_type arg = paddle::any_cast<attr_type>(attrs[attr_idx]);        \
        return InferDtypeCallHelper<Tail...>::                               \
            template InferDtype<in_idx, vec_in_idx, attr_idx + 1>(           \
                input_dtypes, vec_input_dtypes, attrs, pargs..., arg);       \
      } catch (paddle::bad_any_cast&) {                                      \
        PD_THROW(                                                            \
            "Attribute cast error in custom operator InferDtypeFn. "         \
            "Expected " #attr_type                                           \
            " value. InferDtypeFn's attribute list must be exactly same as " \
            "Forward KernelFn's attribute list");                            \
      }                                                                      \
711 712 713
    }                                                                        \
  }

714 715 716 717 718
template <typename F, F f>
struct InferDtypeFuncImpl;

template <typename Return, typename... Args, Return (*impl_fn)(Args...)>
struct InferDtypeFuncImpl<Return (*)(Args...), impl_fn> {
719
  static Return InferDtype(
720
      const std::vector<DataType>& input_dtypes,
721 722 723 724
      const std::vector<std::vector<DataType>>& vec_input_dtypes,
      const std::vector<paddle::any>& attrs) {
    return InferDtypeCallHelper<Args..., TypeTag<int>>::
        template InferDtype<0, 0, 0>(input_dtypes, vec_input_dtypes, attrs);
725 726 727 728 729 730
  }

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

731
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPE(const DataType&);
732
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPES(const std::vector<DataType>&);
733

734
  template <typename... Tail>
735
  struct InferDtypeCallHelper<const paddle::optional<DataType>&, Tail...> {
736 737 738 739
    template <int in_idx,
              int vec_in_idx,
              int attr_idx,
              typename... PreviousArgs>
740 741 742
    static Return InferDtype(
        const std::vector<DataType>& input_dtypes,
        const std::vector<std::vector<DataType>>& vec_input_dtypes,
743
        const std::vector<paddle::any>& attrs,
744 745 746
        const PreviousArgs&... pargs) {
      const DataType& arg = input_dtypes[in_idx];
      if (arg == DataType::UNDEFINED) {
747 748 749
        return InferDtypeCallHelper<Tail...>::
            template InferDtype<in_idx + 1, vec_in_idx, attr_idx>(
                input_dtypes, vec_input_dtypes, attrs, pargs..., paddle::none);
750
      } else {
751 752 753
        return InferDtypeCallHelper<Tail...>::
            template InferDtype<in_idx + 1, vec_in_idx, attr_idx>(
                input_dtypes, vec_input_dtypes, attrs, pargs..., arg);
754 755 756 757
      }
    }
  };

758 759 760
  template <typename... Tail>
  struct InferDtypeCallHelper<const paddle::optional<std::vector<DataType>>&,
                              Tail...> {
761 762 763 764
    template <int in_idx,
              int vec_in_idx,
              int attr_idx,
              typename... PreviousArgs>
765 766 767
    static Return InferDtype(
        const std::vector<DataType>& input_dtypes,
        const std::vector<std::vector<DataType>>& vec_input_dtypes,
768
        const std::vector<paddle::any>& attrs,
769 770 771 772
        const PreviousArgs&... pargs) {
      const std::vector<DataType>& arg = vec_input_dtypes[vec_in_idx];
      if (arg.empty()) {
        return InferDtypeCallHelper<Tail...>::
773 774
            template InferDtype<in_idx, vec_in_idx + 1, attr_idx>(
                input_dtypes, vec_input_dtypes, attrs, pargs..., paddle::none);
775 776
      } else {
        return InferDtypeCallHelper<Tail...>::
777 778
            template InferDtype<in_idx, vec_in_idx + 1, attr_idx>(
                input_dtypes, vec_input_dtypes, attrs, pargs..., arg);
779 780 781 782
      }
    }
  };

783
  // NOTE(HongyuJia): Used to be compatible with the 2.0.1 released
784
  // interface, and will be deprecated in the future
785
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPE(DataType);
786
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPES(std::vector<DataType>);
787

788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(bool);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(int);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(float);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(int64_t);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const std::string&);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const std::vector<int>&);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const std::vector<float>&);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const std::vector<int64_t>&);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const std::vector<std::string>&);

  // NOTE(HongyuJia): Used to be compatible with the 2.0.1 released
  // interface, and will be deprecated in the future
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const bool&);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const int&);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const float&);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(const int64_t&);

  // NOTE(HongyuJia): Used to be compatible with the 2.1 released
  // interface, but not recommended
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(std::string);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(std::vector<int>);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(std::vector<float>);
  PD_SPECIALIZE_InferDtypeCallHelper_FOR_ATTR(std::vector<std::string>);

812 813 814
  // end: base template
  template <typename T>
  struct InferDtypeCallHelper<TypeTag<T>> {
815
    template <int in_idx, int vec_in_idx, int attr_idx>
816
    static Return InferDtype(
817 818
        const std::vector<DataType>& input_dtypes,
        const std::vector<std::vector<DataType>>& vec_input_dtypes,
819
        const std::vector<paddle::any>& attrs,
820
        const Args&... args) {
821 822 823 824 825 826 827 828 829 830
      return impl_fn(args...);
    }
  };
};

#define PD_INFER_DTYPE(...) \
  ::paddle::InferDtypeFuncImpl<decltype(&__VA_ARGS__), &__VA_ARGS__>::InferDtype

////////////////////// Op Meta Info //////////////////////

831
class PADDLE_API OpMetaInfo {
832 833
 public:
  explicit OpMetaInfo(const std::string& op_name) : name_(op_name) {}
834 835

  // format: {"<name1>", "<name2>", ...}
836
  OpMetaInfo& Inputs(std::vector<std::string>&& inputs);
837 838

  // format: {"<name1>", "<name2>", ...}
839
  OpMetaInfo& Outputs(std::vector<std::string>&& outputs);
840

841
  // format: {"<name1>:<type1>", "<name2>:<type2>", ...}
842 843
  OpMetaInfo& Attrs(std::vector<std::string>&& attrs);

844 845
  // format: {"<input_name1>:<output_name1>",
  // "<input_name2>:<output_name2>",...}
846
  OpMetaInfo& SetInplaceMap(
847 848
      std::unordered_map<std::string, std::string>&& inplace_map);

849
  // format: PD_KERNEL(...)
850
  OpMetaInfo& SetKernelFn(KernelFunc&& func);
851 852

  // format: PD_INFER_SHAPE(...)
853
  OpMetaInfo& SetInferShapeFn(InferShapeFunc&& func);
854 855

  // format: PD_INFER_DTYPE(...)
856 857 858
  OpMetaInfo& SetInferDtypeFn(InferDtypeFunc&& func);

 private:
859
  friend class OpMetaInfoHelper;
860 861 862 863 864 865

  // 1. desc info
  std::string name_;
  std::vector<std::string> inputs_;
  std::vector<std::string> outputs_;
  std::vector<std::string> attrs_;
866
  std::unordered_map<std::string, std::string> inplace_map_;
867
  std::unordered_map<std::string, std::string> inplace_reverse_map_;
868
  // 2. func info
869 870 871
  KernelFunc kernel_fn_{nullptr};
  InferShapeFunc infer_shape_fn_{nullptr};
  InferDtypeFunc infer_dtype_fn_{nullptr};
872 873
};

874 875 876
//////////////// Op Meta Info Helper /////////////////
class OpMetaInfoHelper {
 public:
877
  static const std::string& GetOpName(const paddle::OpMetaInfo& info);
878
  static const std::vector<std::string>& GetInputs(
879
      const paddle::OpMetaInfo& info);
880
  static const std::vector<std::string>& GetOutputs(
881
      const paddle::OpMetaInfo& info);
882
  static const std::vector<std::string>& GetAttrs(
883
      const paddle::OpMetaInfo& info);
884
  static const std::unordered_map<std::string, std::string>& GetInplaceMap(
885
      const paddle::OpMetaInfo& info);
886
  static const std::unordered_map<std::string, std::string>&
887 888 889 890
  GetInplaceReverseMap(const paddle::OpMetaInfo& info);
  static const KernelFunc& GetKernelFn(const paddle::OpMetaInfo& info);
  static const InferShapeFunc& GetInferShapeFn(const paddle::OpMetaInfo& info);
  static const InferDtypeFunc& GetInferDtypeFn(const paddle::OpMetaInfo& info);
891 892
};

893 894
//////////////// Op Meta Info Map /////////////////

895
class PADDLE_API OpMetaInfoMap {
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
 public:
  // this function's impl should keep in header file.
  // if move to cc file, meta info can not be added
  // into map
  static OpMetaInfoMap& Instance() {
    static OpMetaInfoMap g_custom_op_meta_info_map;
    return g_custom_op_meta_info_map;
  }

  std::vector<OpMetaInfo>& operator[](const std::string& name);

  const std::unordered_map<std::string, std::vector<OpMetaInfo>>& GetMap()
      const;

 private:
  OpMetaInfoMap() = default;
  std::unordered_map<std::string, std::vector<OpMetaInfo>> map_;

  PD_DISABLE_COPY_AND_ASSIGN(OpMetaInfoMap);
};

//////////////// Op Meta Info Builder /////////////////

919
class PADDLE_API OpMetaInfoBuilder {
920
 public:
921
  explicit OpMetaInfoBuilder(std::string&& name, size_t index);
922 923
  OpMetaInfoBuilder& Inputs(std::vector<std::string>&& inputs);
  OpMetaInfoBuilder& Outputs(std::vector<std::string>&& outputs);
924
  OpMetaInfoBuilder& Attrs(std::vector<std::string>&& attrs);
925
  OpMetaInfoBuilder& SetInplaceMap(
926
      std::unordered_map<std::string, std::string>&& inplace_map);
927 928 929
  OpMetaInfoBuilder& SetKernelFn(KernelFunc func);
  OpMetaInfoBuilder& SetInferShapeFn(InferShapeFunc func);
  OpMetaInfoBuilder& SetInferDtypeFn(InferDtypeFunc func);
930 931 932 933

 private:
  // Forward Op name
  std::string name_;
934
  // ref current info ptr
935
  OpMetaInfo* info_ptr_;
936 937 938
  // The current op meta info index in vector
  // - 0: op, 1: grad_op, 2: grad_grad_op
  size_t index_;
939 940 941 942
};

/////////////////////// Op register Macro /////////////////////////

943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
#define PD_BUILD_OP(op_name)                                                   \
  STATIC_ASSERT_GLOBAL_NAMESPACE(                                              \
      __reg_op__##op_name, "PD_BUILD_OP must be called in global namespace."); \
  static ::paddle::OpMetaInfoBuilder __op_meta_info_##op_name##__ =            \
      ::paddle::OpMetaInfoBuilder(#op_name, 0)

#define PD_BUILD_GRAD_OP(op_name)                                        \
  STATIC_ASSERT_GLOBAL_NAMESPACE(                                        \
      __reg_grad_op__##op_name,                                          \
      "PD_BUILD_GRAD_OP must be called in global namespace.");           \
  static ::paddle::OpMetaInfoBuilder __grad_op_meta_info_##op_name##__ = \
      ::paddle::OpMetaInfoBuilder(#op_name, 1)

#define PD_BUILD_DOUBLE_GRAD_OP(op_name)                                      \
  STATIC_ASSERT_GLOBAL_NAMESPACE(                                             \
      __reg_grad_grad_op__##op_name,                                          \
      "PD_BUILD_DOUBLE_GRAD_OP must be called in global namespace.");         \
  static ::paddle::OpMetaInfoBuilder __grad_grad_op_meta_info_##op_name##__ = \
      ::paddle::OpMetaInfoBuilder(#op_name, 2)
962

963 964 965 966 967 968 969 970
}  // namespace paddle

///////////////////// C API ///////////////////

#ifdef __cplusplus
extern "C" {
#endif

971
#if defined(_WIN32)
972
// C-API to get global OpMetaInfoMap.
973 974 975 976
__declspec(dllexport) inline paddle::OpMetaInfoMap& PD_GetOpMetaInfoMap() {
  return paddle::OpMetaInfoMap::Instance();
}
#endif  // _WIN32
977 978 979 980

#ifdef __cplusplus
}
#endif