custom_operator.cc 48.1 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 23 24 25 26 27
/* 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. */

#include "paddle/fluid/framework/custom_operator.h"

#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

28
#include "paddle/fluid/eager/api/utils/global_utils.h"
29
#include "paddle/fluid/framework/attribute.h"
30
#include "paddle/fluid/framework/convert_utils.h"
31 32
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
33
#include "paddle/fluid/framework/phi_utils.h"
34
#include "paddle/fluid/framework/tensor.h"
35
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
36 37
#include "paddle/fluid/platform/dynload/dynamic_loader.h"
#include "paddle/fluid/string/string_helper.h"
38 39
#include "paddle/phi/api/all.h"
#include "paddle/phi/core/compat/convert_utils.h"
40
#include "paddle/phi/core/tensor_utils.h"
41
#include "paddle/utils/any.h"
H
HongyuJia 已提交
42 43 44
#ifdef PADDLE_WITH_CUSTOM_DEVICE
#include "paddle/phi/backends/device_manager.h"
#endif
45

46
#include "gflags/gflags.h"
47
#include "paddle/phi/api/include/operants_manager.h"
48 49 50 51
#include "paddle/phi/api/include/tensor_operants.h"

DECLARE_string(tensor_operants_mode);

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
namespace paddle {
namespace framework {

namespace detail {

// dynamic lib load func
template <typename T>
static T* DynLoad(void* handle, std::string name) {
  T* func = reinterpret_cast<T*>(dlsym(handle, name.c_str()));
#if !defined(_WIN32)
  auto errorno = dlerror();
#else
  auto errorno = GetLastError();
#endif  // !_WIN32
  PADDLE_ENFORCE_NOT_NULL(
67 68 69 70
      func,
      platform::errors::NotFound(
          "Failed to load dynamic operator library, error message(%s).",
          errorno));
71 72 73
  return func;
}

74
inline static bool IsDuplicableVar(const std::string& var_name) {
75 76 77 78
  std::string suffix = kTensorVectorSuffix;
  return var_name.rfind(suffix) != std::string::npos;
}

79 80 81 82 83
inline static bool IsOptionalVar(const std::string& var_name) {
  std::string suffix = kOptionalSuffix;
  return var_name.rfind(suffix) != std::string::npos;
}

84 85
inline static std::string NoGrad(const std::string& var_name,
                                 bool is_double_grad = false) {
86
  std::string suffix = kGradVarSuffix;
87 88 89 90 91 92 93 94
  std::string new_out_suffix = kDoubleGradNewOutSuffix;
  std::string tmp_var_name(var_name);
  if (is_double_grad &&
      (tmp_var_name.rfind(new_out_suffix) != std::string::npos)) {
    tmp_var_name = tmp_var_name.substr(
        0, tmp_var_name.size() - /*kDoubleGradNewOutSuffix length*/ 4);
  }
  return tmp_var_name.substr(0, tmp_var_name.size() - kGradVarSuffixSize);
95 96
}

97 98 99 100 101 102 103 104 105 106 107
inline static bool IsGradVar(const std::string& var_name, bool is_double_grad) {
  std::string suffix = kGradVarSuffix;
  if (!is_double_grad) {
    return var_name.rfind(suffix) != std::string::npos;
  } else {
    // for double grad cases, the X@GRAD is not a grad var, X@GRAD@GRAD is a
    // grad var, here we remove a @GRAD suffix
    return NoGrad(var_name).rfind(suffix) != std::string::npos;
  }
}

108 109
inline static bool IsMemberOf(const std::vector<std::string>& vec,
                              const std::string& name) {
110 111 112
  return std::find(vec.cbegin(), vec.cend(), name) != vec.cend();
}

113
static std::vector<std::string> ParseAttrStr(const std::string& attr) {
114
  auto split_pos = attr.find_first_of(":");
115 116
  PADDLE_ENFORCE_NE(split_pos,
                    std::string::npos,
117 118 119 120 121 122 123 124 125 126
                    platform::errors::InvalidArgument(
                        "Invalid attribute string format. Attribute string "
                        "format is `<name>:<type>`."));

  std::vector<std::string> rlt;
  // 1. name
  rlt.emplace_back(string::trim_spaces(attr.substr(0, split_pos)));
  // 2. type
  rlt.emplace_back(string::trim_spaces(attr.substr(split_pos + 1)));

127
  VLOG(3) << "attr name: " << rlt[0] << ", attr type str: " << rlt[1];
128 129 130 131

  return rlt;
}

132 133 134 135 136
}  // namespace detail

////////////////// Kernel Define ////////////////////

// custom op kernel call function define
137 138 139 140 141 142 143
static void RunKernelFunc(
    const framework::ExecutionContext& ctx,
    const paddle::KernelFunc& func,
    const std::vector<std::string>& inputs,
    const std::vector<std::string>& outputs,
    const std::vector<std::string>& attrs,
    const std::unordered_map<std::string, std::string>& inplace_map) {
144
  VLOG(3) << "Custom Operator: Start run KernelFunc.";
145 146
  // prepare CustomOpKernelContext
  paddle::CustomOpKernelContext kernel_ctx;
147
  for (auto& in_name : inputs) {
148
    VLOG(3) << "Custom Operator: input name - " << in_name;
149
    if (detail::IsDuplicableVar(in_name)) {  // inputs vector<Tensor>
150
      std::vector<paddle::Tensor> custom_vec_in;
151 152 153 154
      if (ctx.HasInputs(in_name)) {  // general inputs
        // return const std::vector<const phi::DenseTensor*>
        auto vec_x = ctx.MultiInput<phi::DenseTensor>(in_name);
        PADDLE_ENFORCE_NE(vec_x.empty(),
155
                          true,
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
                          platform::errors::NotFound(
                              "Input vector<tensor> (%s) is empty.", in_name));
        for (size_t i = 0; i < vec_x.size(); ++i) {
          auto* x = vec_x[i];
          PADDLE_ENFORCE_NOT_NULL(
              x,
              platform::errors::NotFound(
                  "The %d-th tensor in input vector<tensor> (%s) is nullptr.",
                  i,
                  in_name));
          PADDLE_ENFORCE_EQ(x->IsInitialized(),
                            true,
                            platform::errors::InvalidArgument(
                                "The %d-th tensor in input vector<tensor> (%s) "
                                "is not initialized.",
                                i,
                                in_name));
          paddle::Tensor custom_t;
          custom_t.set_impl(std::make_shared<phi::DenseTensor>(*x));
          custom_vec_in.emplace_back(custom_t);
        }
      } else {  // optional inputs, `custom_vec_in` is empty
        PADDLE_ENFORCE(
            detail::IsOptionalVar(in_name),
            phi::errors::NotFound("Your custom operator's KernelFunc cannot "
                                  "find input parameter `%s`",
                                  in_name));
        VLOG(3) << "Custom Operator: KernelFunc's vector input " << in_name
                << " is optional dtype with None input";
185
      }
186
      kernel_ctx.EmplaceBackInputs(std::move(custom_vec_in));
187 188 189 190 191 192 193 194 195 196 197 198 199
    } else {                        // inputs Tensor
      if (ctx.HasInput(in_name)) {  // general inputs
        auto* x = ctx.Input<phi::DenseTensor>(in_name);
        PADDLE_ENFORCE_NOT_NULL(x,
                                platform::errors::NotFound(
                                    "Input tensor (%s) is nullptr.", in_name));
        PADDLE_ENFORCE_EQ(
            x->IsInitialized(),
            true,
            platform::errors::InvalidArgument(
                "Input tensor (%s) is not initialized.", in_name));
        paddle::Tensor custom_in;
        custom_in.set_impl(std::make_shared<phi::DenseTensor>(*x));
200
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
201 202 203 204 205 206 207 208
        if (custom_in.is_gpu_pinned()) {
          VLOG(3) << "Custom Operator: custom input is gpu pinned tensor";
          auto gpu_place = phi::GPUPlace(platform::GetCurrentDeviceId());
          auto custom_gpu_in = custom_in.copy_to(gpu_place, true);
          kernel_ctx.EmplaceBackInput(std::move(custom_gpu_in));
        } else {
          kernel_ctx.EmplaceBackInput(std::move(custom_in));
        }
209
#else
210
        kernel_ctx.EmplaceBackInput(std::move(custom_in));
211
#endif
212 213 214 215 216 217 218 219 220 221
      } else {  // optional inputs
        PADDLE_ENFORCE(
            detail::IsOptionalVar(in_name),
            phi::errors::NotFound("Your custom operator's KernelFunc cannot "
                                  "find input parameter `%s`",
                                  in_name));
        VLOG(3) << "Custom Operator: KernelFunc's input " << in_name
                << " is optional dtype with None input";
        kernel_ctx.EmplaceBackInput(std::move(paddle::Tensor()));
      }
222
    }
223 224
  }

225 226 227 228 229
  for (auto& attr_str : attrs) {
    auto attr_name_and_type = detail::ParseAttrStr(attr_str);
    auto attr_name = attr_name_and_type[0];
    auto attr_type_str = attr_name_and_type[1];
    if (attr_type_str == "bool") {
230
      kernel_ctx.EmplaceBackAttr(ctx.Attr<bool>(attr_name));
231
    } else if (attr_type_str == "int") {
232
      kernel_ctx.EmplaceBackAttr(ctx.Attr<int>(attr_name));
233
    } else if (attr_type_str == "float") {
234
      kernel_ctx.EmplaceBackAttr(ctx.Attr<float>(attr_name));
235
    } else if (attr_type_str == "int64_t") {
236
      kernel_ctx.EmplaceBackAttr(ctx.Attr<int64_t>(attr_name));
237
    } else if (attr_type_str == "std::string") {
238
      kernel_ctx.EmplaceBackAttr(ctx.Attr<std::string>(attr_name));
239
    } else if (attr_type_str == "std::vector<int>") {
240
      kernel_ctx.EmplaceBackAttr(ctx.Attr<std::vector<int>>(attr_name));
241
    } else if (attr_type_str == "std::vector<float>") {
242
      kernel_ctx.EmplaceBackAttr(ctx.Attr<std::vector<float>>(attr_name));
243
    } else if (attr_type_str == "std::vector<int64_t>") {
244
      kernel_ctx.EmplaceBackAttr(ctx.Attr<std::vector<int64_t>>(attr_name));
245
    } else if (attr_type_str == "std::vector<std::string>") {
246
      kernel_ctx.EmplaceBackAttr(ctx.Attr<std::vector<std::string>>(attr_name));
247 248 249 250 251
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported `%s` type value as custom attribute now. "
          "Supported data types include `bool`, `int`, `float`, "
          "`int64_t`, `std::string`, `std::vector<int>`, "
252
          "`std::vector<float>`, `std::vector<int64_t>`, "
253 254 255 256 257
          "`std::vector<std::string>`, Please check whether "
          "the attribute data type and data type string are matched.",
          attr_type_str));
    }
  }
258

259 260
  VLOG(3) << "Custom Operator: push outputs into CustomOpKernelContext.";
  // cache the target tensor pointers
261
  std::vector<phi::DenseTensor*> true_out_ptrs;
262 263 264 265 266 267 268 269
  for (size_t i = 0; i < outputs.size(); ++i) {
    auto out_name = outputs[i];
    if (detail::IsDuplicableVar(out_name)) {
      PADDLE_ENFORCE(i == 0UL && outputs.size() == 1UL,
                     platform::errors::PreconditionNotMet(
                         "If custom operator's outputs contains `paddle::Vec("
                         ")` type, "
                         "it only can hold one output."));
270
      auto vec_out = ctx.MultiOutput<phi::DenseTensor>(out_name);
271 272
      PADDLE_ENFORCE_NE(vec_out.empty(),
                        true,
273 274
                        platform::errors::NotFound(
                            "Output vector<tensor> (%s) is empty.", out_name));
275
      std::vector<paddle::Tensor> custom_vec_out;
276 277 278 279 280
      for (size_t j = 0; j < vec_out.size(); ++j) {
        auto* out = vec_out[j];
        PADDLE_ENFORCE_NOT_NULL(
            out,
            platform::errors::NotFound(
281 282
                "The %d-th tensor in output vector<tensor> (%s) is nullptr.",
                j,
283 284
                out_name));
        true_out_ptrs.emplace_back(out);
285
        paddle::Tensor custom_t;
286
        // here only can copy the output tensor into context
287
        custom_t.set_impl(std::make_shared<phi::DenseTensor>(*out));
288 289 290 291
        custom_vec_out.emplace_back(custom_t);
      }
      kernel_ctx.EmplaceBackOutputs(std::move(custom_vec_out));
    } else {
292
      auto* out = ctx.Output<phi::DenseTensor>(out_name);
293 294 295
      PADDLE_ENFORCE_NOT_NULL(out,
                              platform::errors::NotFound(
                                  "Output tensor (%s) is nullptr.", out_name));
296
      true_out_ptrs.emplace_back(out);
297
      paddle::Tensor custom_out;
298
      // here only can copy the output tensor into context
299
      custom_out.set_impl(std::make_shared<phi::DenseTensor>(*out));
300 301 302
      kernel_ctx.EmplaceBackOutput(std::move(custom_out));
    }
  }
303

304 305
  try {
    VLOG(3) << "Custom Operator: Run ComputeFunc.";
306 307

    FLAGS_tensor_operants_mode = "phi";
308 309
    if (paddle::OperantsManager::Instance().phi_operants.get() == nullptr) {
      paddle::OperantsManager::Instance().phi_operants.reset(
310 311 312 313
          new paddle::operants::PhiTensorOperants());
      VLOG(4) << "Initialize phi tensor operants successfully";
    }

314
    // handle inplace map
315
    kernel_ctx.MapPlainOutputs(inputs, outputs, inplace_map);
316
    func(&kernel_ctx);
317
    kernel_ctx.AssignInplaceOutputs();
318 319 320 321

    // sync output tensor data into original output
    auto* calc_outs = kernel_ctx.AllMutableOutput();
    PADDLE_ENFORCE_EQ(
322 323
        true_out_ptrs.size(),
        calc_outs->size(),
324 325 326 327
        platform::errors::InvalidArgument(
            "The number of element in custom operator outputs is wrong, "
            "expected contains %d Tensors, but actually contains %d "
            "Tensors.",
328 329
            true_out_ptrs.size(),
            calc_outs->size()));
330 331 332
    for (size_t i = 0; i < true_out_ptrs.size(); ++i) {
      auto* true_out = true_out_ptrs.at(i);
      auto calc_out =
333
          std::dynamic_pointer_cast<phi::DenseTensor>(calc_outs->at(i).impl());
334
      // assign meta info
335
      auto* true_out_meta = phi::DenseTensorUtils::GetMutableMeta(true_out);
336 337 338
      true_out_meta->dims = calc_out->dims();
      true_out_meta->dtype = calc_out->dtype();
      true_out_meta->layout = calc_out->layout();
339 340
      true_out_meta->offset = calc_out->offset();
      // lod no need to be reset
341 342 343
      // reset holder if needed
      if (true_out->Holder() != calc_out->Holder()) {
        true_out->ResetHolder(calc_out->Holder());
344
      }
345 346 347 348 349 350 351
    }
  } catch (platform::EnforceNotMet& exception) {
    throw std::move(exception);
  } catch (std::exception& ex) {
    PADDLE_THROW(platform::errors::External("%s", ex.what()));
  } catch (...) {
    PADDLE_THROW(platform::errors::Fatal(
352
        "Custom operator raises an unknown exception in runtime."));
353 354 355
  }
}

356 357 358 359 360 361 362 363 364 365 366 367
static void RunInferShapeFunc(framework::InferShapeContext* ctx,
                              const paddle::InferShapeFunc& func,
                              const std::vector<std::string>& inputs,
                              const std::vector<std::string>& outputs,
                              const std::vector<std::string>& attrs) {
  std::vector<std::vector<int64_t>> input_shapes;
  std::vector<std::vector<std::vector<int64_t>>> vec_input_shapes;

  VLOG(3) << "Custom Operator: InferShape - get input ddim.";
  for (auto& in_name : inputs) {
    if (detail::IsDuplicableVar(in_name)) {
      std::vector<std::vector<int64_t>> vec_shape;
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
      if (ctx->HasInputs(in_name)) {  // general inputs
        auto vec_ddim = ctx->GetInputsDim(in_name);
        vec_shape.reserve(vec_ddim.size());
        std::transform(vec_ddim.begin(),
                       vec_ddim.end(),
                       std::back_inserter(vec_shape),
                       [&](const DDim& ddim) -> std::vector<int64_t> {
                         return phi::vectorize(ddim);
                       });

      } else {  // optional inputs, `vec_shape` is empty
        PADDLE_ENFORCE(
            detail::IsOptionalVar(in_name),
            phi::errors::NotFound("Your custom operator's InferShapeFunc "
                                  "cannot find input parameter `%s`",
                                  in_name));
        VLOG(3) << "Custom Operator: InferShapeFunc's vector input " << in_name
                << " is optional dtype with None input";
      }
387 388
      vec_input_shapes.emplace_back(vec_shape);
    } else {
389 390 391 392 393 394 395 396 397 398 399 400 401
      if (ctx->HasInput(in_name)) {  // general inputs
        auto ddim = ctx->GetInputDim(in_name);
        input_shapes.emplace_back(phi::vectorize(ddim));
      } else {  // optional inputs
        PADDLE_ENFORCE(
            detail::IsOptionalVar(in_name),
            phi::errors::NotFound("Your custom operator's InferShapeFunc "
                                  "cannot find input parameter `%s`",
                                  in_name));
        input_shapes.emplace_back(std::vector<int64_t>());
        VLOG(3) << "Custom Operator: InferShapeFunc's input " << in_name
                << " is optional dtype with None input";
      }
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    }
  }

  std::vector<paddle::any> custom_attrs;
  for (auto& attr_str : attrs) {
    auto attr_name_and_type = detail::ParseAttrStr(attr_str);
    auto attr_name = attr_name_and_type[0];
    auto attr_type_str = attr_name_and_type[1];
    if (attr_type_str == "bool") {
      custom_attrs.emplace_back(ctx->Attrs().Get<bool>(attr_name));
    } else if (attr_type_str == "int") {
      custom_attrs.emplace_back(ctx->Attrs().Get<int>(attr_name));
    } else if (attr_type_str == "float") {
      custom_attrs.emplace_back(ctx->Attrs().Get<float>(attr_name));
    } else if (attr_type_str == "int64_t") {
      custom_attrs.emplace_back(ctx->Attrs().Get<int64_t>(attr_name));
    } else if (attr_type_str == "std::string") {
      custom_attrs.emplace_back(ctx->Attrs().Get<std::string>(attr_name));
    } else if (attr_type_str == "std::vector<int>") {
      custom_attrs.emplace_back(ctx->Attrs().Get<std::vector<int>>(attr_name));
    } else if (attr_type_str == "std::vector<float>") {
      custom_attrs.emplace_back(
          ctx->Attrs().Get<std::vector<float>>(attr_name));
    } else if (attr_type_str == "std::vector<int64_t>") {
      // 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
      continue;
    } else if (attr_type_str == "std::vector<std::string>") {
      custom_attrs.emplace_back(
          ctx->Attrs().Get<std::vector<std::string>>(attr_name));
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported `%s` type value as custom attribute now. "
          "Supported data types include `bool`, `int`, `float`, "
          "`int64_t`, `std::string`, `std::vector<int>`, "
          "`std::vector<float>`, `std::vector<std::string>`, "
          "Please check whether the attribute data type and "
          "data type string are matched.",
          attr_type_str));
    }
  }

  VLOG(3) << "Custom Operator: InferShape - calc output ddim.";
  auto output_shapes = func(input_shapes, vec_input_shapes, custom_attrs);

  VLOG(3) << "Custom Operator: InferShape - set output ddim.";
  for (size_t i = 0; i < outputs.size(); ++i) {
    auto out_name = outputs[i];
    if (detail::IsDuplicableVar(out_name)) {
      std::vector<DDim> vec_ddim;
      vec_ddim.reserve(output_shapes.size());
454 455
      std::transform(output_shapes.begin(),
                     output_shapes.end(),
456 457
                     std::back_inserter(vec_ddim),
                     [&](const std::vector<int64_t>& shape) -> DDim {
458
                       return phi::make_ddim(shape);
459 460 461
                     });
      ctx->SetOutputsDim(out_name, vec_ddim);
    } else {
462
      ctx->SetOutputDim(out_name, phi::make_ddim(output_shapes[i]));
463 464 465 466
    }
  }
}

467 468 469 470 471 472 473 474 475
//////////////////// Operator Define /////////////////

class CustomOperator : public OperatorWithKernel {
 public:
  using OperatorWithKernel::OperatorWithKernel;

  // Dummy infershape
  // Because it is a pure virtual function, it must be implemented
  void InferShape(framework::InferShapeContext* ctx) const override {
476
    VLOG(3) << "Custom Operator: Dummy infer shape of custom operator.";
477 478 479 480 481 482 483 484 485 486 487 488
  }

  /**
   * NOTE: [Skip the Kernel Selection]
   * Custom Op only registers one Op kernel on each device, so that the
   * data type selection and promotion that depends on GetExpectedKernelType,
   * as well as the adaptation of various other special situations,
   * need users to implement, to avoid users needs to implement
   * GetExpectedKernelType function when expanding other cases.
   * The RAW type is used here as the data type, indicating that
   * it can only be determined at runtime.
   */
489
  phi::KernelKey GetExpectedKernelType(
490
      const framework::ExecutionContext& ctx) const override {
491
    return phi::KernelKey(ctx.GetPlace());
492 493 494 495 496 497 498
  }

  /**
   * NOTE: [Skip Input Variable Cast for DataType]
   * Because the kernel data type is RAW, we should skip the cast for
   * data type difference when PrepareData.
   */
499
  phi::KernelKey GetKernelTypeForVar(
500
      const std::string& var_name,
501
      const phi::DenseTensor& tensor,
502 503 504 505
      const phi::KernelKey& expected_kernel_type) const override {
    return phi::KernelKey(phi::Backend::ALL_BACKEND,
                          tensor.layout(),
                          expected_kernel_type.dtype());
506 507 508 509 510 511 512 513 514 515 516 517
  }
};

class CustomOpMaker : public OpProtoAndCheckerMaker {
 public:
  explicit CustomOpMaker(const std::vector<std::string>& inputs,
                         const std::vector<std::string>& outputs,
                         const std::vector<std::string>& attrs)
      : inputs_(inputs), outputs_(outputs), attrs_(attrs) {}

  void Make() override {
    for (auto& in_name : inputs_) {
518 519
      auto input_var_builder =
          AddInput(in_name, "The input " + in_name + "of Custom operator.");
520
      if (detail::IsDuplicableVar(in_name)) {
521 522 523 524
        input_var_builder.AsDuplicable();
      }
      if (detail::IsOptionalVar(in_name)) {
        input_var_builder.AsDispensable();
525
      }
526 527
    }
    for (auto& out_name : outputs_) {
528 529 530 531 532 533
      if (detail::IsDuplicableVar(out_name)) {
        AddOutput(out_name, "The output " + out_name + "of Custom Operator.")
            .AsDuplicable();
      } else {
        AddOutput(out_name, "The output " + out_name + "of Custom Operator.");
      }
534
    }
535 536 537 538 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 565 566 567 568 569 570 571 572 573
    for (auto& attr : attrs_) {
      auto attr_name_and_type = detail::ParseAttrStr(attr);
      auto attr_name = attr_name_and_type[0];
      auto attr_type_str = attr_name_and_type[1];
      if (attr_type_str == "bool") {
        AddAttr<bool>(attr_name, "custom operator bool attribute.")
            .SetDefault(false);
      } else if (attr_type_str == "int") {
        AddAttr<int>(attr_name, "custom operator int attribute.").SetDefault(1);
      } else if (attr_type_str == "float") {
        AddAttr<float>(attr_name, "custom operator float attribute.")
            .SetDefault(1.0f);
      } else if (attr_type_str == "int64_t") {
        AddAttr<int64_t>(attr_name, "custom operator int64_t attribute.")
            .SetDefault(1);
      } else if (attr_type_str == "std::string") {
        AddAttr<std::string>(attr_name, "custom operator int attribute.")
            .SetDefault("");
      } else if (attr_type_str == "std::vector<int>") {
        AddAttr<std::vector<int>>(attr_name,
                                  "custom operator std::vector<int> attribute.")
            .SetDefault({});
      } else if (attr_type_str == "std::vector<float>") {
        AddAttr<std::vector<float>>(
            attr_name, "custom operator std::vector<float> attribute.")
            .SetDefault({});
      } else if (attr_type_str == "std::vector<int64_t>") {
        AddAttr<std::vector<int64_t>>(
            attr_name, "custom operator std::vector<int64_t> attribute.")
            .SetDefault({});
      } else if (attr_type_str == "std::vector<std::string>") {
        AddAttr<std::vector<std::string>>(
            attr_name, "custom operator std::vector<std::string> attribute.")
            .SetDefault({});
      } else {
        PADDLE_THROW(platform::errors::Unimplemented(
            "Unsupported `%s` type value as custom attribute now. "
            "Supported data types include `bool`, `int`, `float`, "
            "`int64_t`, `std::string`, `std::vector<int>`, "
574
            "`std::vector<float>`, `std::vector<int64_t>`, "
575 576 577 578 579
            "`std::vector<std::string>`, Please check whether "
            "the attribute data type and data type string are matched.",
            attr_type_str));
      }
    }
580 581 582
    AddComment(R"DOC(
Custom Operator.

583
According to the phi::DenseTensor operation function implemented by the user
584
independently of the framework, it is encapsulated into a framework
H
HongyuJia 已提交
585 586
operator to adapt to various execution scenarios such as dynamic graph
mode, static graph mode, and inference mode.
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

)DOC");
  }

 private:
  std::vector<std::string> inputs_;
  std::vector<std::string> outputs_;
  std::vector<std::string> attrs_;
};

template <typename T>
class CustomGradOpMaker;

template <>
class CustomGradOpMaker<OpDesc> : public SingleGradOpMaker<OpDesc> {
 public:
  explicit CustomGradOpMaker(
604 605
      const OpDesc& fwd_op,
      const std::unordered_set<std::string>& no_grad_set,
606
      std::unordered_map<std::string, std::string>* grad_to_var,
607 608
      const std::vector<BlockDesc*>& grad_block,
      const std::string& name,
609
      const std::vector<std::string>& inputs,
610 611
      const std::vector<std::string>& outputs,
      bool is_double_grad)
612 613 614
      : SingleGradOpMaker<OpDesc>(fwd_op, no_grad_set, grad_to_var, grad_block),
        name_(name),
        inputs_(inputs),
615 616
        outputs_(outputs),
        is_double_grad_(is_double_grad) {}
617 618 619 620 621 622 623 624 625

 protected:
  void Apply(GradOpPtr<OpDesc> grad_op) const override {
    grad_op->SetType(name_);

    auto fwd_op_inputs = this->InputNames();
    auto fwd_op_outputs = this->OutputNames();

    for (auto& in_name : inputs_) {
626
      VLOG(3) << "Custom Operator: GradOpDescMaker - input: " << in_name;
627
      if (!detail::IsGradVar(in_name, is_double_grad_)) {
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
        if (detail::IsMemberOf(fwd_op_inputs, in_name)) {
          grad_op->SetInput(in_name, this->Input(in_name));
        } else if (detail::IsMemberOf(fwd_op_outputs, in_name)) {
          grad_op->SetInput(in_name, this->Output(in_name));
        } else {
          PADDLE_THROW(platform::errors::InvalidArgument(
              "The input tensor name `%s` is invalid, expected it is the input "
              "or output of forward operator.",
              in_name));
        }
      } else {
        grad_op->SetInput(in_name, this->OutputGrad(detail::NoGrad(in_name)));
      }
    }
    for (auto& out_name : outputs_) {
643
      VLOG(3) << "Custom Operator: GradOpDescMaker - output: " << out_name;
644
      if (detail::IsDuplicableVar(out_name)) {
645
        grad_op->SetOutput(
646 647 648
            out_name,
            this->InputGrad(detail::NoGrad(out_name, is_double_grad_),
                            /*drop_empty_grad=*/false));
649
      } else {
650 651 652
        grad_op->SetOutput(
            out_name,
            this->InputGrad(detail::NoGrad(out_name, is_double_grad_)));
653
      }
654
    }
655
    grad_op->SetAttrMap(this->Attrs());
656 657 658 659 660 661
  }

 private:
  std::string name_;
  std::vector<std::string> inputs_;
  std::vector<std::string> outputs_;
662
  bool is_double_grad_{false};
663 664 665 666 667 668 669 670 671 672 673 674
};

template <>
class CustomGradOpMaker<imperative::OpBase>
    : public SingleGradOpMaker<imperative::OpBase> {
 public:
  explicit CustomGradOpMaker(
      const std::string& type,
      const imperative::NameVarBaseMap& var_base_map_in,
      const imperative::NameVarBaseMap& var_base_map_out,
      const AttributeMap& attrs,
      const std::map<std::string, std::string>& inplace_map,
675 676 677 678
      const std::string& name,
      const std::vector<std::string>& inputs,
      const std::vector<std::string>& outputs,
      bool is_double_grad)
679 680 681 682
      : SingleGradOpMaker<imperative::OpBase>(
            type, var_base_map_in, var_base_map_out, attrs, inplace_map),
        name_(name),
        inputs_(inputs),
683 684
        outputs_(outputs),
        is_double_grad_(is_double_grad) {}
685 686 687 688 689 690 691 692 693 694 695 696 697 698

 protected:
  // TODO(chenweihang): The code is duplicated with the previous one, because
  // ere OpMaker's Input, Output and other methods are protected. Putting the
  // function implementation outside the class will cause the method to be
  // uncallable,
  // so it is still implemented in the class for the time being.
  void Apply(GradOpPtr<imperative::OpBase> grad_op) const override {
    grad_op->SetType(name_);

    auto fwd_op_inputs = this->InputNames();
    auto fwd_op_outputs = this->OutputNames();

    for (auto& in_name : inputs_) {
699
      VLOG(3) << "Custom Operator: GradOpBaseMaker - input: " << in_name;
700
      if (!detail::IsGradVar(in_name, is_double_grad_)) {
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        if (detail::IsMemberOf(fwd_op_inputs, in_name)) {
          grad_op->SetInput(in_name, this->Input(in_name));
        } else if (detail::IsMemberOf(fwd_op_outputs, in_name)) {
          grad_op->SetInput(in_name, this->Output(in_name));
        } else {
          PADDLE_THROW(platform::errors::InvalidArgument(
              "The input tensor name `%s` is invalid, expected it is the input "
              "or output of forward operator.",
              in_name));
        }
      } else {
        grad_op->SetInput(in_name, this->OutputGrad(detail::NoGrad(in_name)));
      }
    }
    for (auto& out_name : outputs_) {
716
      VLOG(3) << "Custom Operator: GradOpBaseMaker - output: " << out_name;
717 718
      grad_op->SetOutput(
          out_name, this->InputGrad(detail::NoGrad(out_name, is_double_grad_)));
719
    }
720
    grad_op->SetAttrMap(this->Attrs());
721 722 723 724 725 726
  }

 private:
  std::string name_;
  std::vector<std::string> inputs_;
  std::vector<std::string> outputs_;
727
  bool is_double_grad_{false};
728 729 730 731
};

//////////// Operator and Kernel Register //////////////

732 733 734
static void RegisterOperatorKernelWithPlace(
    const std::string& name,
    const OperatorWithKernel::OpKernelFunc& op_kernel_func,
735 736
    const proto::VarType::Type type,
    const platform::Place& place) {
737
  OpKernelType key(type, place);
738
  VLOG(3) << "Custom Operator: op kernel key: " << key;
739
  OperatorWithKernel::AllOpKernels()[name][key] = op_kernel_func;
740 741
}

742 743 744 745 746 747 748 749
static void RegisterOperatorKernel(
    const std::string& name,
    const paddle::KernelFunc& kernel_func,
    const std::vector<std::string>& inputs,
    const std::vector<std::string>& outputs,
    const std::vector<std::string>& attrs,
    const std::unordered_map<std::string, std::string>& inplace_map,
    void* dso_handle) {
750
  VLOG(3) << "Custom Operator: op name in kernel: " << name;
751 752 753 754 755
  // NOTE [ Dummy Op Kernel Key ]
  // TODO(chenweihang): Because execute engine need get device context based
  // op_kernel_key.place_, so we should register kernel for each
  // device. But this is not entirely correct, if user only give a cpu kernel,
  // but call api in gpu device, it will cause error.
756 757 758
  OperatorWithKernel::OpKernelFunc op_kernel_func;
  if (kernel_func) {
    VLOG(3) << "Register custom operator " << name << " with kernel func";
759
    op_kernel_func = [kernel_func, inputs, outputs, attrs, inplace_map](
760
                         const framework::ExecutionContext& ctx) {
761
      VLOG(3) << "Custom Operator: run custom kernel func in lambda.";
762
      RunKernelFunc(ctx, kernel_func, inputs, outputs, attrs, inplace_map);
763 764 765 766 767 768 769 770 771 772 773 774 775
    };
  } else {
    VLOG(3) << "Register custom operator " << name
            << " with raw op kernel func";
    PADDLE_ENFORCE_NOT_NULL(
        dso_handle,
        platform::errors::InvalidArgument(
            "The dso handle must be provided if kernel_func is nullptr."));
    using OpKernelFuncPtr = void(const framework::ExecutionContext&);
    auto symbol_name = "PD_" + name + "_raw_op_kernel_func";
    auto* func = detail::DynLoad<OpKernelFuncPtr>(dso_handle, symbol_name);
    op_kernel_func = func;
  }
776 777
  RegisterOperatorKernelWithPlace(
      name, op_kernel_func, proto::VarType::RAW, platform::CPUPlace());
778
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
779 780
  RegisterOperatorKernelWithPlace(
      name, op_kernel_func, proto::VarType::RAW, platform::CUDAPlace());
781
#endif
782 783 784 785
#if defined(PADDLE_WITH_XPU)
  RegisterOperatorKernelWithPlace(
      name, op_kernel_func, proto::VarType::RAW, platform::XPUPlace());
#endif
H
HongyuJia 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  auto device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
  for (const auto& dev_type : device_types) {
    for (size_t dev_id = 0;
         dev_id < phi::DeviceManager::GetDeviceCount(dev_type);
         dev_id++) {
      RegisterOperatorKernelWithPlace(name,
                                      op_kernel_func,
                                      proto::VarType::RAW,
                                      platform::CustomPlace(dev_type, dev_id));
    }
  }
#endif
799 800
}

801 802
void RegisterOperatorWithMetaInfo(const std::vector<OpMetaInfo>& op_meta_infos,
                                  void* dso_handle) {
803 804 805 806 807 808
  /* Op register */
  OpInfo info;

  auto& base_op_meta = op_meta_infos.front();

  auto op_name = OpMetaInfoHelper::GetOpName(base_op_meta);
809 810

  if (OpInfoMap::Instance().Has(op_name)) {
811
    LOG(WARNING) << "Operator (" << op_name << ") has been registered.";
812 813 814
    return;
  }

815 816 817
  auto& op_inputs = OpMetaInfoHelper::GetInputs(base_op_meta);
  auto& op_outputs = OpMetaInfoHelper::GetOutputs(base_op_meta);
  auto& op_attrs = OpMetaInfoHelper::GetAttrs(base_op_meta);
818
  auto& op_inplace_map = OpMetaInfoHelper::GetInplaceMap(base_op_meta);
819 820 821 822
  auto& kernel_fn = OpMetaInfoHelper::GetKernelFn(base_op_meta);
  auto& infer_shape_func = OpMetaInfoHelper::GetInferShapeFn(base_op_meta);
  auto& infer_dtype_func = OpMetaInfoHelper::GetInferDtypeFn(base_op_meta);

823 824
  VLOG(3) << "Custom Operator: forward, op name: " << op_name;
  VLOG(3) << "Custom Operator: forward, op inputs: "
825
          << string::join_strings(op_inputs, ',');
826
  VLOG(3) << "Custom Operator: forward, op outputs: "
827
          << string::join_strings(op_outputs, ',');
828
  VLOG(3) << "Custom Operator: forward, op attrs: "
829
          << string::join_strings(op_attrs, ',');
830 831 832 833 834 835
  if (!op_inplace_map.empty()) {
    VLOG(3) << "Custom Operator: forward, op inplace_map: "
            << string::join_strings(op_inplace_map, ',', [](auto& pair) {
                 return pair.first + ": " + pair.second;
               });
  }
836 837

  // Op
838 839
  info.creator_ = [](const std::string& op_name,
                     const VariableNameMap& inputs,
840 841 842 843 844 845 846 847 848 849 850 851 852
                     const VariableNameMap& outputs,
                     const AttributeMap& attrs) {
    return new CustomOperator(op_name, inputs, outputs, attrs);
  };

  // OpMaker
  info.proto_ = new proto::OpProto;
  info.proto_->set_type(op_name);

  info.checker_ = new OpAttrChecker();
  CustomOpMaker custom_maker(op_inputs, op_outputs, op_attrs);
  custom_maker(info.proto_, info.checker_);
  PADDLE_ENFORCE_EQ(
853 854
      info.proto_->IsInitialized(),
      true,
855 856
      platform::errors::PreconditionNotMet(
          "Fail to initialize %s's OpProto, because %s is not initialized.",
857 858
          op_name,
          info.proto_->InitializationErrorString()));
859

860 861 862 863 864 865 866
  // Inplace
  if (!op_inplace_map.empty()) {
    info.infer_inplace_ = [op_inplace_map](bool use_cuda) {
      return op_inplace_map;
    };
  }

867
  // InferShape
868 869 870 871
  if (infer_shape_func == nullptr) {
    // use default InferShape
    info.infer_shape_ = [op_inputs, op_outputs](InferShapeContext* ctx) {
      PADDLE_ENFORCE_EQ(
872 873
          op_inputs.size(),
          1UL,
874 875 876
          platform::errors::Unavailable(
              "Your custom operator contains multiple inputs. "
              "We only allow a custom operator that contains only one input "
877 878 879
              "and only one output without setting the InferShapeFn. "
              "At this time, the input shape will be directly set to "
              "the output shape.\n"
880 881 882
              "Please set the InferShapeFn of custom "
              "operator by .SetInferShapeFn(PD_INFER_SHAPE(...))"));
      PADDLE_ENFORCE_EQ(
883 884
          op_outputs.size(),
          1UL,
885 886 887
          platform::errors::Unavailable(
              "Your custom operator contains multiple outputs. "
              "We only allow a custom operator that contains only one input "
888 889 890
              "and only one output without setting the InferShapeFn. "
              "At this time, the input shape will be directly set to "
              "the output shape.\n"
891 892 893
              "Please set the InferShapeFn of custom "
              "operator by .SetInferShapeFn(PD_INFER_SHAPE(...))"));

894
      VLOG(3) << "Custom Operator: Default InferShape - share ddim.";
895 896 897
      ctx->ShareDim(op_inputs[0], op_outputs[0]);
    };
  } else {
898 899
    info.infer_shape_ = [op_inputs, op_outputs, op_attrs, infer_shape_func](
                            InferShapeContext* ctx) {
900
      RunInferShapeFunc(ctx, infer_shape_func, op_inputs, op_outputs, op_attrs);
901 902
    };
  }
903 904

  // Infer Dtype
905
  if (infer_dtype_func == nullptr) {
906
    // use default InferDtype
907 908
    info.infer_var_type_ = [op_inputs, op_outputs](InferVarTypeContext* ctx) {
      PADDLE_ENFORCE_EQ(
909 910
          op_inputs.size(),
          1UL,
911 912 913
          platform::errors::Unavailable(
              "Your custom operator contains multiple inputs. "
              "We only allow a custom operator that contains only one input "
914 915 916
              "and only one output without setting the InferDtypeFn. "
              "At this time, the input dtype will be directly set to "
              "the output dtype.\n"
917 918 919
              "Please set the InferDtypeFn of custom "
              "operator by .SetInferDtypeFn(PD_INFER_DTYPE(...))"));
      PADDLE_ENFORCE_EQ(
920 921
          op_outputs.size(),
          1UL,
922 923 924
          platform::errors::Unavailable(
              "Your custom operator contains multiple outputs. "
              "We only allow a custom operator that contains only one input "
925 926 927
              "and only one output without setting the InferDtypeFn. "
              "At this time, the input dtype will be directly set to "
              "the output dtype.\n"
928 929 930
              "Please set the InferDtypeFn of custom "
              "operator by .SetInferDtypeFn(PD_INFER_DTYPE(...))"));

931
      VLOG(3) << "Custom Operator: InferDtype - share dtype.";
932 933 934 935
      auto dtype = ctx->GetInputDataType(op_inputs[0]);
      ctx->SetOutputDataType(op_outputs[0], dtype);
    };
  } else {
936 937 938 939 940 941 942 943 944
    info.infer_var_type_ =
        [op_inputs, op_outputs, infer_dtype_func](InferVarTypeContext* ctx) {
          std::vector<DataType> input_dtypes;
          std::vector<std::vector<DataType>> vec_input_dtypes;

          VLOG(3) << "Custom Operator: InferDtype - get input dtype.";
          for (auto& in_name : op_inputs) {
            if (detail::IsDuplicableVar(in_name)) {
              std::vector<DataType> vec_custom_dtype;
945 946 947 948 949 950 951 952 953 954 955 956 957 958
              if (ctx->HasInput(in_name)) {  // general inputs
                for (size_t i = 0; i < ctx->InputSize(in_name); ++i) {
                  auto dtype = ctx->GetInputDataType(in_name, i);
                  vec_custom_dtype.emplace_back(
                      paddle::framework::TransToPhiDataType(dtype));
                }
              } else {  // optional inputs, `vec_custom_dtype` is empty
                PADDLE_ENFORCE(
                    detail::IsOptionalVar(in_name),
                    phi::errors::NotFound("Your custom operator's InferDtypeFn "
                                          "cannot find input parameter `%s`",
                                          in_name));
                VLOG(3) << "Custom Operator: InferDtypeFn's vector input "
                        << in_name << " is optional dtype with None input";
959 960 961
              }
              vec_input_dtypes.emplace_back(vec_custom_dtype);
            } else {
962 963 964 965 966 967 968 969 970 971 972 973 974 975
              if (ctx->HasInput(in_name)) {  // general inputs
                auto dtype = ctx->GetInputDataType(in_name);
                input_dtypes.emplace_back(
                    paddle::framework::TransToPhiDataType(dtype));
              } else {  // optional inputs
                PADDLE_ENFORCE(
                    detail::IsOptionalVar(in_name),
                    phi::errors::NotFound("Your custom operator's InferDtypeFn "
                                          "cannot find input parameter `%s`",
                                          in_name));
                input_dtypes.emplace_back(DataType::UNDEFINED);
                VLOG(3) << "Custom Operator: InferDtypeFn's input " << in_name
                        << " is optional dtype with None input";
              }
976
            }
977
          }
978

979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
          VLOG(3) << "Custom Operator: InferDtype - infer output dtype.";
          auto output_dtypes = infer_dtype_func(input_dtypes, vec_input_dtypes);

          VLOG(3) << "Custom Operator: InferDtype - set output dtype.";
          for (size_t i = 0; i < op_outputs.size(); ++i) {
            auto out_name = op_outputs[i];
            if (detail::IsDuplicableVar(out_name)) {
              for (size_t j = 0; j < output_dtypes.size(); ++j) {
                auto dtype =
                    paddle::framework::TransToProtoVarType(output_dtypes[i]);
                ctx->SetOutputDataType(out_name, dtype, j);
              }
            } else {
              ctx->SetOutputDataType(
                  out_name,
                  paddle::framework::TransToProtoVarType(output_dtypes[i]));
            }
996
          }
997
        };
998
  }
999 1000

  // Kernel func
1001 1002 1003 1004 1005 1006 1007
  RegisterOperatorKernel(op_name,
                         kernel_fn,
                         op_inputs,
                         op_outputs,
                         op_attrs,
                         op_inplace_map,
                         dso_handle);
1008 1009 1010 1011 1012 1013 1014 1015 1016

  // If grad op or double grad op exists
  std::string cur_op_name = op_name;
  for (size_t i = 1; i < op_meta_infos.size(); ++i) {
    auto& cur_grad_op = op_meta_infos[i];

    auto& grad_op_name = OpMetaInfoHelper::GetOpName(cur_grad_op);
    auto& grad_op_inputs = OpMetaInfoHelper::GetInputs(cur_grad_op);
    auto& grad_op_outputs = OpMetaInfoHelper::GetOutputs(cur_grad_op);
1017
    auto& grad_op_attrs = OpMetaInfoHelper::GetAttrs(cur_grad_op);
1018
    auto& grad_op_inplace_map = OpMetaInfoHelper::GetInplaceMap(cur_grad_op);
1019
    auto& grad_kernel_fn = OpMetaInfoHelper::GetKernelFn(cur_grad_op);
1020
    auto& grad_infer_shape_fn = OpMetaInfoHelper::GetInferShapeFn(cur_grad_op);
1021

1022 1023
    VLOG(3) << "Custom Operator: backward, op name: " << grad_op_name;
    VLOG(3) << "Custom Operator: backward, op inputs: "
1024
            << string::join_strings(grad_op_inputs, ',');
1025
    VLOG(3) << "Custom Operator: backward, op outputs: "
1026
            << string::join_strings(grad_op_outputs, ',');
1027 1028 1029 1030 1031 1032 1033 1034
    VLOG(3) << "Custom Operator: backward, op attrs: "
            << string::join_strings(grad_op_attrs, ',');
    if (!op_inplace_map.empty()) {
      VLOG(3) << "Custom Operator: backward, op inplace_map: "
              << string::join_strings(grad_op_inplace_map, ',', [](auto& pair) {
                   return pair.first + ": " + pair.second;
                 });
    }
1035

1036 1037
    bool is_double_grad = (i == 2);

1038
    // GradOpDescMaker
1039 1040 1041 1042 1043 1044
    info.grad_op_maker_ =
        [grad_op_name, grad_op_inputs, grad_op_outputs, is_double_grad](
            const OpDesc& fwd_op,
            const std::unordered_set<std::string>& no_grad_set,
            std::unordered_map<std::string, std::string>* grad_to_var,
            const std::vector<BlockDesc*>& grad_block) {
1045 1046 1047 1048 1049 1050 1051 1052
          CustomGradOpMaker<paddle::framework::OpDesc> maker(fwd_op,
                                                             no_grad_set,
                                                             grad_to_var,
                                                             grad_block,
                                                             grad_op_name,
                                                             grad_op_inputs,
                                                             grad_op_outputs,
                                                             is_double_grad);
1053 1054
          return maker();
        };
1055 1056

    // GradOpBaseMaker
1057 1058 1059 1060 1061 1062 1063 1064
    info.dygraph_grad_op_maker_ =
        [grad_op_name, grad_op_inputs, grad_op_outputs, is_double_grad](
            const std::string& type,
            const imperative::NameVarBaseMap& var_base_map_in,
            const imperative::NameVarBaseMap& var_base_map_out,
            const framework::AttributeMap& attrs,
            const framework::AttributeMap& default_attrs,
            const std::map<std::string, std::string>& inplace_map) {
1065 1066 1067 1068 1069 1070 1071 1072 1073
          CustomGradOpMaker<paddle::imperative::OpBase> maker(type,
                                                              var_base_map_in,
                                                              var_base_map_out,
                                                              attrs,
                                                              inplace_map,
                                                              grad_op_name,
                                                              grad_op_inputs,
                                                              grad_op_outputs,
                                                              is_double_grad);
1074 1075 1076
          maker.SetDygraphDefaultAttrsMap(default_attrs);
          return maker();
        };
1077 1078 1079 1080 1081

    /* Grad op register */
    OpInfo grad_info;

    // Grad Op
1082 1083 1084 1085 1086 1087
    grad_info.creator_ = [](const std::string& type,
                            const VariableNameMap& inputs,
                            const VariableNameMap& outputs,
                            const AttributeMap& attrs) {
      return new CustomOperator(type, inputs, outputs, attrs);
    };
1088

1089
    // Grad InferShape
1090
    if (grad_infer_shape_fn == nullptr) {
1091 1092
      grad_info.infer_shape_ = [grad_op_inputs,
                                grad_op_outputs,
1093
                                is_double_grad](InferShapeContext* ctx) {
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
        // 1. if forward input exists, gradient's shape is same with forward
        // input
        // default
        //    [Suitable for most situations]
        // 2. if forward input not exists, and only contains one grad input and
        // output,
        //    use grad input shape as grad output shape
        //    [Suitable for the situation that forward input is not used as
        //    backward input]
        for (auto& out_name : grad_op_outputs) {
1104
          auto fwd_name = detail::NoGrad(out_name, is_double_grad);
1105 1106
          if (detail::IsDuplicableVar(fwd_name)) {
            // Duplicable forward var must as backward input
1107 1108
            ctx->ShareDim(fwd_name, out_name);
          } else {
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
            if (ctx->HasInput(fwd_name)) {
              ctx->ShareDim(fwd_name, out_name);
            } else {
              PADDLE_ENFORCE_EQ(
                  grad_op_inputs.size() == 1UL && grad_op_outputs.size() == 1UL,
                  true,
                  platform::errors::Unavailable(
                      "Custom grad operator infershape error. "
                      "If a custom grad operator contains only one input and "
                      "only one output, the input shape will be directly set "
H
HongyuJia 已提交
1119
                      "to the output shape. Otherwise, Please set the forward "
1120
                      "input as the grad operator's input or set the "
H
HongyuJia 已提交
1121
                      "InferShapeFn of custom grad operator by "
1122 1123 1124
                      ".SetInferShapeFn(PD_INFER_SHAPE(...))"));
              ctx->ShareDim(grad_op_inputs[0], out_name);
            }
1125 1126
          }
        }
1127 1128
      };
    } else {
1129 1130 1131
      grad_info.infer_shape_ = [grad_op_inputs,
                                grad_op_outputs,
                                grad_op_attrs,
1132
                                grad_infer_shape_fn](InferShapeContext* ctx) {
1133 1134 1135 1136 1137
        RunInferShapeFunc(ctx,
                          grad_infer_shape_fn,
                          grad_op_inputs,
                          grad_op_outputs,
                          grad_op_attrs);
1138 1139
      };
    }
1140 1141

    // Kernel func
1142 1143 1144 1145 1146
    RegisterOperatorKernel(grad_op_name,
                           grad_kernel_fn,
                           grad_op_inputs,
                           grad_op_outputs,
                           grad_op_attrs,
1147
                           grad_op_inplace_map,
1148
                           dso_handle);
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

    // update current info
    OpInfoMap::Instance().Insert(cur_op_name, info);
    cur_op_name = grad_op_name;
    info = grad_info;
  }
  // insert last info
  OpInfoMap::Instance().Insert(cur_op_name, info);
}

void RegisterOperatorWithMetaInfoMap(
1160
    const paddle::OpMetaInfoMap& op_meta_info_map, void* dso_handle) {
1161
  auto& meta_info_map = op_meta_info_map.GetMap();
1162
  VLOG(3) << "Custom Operator: size of op meta info map - "
1163 1164 1165
          << meta_info_map.size();
  // pair: {op_type, OpMetaInfo}
  for (auto& pair : meta_info_map) {
1166
    VLOG(3) << "Custom Operator: pair first -> op name: " << pair.first;
1167
    RegisterOperatorWithMetaInfo(pair.second, dso_handle);
1168 1169 1170 1171 1172 1173
  }
}

////////////////////// User APIs ///////////////////////

// load op api
1174 1175
const std::unordered_map<std::string, std::vector<OpMetaInfo>>&
LoadOpMetaInfoAndRegisterOp(const std::string& dso_name) {
1176
  void* handle = paddle::platform::dynload::GetOpDsoHandle(dso_name);
1177
  VLOG(3) << "load custom_op lib: " << dso_name;
1178 1179 1180 1181
  typedef OpMetaInfoMap& get_op_meta_info_map_t();
  auto* get_op_meta_info_map =
      detail::DynLoad<get_op_meta_info_map_t>(handle, "PD_GetOpMetaInfoMap");
  auto& op_meta_info_map = get_op_meta_info_map();
1182
  RegisterOperatorWithMetaInfoMap(op_meta_info_map, handle);
1183
  return op_meta_info_map.GetMap();
1184 1185 1186 1187
}

}  // namespace framework
}  // namespace paddle