pybind.cc 110.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2
Copyright (c) 2022 NVIDIA Authors. All Rights Reserved.
3 4 5 6 7

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

8
http://www.apache.org/licenses/LICENSE-2.0
9 10 11 12 13 14

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. */
L
lgone2000 已提交
15
#include <Python.h>
16 17 18 19
// Avoid a problem with copysign defined in pyconfig.h on Windows.
#ifdef copysign
#undef copysign
#endif
20

C
chengduoZH 已提交
21
#include <algorithm>
22
#include <cctype>
23
#include <cstdlib>
24
#include <iterator>
C
chengduoZH 已提交
25
#include <map>
S
sneaxiy 已提交
26
#include <memory>
C
chengduoZH 已提交
27
#include <mutex>  // NOLINT // for call_once
28
#include <sstream>
C
chengduoZH 已提交
29
#include <string>
30 31
#include <tuple>
#include <type_traits>
C
chengduoZH 已提交
32
#include <unordered_map>
33
#include <unordered_set>
C
chengduoZH 已提交
34 35
#include <utility>
#include <vector>
36

37
#include "paddle/fluid/framework/convert_utils.h"
38
#include "paddle/fluid/framework/custom_operator.h"
39
#include "paddle/fluid/framework/data_layout.h"
L
Leo Chen 已提交
40
#include "paddle/fluid/framework/data_type_transform.h"
41
#include "paddle/fluid/framework/details/nan_inf_utils_detail.h"
Y
Yi Wang 已提交
42
#include "paddle/fluid/framework/executor.h"
43
#include "paddle/fluid/framework/executor_cache.h"
44
#include "paddle/fluid/framework/executor_gc_helper.h"
Y
Yi Wang 已提交
45
#include "paddle/fluid/framework/feed_fetch_method.h"
Z
Zhen Wang 已提交
46
#include "paddle/fluid/framework/feed_fetch_type.h"
S
sneaxiy 已提交
47
#include "paddle/fluid/framework/garbage_collector.h"
H
hutuxian 已提交
48
#include "paddle/fluid/framework/io/fs.h"
49
#include "paddle/fluid/framework/ir/coalesce_grad_tensor_pass.h"
H
Huihuang Zheng 已提交
50
#include "paddle/fluid/framework/ir/cost_model.h"
51
#include "paddle/fluid/framework/ir/generate_pass.h"
52
#include "paddle/fluid/framework/ir/pass_builder.h"
Y
Yi Wang 已提交
53 54
#include "paddle/fluid/framework/lod_rank_table.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
L
liutiexing 已提交
55
#include "paddle/fluid/framework/new_executor/executor_statistics.h"
56
#include "paddle/fluid/framework/new_executor/standalone_executor.h"
S
sneaxiy 已提交
57
#include "paddle/fluid/framework/op_info.h"
58
#include "paddle/fluid/framework/op_registry.h"
59
#include "paddle/fluid/framework/op_version_registry.h"
Y
Yu Yang 已提交
60
#include "paddle/fluid/framework/parallel_executor.h"
61
#include "paddle/fluid/framework/phi_utils.h"
Y
Yi Wang 已提交
62
#include "paddle/fluid/framework/prune.h"
63
#include "paddle/fluid/framework/raw_tensor.h"
Y
Refine  
Yu Yang 已提交
64
#include "paddle/fluid/framework/reader.h"
S
sneaxiy 已提交
65
#include "paddle/fluid/framework/scope_pool.h"
66
#include "paddle/fluid/framework/selected_rows_utils.h"
67
#include "paddle/fluid/framework/tensor_util.h"
68
#include "paddle/fluid/framework/trainer.h"
69
#include "paddle/fluid/framework/type_defs.h"
X
Xin Pan 已提交
70
#include "paddle/fluid/framework/version.h"
L
Leo Chen 已提交
71
#include "paddle/fluid/imperative/amp_auto_cast.h"
H
hong 已提交
72
#include "paddle/fluid/imperative/layer.h"
Y
Refine  
Yu Yang 已提交
73
#include "paddle/fluid/memory/allocation/allocator_strategy.h"
74 75
#include "paddle/fluid/platform/bfloat16.h"
#include "paddle/fluid/platform/float16.h"
J
Jiabin Yang 已提交
76
#include "paddle/fluid/prim/utils/utils.h"
77 78 79
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/memory/allocation/cuda_ipc_allocator.h"
#endif
80
#include "paddle/fluid/memory/allocation/mmap_allocator.h"
D
dzhwinter 已提交
81
#include "paddle/fluid/operators/activation_op.h"
L
Leo Chen 已提交
82
#include "paddle/fluid/operators/common_infer_shape_functions.h"
83
#include "paddle/fluid/operators/ops_extra_info.h"
S
sneaxiy 已提交
84
#include "paddle/fluid/operators/py_func_op.h"
85
#include "paddle/fluid/platform/cpu_helper.h"
86
#include "paddle/fluid/platform/device/device_wrapper.h"
87
#include "paddle/fluid/platform/device_context.h"
88
#include "paddle/fluid/platform/dynload/dynamic_loader.h"
Y
Yi Wang 已提交
89
#include "paddle/fluid/platform/enforce.h"
90
#include "paddle/fluid/platform/init.h"
91
#include "paddle/fluid/platform/init_phi.h"
H
hutuxian 已提交
92
#include "paddle/fluid/platform/monitor.h"
Y
Yi Wang 已提交
93 94
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/platform/profiler.h"
C
chenjian 已提交
95 96 97
#include "paddle/fluid/platform/profiler/event_python.h"
#include "paddle/fluid/platform/profiler/event_tracing.h"
#include "paddle/fluid/platform/profiler/profiler.h"
98
#include "paddle/fluid/pybind/cuda_streams_py.h"
99
#include "paddle/fluid/pybind/custom_device_py.h"
100
#include "paddle/fluid/pybind/distributed_py.h"
101
#include "paddle/fluid/pybind/eager.h"
J
Jiabin Yang 已提交
102
#include "paddle/fluid/pybind/imperative.h"
103
#include "paddle/fluid/pybind/io.h"
104
#include "paddle/fluid/pybind/jit.h"
J
james 已提交
105
#include "paddle/fluid/pybind/xpu_streams_py.h"
106
#include "paddle/phi/backends/cpu/cpu_info.h"
107 108
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/lod_utils.h"
109
#include "paddle/utils/none.h"
110 111 112
#ifdef PADDLE_WITH_ASCEND
#include "paddle/fluid/pybind/ascend_wrapper_py.h"
#endif
113
#include "paddle/fluid/pybind/auto_parallel_py.h"
H
Huihuang Zheng 已提交
114
#include "paddle/fluid/pybind/bind_cost_model.h"
L
LiYuRio 已提交
115
#include "paddle/fluid/pybind/bind_fleet_executor.h"
H
hutuxian 已提交
116
#include "paddle/fluid/pybind/box_helper_py.h"
117
#include "paddle/fluid/pybind/communication.h"
118
#include "paddle/fluid/pybind/compatible.h"
Y
Yi Wang 已提交
119
#include "paddle/fluid/pybind/const_value.h"
D
dongdaxiang 已提交
120
#include "paddle/fluid/pybind/data_set_py.h"
Y
Yi Wang 已提交
121
#include "paddle/fluid/pybind/exception.h"
D
dongdaxiang 已提交
122
#include "paddle/fluid/pybind/fleet_wrapper_py.h"
Y
yaoxuefeng 已提交
123
#include "paddle/fluid/pybind/generator_py.h"
124
#include "paddle/fluid/pybind/global_value_getter_setter.h"
125
#include "paddle/fluid/pybind/gloo_context_py.h"
126
#include "paddle/fluid/pybind/gloo_wrapper_py.h"
T
Thunderbrook 已提交
127
#include "paddle/fluid/pybind/heter_wrapper_py.h"
F
flame 已提交
128
#include "paddle/fluid/pybind/inference_api.h"
F
flame 已提交
129
#include "paddle/fluid/pybind/ir.h"
130
#include "paddle/fluid/pybind/metrics_py.h"
T
Thunderbrook 已提交
131
#include "paddle/fluid/pybind/ps_gpu_wrapper_py.h"
132
#include "paddle/fluid/pybind/pybind_variant_caster.h"
133
#include "paddle/phi/backends/device_manager.h"
134

135
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
D
dongdaxiang 已提交
136
#include "paddle/fluid/pybind/nccl_wrapper_py.h"
W
wopeizl 已提交
137
#endif
138
#include "paddle/fluid/framework/data_type.h"
139 140
#include "paddle/fluid/pybind/parallel_executor.h"
#include "paddle/fluid/pybind/place.h"
141 142
#include "paddle/fluid/pybind/protobuf.h"
#include "paddle/fluid/pybind/pybind.h"  // NOLINT
S
sneaxiy 已提交
143
#include "paddle/fluid/pybind/reader_py.h"
144
#include "paddle/fluid/pybind/tensor.h"
Y
Yi Wang 已提交
145
#include "paddle/fluid/pybind/tensor_py.h"
146
#include "paddle/fluid/string/to_string.h"
147 148
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
Y
Yi Wang 已提交
149
#include "paddle/fluid/operators/nccl/nccl_gpu_common.h"
P
peizhilin 已提交
150
#endif
151
#ifndef PADDLE_WITH_HIP
152
#include "paddle/fluid/platform/device/gpu/cuda/cuda_profiler.h"
153
#endif
154
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
D
Dong Zhihong 已提交
155 156
#endif

157
#ifdef PADDLE_WITH_ASCEND_CL
158
#include "paddle/fluid/platform/collective_helper.h"
159 160
#include "paddle/fluid/platform/device/npu/npu_info.h"
#include "paddle/fluid/platform/device/npu/npu_profiler.h"
161 162
#endif

163
#ifdef PADDLE_WITH_XPU
164
#include "paddle/fluid/platform/device/xpu/xpu_info.h"
T
TTerror 已提交
165
#include "paddle/fluid/platform/device/xpu/xpu_op_list.h"
166 167
#endif

168
#ifdef PADDLE_WITH_CUSTOM_DEVICE
169
#include "paddle/fluid/operators/custom_device_common_op_registry.h"
170 171 172
#include "paddle/phi/capi/capi.h"
#endif

173
#include "paddle/fluid/platform/cuda_graph_with_memory_pool.h"
A
Allen Guo 已提交
174

J
jianghaicheng 已提交
175
#ifdef PADDLE_WITH_IPU
A
Allen Guo 已提交
176 177
#include "paddle/fluid/platform/device/ipu/ipu_backend.h"
#include "paddle/fluid/platform/device/ipu/ipu_info.h"
J
jianghaicheng 已提交
178
#endif
179

180 181 182 183
#ifdef PADDLE_WITH_MLU
#include "paddle/fluid/platform/device/mlu/mlu_info.h"
#endif

Y
Yanghello 已提交
184 185 186 187
#ifdef PADDLE_WITH_CRYPTO
#include "paddle/fluid/pybind/crypto.h"
#endif

T
tangwei12 已提交
188
#if defined PADDLE_WITH_PSCORE
T
tangwei12 已提交
189 190 191
#include "paddle/fluid/pybind/fleet_py.h"
#endif

192 193 194 195
#ifdef PADDLE_WITH_CINN
#include "paddle/fluid/framework/paddle2cinn/cinn_compiler.h"
#endif

X
Xinger 已提交
196
#if defined(PADDLE_WITH_RPC)
197 198 199
#include "paddle/fluid/pybind/rpc.h"
#endif

200
#include "paddle/fluid/eager/api/utils/global_utils.h"
201
#include "paddle/fluid/imperative/layout_autotune.h"
202 203
#include "paddle/fluid/prim/utils/eager/eager_tensor_operants.h"
#include "paddle/fluid/prim/utils/static/static_tensor_operants.h"
204 205
#include "paddle/fluid/pybind/eager_utils.h"
#include "paddle/phi/api/ext/op_meta_info.h"
206 207
#include "paddle/phi/api/include/operants_manager.h"
#include "paddle/phi/api/include/tensor_operants.h"
208 209
#include "paddle/phi/kernels/autotune/cache.h"
#include "paddle/phi/kernels/autotune/switch_autotune.h"
M
minqiyang 已提交
210 211
#include "pybind11/stl.h"

212
DECLARE_bool(use_mkldnn);
213

Q
Qiao Longfei 已提交
214 215
// disable auto conversion to list in Python
PYBIND11_MAKE_OPAQUE(paddle::framework::LoDTensorArray);
216 217 218
PYBIND11_MAKE_OPAQUE(paddle::framework::FetchUnmergedList);
PYBIND11_MAKE_OPAQUE(paddle::framework::FetchList);
PYBIND11_MAKE_OPAQUE(paddle::framework::FetchType);
Q
Qiao Longfei 已提交
219

220
DECLARE_FILE_SYMBOLS(init_phi);
221
namespace paddle {
222
namespace pybind {
223

0
0x45f 已提交
224
PyTypeObject *g_framework_scope_pytype = nullptr;
225
PyTypeObject *g_framework_lodtensorarray_pytype = nullptr;
226
PyTypeObject *g_custom_op_kernel_ctx_pytype = nullptr;
227

228 229 230 231 232 233 234 235
bool IsCompiledWithAVX() {
#ifndef PADDLE_WITH_AVX
  return false;
#else
  return true;
#endif
}

236
bool IsCompiledWithCUDA() {
237 238 239 240 241 242 243
#if !defined(PADDLE_WITH_CUDA) && !defined(PADDLE_WITH_HIP)
  return false;
#else
  return true;
#endif
}

244 245 246 247 248 249 250 251
bool IsCompiledWithNCCL() {
#ifdef PADDLE_WITH_NCCL
  return true;
#else
  return false;
#endif
}

W
wuhuachaocoding 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
bool IsCompiledWithMPI() {
#ifdef PADDLE_WITH_MPI
  return true;
#else
  return false;
#endif
}

// NOTE some mpi lib can support cuda aware, support it in the future.
bool IsCompiledWithMPIAWARE() {
#ifdef PADDLE_WITH_MPI_AWARE
  return true;
#else
  return false;
#endif
}

269 270
bool IsCompiledWithROCM() {
#ifndef PADDLE_WITH_HIP
Q
qijun 已提交
271 272 273 274 275 276
  return false;
#else
  return true;
#endif
}

277 278 279 280 281 282 283 284
bool IsCompiledWithAscend() {
#ifndef PADDLE_WITH_ASCEND
  return false;
#else
  return true;
#endif
}

285 286 287 288 289 290 291 292
bool IsCompiledWithXPU() {
#ifndef PADDLE_WITH_XPU
  return false;
#else
  return true;
#endif
}

293 294 295 296 297 298 299 300
bool IsCompiledWithNPU() {
#ifndef PADDLE_WITH_ASCEND_CL
  return false;
#else
  return true;
#endif
}

301 302 303 304 305 306 307 308 309 310 311 312 313 314
bool IsCompiledWithCustomDevice(std::string device_type) {
#ifndef PADDLE_WITH_CUSTOM_DEVICE
  return false;
#else
  std::vector<std::string> device_types;
  device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
  if (std::count(device_types.begin(), device_types.end(), device_type)) {
    return true;
  } else {
    return false;
  }
#endif
}

J
jianghaicheng 已提交
315 316 317 318 319 320 321 322
bool IsCompiledWithIPU() {
#ifndef PADDLE_WITH_IPU
  return false;
#else
  return true;
#endif
}

323 324 325 326 327 328 329 330
bool IsCompiledWithMKLDNN() {
#ifndef PADDLE_WITH_MKLDNN
  return false;
#else
  return true;
#endif
}

331 332 333 334 335 336 337 338
bool IsCompiledWithCINN() {
#ifndef PADDLE_WITH_CINN
  return false;
#else
  return true;
#endif
}

339 340 341 342 343 344 345 346
bool IsCompiledWithMLU() {
#ifndef PADDLE_WITH_MLU
  return false;
#else
  return true;
#endif
}

347 348 349 350 351 352 353 354
bool IsCompiledWithHETERPS() {
#ifndef PADDLE_WITH_HETERPS
  return false;
#else
  return true;
#endif
}

355 356 357 358
bool SupportsBfloat16() {
#ifndef PADDLE_WITH_MKLDNN
  return false;
#else
359
  if (phi::backends::cpu::MayIUse(phi::backends::cpu::cpu_isa_t::avx512_core))
360 361 362 363 364 365
    return true;
  else
    return false;
#endif
}

366 367 368 369
bool SupportsBfloat16FastPerformance() {
#ifndef PADDLE_WITH_MKLDNN
  return false;
#else
370
  if (phi::backends::cpu::MayIUse(phi::backends::cpu::cpu_isa_t::avx512_bf16))
371 372 373 374 375 376
    return true;
  else
    return false;
#endif
}

377 378 379 380
bool SupportsInt8() {
#ifndef PADDLE_WITH_MKLDNN
  return false;
#else
381 382
  return (phi::backends::cpu::MayIUse(phi::backends::cpu::cpu_isa_t::avx2) ||
          phi::backends::cpu::MayIUse(phi::backends::cpu::cpu_isa_t::avx512f));
383 384 385 386 387 388 389
#endif
}

bool SupportsVNNI() {
#ifndef PADDLE_WITH_MKLDNN
  return false;
#else
390 391
  return phi::backends::cpu::MayIUse(
      phi::backends::cpu::cpu_isa_t::avx512_core_vnni);
392 393 394
#endif
}

395
bool IsCompiledWithBrpc() {
396
#ifndef PADDLE_WITH_DISTRIBUTE
397
  return false;
398
#else
399
  return true;
400
#endif
401 402
}

Y
update  
Yancey1989 已提交
403
bool IsCompiledWithDIST() {
Y
Yancey1989 已提交
404
#ifdef PADDLE_WITH_DISTRIBUTE
Y
update  
Yancey1989 已提交
405 406 407 408 409 410
  return true;
#else
  return false;
#endif
}

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 454 455 456
struct iinfo {
  int64_t min, max;
  int bits;
  std::string dtype;

  explicit iinfo(const framework::proto::VarType::Type &type) {
    switch (type) {
      case framework::proto::VarType::INT16:
        min = std::numeric_limits<int16_t>::min();
        max = std::numeric_limits<int16_t>::max();
        bits = 16;
        dtype = "int16";
        break;
      case framework::proto::VarType::INT32:
        min = std::numeric_limits<int32_t>::min();
        max = std::numeric_limits<int32_t>::max();
        bits = 32;
        dtype = "int32";
        break;
      case framework::proto::VarType::INT64:
        min = std::numeric_limits<int64_t>::min();
        max = std::numeric_limits<int64_t>::max();
        bits = 64;
        dtype = "int64";
        break;
      case framework::proto::VarType::INT8:
        min = std::numeric_limits<int8_t>::min();
        max = std::numeric_limits<int8_t>::max();
        bits = 8;
        dtype = "int8";
        break;
      case framework::proto::VarType::UINT8:
        min = std::numeric_limits<uint8_t>::min();
        max = std::numeric_limits<uint8_t>::max();
        bits = 8;
        dtype = "uint8";
        break;
      default:
        PADDLE_THROW(platform::errors::InvalidArgument(
            "the argument of paddle.iinfo can only be paddle.int8, "
            "paddle.int16, paddle.int32, paddle.int64, or paddle.uint8"));
        break;
    }
  }
};

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 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 517 518 519 520 521 522 523
struct finfo {
  int64_t bits;
  double eps;
  double min;  // lowest()
  double max;
  double tiny;
  double smallest_normal;  // min()
  double resolution;
  std::string dtype;

  explicit finfo(const framework::proto::VarType::Type &type) {
    switch (type) {
      case framework::proto::VarType::FP16:
        eps = std::numeric_limits<paddle::platform::float16>::epsilon();
        min = std::numeric_limits<paddle::platform::float16>::lowest();
        max = std::numeric_limits<paddle::platform::float16>::max();
        smallest_normal = std::numeric_limits<paddle::platform::float16>::min();
        tiny = smallest_normal;
        resolution = std::pow(
            10, -std::numeric_limits<paddle::platform::float16>::digits10);
        bits = 16;
        dtype = "float16";
        break;
      case framework::proto::VarType::FP32:
      case framework::proto::VarType::COMPLEX64:
        eps = std::numeric_limits<float>::epsilon();
        min = std::numeric_limits<float>::lowest();
        max = std::numeric_limits<float>::max();
        smallest_normal = std::numeric_limits<float>::min();
        tiny = smallest_normal;
        resolution = std::pow(10, -std::numeric_limits<float>::digits10);
        bits = 32;
        dtype = "float32";
        break;
      case framework::proto::VarType::FP64:
      case framework::proto::VarType::COMPLEX128:
        eps = std::numeric_limits<double>::epsilon();
        min = std::numeric_limits<double>::lowest();
        max = std::numeric_limits<double>::max();
        smallest_normal = std::numeric_limits<double>::min();
        tiny = smallest_normal;
        resolution = std::pow(10, -std::numeric_limits<double>::digits10);
        bits = 64;
        dtype = "float64";
        break;
      case framework::proto::VarType::BF16:
        eps = std::numeric_limits<paddle::platform::bfloat16>::epsilon();
        min = std::numeric_limits<paddle::platform::bfloat16>::lowest();
        max = std::numeric_limits<paddle::platform::bfloat16>::max();
        smallest_normal =
            std::numeric_limits<paddle::platform::bfloat16>::min();
        tiny = smallest_normal;
        resolution = std::pow(
            10, -std::numeric_limits<paddle::platform::bfloat16>::digits10);
        bits = 16;
        dtype = "bfloat16";
        break;
      default:
        PADDLE_THROW(platform::errors::InvalidArgument(
            "the argument of paddle.finfo can only be paddle.float32, "
            "paddle.float64, paddle.float16, paddle.bfloat16"
            "paddle.complex64, or paddle.complex128"));
        break;
    }
  }
};

H
hong 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
static PyObject *GetPythonAttribute(PyObject *obj, const char *attr_name) {
  // NOTE(zjl): PyObject_GetAttrString would return nullptr when attr_name
  // is not inside obj, but it would also set the error flag of Python.
  // If the error flag is set in C++, C++ code would not raise Exception,
  // but Python would raise Exception once C++ call ends.
  // To avoid unexpected Exception raised in Python, we check whether
  // attribute exists before calling PyObject_GetAttrString.
  //
  // Caution: PyObject_GetAttrString would increase reference count of PyObject.
  // Developer should call Py_DECREF manually after the attribute is not used.
  if (PyObject_HasAttrString(obj, attr_name)) {
    return PyObject_GetAttrString(obj, attr_name);
  } else {
    return nullptr;
  }
}

template <typename T>
static T PyObjectCast(PyObject *obj) {
  try {
    return py::cast<T>(py::handle(obj));
  } catch (py::cast_error &) {
546 547
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Python object is not type of %s, the real type is %s",
548 549
        typeid(T).name(),
        obj->ob_type->tp_name));
H
hong 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562
  }
}

using PyNameVarBaseMap = std::unordered_map<std::string, py::handle>;

static std::vector<std::shared_ptr<imperative::VarBase>> GetVarBaseList(
    const PyNameVarBaseMap &state_dict) {
  std::vector<std::shared_ptr<imperative::VarBase>> vec_res;
  vec_res.reserve(state_dict.size());

  for (auto &para : state_dict) {
    PyObject *py_obj = para.second.ptr();
    if (!py_obj || py_obj == Py_None) {
563 564
      PADDLE_THROW(platform::errors::InvalidArgument(
          "The parameter [%s] to save is None", para.first));
H
hong 已提交
565 566
    }
    vec_res.emplace_back(
567
        PyObjectCast<std::shared_ptr<imperative::VarBase>>(py_obj));
H
hong 已提交
568 569 570 571 572 573 574 575 576 577 578 579
  }

  return vec_res;
}

static std::vector<std::string> inline GetNameList(
    const py::handle &py_handle) {
  std::vector<std::string> vec_res;

  PyObject *py_obj = py_handle.ptr();  // get underlying PyObject
  // Python None is not nullptr in C++!
  if (!py_obj || py_obj == Py_None) {
580 581
    PADDLE_THROW(platform::errors::InvalidArgument(
        "The parameter list to save is None"));
H
hong 已提交
582 583 584 585 586 587 588 589 590 591 592 593
  }

  if (PyList_Check(py_obj)) {
    size_t len = PyList_GET_SIZE(py_obj);

    vec_res.reserve(len);

    const char *kNameField = "name";

    for (size_t i = 0; i < len; ++i) {
      PyObject *py_name =
          PyObject_GetAttrString(PyList_GET_ITEM(py_obj, i), kNameField);
594 595 596
      PADDLE_ENFORCE_NOT_NULL(py_name,
                              platform::errors::InvalidArgument(
                                  "The name of parameter to save is None"));
H
hong 已提交
597 598 599 600
      vec_res.emplace_back(PyObjectCast<std::string>(py_name));
      Py_DECREF(py_name);
    }
  } else {
601 602
    PADDLE_THROW(platform::errors::InvalidArgument(
        "The parameters to save is not a list"));
H
hong 已提交
603 604 605 606
  }
  return vec_res;
}

O
OccupyMars2025 已提交
607
static void inline CreateVariableIfNotExist(
608 609
    const py::handle &py_handle,
    const framework::Scope &scope,
610 611 612 613 614 615
    const framework::Executor *exe = nullptr) {
  std::vector<std::string> vec_res;

  PyObject *py_obj = py_handle.ptr();  // get underlying PyObject
  // Python None is not nullptr in C++!
  if (!py_obj || py_obj == Py_None) {
616 617
    PADDLE_THROW(
        platform::errors::InvalidArgument("The parameter list to set is None"));
618 619 620 621 622 623 624 625 626 627 628 629 630
  }

  if (PyList_Check(py_obj)) {
    size_t len = PyList_GET_SIZE(py_obj);

    vec_res.reserve(len);

    const char *kNameField = "name";
    const char *kVarDescField = "desc";

    for (size_t i = 0; i < len; ++i) {
      PyObject *py_name =
          PyObject_GetAttrString(PyList_GET_ITEM(py_obj, i), kNameField);
631 632 633
      PADDLE_ENFORCE_NOT_NULL(py_name,
                              platform::errors::InvalidArgument(
                                  "The name of parameter to set is None"));
634 635 636 637 638
      auto para_name = PyObjectCast<std::string>(py_name);
      Py_DECREF(py_name);

      auto var = scope.FindVar(para_name);
      if (var == nullptr) {
639 640 641 642 643
        PADDLE_ENFORCE_NOT_NULL(exe,
                                platform::errors::InvalidArgument(
                                    "Parameter not Initialized, "
                                    "Please set argument [executor] not None "
                                    "or run startup program first"));
644 645
        PyObject *py_var_desc =
            PyObject_GetAttrString(PyList_GET_ITEM(py_obj, i), kVarDescField);
646
        PADDLE_ENFORCE_NOT_NULL(
647 648 649
            py_var_desc,
            platform::errors::InvalidArgument(
                "The var_desc of parameter to set is None"));
650 651 652
        auto var_desc = PyObjectCast<framework::VarDesc>(py_var_desc);
        Py_DECREF(py_var_desc);
        var = const_cast<framework::Scope *>(&scope)->Var(para_name);
653
        auto *tensor_temp = var->GetMutable<phi::DenseTensor>();
654
        tensor_temp->Resize(phi::make_ddim(var_desc.GetShape()));
655 656
        tensor_temp->mutable_data(
            exe->GetPlace(),
657
            framework::TransToPhiDataType(var_desc.GetDataType()));
658 659 660
      }
    }
  } else {
661 662
    PADDLE_THROW(platform::errors::InvalidArgument(
        "The parameters to set is not a list"));
663 664 665 666 667
  }

  return;
}

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
static void AssertStaticGraphAndDygraphGradMakerNoDiff() {
  std::set<std::string> ops;
  for (auto &pair : framework::OpInfoMap::Instance().map()) {
    bool has_static_grad_maker = (pair.second.grad_op_maker_ != nullptr);
    bool has_dygraph_grad_maker =
        (pair.second.dygraph_grad_op_maker_ != nullptr);
    if (has_static_grad_maker ^ has_dygraph_grad_maker) {
      bool has_kernel =
          (framework::OperatorWithKernel::AllOpKernels().count(pair.first) > 0);
      if (has_kernel) {
        ops.insert(pair.first);
      } else {
        VLOG(5) << pair.first << " has no kernels, skip";
      }
    }
  }
684 685
  PADDLE_ENFORCE_EQ(ops.empty(),
                    true,
686 687 688 689 690 691 692
                    platform::errors::Unimplemented(
                        "OperatorWithKernel [%s] have only static graph grad "
                        "maker or have only dygraph grad maker, which is not "
                        "allowed",
                        string::join_strings(ops, ',')));
}

Z
Zeng Jinle 已提交
693 694 695 696
#ifdef PADDLE_WITH_NCCL
static int GetNCCLVersion() {
#if NCCL_VERSION_CODE >= 2304
  int ver;
697
  PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclGetVersion(&ver));
Z
Zeng Jinle 已提交
698 699 700 701 702 703 704 705
  return ver;
#else
  PADDLE_THROW(platform::errors::External(
      "Cannot get NCCL version successfully when nccl version < 2.3.4"));
#endif
}
#endif

706
PYBIND11_MODULE(libpaddle, m) {
J
Jiabin Yang 已提交
707
  BindImperative(&m);
708
  BindEager(&m);
J
Jack Zhou 已提交
709
  BindEagerStringTensor(&m);
710
  BindCudaStream(&m);
J
james 已提交
711
  BindXpuStream(&m);
712
  BindJit(&m);
713
  BindCustomDevicePy(&m);
714

Y
Yu Yang 已提交
715
  // Not used, just make sure cpu_info.cc is linked.
716
  phi::backends::cpu::CpuTotalPhysicalMemory();
Y
Yu Yang 已提交
717

Y
Refine  
Yu Yang 已提交
718
  paddle::memory::allocation::UseAllocatorStrategyGFlag();
S
sneaxiy 已提交
719

720 721
  AssertStaticGraphAndDygraphGradMakerNoDiff();

722
  m.doc() = "C++ core of PaddlePaddle";
723

724 725 726 727
  // using framework in this function. Since it is inside a function, it will
  // not cause namespace pollution.
  using namespace paddle::framework;  // NOLINT

728
  BindException(&m);
Y
Yu Yang 已提交
729

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  py::class_<iinfo>(m, "iinfo")
      .def(py::init<const framework::proto::VarType::Type &>())
      .def_readonly("min", &iinfo::min)
      .def_readonly("max", &iinfo::max)
      .def_readonly("bits", &iinfo::bits)
      .def_readonly("dtype", &iinfo::dtype)
      .def("__repr__", [](const iinfo &a) {
        std::ostringstream oss;
        oss << "paddle.iinfo(min=" << a.min;
        oss << ", max=" << a.max;
        oss << ", bits=" << a.bits;
        oss << ", dtype=" << a.dtype << ")";
        return oss.str();
      });

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
  py::class_<finfo>(m, "finfo")
      .def(py::init<const framework::proto::VarType::Type &>())
      .def_readonly("min", &finfo::min)
      .def_readonly("max", &finfo::max)
      .def_readonly("bits", &finfo::bits)
      .def_readonly("eps", &finfo::eps)
      .def_readonly("resolution", &finfo::resolution)
      .def_readonly("smallest_normal", &finfo::smallest_normal)
      .def_readonly("tiny", &finfo::tiny)
      .def_readonly("dtype", &finfo::dtype)
      .def("__repr__", [](const finfo &a) {
        std::ostringstream oss;
        oss << "paddle.finfo(min=" << a.min;
        oss << ", max=" << a.max;
        oss << ", eps=" << a.eps;
        oss << ", resolution=" << a.resolution;
        oss << ", smallest_normal=" << a.smallest_normal;
        oss << ", tiny=" << a.tiny;
        oss << ", bits=" << a.bits;
        oss << ", dtype=" << a.dtype << ")";
        return oss.str();
      });

768 769 770 771 772 773 774 775 776 777
  m.def("__set_bwd_prim_enabled",
        &paddle::prim::PrimCommonUtils::SetBwdPrimEnabled);
  m.def("_is_bwd_prim_enabled",
        &paddle::prim::PrimCommonUtils::IsBwdPrimEnabled);
  m.def("__set_fwd_prim_enabled",
        &paddle::prim::PrimCommonUtils::SetFwdPrimEnabled);
  m.def("_is_fwd_prim_enabled",
        &paddle::prim::PrimCommonUtils::IsFwdPrimEnabled);
  m.def("__set_all_prim_enabled",
        &paddle::prim::PrimCommonUtils::SetAllPrimEnabled);
778 779 780 781
  m.def("_is_eager_prim_enabled",
        &paddle::prim::PrimCommonUtils::IsEagerPrimEnabled);
  m.def("__set_eager_prim_enabled",
        &paddle::prim::PrimCommonUtils::SetEagerPrimEnabled);
782 783
  m.def("_set_prim_target_grad_name",
        &paddle::prim::PrimCommonUtils::SetTargetGradName);
784 785
  m.def("set_num_threads", &platform::SetNumThreads);

786 787
  m.def("disable_signal_handler", &DisableSignalHandler);

788 789 790 791 792 793 794 795
  m.def("clear_gradients",
        [](std::vector<std::shared_ptr<imperative::VarBase>> param_list,
           bool set_to_zero) {
          for (auto param : param_list) {
            param->ClearGradient(set_to_zero);
          }
        });

796
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
797
  m.def("cudnn_version", &platform::DnnVersion);
798 799 800 801 802 803
  m.def("gpu_memory_available", []() {
    size_t available = 0;
    size_t total = 0;
    paddle::platform::GpuMemoryUsage(&available, &total);
    return available;
  });
804
#endif
805

Z
Zeng Jinle 已提交
806 807 808 809
#ifdef PADDLE_WITH_NCCL
  m.def("nccl_version", &GetNCCLVersion);
#endif

810 811
  m.def("is_cuda_graph_capturing", &platform::IsCUDAGraphCapturing);
#ifdef PADDLE_WITH_CUDA
812
  py::class_<phi::backends::gpu::CUDAGraph>(m, "CUDAGraph")
813 814 815 816 817 818
      .def_static("begin_capture",
                  [](platform::CUDAPlace place, int mode) {
                    platform::BeginCUDAGraphCapture(
                        place, static_cast<cudaStreamCaptureMode>(mode));
                  })
      .def_static("end_capture", &platform::EndCUDAGraphCapture)
819
      .def_static("gen_new_memory_pool_id",
820 821 822 823 824
                  &phi::backends::gpu::CUDAGraph::UniqueMemoryPoolID)
      .def("replay", &phi::backends::gpu::CUDAGraph::Replay)
      .def("reset", &phi::backends::gpu::CUDAGraph::Reset)
      .def("print_to_dot_files",
           &phi::backends::gpu::CUDAGraph::PrintToDotFiles);
825 826
#endif

Z
Zeng Jinle 已提交
827 828 829 830
  m.def("wait_device", [](const platform::Place &place) {
    platform::DeviceContextPool::Instance().Get(place)->Wait();
  });

6
633WHU 已提交
831 832 833
  m.def("from_dlpack", [](py::capsule *dltensor) {
    DLManagedTensor *dmt = reinterpret_cast<DLManagedTensor *>(
        PyCapsule_GetPointer(dltensor->ptr(), "dltensor"));
834 835

    PADDLE_ENFORCE_NOT_NULL(
836 837 838 839
        dmt,
        platform::errors::InvalidArgument(
            "from_dlpack received an invalid capsule. "
            "Note that a DLPack tensor can be consumed only once."));
840

6
633WHU 已提交
841 842
    PyCapsule_SetName(dltensor->ptr(), "used_dltensor");
    DLTensor dl = dmt->dl_tensor;
843
    phi::DenseTensor tensor;
6
633WHU 已提交
844

S
Siming Dai 已提交
845
    if (dl.device.device_type == kDLCPU) {
S
Siming Dai 已提交
846
      paddle::framework::TensorFromDLPack(dmt, &tensor);
6
633WHU 已提交
847
    }
848
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
S
Siming Dai 已提交
849
    if (dl.device.device_type == kDLGPU) {
S
Siming Dai 已提交
850
      paddle::framework::TensorFromDLPack(dmt, &tensor);
6
633WHU 已提交
851 852 853 854
    }
#endif
    return tensor;
  });
H
hong 已提交
855

856
  m.def("_create_loaded_parameter",
857 858
        [](const py::handle &vec_var_list,
           const Scope &scope,
859
           const Executor *executor) {
O
OccupyMars2025 已提交
860
          CreateVariableIfNotExist(vec_var_list, scope, executor);
861 862
        });

863 864 865 866 867 868
  m.def("save_op_version_info", [](framework::ProgramDesc &desc) {
    framework::compatible::pb::OpVersionMap pb_vmap{desc.OpVersionMap()};
    framework::compatible::SaveOpVersions(
        framework::compatible::OpVersionRegistrar::GetInstance()
            .GetVersionMap(),
        &pb_vmap);
869 870
  });

871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
  m.def("set_printoptions", [](const py::kwargs &kwargs) {
    auto &print_opt = framework::PrintOptions::Instance();
    if (kwargs.contains("precision")) {
      print_opt.precision = kwargs["precision"].cast<int>();
    }
    if (kwargs.contains("threshold")) {
      print_opt.threshold = kwargs["threshold"].cast<int>();
    }
    if (kwargs.contains("edgeitems")) {
      print_opt.edgeitems = kwargs["edgeitems"].cast<int>();
    }
    if (kwargs.contains("linewidth")) {
      print_opt.linewidth = kwargs["linewidth"].cast<int>();
    }
    if (kwargs.contains("sci_mode")) {
      print_opt.sci_mode = kwargs["sci_mode"].cast<bool>();
    }

    VLOG(4) << "Set printoptions: precision=" << print_opt.precision
            << ", threshold=" << print_opt.threshold
            << ", edgeitems=" << print_opt.edgeitems
            << ", linewidth=" << print_opt.linewidth
            << ", sci_mode=" << print_opt.sci_mode;
  });

896 897 898 899 900 901
  m.def(
      "broadcast_shape",
      [](const std::vector<int64_t> &x_dim, const std::vector<int64_t> &y_dim) {
        return phi::vectorize(operators::details::BroadcastTwoDims(
            phi::make_ddim(x_dim), phi::make_ddim(y_dim), -1));
      });
L
Leo Chen 已提交
902

S
sneaxiy 已提交
903
  m.def(
S
sneaxiy 已提交
904
      "_append_python_callable_object_and_return_id",
S
sneaxiy 已提交
905 906 907 908
      [](py::object py_obj) -> size_t {
        return paddle::operators::AppendPythonCallableObjectAndReturnId(py_obj);
      });

S
sneaxiy 已提交
909 910 911
  m.def("_get_use_default_grad_op_desc_maker_ops",
        [] { return OpInfoMap::Instance().GetUseDefaultGradOpDescMakerOps(); });

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  m.def(
      "_get_all_register_op_kernels",
      [](const std::string &lib) {
        std::unordered_map<std::string, std::vector<std::string>>
            all_kernels_info;
        if (lib == "fluid" || lib == "all") {
          auto &all_kernels =
              paddle::framework::OperatorWithKernel::AllOpKernels();

          for (auto &kernel_pair : all_kernels) {
            auto op_type = kernel_pair.first;
            std::vector<std::string> kernel_types;
            for (auto &info_pair : kernel_pair.second) {
              paddle::framework::OpKernelType kernel_type = info_pair.first;
              kernel_types.emplace_back(
                  paddle::framework::KernelTypeToString(kernel_type));
928
            }
929
            all_kernels_info.emplace(op_type, kernel_types);
930
          }
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
        }
        if (lib == "phi" || lib == "all") {
          auto phi_kernels = phi::KernelFactory::Instance().kernels();
          for (auto &kernel_pair : phi_kernels) {
            auto op_type = phi::TransToFluidOpName(kernel_pair.first);
            std::vector<std::string> kernel_types;
            for (auto &info_pair : kernel_pair.second) {
              framework::OpKernelType kernel_type =
                  framework::TransPhiKernelKeyToOpKernelType(info_pair.first);
              auto kernel_type_str = framework::KernelTypeToString(kernel_type);
              if (all_kernels_info.count(op_type)) {
                if (std::find(all_kernels_info[op_type].begin(),
                              all_kernels_info[op_type].end(),
                              kernel_type_str) ==
                    all_kernels_info[op_type].end()) {
                  all_kernels_info[op_type].emplace_back(kernel_type_str);
947
                }
948 949
              } else {
                kernel_types.emplace_back(kernel_type_str);
950
              }
951
            }
952 953 954
            if (!kernel_types.empty()) {
              all_kernels_info.emplace(op_type, kernel_types);
            }
955
          }
956
        }
957

958 959 960 961
        return all_kernels_info;
      },
      py::arg("lib") = "all",
      R"DOC(
962 963 964
           Return the registered kernels in paddle.

           Args:
965
               lib[string]: the libarary, could be 'phi', 'fluid' and 'all'.
966
           )DOC");
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  m.def(
      "_get_registered_phi_kernels",
      [](const std::string &kernel_registered_type) {
        std::unordered_map<std::string, std::vector<std::string>>
            all_kernels_info;
        auto phi_kernels = phi::KernelFactory::Instance().kernels();
        for (auto &kernel_pair : phi_kernels) {
          auto kernel_name = kernel_pair.first;
          std::vector<std::string> kernel_keys;
          for (auto &info_pair : kernel_pair.second) {
            bool get_function_kernel =
                kernel_registered_type == "function" &&
                info_pair.second.GetKernelRegisteredType() ==
                    phi::KernelRegisteredType::FUNCTION;
            bool get_structure_kernel =
                kernel_registered_type == "structure" &&
                info_pair.second.GetKernelRegisteredType() ==
                    phi::KernelRegisteredType::STRUCTURE;
            if (kernel_registered_type == "all" || get_function_kernel ||
                get_structure_kernel) {
              std::ostringstream stream;
              stream << info_pair.first;
              std::string kernel_key_str = stream.str();
              if (all_kernels_info.count(kernel_name)) {
                bool kernel_exist =
                    std::find(all_kernels_info[kernel_name].begin(),
                              all_kernels_info[kernel_name].end(),
                              kernel_key_str) !=
                    all_kernels_info[kernel_name].end();
                if (!kernel_exist) {
                  all_kernels_info[kernel_name].emplace_back(kernel_key_str);
                }
              } else {
                kernel_keys.emplace_back(kernel_key_str);
              }
            }
          }
          if (!kernel_keys.empty()) {
            all_kernels_info.emplace(kernel_name, kernel_keys);
          }
        }

        return all_kernels_info;
      },
      py::arg("kernel_registered_type") = "function",
      R"DOC(
           Return the registered kernels in phi.

           Args:
               kernel_registered_type[string]: the libarary, could be 'function', 'structure', and 'all'.
           )DOC");

1020 1021 1022 1023 1024 1025
  // NOTE(Aganlengzi): KernelFactory static instance is initialized BEFORE
  // plugins are loaded for custom kernels, but de-initialized AFTER they are
  // unloaded. We need manually clear symbols(may contain plugins' symbols)
  // stored in this static instance to avoid illegal memory access.
  m.def("clear_kernel_factory",
        []() { phi::KernelFactory::Instance().kernels().clear(); });
1026 1027 1028 1029 1030
  m.def("clear_device_manager", []() {
#ifdef PADDLE_WITH_CUSTOM_DEVICE
    phi::DeviceManager::Clear();
#endif
  });
1031

S
sneaxiy 已提交
1032 1033 1034
  // NOTE(zjl): ctest would load environment variables at the beginning even
  // though we have not `import paddle.fluid as fluid`. So we add this API
  // to enable eager deletion mode in unittest.
S
sneaxiy 已提交
1035
  m.def("_set_eager_deletion_mode", &paddle::framework::SetEagerDeletionMode);
S
sneaxiy 已提交
1036

1037
  m.def("_set_fuse_parameter_group_size",
1038
        &paddle::framework::ir::SetFuseParameterGroupsSize);
1039
  m.def("_set_fuse_parameter_memory_size",
1040
        &paddle::framework::ir::SetFuseParameterMemorySize);
1041

S
sneaxiy 已提交
1042 1043 1044
  m.add_object("_cleanup",
               py::capsule([]() { ScopePool::Instance().Clear(); }));

1045 1046
  m.def("_set_paddle_lib_path", &paddle::platform::dynload::SetPaddleLibPath);

L
Leo Chen 已提交
1047 1048
  m.def("set_current_thread_name", &paddle::platform::SetCurrentThreadName);

1049 1050 1051
  m.def("_promote_types_if_complex_exists",
        &paddle::framework::PromoteTypesIfComplexExists);

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  py::class_<paddle::CustomOpKernelContext> custom_op_kernel_ctx(
      m, "CustomOpKernelContext", R"DOC()DOC");
  g_custom_op_kernel_ctx_pytype =
      reinterpret_cast<PyTypeObject *>(custom_op_kernel_ctx.ptr());
  custom_op_kernel_ctx.def(py::init<>())
      .def("add_inputs",
           [](paddle::CustomOpKernelContext &self, const py::handle &input) {
             PyObject *obj = input.ptr();
             if (PyList_Check(obj) || PyTuple_Check(obj)) {
               self.EmplaceBackInputs(
                   std::move(CastPyArg2VectorOfTensor(obj, 1)));
1063 1064 1065
             } else if (obj == Py_None) {
               // Check optional Tensor, use one un-initialized tensor to
               // indicate both Tensor and vector<Tensor> inputs
1066
               self.EmplaceBackInput(std::move(paddle::Tensor()));
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
             } else {
               self.EmplaceBackInput(std::move(CastPyArg2Tensor(obj, 1)));
             }
           })
      .def("add_outputs",
           [](paddle::CustomOpKernelContext &self, py::handle &outputs) {
             PyObject *obj = outputs.ptr();
             if (PyList_Check(obj) || PyTuple_Check(obj)) {
               self.EmplaceBackOutputs(
                   std::move(CastPyArg2VectorOfTensor(obj, 1)));
             } else {
               self.EmplaceBackOutput(std::move(CastPyArg2Tensor(obj, 1)));
             }
           })
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self, bool attr) {
             self.EmplaceBackAttr(attr);
           })
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self, int attr) {
             self.EmplaceBackAttr(attr);
           })
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self, float attr) {
             self.EmplaceBackAttr(attr);
           })
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self, int64_t attr) {
             self.EmplaceBackAttr(attr);
           })
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self, const std::string &attr) {
             self.EmplaceBackAttr(attr);
           })
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self,
              const std::vector<int> &attr) { self.EmplaceBackAttr(attr); })
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self,
              const std::vector<float> &attr) { self.EmplaceBackAttr(attr); })
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self,
              const std::vector<int64_t> &attr) { self.EmplaceBackAttr(attr); })
1110 1111 1112 1113 1114
      .def("add_attr",
           [](paddle::CustomOpKernelContext &self,
              const std::vector<std::string> &attr) {
             self.EmplaceBackAttr(attr);
           });
1115

1116
  py::class_<Variable>(m, "Variable", R"DOC(Variable Class.
1117 1118 1119

All parameter, weight, gradient are variables in Paddle.
)DOC")
S
sneaxiy 已提交
1120
      .def(py::init<>())
1121
      .def("is_int", [](const Variable &var) { return var.IsType<int>(); })
1122
      .def("set_int",
1123 1124
           [](Variable &var, int val) -> void { *var.GetMutable<int>() = val; })
      .def("get_int", [](const Variable &var) -> int { return var.Get<int>(); })
1125 1126 1127 1128 1129 1130 1131
      .def("is_float", [](const Variable &var) { return var.IsType<float>(); })
      .def("set_float",
           [](Variable &var, float val) -> void {
             *var.GetMutable<float>() = val;
           })
      .def("get_float",
           [](const Variable &var) -> float { return var.Get<float>(); })
1132 1133
      .def(
          "get_tensor",
1134 1135
          [](Variable &self) -> phi::DenseTensor * {
            return self.GetMutable<phi::DenseTensor>();
1136 1137
          },
          py::return_value_policy::reference)
1138 1139
      .def("get_bytes",
           [](Variable &self) {
1140 1141 1142 1143 1144 1145
             if (self.IsType<String>()) {
               return py::bytes(*(self.GetMutable<String>()));
             } else {
               return py::bytes(
                   *(self.GetMutable<RawTensor>()->GetMutable<std::string>()));
             }
1146
           })
S
Steffy-zxf 已提交
1147
      .def("set_string_list",
1148
           [](Variable &self, std::vector<std::string> str_list) {
S
Steffy-zxf 已提交
1149 1150
             *self.GetMutable<Strings>() = str_list;
           })
1151
      .def("set_vocab",
1152 1153
           [](Variable &self,
              const std::unordered_map<std::wstring, std::int32_t> &vocab) {
1154 1155
             *self.GetMutable<Vocab>() = vocab;
           })
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
      .def(
          "get_string_tensor",
          [](Variable &self) { return self.GetMutable<Strings>(); },
          py::return_value_policy::reference)
      .def(
          "get_map_tensor",
          [](Variable &self) { return self.GetMutable<Vocab>(); },
          py::return_value_policy::reference)
      .def(
          "get_lod_rank_table",
          [](Variable &self) { return self.GetMutable<LoDRankTable>(); },
          py::return_value_policy::reference)
      .def(
          "get_selected_rows",
          [](Variable &self) -> phi::SelectedRows * {
            return self.GetMutable<phi::SelectedRows>();
          },
          py::return_value_policy::reference)
      .def(
          "get_lod_tensor_array",
          [](Variable &self) { return self.GetMutable<LoDTensorArray>(); },
          py::return_value_policy::reference)
      .def(
          "get_fetch_list",
          [](Variable &self) { return self.GetMutable<FetchList>(); },
          py::return_value_policy::reference)
1182
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
1183 1184 1185 1186 1187 1188
      .def(
          "get_communicator",
          [](Variable &self) -> platform::Communicator * {
            return self.GetMutable<platform::Communicator>();
          },
          py::return_value_policy::reference)
Y
Yu Yang 已提交
1189
#endif
1190 1191 1192
      .def(
          "get_reader",
          [](Variable &self) -> framework::ReaderHolder * {
1193 1194
            PADDLE_ENFORCE_EQ(self.IsType<framework::ReaderHolder>(),
                              true,
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
                              platform::errors::InvalidArgument(
                                  "The variable is not type of ReaderHolder."));
            return self.GetMutable<framework::ReaderHolder>();
          },
          py::return_value_policy::reference)
      .def(
          "get_scope",
          [](Variable &self) -> Scope * {
            auto scope_vec = self.GetMutable<std::vector<framework::Scope *>>();
            PADDLE_ENFORCE_GT(
1205 1206
                scope_vec->size(),
                0,
1207 1208 1209 1210 1211
                platform::errors::InvalidArgument(
                    "The size of scope_vec should be greater than 0"));
            return scope_vec->front();
          },
          py::return_value_policy::reference)
1212 1213 1214 1215
      .def("set_scope", [](Variable &self, Scope &scope) {
        auto scope_vec = self.GetMutable<std::vector<framework::Scope *>>();
        scope_vec->emplace_back(&scope);
      });
1216

S
sneaxiy 已提交
1217
  BindReader(&m);
Y
Refine  
Yu Yang 已提交
1218

0
0x45f 已提交
1219
  py::class_<Scope> _Scope(m, "_Scope", R"DOC(
Q
Qiao Longfei 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    Scope is an association of a name to Variable. All variables belong to Scope.

    Variables in a parent scope can be retrieved from local scope.

    You need to specify a scope to run a Net, i.e., `exe.Run(&scope)`.
    One net can run in different scopes and update different variable in the
    scope.

    You can create var in a scope and get it from the scope.

    Examples:
        .. code-block:: python

1233
          import paddle.fluid as fluid
Q
Qiao Longfei 已提交
1234 1235 1236 1237 1238
          # create tensor from a scope and set value to it.
          param = scope.var('Param').get_tensor()
          param_array = np.full((height, row_numel), 5.0).astype("float32")
          param.set(param_array, place)

0
0x45f 已提交
1239 1240 1241
        )DOC");
  g_framework_scope_pytype = reinterpret_cast<PyTypeObject *>(_Scope.ptr());
  _Scope
S
sneaxiy 已提交
1242 1243
      .def("_remove_from_pool",
           [](Scope &self) { ScopePool::Instance().Remove(&self); })
1244 1245 1246 1247 1248 1249 1250
      .def(
          "var",
          [](Scope &self, const std::string &name) -> Variable * {
            return self.Var(name);
          },
          py::arg("name"),
          R"DOC(
1251
           Find or create variable named :code:`name` in the current scope.
S
sneaxiy 已提交
1252

1253
           If the variable named :code:`name` does not exist in the
S
sneaxiy 已提交
1254
           current scope, the variable would be created. Otherwise,
1255
           return the existing variable.
S
sneaxiy 已提交
1256 1257

           Args:
1258 1259
               name (str): the variable name.

S
sneaxiy 已提交
1260
           Returns:
1261
               out (core.Variable): the found or created variable.
S
sneaxiy 已提交
1262
           )DOC",
1263
          py::return_value_policy::reference)
1264 1265 1266
      .def("find_var",
           &Scope::FindVar,
           py::arg("name"),
S
sneaxiy 已提交
1267
           R"DOC(
1268
           Find variable named :code:`name` in the current scope or
1269
           its parent scope. Return None if not found.
1270

S
sneaxiy 已提交
1271 1272
           Args:
               name (str): the variable name.
1273

S
sneaxiy 已提交
1274
           Returns:
1275
               out (core.Variable|None): the found variable or None.
S
sneaxiy 已提交
1276
           )DOC",
1277
           py::return_value_policy::reference)
1278
      .def("size", &Scope::Size)
1279 1280 1281
      .def("erase",
           &Scope::EraseVars,
           py::arg("names"),
1282 1283
           R"DOC(
           Find variable named :code:`name` in the current scope or
1284
           its parent scope. Return None if not found.
1285 1286 1287 1288 1289 1290 1291 1292

           Args:
               name (str): the variable names to be erase.

           Returns:
               None
           )DOC",
           py::return_value_policy::reference)
1293
      .def(
1294 1295
          "new_scope",
          [](Scope &self) -> Scope * { return &self.NewScope(); },
1296
          R"DOC(
S
sneaxiy 已提交
1297 1298 1299 1300 1301
           Create a new sub-scope of the current scope.

           Returns:
               out (core._Scope): the created sub-scope.
           )DOC",
1302
          py::return_value_policy::reference)
1303 1304
      .def("drop_kids",
           &Scope::DropKids,
S
sneaxiy 已提交
1305 1306
           R"DOC(
           Delete all sub-scopes of the current scope.
S
sneaxiy 已提交
1307
           )DOC")
1308 1309
      .def("_kids", &Scope::kids)
      .def_property("_can_reuesd", &Scope::CanReuesd, &Scope::SetCanReuesd);
1310

1311 1312 1313 1314 1315 1316 1317 1318
  m.def(
      "Scope",
      []() -> Scope * {
        auto *s = new Scope();
        ScopePool::Instance().Insert(std::unique_ptr<Scope>(s));
        return s;
      },
      R"DOC(
S
sneaxiy 已提交
1319
        Create a new scope.
1320

S
sneaxiy 已提交
1321 1322 1323
        Returns:
            out (core._Scope): the created scope.
        )DOC",
1324
      py::return_value_policy::reference);
S
sneaxiy 已提交
1325

Y
Yu Yang 已提交
1326 1327
  //! @note: Be careful! PyBind will return std::string as an unicode, not
  //! Python str. If you want a str object, you should cast them in Python.
Y
Yu Yang 已提交
1328 1329
  m.def("get_all_op_protos", []() -> std::vector<py::bytes> {
    std::vector<py::bytes> ret_values;
1330 1331 1332 1333
    for (auto &iter : OpInfoMap::Instance().map()) {
      auto &info = iter.second;
      if (info.HasOpProtoAndChecker()) {
        std::string str;
C
chengduo 已提交
1334
        PADDLE_ENFORCE_EQ(
1335 1336
            info.Proto().SerializeToString(&str),
            true,
1337 1338
            platform::errors::Fatal(
                "Serialize OpProto Error. This could be a bug of Paddle."));
1339 1340 1341
        ret_values.emplace_back(str);
      }
    }
Y
Yu Yang 已提交
1342 1343
    return ret_values;
  });
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
  m.def(
      "get_all_op_names",
      [](const std::string &lib) {
        std::vector<std::string> op_names;
        for (auto &iter : OpInfoMap::Instance().map()) {
          op_names.emplace_back(iter.first);
        }
        if (lib == "phi") {
          std::vector<std::string> ops_with_phi_kernel;
          for (const auto &op_name : op_names) {
            if (phi::KernelFactory::Instance().HasCompatiblePhiKernel(
                    op_name)) {
              ops_with_phi_kernel.emplace_back(op_name);
            }
          }
          return ops_with_phi_kernel;
        } else if (lib == "fluid") {
          std::vector<std::string> ops_with_fluid_kernel;
          auto all_fluid_op_kernels =
              paddle::framework::OperatorWithKernel::AllOpKernels();
          for (const auto &op_name : op_names) {
            if (all_fluid_op_kernels.find(op_name) !=
                all_fluid_op_kernels.end()) {
              ops_with_fluid_kernel.emplace_back(op_name);
            }
          }
          return ops_with_fluid_kernel;
        } else {
          return op_names;
        }
      },
      py::arg("lib") = "all",
      R"DOC(
      Return the operator names in paddle.

      Args:
          lib[string]: the library contains corresponding OpKernel, could be 'phi', 'fluid' and 'all'. Default value is 'all'.
  )DOC");
1382 1383 1384 1385 1386 1387 1388 1389
  m.def("get_op_attrs_default_value",
        [](py::bytes byte_name) -> paddle::framework::AttributeMap {
          std::string op_type = byte_name;
          paddle::framework::AttributeMap res;
          auto info = OpInfoMap::Instance().GetNullable(op_type);
          if (info != nullptr) {
            if (info->HasOpProtoAndChecker()) {
              auto op_checker = info->Checker();
1390
              res = op_checker->GetDefaultAttrsMap();
1391 1392 1393 1394
            }
          }
          return res;
        });
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
  m.def(
      "get_op_extra_attrs",
      [](const std::string &op_type)
          -> const paddle::framework::AttributeMap & {
        return operators::ExtraInfoUtils::Instance().GetExtraAttrsMap(op_type);
      });
  m.def(
      "get_attrtibute_type",
      [](const std::string &op_type,
         const std::string &attr_name) -> paddle::framework::proto::AttrType {
        const auto &defalut_val =
            operators::ExtraInfoUtils::Instance().GetExtraAttrsMap(op_type).at(
                attr_name);
        return static_cast<paddle::framework::proto::AttrType>(
            defalut_val.index() - 1);
      });
1411 1412 1413
  m.def("_add_skip_comp_ops", &paddle::prim::PrimCommonUtils::AddSkipCompOps);
  m.def("_remove_skip_comp_ops",
        &paddle::prim::PrimCommonUtils::RemoveSkipCompOps);
1414 1415 1416 1417 1418
  m.def("get_grad_op_desc",
        [](const OpDesc &op_desc,
           const std::unordered_set<std::string> &no_grad_set,
           const std::vector<BlockDesc *> &grad_sub_block) {
          std::unordered_map<std::string, std::string> grad_to_var;
J
Jiabin Yang 已提交
1419 1420 1421

          auto op_info = framework::OpInfoMap::Instance().Get(op_desc.Type());
          auto grad_op_maker = op_info.GradOpMaker();
1422
          auto grad_comp_op_maker = op_info.CompGradOpMaker();
J
Jiabin Yang 已提交
1423 1424 1425 1426 1427 1428 1429

          if ((grad_op_maker == nullptr) && (grad_comp_op_maker == nullptr)) {
            // Normally, proto_ should not be null, except some special
            // operators, such as LeaklyReluDoubleGrad op.
            std::string type =
                op_info.proto_ ? op_info.proto_->type() : "unknown";
            PADDLE_THROW(platform::errors::NotFound(
1430
                "Neither operator %s's GradOpMaker nor CompGradOpMaker has "
J
Jiabin Yang 已提交
1431 1432 1433 1434 1435 1436 1437 1438
                "been registered.\nPlease check whether (%s) operator has "
                "gradient operator.\nIf not, please set stop_gradient to be "
                "True for its input and output variables using "
                "var.stop_gradient=True.",
                type.c_str(),
                type.c_str()));
          }

1439
          // In PrimEnabled mode, the priority of CompGradOpMaker is greater
J
Jiabin Yang 已提交
1440 1441
          // than GradCompMaker as we need split first-order grad operator into
          // primitive operators for compiler. In PrimDisabled mode, the
1442
          // priority of CompGradOpMaker is less than GradCompMaker for better
J
Jiabin Yang 已提交
1443 1444
          // performance.
          std::vector<std::unique_ptr<OpDesc>> grad_op_descs;
1445 1446 1447
          auto need_skip =
              paddle::prim::PrimCommonUtils::CheckSkipCompOps(op_desc.Type());
          VLOG(3) << "need skip: " << need_skip << std::endl;
1448
          if (paddle::prim::PrimCommonUtils::IsBwdPrimEnabled()) {
1449
            if ((grad_comp_op_maker != nullptr) && (!need_skip)) {
1450
              VLOG(3) << "Runing composite fun for " << op_desc.Type();
J
Jiabin Yang 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
              grad_op_descs = grad_comp_op_maker(op_desc,
                                                 no_grad_set,
                                                 &grad_to_var,
                                                 op_desc.Block(),
                                                 grad_sub_block);
            } else {
              grad_op_descs = grad_op_maker(
                  op_desc, no_grad_set, &grad_to_var, grad_sub_block);
            }
          } else {
            if (grad_op_maker != nullptr) {
              grad_op_descs = grad_op_maker(
                  op_desc, no_grad_set, &grad_to_var, grad_sub_block);
            } else {
              grad_op_descs = grad_comp_op_maker(op_desc,
                                                 no_grad_set,
                                                 &grad_to_var,
                                                 op_desc.Block(),
                                                 grad_sub_block);
            }
          }

1473 1474 1475 1476 1477 1478 1479 1480
          std::vector<OpDesc *> grad_op_desc_ptrs(grad_op_descs.size());
          std::transform(
              grad_op_descs.begin(),
              grad_op_descs.end(),
              grad_op_desc_ptrs.begin(),
              [](std::unique_ptr<OpDesc> &p) { return p.release(); });
          return std::make_pair(grad_op_desc_ptrs, grad_to_var);
        });
1481 1482 1483
  m.def("has_comp_grad_op_maker", [](const std::string op_type) {
    return framework::OpInfoMap::Instance().Get(op_type).HasCompGradOpMaker();
  });
1484 1485 1486
  m.def("has_grad_op_maker", [](const std::string op_type) {
    return framework::OpInfoMap::Instance().Get(op_type).HasGradOpMaker();
  });
1487 1488 1489 1490 1491
  m.def("has_non_empty_grad_op_maker", [](const std::string op_type) {
    return framework::OpInfoMap::Instance()
        .Get(op_type)
        .HasNonEmptyGradOpMaker();
  });
1492 1493 1494
  m.def("has_infer_inplace", [](const std::string op_type) {
    return framework::OpInfoMap::Instance().Get(op_type).HasInferInplace();
  });
1495
  m.def("infer_no_need_buffer_slots",
1496 1497
        [](const std::string op_type,
           const framework::VariableNameMap &inputs,
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
           const framework::VariableNameMap &outputs,
           const framework::AttributeMap &attrs) {
          auto infer_func = framework::OpInfoMap::Instance()
                                .Get(op_type)
                                .NoNeedBufferVarsInferer();
          if (infer_func) {
            return infer_func(inputs, outputs, attrs);
          } else {
            std::unordered_set<std::string> empty = {};
            return empty;
          }
        });
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
  m.def("prune",
        [](const ProgramDesc &origin,
           const std::set<std::string> &feeded_var_names,
           const std::vector<std::array<size_t, 2>> &targets) {
          ProgramDesc prog_with_targets(origin);

          for (const auto &t : targets) {
            prog_with_targets.MutableBlock(t[0])->Op(t[1])->SetIsTarget(true);
          }
          proto::ProgramDesc pruned_desc;
          auto pruned_origin_block_id_map =
              Prune(*prog_with_targets.Proto(), feeded_var_names, &pruned_desc);
          return std::make_tuple(ProgramDesc(pruned_desc),
                                 pruned_origin_block_id_map);
        });
1525 1526 1527 1528 1529 1530
  m.def(
      "prune_backward",
      [](const framework::ProgramDesc &program) {
        return PruneBackward(program);
      },
      R"DOC(
1531 1532
             Prune the backward part of a program, mostly called in
             program.clone(for_test=True).
1533

1534
            Args:
1535 1536 1537
                   program (ProgramDesc): The original program.

             Returns:
1538
                   tuple(ProgramDesc, map<int, int>): The first part is
1539 1540 1541 1542
                   the pruned program desc, and the second part is a map
                   which contains the id pair of pruned block and corresponding
                   origin block.
           )DOC");
1543 1544 1545 1546
  m.def("get_serialize_comile_key", [](int64_t compilation_key) {
#ifdef PADDLE_WITH_CINN
    auto compiler = framework::paddle2cinn::CinnCompiler::GetInstance();
    auto s = compiler->SerializeKey(compilation_key);
1547 1548
    VLOG(4) << s;
    return s;
1549 1550 1551 1552 1553 1554
#else
    PADDLE_THROW(
                 platform::errors::PermissionDenied(
                 "Cannot get compilation key in non-CINN version, "
                 "Please recompile or reinstall Paddle with CINN support."));
#endif
1555
  });
1556 1557 1558 1559
  m.def("empty_var_name",
        []() { return std::string(framework::kEmptyVarName); });
  m.def("grad_var_suffix",
        []() { return std::string(framework::kGradVarSuffix); });
1560 1561 1562
  m.def_submodule(
       "var_names",
       "The module will return special predefined variable name in Paddle")
Y
Yi Wang 已提交
1563 1564
      .def("empty", []() { return kEmptyVarName; })
      .def("temp", []() { return kTempVarName; });
1565

Y
Yu Yang 已提交
1566
  py::class_<paddle::platform::DeviceContext>(m, "DeviceContext")
Q
qijun 已提交
1567
      .def_static("create",
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
                  [](paddle::platform::CPUPlace &place)
                      -> paddle::platform::DeviceContext * {
                    auto *context = new phi::CPUContext();
                    context->SetAllocator(
                        paddle::memory::allocation::AllocatorFacade::Instance()
                            .GetAllocator(place)
                            .get());
                    context->SetHostAllocator(
                        paddle::memory::allocation::AllocatorFacade::Instance()
                            .GetAllocator(paddle::platform::CPUPlace())
                            .get());
                    context->SetZeroAllocator(
                        paddle::memory::allocation::AllocatorFacade::Instance()
                            .GetZeroAllocator(place)
                            .get());
1583 1584 1585 1586
                    context->SetHostZeroAllocator(
                        paddle::memory::allocation::AllocatorFacade::Instance()
                            .GetZeroAllocator(paddle::platform::CPUPlace())
                            .get());
1587
                    return context;
Q
qijun 已提交
1588
                  })
1589 1590 1591 1592
      .def_static(
          "create",
          [](paddle::platform::XPUPlace &place)
              -> paddle::platform::DeviceContext * {
1593
#ifndef PADDLE_WITH_XPU
1594 1595 1596
            PADDLE_THROW(platform::errors::PermissionDenied(
                "Cannot use XPUPlace in CPU/GPU version, "
                "Please recompile or reinstall Paddle with XPU support."));
1597
#else
W
Wilber 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
      auto* context = new paddle::platform::XPUDeviceContext(place);
      context->SetAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(place)
          .get());
      context->SetHostAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(paddle::platform::CPUPlace())
          .get());
      context->SetZeroAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
          .GetZeroAllocator(place)
          .get());
1611 1612 1613 1614
      context->SetHostZeroAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
          .GetZeroAllocator(paddle::platform::CPUPlace())
          .get());
W
Wilber 已提交
1615
      return context;
1616
#endif
1617 1618 1619 1620 1621
          })
      .def_static(
          "create",
          [](paddle::platform::MLUPlace &place)
              -> paddle::platform::DeviceContext * {
1622
#ifndef PADDLE_WITH_MLU
1623 1624 1625
            PADDLE_THROW(platform::errors::PermissionDenied(
                "Cannot use MLUPlace in CPU/GPU version, "
                "Please recompile or reinstall Paddle with MLU support."));
1626 1627
#else
                    return new paddle::platform::MLUDeviceContext(place);
1628
#endif
1629 1630 1631 1632 1633
          })
      .def_static(
          "create",
          [](paddle::platform::NPUPlace &place)
              -> paddle::platform::DeviceContext * {
1634
#ifndef PADDLE_WITH_ASCEND_CL
1635 1636 1637
            PADDLE_THROW(platform::errors::PermissionDenied(
                "Cannot use NPUPlace in CPU/GPU/XPU version, "
                "Please recompile or reinstall Paddle with NPU support."));
1638 1639
#else
                return new paddle::platform::NPUDeviceContext(place);
R
ronnywang 已提交
1640
#endif
1641 1642 1643 1644
          })
      .def_static("create",
                  [](paddle::platform::CustomPlace &place)
                      -> paddle::platform::DeviceContext * {
R
ronnywang 已提交
1645
#ifndef PADDLE_WITH_CUSTOM_DEVICE
1646 1647 1648 1649
                    PADDLE_THROW(platform::errors::PermissionDenied(
                        "Cannot use CustomPlace in CPU/GPU/XPU version, "
                        "Please recompile or reinstall Paddle with "
                        "CustomDevice support."));
R
ronnywang 已提交
1650 1651
#else
                return new paddle::platform::CustomDeviceContext(place);
1652
#endif
1653 1654 1655 1656 1657
                  })
      .def_static(
          "create",
          [](paddle::platform::CUDAPlace &place)
              -> paddle::platform::DeviceContext * {
1658
#if !defined(PADDLE_WITH_CUDA) && !defined(PADDLE_WITH_HIP)
1659 1660 1661
            PADDLE_THROW(platform::errors::PermissionDenied(
                "Cannot use CUDAPlace in CPU only version, "
                "Please recompile or reinstall Paddle with CUDA support."));
Q
qijun 已提交
1662
#else
L
Leo Chen 已提交
1663
      auto* context = new phi::GPUContext(place);
W
Wilber 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
      context->SetAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(place, context->stream())
          .get());
      context->SetHostAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(paddle::platform::CPUPlace())
          .get());
      context->SetZeroAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
        .GetZeroAllocator(place)
        .get());
1676 1677 1678 1679
      context->SetHostZeroAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
        .GetZeroAllocator(paddle::platform::CPUPlace())
        .get());
W
wanghuancoder 已提交
1680 1681 1682 1683
      context->SetPinnedAllocator(
        paddle::memory::allocation::AllocatorFacade::Instance()
          .GetAllocator(paddle::platform::CUDAPinnedPlace())
          .get());
W
Wilber 已提交
1684 1685
      context->PartialInitWithAllocator();
      return context;
Q
qijun 已提交
1686
#endif
1687 1688 1689 1690 1691
          })
      .def_static(
          "create",
          [](paddle::platform::CUDAPinnedPlace &place)
              -> paddle::platform::DeviceContext * {
1692
#if !defined(PADDLE_WITH_CUDA) && !defined(PADDLE_WITH_HIP)
1693 1694 1695
            PADDLE_THROW(platform::errors::PermissionDenied(
                "Cannot use CUDAPinnedPlace in CPU only version, "
                "Please recompile or reinstall Paddle with CUDA support."));
C
chengduoZH 已提交
1696 1697 1698
#else
                  return new paddle::platform::CUDAPinnedDeviceContext(place);
#endif
1699
          });
1700
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
D
Dong Zhihong 已提交
1701 1702
  py::class_<platform::Communicator>(m, "Communicator").def(py::init<>());
#endif
1703 1704 1705
  m.def("get_all_device_type", []() {
    std::vector<std::string> device_types;
#ifdef PADDLE_WITH_CUSTOM_DEVICE
1706
    device_types = phi::DeviceManager::GetAllDeviceTypes();
1707
#else
R
ronnywang 已提交
1708
          VLOG(1) << string::Sprintf(
1709 1710 1711 1712
              "Cannot use get_all_device_type because you have installed"
              "CPU/GPU version PaddlePaddle.\n"
              "If you want to use get_all_device_type, please try to install"
              "CustomDevice version "
R
ronnywang 已提交
1713
              "PaddlePaddle by: pip install paddlepaddle\n");
1714 1715 1716 1717 1718 1719
#endif
    return device_types;
  });
  m.def("get_all_custom_device_type", []() {
    std::vector<std::string> device_types;
#ifdef PADDLE_WITH_CUSTOM_DEVICE
1720
    device_types = phi::DeviceManager::GetAllCustomDeviceTypes();
1721
#else
R
ronnywang 已提交
1722
          VLOG(1) << string::Sprintf(
1723 1724 1725 1726
              "Cannot use get_all_custom_device_type because you have installed"
              "CPU/GPU version PaddlePaddle.\n"
              "If you want to use get_all_custom_device_type, please try to "
              "install CustomDevice version "
R
ronnywang 已提交
1727
              "PaddlePaddle by: pip install paddlepaddle\n");
1728 1729 1730 1731 1732 1733
#endif
    return device_types;
  });
  m.def("get_available_device", [] {
    std::vector<std::string> devices;
#ifdef PADDLE_WITH_CUSTOM_DEVICE
1734
    devices = phi::DeviceManager::GetAllDeviceList();
1735
#else
R
ronnywang 已提交
1736
          VLOG(1) << string::Sprintf(
1737 1738 1739 1740
              "Cannot use get_available_device because you have installed"
              "CPU/GPU version PaddlePaddle.\n"
              "If you want to use get_available_device, please try to install"
              "CustomDevice version "
R
ronnywang 已提交
1741
              "PaddlePaddle by: pip install paddlepaddle\n");
1742 1743 1744 1745 1746 1747
#endif
    return devices;
  });
  m.def("get_available_custom_device", [] {
    std::vector<std::string> devices;
#ifdef PADDLE_WITH_CUSTOM_DEVICE
1748
    devices = phi::DeviceManager::GetAllCustomDeviceList();
1749
#else
R
ronnywang 已提交
1750
          VLOG(1) << string::Sprintf(
1751 1752 1753 1754 1755 1756
              "Cannot use get_available_custom_device because you have "
              "installed"
              "CPU/GPU version PaddlePaddle.\n"
              "If you want to use get_available_custom_device, please try to "
              "install"
              "CustomDevice version "
R
ronnywang 已提交
1757
              "PaddlePaddle by: pip install paddlepaddle\n");
1758 1759 1760
#endif
    return devices;
  });
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
  m.def("get_custom_device_count", [](const std::string &device_type) {
    size_t device_count = 0;
#ifdef PADDLE_WITH_CUSTOM_DEVICE
    // TODO(duanyanhui): Optimize DeviceManager::GetDeviceCount to support
    // returning default device when only one device is registered in
    // DeviceManager.
    device_count = phi::DeviceManager::GetDeviceCount(device_type);
#else
          VLOG(1) << string::Sprintf(
              "Cannot use get_custom_device_count because you have "
              "installed"
              "CPU/GPU version PaddlePaddle.\n"
              "If you want to use get_custom_device_count, please try to "
              "install"
              "CustomDevice version "
              "PaddlePaddle by: pip install paddlepaddle\n");
#endif
    return device_count;
  });
Y
Yu Yang 已提交
1780

Y
Yu Yang 已提交
1781
  py::class_<OperatorBase>(m, "Operator")
1782 1783 1784 1785 1786 1787 1788
      .def_static("create",
                  [](py::bytes protobin) {
                    proto::OpDesc desc;
                    PADDLE_ENFORCE_EQ(desc.ParsePartialFromString(protobin),
                                      true,
                                      platform::errors::InvalidArgument(
                                          "Cannot parse user input to OpDesc"));
1789 1790
                    PADDLE_ENFORCE_EQ(desc.IsInitialized(),
                                      true,
1791 1792 1793 1794 1795 1796
                                      platform::errors::InvalidArgument(
                                          "The provided OpDesc is not "
                                          "initialized, the reason is: %s",
                                          desc.InitializationErrorString()));
                    return OpRegistry::CreateOp(desc);
                  })
1797
      .def("run",
1798 1799
           [](OperatorBase &self,
              const Scope &scope,
1800 1801 1802 1803
              const platform::CPUPlace &place) {
             pybind11::gil_scoped_release release;
             self.Run(scope, place);
           })
1804
      .def("run",
1805 1806
           [](OperatorBase &self,
              const Scope &scope,
1807 1808 1809 1810
              const platform::XPUPlace &place) {
             pybind11::gil_scoped_release release;
             self.Run(scope, place);
           })
1811
      .def("run",
1812 1813
           [](OperatorBase &self,
              const Scope &scope,
1814 1815 1816 1817
              const platform::NPUPlace &place) {
             pybind11::gil_scoped_release release;
             self.Run(scope, place);
           })
D
dzhwinter 已提交
1818
      .def("run",
1819 1820
           [](OperatorBase &self,
              const Scope &scope,
1821 1822 1823 1824
              const platform::CUDAPlace &place) {
             pybind11::gil_scoped_release release;
             self.Run(scope, place);
           })
C
chengduoZH 已提交
1825
      .def("run",
1826 1827
           [](OperatorBase &self,
              const Scope &scope,
C
chengduoZH 已提交
1828
              const platform::CUDAPinnedPlace &place) {
1829
             pybind11::gil_scoped_release release;
C
chengduoZH 已提交
1830 1831
             self.Run(scope, place);
           })
1832
      .def("run",
1833 1834
           [](OperatorBase &self,
              const Scope &scope,
1835 1836 1837 1838
              const platform::MLUPlace &place) {
             pybind11::gil_scoped_release release;
             self.Run(scope, place);
           })
R
ronnywang 已提交
1839
      .def("run",
1840 1841
           [](OperatorBase &self,
              const Scope &scope,
R
ronnywang 已提交
1842 1843 1844 1845
              const platform::CustomPlace &place) {
             pybind11::gil_scoped_release release;
             self.Run(scope, place);
           })
Y
Yu Yang 已提交
1846 1847 1848 1849 1850
      .def("type",
           [](const OperatorBase &op) -> std::string { return op.Type(); })
      .def("outputs",
           [](const OperatorBase &op)
               -> std::map<std::string, std::vector<std::string>> {
1851 1852
             return op.Outputs();
           })
Q
qijun 已提交
1853 1854
      .def("output_vars",
           [](const OperatorBase &op) { return op.OutputVars(true); })
Y
Yu Yang 已提交
1855
      .def("inputs", [](const OperatorBase &op) { return op.Inputs(); })
Q
qijun 已提交
1856
      .def("input_vars", [](const OperatorBase &op) { return op.InputVars(); })
Y
Yu Yang 已提交
1857 1858 1859 1860
      .def("__str__", &OperatorBase::DebugString)
      .def("no_intermediate_outputs",
           [](const OperatorBase &op) { return op.OutputVars(false); })
      .def("support_gpu", &OperatorBase::SupportGPU);
Y
Yu Yang 已提交
1861

1862 1863 1864
  py::class_<framework::ExecutorPrepareContext>(m, "ExecutorPrepareContext")
      .def(py::init<const ProgramDesc &, size_t>());

1865 1866
  py::class_<framework::TrainerBase, std::shared_ptr<framework::TrainerBase>>(
      m, "TrainerBase")
1867 1868 1869 1870 1871 1872
      .def(
          "get_worker_scope",
          [](TrainerBase &self, int thread_id) -> Scope * {
            return self.GetWorkerScope(thread_id);
          },
          py::return_value_policy::reference)
1873 1874
      .def("finalize", &TrainerBase::Finalize)
      .def("ResetDataset", &TrainerBase::ResetDataset);
1875

1876 1877
  m.def("_get_eager_deletion_vars", &framework::GetEagerDeletionCleanVars);

F
fengjiayi 已提交
1878
  py::class_<framework::Executor>(m, "Executor")
D
dzhwinter 已提交
1879
      .def(py::init<const platform::Place &>())
Y
Yancey1989 已提交
1880
      .def("close", &Executor::Close)
1881 1882
      .def("run_from_dataset",
           &Executor::RunFromDataset,
1883
           py::call_guard<py::gil_scoped_release>())
1884 1885
      .def("release_trainer",
           &Executor::ReleaseTrainer,
D
Dong Daxiang 已提交
1886
           py::call_guard<py::gil_scoped_release>())
1887
      .def("init_for_dataset",
1888 1889 1890 1891
           [](Executor &self,
              const ProgramDesc &prog,
              const std::string &trainer_desc,
              Scope *scope,
1892
              Dataset *dataset) -> std::shared_ptr<TrainerBase> {
D
Dong Daxiang 已提交
1893
             pybind11::gil_scoped_release release;
1894 1895 1896 1897 1898 1899 1900
             return self.InitForDataset(prog, trainer_desc, scope, dataset);
           })
      .def("run_from_dataset",
           [](Executor &self, std::shared_ptr<TrainerBase> trainer) {
             pybind11::gil_scoped_release release;
             self.RunFromDataset(trainer);
           })
1901
      .def("run_prepared_ctx",
1902 1903 1904
           [](Executor &self,
              ExecutorPrepareContext *ctx,
              Scope *scope,
1905
              std::map<std::string, const phi::DenseTensor *> *feed_targets,
1906
              std::map<std::string, FetchType *> *fetch_targets,
1907 1908
              bool create_local_scope = true,
              bool create_vars = true,
1909 1910 1911
              const std::string &feed_holder_name = "feed",
              const std::string &fetch_holder_name = "fetch") {
             pybind11::gil_scoped_release release;
1912 1913 1914 1915 1916 1917 1918 1919
             self.RunPreparedContext(ctx,
                                     scope,
                                     feed_targets,
                                     fetch_targets,
                                     create_local_scope,
                                     create_vars,
                                     feed_holder_name,
                                     fetch_holder_name);
1920
           })
1921
      .def("run_prepared_ctx",
1922 1923 1924 1925 1926
           [](Executor &self,
              ExecutorPrepareContext *ctx,
              Scope *scope,
              bool create_local_scope = true,
              bool create_vars = true,
G
guru4elephant 已提交
1927 1928
              bool keep_kids = false) {
             pybind11::gil_scoped_release release;
1929 1930
             self.RunPreparedContext(
                 ctx, scope, create_local_scope, create_vars, keep_kids);
G
guru4elephant 已提交
1931
           })
1932
      .def("prepare",
1933 1934 1935
           [](Executor &self,
              const ProgramDesc &program,
              int block_id,
1936 1937 1938 1939
              const std::vector<std::string> &skip_ref_cnt_vars =
                  std::vector<std::string>(),
              bool force_disable_gc = false) {
             pybind11::gil_scoped_release release;
1940 1941
             return self.Prepare(
                 program, block_id, skip_ref_cnt_vars, force_disable_gc);
1942 1943
           })
      .def("create_variables", &Executor::CreateVariables)
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
      .def("run",
           [](Executor &self,
              const ProgramDesc &prog,
              Scope *scope,
              int block_id,
              bool create_local_scope,
              bool create_vars,
              const std::vector<std::string> &fetch_vars) {
             pybind11::gil_scoped_release release;
             self.Run(prog,
                      scope,
                      block_id,
                      create_local_scope,
                      create_vars,
                      fetch_vars);
           });
S
sneaxiy 已提交
1960

1961
  py::class_<framework::interpreter::CostInfo>(m, "CostInfo")
1962
      .def(py::init<>())
1963 1964 1965 1966 1967
      .def("total_time",
           [](interpreter::CostInfo &self) { return self.total_time; })
      .def("device_memory_bytes", [](interpreter::CostInfo &self) {
        return self.device_memory_bytes;
      });
1968

1969
  py::class_<framework::StandaloneExecutor>(m, "StandaloneExecutor")
L
Leo Chen 已提交
1970
      .def(py::init<const platform::Place &, const ProgramDesc &>())
1971
      .def("run",
1972
           [](StandaloneExecutor &self,
1973
              Scope *scope,
1974
              std::vector<std::string> feed_names,
1975 1976 1977 1978
              std::vector<std::string> fetch_names) {
             paddle::framework::FetchList ret;
             {
               pybind11::gil_scoped_release release;
1979
               ret = self.Run(scope, feed_names, fetch_names);
1980 1981 1982
             }
             return py::cast(std::move(ret));
           })
1983 1984
      .def("dry_run",
           [](StandaloneExecutor &self,
1985
              Scope *scope,
1986
              const std::unordered_map<std::string, py::array> &input_dict) {
1987
             std::vector<phi::DenseTensor> feed_tensors;
1988 1989 1990
             std::vector<std::string> feed_names;

             for (auto &item : input_dict) {
1991
               phi::DenseTensor t;
1992 1993 1994 1995 1996 1997
               SetTensorFromPyArray<platform::CPUPlace>(
                   &t, item.second, platform::CPUPlace(), false);
               feed_names.push_back(item.first);
               feed_tensors.push_back(t);
             }

1998
             framework::interpreter::CostInfo cost_info;
1999 2000
             {
               pybind11::gil_scoped_release release;
2001
               cost_info = self.DryRun(scope, feed_names, feed_tensors);
2002 2003
             }
             return cost_info;
H
hong 已提交
2004 2005
           });

D
dzhwinter 已提交
2006
  m.def("init_gflags", framework::InitGflags);
Y
Yang Yu 已提交
2007
  m.def("init_glog", framework::InitGLOG);
2008
  m.def("init_memory_method", framework::InitMemoryMethod);
2009 2010 2011 2012
  m.def("load_op_meta_info_and_register_op", [](const std::string dso_name) {
    egr::Controller::Instance().MergeOpMetaInfoMap(
        framework::LoadOpMetaInfoAndRegisterOp(dso_name));
  });
2013 2014 2015 2016 2017 2018 2019 2020
  m.def("init_devices", []() {
    framework::InitDevices();
#ifdef PADDLE_WITH_CUSTOM_DEVICE
    for (auto &dev_type : phi::DeviceManager::GetAllCustomDeviceTypes()) {
      paddle::operators::RegisterCustomDeviceCommonKernel(dev_type);
    }
#endif
  });
2021 2022
  m.def("init_default_kernel_signatures",
        []() { framework::InitDefaultKernelSignatureMap(); });
2023 2024 2025 2026 2027 2028 2029 2030 2031
  m.def("init_tensor_operants", []() {
    paddle::OperantsManager::Instance().eager_operants.reset(
        new paddle::prim::EagerTensorOperants());
    paddle::OperantsManager::Instance().static_operants.reset(
        new paddle::prim::StaticTensorOperants());
    paddle::OperantsManager::Instance().phi_operants.reset(
        new paddle::operants::PhiTensorOperants());
    VLOG(4) << "Initialize tensor operants successfully";
  });
2032
  m.def("is_compiled_with_avx", IsCompiledWithAVX);
2033
  m.def("is_compiled_with_cuda", IsCompiledWithCUDA);
2034
  m.def("is_compiled_with_ascend", IsCompiledWithAscend);
2035
  m.def("is_compiled_with_rocm", IsCompiledWithROCM);
2036
  m.def("is_compiled_with_npu", IsCompiledWithNPU);
2037
  m.def("is_compiled_with_custom_device", IsCompiledWithCustomDevice);
J
jianghaicheng 已提交
2038
  m.def("is_compiled_with_ipu", IsCompiledWithIPU);
2039
  m.def("is_compiled_with_xpu", IsCompiledWithXPU);
2040
  m.def("is_compiled_with_mkldnn", IsCompiledWithMKLDNN);
2041
  m.def("is_compiled_with_nccl", IsCompiledWithNCCL);
W
wuhuachaocoding 已提交
2042 2043
  m.def("is_compiled_with_mpi", IsCompiledWithMPI);
  m.def("is_compiled_with_mpi_aware", IsCompiledWithMPIAWARE);
2044
  m.def("is_compiled_with_cinn", IsCompiledWithCINN);
2045
  m.def("is_compiled_with_mlu", IsCompiledWithMLU);
2046
  m.def("_is_compiled_with_heterps", IsCompiledWithHETERPS);
2047
  m.def("supports_bfloat16", SupportsBfloat16);
2048
  m.def("supports_bfloat16_fast_performance", SupportsBfloat16FastPerformance);
2049 2050
  m.def("supports_int8", SupportsInt8);
  m.def("supports_vnni", SupportsVNNI);
L
Leo Chen 已提交
2051
  m.def("op_supported_infos", imperative::OpSupportedInfos);
2052
  m.def("is_compiled_with_brpc", IsCompiledWithBrpc);
Y
update  
Yancey1989 已提交
2053
  m.def("is_compiled_with_dist", IsCompiledWithDIST);
2054 2055 2056
  m.def("_cuda_synchronize", [](const platform::CUDAPlace &place) {
    platform::DeviceContextPool::Instance().Get(place)->Wait();
  });
H
hutuxian 已提交
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075

  m.def("get_float_stats", []() {
    std::vector<paddle::platform::ExportedStatValue<float>> float_stats;
    paddle::platform::StatRegistry<float>::Instance().publish(float_stats);
    std::unordered_map<std::string, float> stats_map;
    for (const auto &stat : float_stats) {
      stats_map[stat.key] = stat.value;
    }
    return stats_map;
  });
  m.def("get_int_stats", []() {
    std::vector<paddle::platform::ExportedStatValue<int64_t>> int_stats;
    paddle::platform::StatRegistry<int64_t>::Instance().publish(int_stats);
    std::unordered_map<std::string, int64_t> stats_map;
    for (const auto &stat : int_stats) {
      stats_map[stat.key] = stat.value;
    }
    return stats_map;
  });
2076 2077 2078
  m.def("device_memory_stat_current_value",
        memory::DeviceMemoryStatCurrentValue);
  m.def("device_memory_stat_peak_value", memory::DeviceMemoryStatPeakValue);
2079 2080
  m.def(
      "run_cmd",
2081 2082
      [](const std::string &cmd,
         int time_out = -1,
2083
         int sleep_inter = -1) -> const std::string {
2084 2085
        return paddle::framework::shell_get_command_output(
            cmd, time_out, sleep_inter);
2086
      },
2087 2088 2089
      py::arg("cmd"),
      py::arg("time_out") = -1,
      py::arg("sleep_inter") = -1);
2090 2091
  m.def(
      "shell_execute_cmd",
2092 2093 2094
      [](const std::string &cmd,
         int time_out = 0,
         int sleep_inter = 0,
2095
         bool redirect_stderr = false) -> std::vector<std::string> {
2096 2097
        return paddle::framework::shell_execute_cmd(
            cmd, time_out, sleep_inter, redirect_stderr);
2098
      },
2099 2100 2101
      py::arg("cmd"),
      py::arg("time_out") = 0,
      py::arg("sleep_inter") = 0,
2102
      py::arg("redirect_stderr") = false);
G
gongweibao 已提交
2103

2104
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
2105 2106
  m.def("is_float16_supported", [](const platform::CUDAPlace &place) -> bool {
    // Only GPUs with Compute Capability >= 53 support float16
2107
    return platform::GetGPUComputeCapability(place.device) >= 53;
2108
  });
2109 2110 2111 2112
  m.def("is_bfloat16_supported", [](const platform::CUDAPlace &place) -> bool {
    // Only GPUs with Compute Capability >= 80 support bfloat16
    return platform::GetGPUComputeCapability(place.device) >= 80;
  });
2113
#endif
2114

S
Steffy-zxf 已提交
2115
  m.def("set_feed_variable",
2116 2117
        static_cast<void (*)(  // NOLINT
            Scope *,
2118
            const phi::DenseTensor &,
2119 2120
            const std::string &,
            size_t)>(&framework::SetFeedVariable));
S
Steffy-zxf 已提交
2121
  m.def("set_feed_variable",
2122 2123
        static_cast<void (*)(  // NOLINT
            Scope *,
2124
            const std::vector<std::string> &,
2125 2126
            const std::string &,
            size_t)>(&framework::SetFeedVariable));
2127
  m.def("get_fetch_variable",
2128 2129
        [](const Scope &scope,
           const std::string &var_name,
2130 2131 2132
           size_t index) -> py::object {
          auto &var = framework::GetFetchVariable(scope, var_name, index);
          if (data_is_lod_tensor(var)) {
2133
            return py::cast(PADDLE_GET(phi::DenseTensor, var));
2134
          } else {
R
Ruibiao Chen 已提交
2135
            return py::cast(PADDLE_GET(LoDTensorArray, var));
2136 2137
          }
        });
2138
  m.def("get_variable_tensor", framework::GetVariableTensor);
Q
qijun 已提交
2139

X
Xin Pan 已提交
2140 2141
  m.def("_is_program_version_supported", IsProgramVersionSupported);

2142 2143 2144 2145
  BindProgramDesc(&m);
  BindBlockDesc(&m);
  BindVarDsec(&m);
  BindOpDesc(&m);
H
Huihuang Zheng 已提交
2146
  BindCostModel(&m);
2147
  BindConstValue(&m);
2148
  BindGlobalValueGetterSetter(&m);
L
LiYuRio 已提交
2149
  BindFleetExecutor(&m);
2150
  BindTCPStore(&m);
2151
  BindCommContextManager(&m);
2152
  BindAutoParallel(&m);
2153
  BindJitProperty(&m);
Y
Yu Yang 已提交
2154

Y
Yu Yang 已提交
2155 2156 2157 2158 2159 2160 2161 2162 2163
  py::class_<framework::LoDRankTable>(m, "LodRankTable")
      .def("items", [](framework::LoDRankTable &table) {
        std::vector<std::pair<size_t, size_t>> res;
        for (auto &item : table.items()) {
          res.push_back({item.index, item.length});
        }
        return res;
      });

2164
  py::class_<LoDTensorArray> pylodtensorarray(m, "LoDTensorArray", R"DOC(
2165
    LoDTensorArray is array of LoDTensor, it supports operator[], len() and for-loop iteration.
Z
Zeng Jinle 已提交
2166 2167 2168

    Examples:
        .. code-block:: python
2169

Z
Zeng Jinle 已提交
2170 2171 2172
          import paddle.fluid as fluid

          arr = fluid.LoDTensorArray()
2173 2174 2175 2176
)DOC");
  g_framework_lodtensorarray_pytype =
      reinterpret_cast<PyTypeObject *>(pylodtensorarray.ptr());
  pylodtensorarray
S
sneaxiy 已提交
2177 2178
      .def("__init__",
           [](LoDTensorArray &instance) { new (&instance) LoDTensorArray(); })
2179 2180 2181 2182
      .def(
          "__getitem__",
          [](LoDTensorArray &self, size_t i) { return &self.at(i); },
          py::return_value_policy::reference)
Y
Yu Yang 已提交
2183 2184
      .def("__len__", [](LoDTensorArray &self) { return self.size(); })
      .def("__setitem__",
2185
           [](LoDTensorArray &self, size_t i, const phi::DenseTensor &t) {
2186 2187
             PADDLE_ENFORCE_LT(i,
                               self.size(),
2188 2189 2190
                               platform::errors::InvalidArgument(
                                   "The index to set is larger than the size "
                                   "of LoDTensorArray."));
Y
Yu Yang 已提交
2191 2192 2193
             self[i].ShareDataWith(t);
             self[i].set_lod(t.lod());
           })
2194 2195
      .def(
          "append",
2196
          [](LoDTensorArray &self, const phi::DenseTensor &t) {
2197 2198 2199 2200
            self.emplace_back();
            self.back().ShareDataWith(t);
            self.back().set_lod(t.lod());
          },
2201 2202
          py::arg("tensor"),
          R"DOC(
Z
Zeng Jinle 已提交
2203
             Append a LoDensor to LoDTensorArray.
2204

2205 2206 2207 2208 2209
             Args:
                   tensor (LoDTensor): The LoDTensor to be appended.

             Returns:
                   None.
Z
Zeng Jinle 已提交
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220

             Examples:
                 .. code-block:: python

                   import paddle.fluid as fluid
                   import numpy as np

                   arr = fluid.LoDTensorArray()
                   t = fluid.LoDTensor()
                   t.set(np.ndarray([5, 30]), fluid.CPUPlace())
                   arr.append(t)
2221
           )DOC")
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
      .def(
          "_move_to_list",
          [](LoDTensorArray &self) -> py::list {
            py::list res(self.size());
            for (size_t i = 0; i < self.size(); ++i) {
              res[i] = py::cast(std::move(self[i]));
            }
            self.clear();
            return res;
          },
          py::return_value_policy::take_ownership);
Y
Yu Yang 已提交
2233

2234
  py::class_<FetchList>(m, "FetchList", R"DOC( FetchList is a
R
Ruibiao Chen 已提交
2235
        vector of paddle::variant<LoDTensor, LoDTensorArray>.
2236
        )DOC")
2237 2238 2239 2240 2241 2242
      .def(
          "_move_to_list",
          [](FetchList &self) -> py::list {
            py::list res(self.size());
            for (size_t i = 0; i < self.size(); ++i) {
              if (data_is_lod_tensor(self[i])) {
2243
                auto &data = PADDLE_GET(phi::DenseTensor, self[i]);
2244
                res[i] = py::cast(std::move(data));
2245 2246 2247
              } else if (data_is_sparse_coo_tensor(self[i])) {
                auto &data = PADDLE_GET(phi::SparseCooTensor, self[i]);
                res[i] = py::cast(std::move(data));
2248
              } else {
R
Ruibiao Chen 已提交
2249
                auto &data = PADDLE_GET(LoDTensorArray, self[i]);
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
                py::list tmp(data.size());
                for (size_t j = 0; j < data.size(); ++j) {
                  tmp[j] = py::cast(std::move(data[j]));
                }
                res[i] = std::move(tmp);
              }
            }
            self.clear();
            return res;
          },
          py::return_value_policy::take_ownership)
2261

2262 2263
      .def(
          "append",
2264
          [](FetchList &self, const phi::DenseTensor &t) {
2265
            self.emplace_back();
2266
            auto &lod_tensor = PADDLE_GET(phi::DenseTensor, self.back());
2267 2268 2269 2270 2271 2272 2273 2274 2275
            lod_tensor.ShareDataWith(t);
            lod_tensor.set_lod(t.lod());
          },
          py::arg("var"))

      .def(
          "append",
          [](FetchList &self, const LoDTensorArray &t) {
            self.emplace_back();
R
Ruibiao Chen 已提交
2276
            auto &lod_tensor_array = PADDLE_GET(LoDTensorArray, self.back());
2277 2278 2279 2280 2281 2282
            for (size_t i = 0; i < t.size(); ++i) {
              lod_tensor_array[i].ShareDataWith(t[i]);
              lod_tensor_array[i].set_lod(t[i].lod());
            }
          },
          py::arg("var"));
2283 2284

  py::class_<FetchUnmergedList>(m, "FetchUnmergedList", R"DOC(
R
Ruibiao Chen 已提交
2285
        FetchUnmergedList is 2-D array of FetchType(paddle::variant(LoDTensor, LoDTensorArray)).
Z
Zhen Wang 已提交
2286
        )DOC")
2287 2288 2289 2290 2291 2292 2293 2294
      .def(
          "_move_to_list",
          [](FetchUnmergedList &self) -> py::list {
            py::list res(self.size());
            for (size_t i = 0; i < self.size(); ++i) {
              py::list tmp(self[i].size());
              for (size_t j = 0; j < self[i].size(); ++j) {
                if (data_is_lod_tensor(self[i][j])) {
2295
                  auto &var = PADDLE_GET(phi::DenseTensor, self[i][j]);
2296 2297
                  tmp[j] = py::cast(std::move(var));
                } else {
R
Ruibiao Chen 已提交
2298
                  auto &var = PADDLE_GET(LoDTensorArray, self[i][j]);
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
                  py::list tmp_array(var.size());
                  for (size_t k = 0; k < var.size(); ++k) {
                    tmp_array[k] = std::move(var[k]);
                  }
                  tmp[j] = std::move(tmp_array);
                }
              }
              res[i] = std::move(tmp);
              self[i].clear();
            }
            self.clear();
            return res;
          },
          py::return_value_policy::take_ownership);
Z
Zhen Wang 已提交
2313

Y
Yu Yang 已提交
2314
  m.def("op_support_gpu", OpSupportGPU);
2315
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
2316
  m.def("get_cuda_device_count", platform::GetGPUDeviceCount);
2317
  m.def("get_cuda_current_device_id", &platform::GetCurrentDeviceId);
2318 2319 2320 2321 2322 2323 2324 2325
  m.def("cuda_empty_cache", [] {
    for (int dev_id : platform::GetSelectedDevices()) {
      auto *dev_ctx = platform::DeviceContextPool::Instance().GetByPlace(
          platform::CUDAPlace(dev_id));
      dev_ctx->cudnn_workspace_handle().ResetWorkspace();
    }
    platform::EmptyCache();
  });
2326 2327 2328 2329 2330 2331
  m.def(
      "get_device_properties",
      [](int id) -> const gpuDeviceProp & {
        return platform::GetDeviceProperties(id);
      },
      py::return_value_policy::copy);
2332 2333

  py::class_<gpuDeviceProp>(m, "_gpuDeviceProperties")
Y
Yanxing Shi 已提交
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
      .def_property_readonly(
          "name", [](const gpuDeviceProp &prop) { return prop.name; })
      .def_property_readonly(
          "major", [](const gpuDeviceProp &prop) { return prop.major; })
      .def_property_readonly(
          "minor", [](const gpuDeviceProp &prop) { return prop.minor; })
      .def_property_readonly(
          "total_memory",
          [](const gpuDeviceProp &prop) { return prop.totalGlobalMem; })
      .def_property_readonly(
          "multi_processor_count",
          [](const gpuDeviceProp &prop) { return prop.multiProcessorCount; })
      .def_property_readonly(
          "is_multi_gpu_board",
          [](const gpuDeviceProp &prop) { return prop.isMultiGpuBoard; })
      .def_property_readonly(
          "is_integrated",
          [](const gpuDeviceProp &prop) { return prop.integrated; })
      .def("__repr__", [](const gpuDeviceProp &prop) {
        std::stringstream ostr;
        ostr << "_gpuDeviceProperties(name='" << prop.name
             << "', major=" << prop.major << ", minor=" << prop.minor
             << ", total_memory=" << prop.totalGlobalMem / (1024 * 1024)
             << "MB, multi_processor_count=" << prop.multiProcessorCount << ")";
        return ostr.str();
2359
      });
D
dangqingqing 已提交
2360

2361
#if !defined(PADDLE_WITH_HIP) && !defined(_WIN32)
D
dangqingqing 已提交
2362 2363 2364
  m.def("nvprof_init", platform::CudaProfilerInit);
  m.def("nvprof_start", platform::CudaProfilerStart);
  m.def("nvprof_stop", platform::CudaProfilerStop);
2365 2366 2367
  m.def("nvprof_nvtx_push", [](const std::string &name) {
    platform::CudaNvtxRangePush(name, platform::NvtxRangeColor::Green);
  });
2368 2369 2370
  m.def("nvprof_nvtx_pop", platform::CudaNvtxRangePop);
  m.def("nvprof_enable_record_event", platform::NvprofEnableRecordEvent);
  m.def("nvprof_disable_record_event", platform::NvprofDisableRecordEvent);
D
Dong Zhihong 已提交
2371
#endif
P
peizhilin 已提交
2372
#endif
Y
Yu Yang 已提交
2373

2374 2375
#ifdef PADDLE_WITH_ASCEND_CL
  m.def("get_npu_device_count", platform::GetNPUDeviceCount);
2376
  m.def("npu_finalize", []() {
2377 2378
    platform::HCCLCommContext::Instance().ReleaseHCCLComms();

2379 2380 2381
    auto &pool = platform::DeviceContextPool::Instance();
    auto devices = platform::GetSelectedNPUDevices();
    for (size_t i = 0; i < devices.size(); ++i) {
R
ronnywang 已提交
2382
      platform::NPUDeviceGuard guard(devices[i]);
2383 2384 2385 2386
      pool.Get(platform::NPUPlace(devices[i]))->Wait();
    }
    platform::AclInstance::Instance().Finalize();
  });
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406

  py::class_<platform::NPUProfConfigWrapper>(m, "NPUProfConfigWrapper");

  m.def("npu_prof_init", platform::NPUProfilerInit);
  m.def("npu_prof_start", [](platform::NPUProfConfigWrapper c) {
    platform::NPUProfilerStart(c.ptr());
  });
  m.def("npu_prof_stop", [](platform::NPUProfConfigWrapper c) {
    platform::NPUProfilerStop(c.ptr());
  });
  m.def("npu_prof_finalize", platform::NPUProfilerFinalize);
  m.def("npu_prof_create_config", []() {
    return platform::NPUProfConfigWrapper(platform::NPUProfilerCreateConfig());
  });

  m.def("npu_prof_destropy_config", [](platform::NPUProfConfigWrapper c) {
    platform::NPUProfilerDestroyConfig(c.ptr());
  });
#endif

J
jianghaicheng 已提交
2407 2408 2409 2410
#ifdef PADDLE_WITH_IPU
  m.def("get_ipu_device_count", platform::GetIPUDeviceCount);
#endif

2411 2412 2413 2414
#ifdef PADDLE_WITH_MLU
  m.def("get_mlu_device_count", platform::GetMLUDeviceCount);
#endif

2415 2416 2417 2418 2419 2420
  py::enum_<platform::TracerOption>(m, "TracerOption", py::arithmetic())
      .value("kDefault", platform::TracerOption::kDefault)
      .value("kOpDetail", platform::TracerOption::kOpDetail)
      .value("kAllOpDetail", platform::TracerOption::kAllOpDetail)
      .export_values();

2421 2422 2423 2424
  py::enum_<platform::ProfilerState>(m, "ProfilerState", py::arithmetic())
      .value("kDisabled", platform::ProfilerState::kDisabled)
      .value("kCPU", platform::ProfilerState::kCPU)
      .value("kCUDA", platform::ProfilerState::kCUDA)
2425
      .value("kAll", platform::ProfilerState::kAll)
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
      .export_values();

  py::enum_<platform::EventSortingKey>(m, "EventSortingKey", py::arithmetic())
      .value("kDefault", platform::EventSortingKey::kDefault)
      .value("kCalls", platform::EventSortingKey::kCalls)
      .value("kTotal", platform::EventSortingKey::kTotal)
      .value("kMin", platform::EventSortingKey::kMin)
      .value("kMax", platform::EventSortingKey::kMax)
      .value("kAve", platform::EventSortingKey::kAve)
      .export_values();

2437
  m.def("set_tracer_option", platform::SetTracerOption);
2438 2439
  m.def("enable_profiler", platform::EnableProfiler);
  m.def("disable_profiler", platform::DisableProfiler);
X
Xin Pan 已提交
2440
  m.def("is_profiler_enabled", platform::IsProfileEnabled);
2441
  m.def("reset_profiler", platform::ResetProfiler);
W
wuhuanzhou 已提交
2442
  m.def("register_pass", [](const std::string &pass_type, py::object callable) {
2443
    PADDLE_ENFORCE_EQ(
2444 2445
        framework::ir::PassRegistry::Instance().Has(pass_type),
        false,
2446 2447 2448
        platform::errors::AlreadyExists("Pass '%s' is registered more than "
                                        "once. Please use another name.",
                                        pass_type));
W
wuhuanzhou 已提交
2449
    callable.inc_ref();
2450 2451 2452 2453 2454 2455 2456 2457
    framework::ir::PassRegistry::Instance().Insert(
        pass_type, [pass_type, callable]() {
          py::gil_scoped_acquire guard;
          std::unique_ptr<framework::ir::Pass> pass(
              new framework::ir::GeneratePass(
                  py::cast<std::string>(callable())));
          return pass;
        });
2458
  });
2459
  m.def("get_pass", [](const std::string &pass_type) {
W
WangZhen 已提交
2460 2461 2462
    auto pass = framework::ir::PassRegistry::Instance().Get(pass_type);
    return std::shared_ptr<framework::ir::Pass>(std::move(pass));
  });
Y
Yu Yang 已提交
2463

2464
  m.def("size_of_dtype", framework::SizeOfType);
C
chenjian 已提交
2465 2466
  py::class_<paddle::platform::ProfilerResult>(m, "_ProfilerResult")
      .def(py::init<>())
2467 2468
      .def("get_data",
           &paddle::platform::ProfilerResult::GetData,
C
chenjian 已提交
2469 2470
           py::return_value_policy::automatic_reference)
      .def("save", &paddle::platform::ProfilerResult::Save)
2471 2472 2473 2474 2475 2476 2477 2478 2479
      .def("get_extra_info", &paddle::platform::ProfilerResult::GetExtraInfo)
      .def("get_version", &paddle::platform::ProfilerResult::GetVersion)
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
      .def("get_span_indx", &paddle::platform::ProfilerResult::GetSpanIndx)
      .def("get_device_property",
           &paddle::platform::ProfilerResult::GetDeviceProperty);
#else
      .def("get_span_indx", &paddle::platform::ProfilerResult::GetSpanIndx);
#endif
C
chenjian 已提交
2480

2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
  py::class_<paddle::platform::MemPythonNode>(m, "MemPythonNode")
      .def(py::init<>())
      .def_readwrite("timestamp_ns",
                     &paddle::platform::MemPythonNode::timestamp_ns)
      .def_readwrite("addr", &paddle::platform::MemPythonNode::addr)
      .def_readwrite("type", &paddle::platform::MemPythonNode::type)
      .def_readwrite("process_id", &paddle::platform::MemPythonNode::process_id)
      .def_readwrite("thread_id", &paddle::platform::MemPythonNode::thread_id)
      .def_readwrite("increase_bytes",
                     &paddle::platform::MemPythonNode::increase_bytes)
      .def_readwrite("place", &paddle::platform::MemPythonNode::place)
      .def_readwrite("current_allocated",
                     &paddle::platform::MemPythonNode::current_allocated)
      .def_readwrite("current_reserved",
                     &paddle::platform::MemPythonNode::current_reserved)
      .def_readwrite("peak_allocated",
                     &paddle::platform::MemPythonNode::peak_allocated)
      .def_readwrite("peak_reserved",
                     &paddle::platform::MemPythonNode::peak_reserved);

C
chenjian 已提交
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
  py::class_<paddle::platform::DevicePythonNode>(m, "DevicePythonNode")
      .def(py::init<>())
      .def_readwrite("name", &paddle::platform::DevicePythonNode::name)
      .def_readwrite("type", &paddle::platform::DevicePythonNode::type)
      .def_readwrite("start_ns", &paddle::platform::DevicePythonNode::start_ns)
      .def_readwrite("end_ns", &paddle::platform::DevicePythonNode::end_ns)
      .def_readwrite("device_id",
                     &paddle::platform::DevicePythonNode::device_id)
      .def_readwrite("context_id",
                     &paddle::platform::DevicePythonNode::context_id)
      .def_readwrite("stream_id",
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
                     &paddle::platform::DevicePythonNode::stream_id)
      .def_readwrite("correlation_id",
                     &paddle::platform::DevicePythonNode::correlation_id)
      .def_readwrite("block_x", &paddle::platform::DevicePythonNode::block_x)
      .def_readwrite("block_y", &paddle::platform::DevicePythonNode::block_y)
      .def_readwrite("block_z", &paddle::platform::DevicePythonNode::block_z)
      .def_readwrite("grid_x", &paddle::platform::DevicePythonNode::grid_x)
      .def_readwrite("grid_y", &paddle::platform::DevicePythonNode::grid_y)
      .def_readwrite("grid_z", &paddle::platform::DevicePythonNode::grid_z)
      .def_readwrite("shared_memory",
                     &paddle::platform::DevicePythonNode::shared_memory)
      .def_readwrite("registers_per_thread",
                     &paddle::platform::DevicePythonNode::registers_per_thread)
      .def_readwrite("blocks_per_sm",
                     &paddle::platform::DevicePythonNode::blocks_per_sm)
      .def_readwrite("warps_per_sm",
                     &paddle::platform::DevicePythonNode::warps_per_sm)
      .def_readwrite("occupancy",
                     &paddle::platform::DevicePythonNode::occupancy)
      .def_readwrite("num_bytes",
                     &paddle::platform::DevicePythonNode::num_bytes)
      .def_readwrite("value", &paddle::platform::DevicePythonNode::value);
C
chenjian 已提交
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543

  py::class_<paddle::platform::HostPythonNode>(m, "HostPythonNode")
      .def(py::init<>())
      .def_readwrite("name", &paddle::platform::HostPythonNode::name)
      .def_readwrite("type", &paddle::platform::HostPythonNode::type)
      .def_readwrite("start_ns", &paddle::platform::HostPythonNode::start_ns)
      .def_readwrite("end_ns", &paddle::platform::HostPythonNode::end_ns)
      .def_readwrite("process_id",
                     &paddle::platform::HostPythonNode::process_id)
      .def_readwrite("thread_id", &paddle::platform::HostPythonNode::thread_id)
2544 2545
      .def_readwrite("correlation_id",
                     &paddle::platform::HostPythonNode::correlation_id)
2546 2547 2548 2549
      .def_readwrite("input_shapes",
                     &paddle::platform::HostPythonNode::input_shapes)
      .def_readwrite("dtypes", &paddle::platform::HostPythonNode::dtypes)
      .def_readwrite("callstack", &paddle::platform::HostPythonNode::callstack)
2550 2551 2552
      .def_readwrite("attributes",
                     &paddle::platform::HostPythonNode::attributes)
      .def_readwrite("op_id", &paddle::platform::HostPythonNode::op_id)
C
chenjian 已提交
2553 2554 2555 2556 2557
      .def_readwrite("children_node",
                     &paddle::platform::HostPythonNode::children_node_ptrs)
      .def_readwrite("runtime_node",
                     &paddle::platform::HostPythonNode::runtime_node_ptrs)
      .def_readwrite("device_node",
2558 2559 2560
                     &paddle::platform::HostPythonNode::device_node_ptrs)
      .def_readwrite("mem_node",
                     &paddle::platform::HostPythonNode::mem_node_ptrs);
C
chenjian 已提交
2561 2562

  py::class_<paddle::platform::Profiler>(m, "_Profiler")
2563 2564
      .def("create",
           &paddle::platform::Profiler::Create,
C
chenjian 已提交
2565
           py::return_value_policy::take_ownership)
C
chenjian 已提交
2566
      .def("is_cupti_supported", &paddle::platform::Profiler::IsCuptiSupported)
F
fwenguang 已提交
2567 2568
      .def("is_cnpapi_supported",
           &paddle::platform::Profiler::IsCnpapiSupported)
C
chenjian 已提交
2569 2570 2571 2572 2573 2574
      .def("prepare",
           [](paddle::platform::Profiler *profiler) {
             platform::EnableHostEventRecorder();
             profiler->Prepare();
           })
      .def("start", &paddle::platform::Profiler::Start)
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
      .def(
          "stop",
          [](paddle::platform::Profiler *profiler) {
            platform::DisableHostEventRecorder();
            auto result = profiler->Stop();
            framework::StaticGraphExecutorPerfStatistics(
                result->GetNodeTrees());
            return result;
          },
          py::return_value_policy::automatic_reference);
C
chenjian 已提交
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597

  py::class_<paddle::platform::ProfilerOptions>(m, "ProfilerOptions")
      .def(py::init<>())
      .def_readwrite("trace_switch",
                     &paddle::platform::ProfilerOptions::trace_switch);

  py::class_<platform::RecordEvent>(m, "_RecordEvent")
      .def(py::init([](std::string name, platform::TracerEventType type) {
        return std::make_unique<platform::RecordEvent>(
            name, type, 1, paddle::platform::EventRole::kOrdinary);
      }))
      .def("end", [](platform::RecordEvent *event) { event->End(); });

2598 2599 2600 2601 2602 2603 2604 2605
  py::enum_<paddle::platform::TracerMemEventType>(m, "TracerMemEventType")
      .value("Allocate", paddle::platform::TracerMemEventType::Allocate)
      .value("Free", paddle::platform::TracerMemEventType::Free)
      .value("ReservedAllocate",
             paddle::platform::TracerMemEventType::ReservedAllocate)
      .value("ReservedFree",
             paddle::platform::TracerMemEventType::ReservedFree);

C
chenjian 已提交
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
  py::enum_<paddle::platform::TracerEventType>(m, "TracerEventType")
      .value("Operator", paddle::platform::TracerEventType::Operator)
      .value("Dataloader", paddle::platform::TracerEventType::Dataloader)
      .value("ProfileStep", paddle::platform::TracerEventType::ProfileStep)
      .value("CudaRuntime", paddle::platform::TracerEventType::CudaRuntime)
      .value("Kernel", paddle::platform::TracerEventType::Kernel)
      .value("Memcpy", paddle::platform::TracerEventType::Memcpy)
      .value("Memset", paddle::platform::TracerEventType::Memset)
      .value("UserDefined", paddle::platform::TracerEventType::UserDefined)
      .value("OperatorInner", paddle::platform::TracerEventType::OperatorInner)
      .value("Forward", paddle::platform::TracerEventType::Forward)
      .value("Backward", paddle::platform::TracerEventType::Backward)
      .value("Optimization", paddle::platform::TracerEventType::Optimization)
      .value("Communication", paddle::platform::TracerEventType::Communication)
      .value("PythonOp", paddle::platform::TracerEventType::PythonOp)
      .value("PythonUserDefined",
             paddle::platform::TracerEventType::PythonUserDefined);
  m.def("load_profiler_result", &paddle::platform::LoadProfilerResult);
2624 2625
  m.def("enable_memory_recorder", &paddle::platform::EnableMemoryRecorder);
  m.def("disable_memory_recorder", &paddle::platform::DisableMemoryRecorder);
2626 2627
  m.def("enable_op_info_recorder", &phi::EnableOpInfoRecorder);
  m.def("disable_op_info_recorder", &phi::DisableOpInfoRecorder);
2628

2629
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
2630 2631 2632 2633
  m.def("set_cublas_switch", phi::SetAllowTF32Cublas);
  m.def("get_cublas_switch", phi::AllowTF32Cublas);
  m.def("set_cudnn_switch", phi::SetAllowTF32Cudnn);
  m.def("get_cudnn_switch", phi::AllowTF32Cudnn);
2634
#endif  // PADDLE_WITH_CUDA
2635 2636 2637 2638 2639 2640 2641 2642
  m.def("clear_executor_cache", []() {
    pybind11::gil_scoped_release release;
    framework::ExecutorInfoCache::Instance().Finalize();
    framework::InterpreterCoreInfoCache::Instance().Finalize();
  });

  m.def("parse_safe_eager_deletion_skip_vars",
        paddle::framework::details::ParseSafeEagerDeletionSkipVarsSet);
2643

J
jianghaicheng 已提交
2644 2645
#ifdef PADDLE_WITH_IPU
  py::class_<platform::ipu::IpuBackend,
2646 2647 2648
             std::unique_ptr<platform::ipu::IpuBackend, py::nodelete>>(
      m, "IpuBackend")
      // manage IpuBackend in C++
2649 2650 2651 2652 2653 2654 2655
      .def(
          "get_instance",
          []() {
            return std::unique_ptr<platform::ipu::IpuBackend, py::nodelete>(
                platform::ipu::IpuBackend::GetInstance());
          },
          py::return_value_policy::reference)
A
Allen Guo 已提交
2656
      .def("weights_to_host", &platform::ipu::IpuBackend::WeightsToHost)
2657 2658
      .def("detach", &platform::ipu::IpuBackend::Detach)
      .def("reset", &platform::ipu::IpuBackend::Reset)
J
jianghaicheng 已提交
2659
      .def("set_scope", &platform::ipu::IpuBackend::SetScope)
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
      .def("set_ipu_strategy", &platform::ipu::IpuBackend::SetIpuStrategy)
      .def("save_model_proto", &platform::ipu::IpuBackend::SaveModelProto);

  py::class_<platform::ipu::IpuStrategy>(m, "IpuStrategy")
      .def(py::init())
      .def("set_options",
           [](platform::ipu::IpuStrategy &self, const py::dict &opt) {
             for (auto element : opt) {
               auto option_name = element.first.cast<std::string>();
               VLOG(10) << "Set option: " << option_name;
A
Allen Guo 已提交
2670 2671 2672 2673
               if (option_name == "compilation_progress_logger") {
                 self.SetCompilationProgressLogger(
                     element.second.cast<py::function>());
               } else if (py::isinstance<py::bool_>(element.second)) {
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
                 self.AddBoolOption(option_name, element.second.cast<bool>());
               } else if (py::isinstance<py::float_>(element.second)) {
                 self.AddDoubleOption(option_name,
                                      element.second.cast<double>());
               } else if (py::isinstance<py::int_>(element.second)) {
                 self.AddUint64Option(option_name,
                                      element.second.cast<std::uint64_t>());
               } else if (py::isinstance<py::str>(element.second)) {
                 self.AddStringOption(option_name,
                                      element.second.cast<std::string>());
               } else if (py::isinstance<py::set>(element.second) ||
                          py::isinstance<py::list>(element.second)) {
                 for (auto option : element.second.cast<py::list>()) {
                   std::string option_val;
                   if (py::isinstance<py::str>(option)) {
                     option_val = option.cast<std::string>();
                   } else if (py::isinstance<py::int_>(option)) {
                     option_val = std::to_string(option.cast<std::uint64_t>());
                   } else {
                     PADDLE_THROW(platform::errors::Unimplemented(
                         "Failed to convert type: %s when set IpuStrategy "
                         "option: %s",
2696 2697
                         option.get_type(),
                         option_name));
2698 2699 2700 2701 2702 2703 2704
                   }
                   self.InsertStringOption(option_name, option_val);
                 }
               } else if (py::isinstance<py::dict>(element.second)) {
                 if (option_name.rfind("location_", 0) == 0) {
                   for (auto option : element.second.cast<py::dict>()) {
                     self.SetTensorLocation(
2705 2706
                         option_name,
                         option.first.cast<std::string>(),
2707 2708
                         option.second.cast<std::uint64_t>());
                   }
2709 2710 2711 2712 2713 2714
                 } else if (option_name == "replicated_collectives_settings") {
                   for (auto option : element.second.cast<py::dict>()) {
                     self.SetReplicatedCollectivesSettings(
                         option.first.cast<std::string>(),
                         option.second.cast<bool>());
                   }
A
Allen Guo 已提交
2715 2716 2717 2718 2719 2720 2721 2722 2723
                 } else if (option_name == "accumulate_outer_fragment") {
                   for (auto option : element.second.cast<py::dict>()) {
                     std::vector<int> values;
                     for (auto value : option.second.cast<py::list>()) {
                       values.push_back(value.cast<int>());
                     }
                     self.SetAccumulateOuterFragmentSettings(
                         option.first.cast<std::uint64_t>(), values);
                   }
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
                 } else if (option_name == "custom_op") {
                   std::string paddle_op;
                   std::string popart_op;
                   std::string domain;
                   int version = -1;
                   for (auto option : element.second.cast<py::dict>()) {
                     std::string option_key = option.first.cast<std::string>();
                     if (option_key == "paddle_op") {
                       paddle_op = option.second.cast<std::string>();
                     } else if (option_key == "popart_op") {
                       popart_op = option.second.cast<std::string>();
                     } else if (option_key == "domain") {
                       domain = option.second.cast<std::string>();
                     } else if (option_key == "version") {
                       version = option.second.cast<int>();
                     } else {
                       PADDLE_THROW(platform::errors::InvalidArgument(
                           "Invalid argument, key must be one of paddle_op, "
                           "popart_op, domain or version, but revecived %s",
                           option_key));
                     }
                   }
                   self.AddCustomOp(paddle_op, popart_op, domain, version);
                 } else {
                   for (auto option : element.second.cast<py::dict>()) {
                     std::string option_key = option.first.cast<std::string>();
                     std::string option_val;
                     if (py::isinstance<py::str>(option.second)) {
                       option_val = option.second.cast<std::string>();
                     } else if (py::isinstance<py::int_>(option.second)) {
                       option_val =
                           std::to_string(option.second.cast<std::uint64_t>());
                     } else {
                       PADDLE_THROW(platform::errors::Unimplemented(
                           "Failed to convert value type: %s when set "
                           "IpuStrategy option: %s",
2760 2761
                           option.second.get_type(),
                           option_key));
2762
                     }
2763 2764
                     self.InsertStringPairOption(
                         option_name, option_key, option_val);
2765 2766 2767 2768 2769 2770
                   }
                 }
               } else {
                 PADDLE_THROW(platform::errors::InvalidArgument(
                     "Invalid IpuStrategy option value type: %s, please check "
                     "input value for option: %s",
2771 2772
                     element.second.get_type(),
                     option_name));
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
               }
             }
           })
      .def("get_option",
           [](platform::ipu::IpuStrategy &self, const std::string &name) {
             py::dict res;
             auto option_type = self.GetOptionType(name);
             res["name"] = name;
             res["type"] = option_type;
             if (option_type == "vector") {
               auto value = self.GetVectorOption(name);
               res["value"] = value;
             } else if (option_type == "map") {
               auto value = self.GetMapOption(name);
               res["value"] = value;
             } else {
               auto value_s = self.GetOption(name);
               res["value_s"] = value_s;
               if (option_type == "bool") {
                 res["value"] = static_cast<bool>(std::stoi(value_s));
               } else if (option_type == "uint64") {
                 res["value"] = std::stoul(value_s);
               } else if (option_type == "double") {
                 res["value"] = std::stod(value_s);
               } else if (option_type == "string") {
                 res["value"] = value_s;
               }
             }
             return res;
           })
2803 2804
      .def("get_all_option_names",
           &platform::ipu::IpuStrategy::GetAllOptionNames)
2805 2806 2807
      .def("enable_pattern", &platform::ipu::IpuStrategy::EnablePattern)
      .def("disable_pattern", &platform::ipu::IpuStrategy::DisablePattern)
      .def("is_pattern_enabled", &platform::ipu::IpuStrategy::IsPatternEnabled);
J
jianghaicheng 已提交
2808 2809
#endif

2810 2811 2812 2813 2814 2815 2816 2817
  m.def("enable_autotune", [] {
    return phi::autotune::AutoTuneStatus::Instance().EnableAutoTune();
  });

  m.def("disable_autotune", [] {
    return phi::autotune::AutoTuneStatus::Instance().DisableAutoTune();
  });

2818
  m.def("set_autotune_range", [](int64_t start, int64_t stop) {
2819 2820 2821 2822 2823 2824 2825
    return phi::autotune::AutoTuneStatus::Instance().SetAutoTuneRange(start,
                                                                      stop);
  });

  m.def("update_autotune_status",
        [] { return phi::autotune::AutoTuneStatus::Instance().Update(); });

2826
  m.def("get_low_precision_op_list", [] {
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
    py::dict op_list;
    auto list_op = phi::KernelFactory::Instance().GetLowPrecisionKernelList();
    for (auto iter = list_op.begin(); iter != list_op.end(); iter++) {
      auto op_name = (iter->first).c_str();
      auto counts = iter->second;
      op_list[op_name] = std::to_string(counts.fp16_called_) + "," +
                         std::to_string(counts.bf16_called_) + "," +
                         std::to_string(counts.fp32_called_) + "," +
                         std::to_string(counts.other_called_);
    }
    return op_list;
2838 2839
  });

2840 2841
  m.def("autotune_status", [] {
    py::dict res;
2842
    phi::autotune::AutoTuneCache::Instance().UpdateStatus();
2843 2844 2845 2846 2847 2848 2849
    res["step_id"] = phi::autotune::AutoTuneStatus::Instance().StepID();
    res["cache_size"] = phi::autotune::AutoTuneCache::Instance().Size();
    res["cache_hit_rate"] =
        phi::autotune::AutoTuneCache::Instance().CacheHitRate();
    return res;
  });

2850 2851
  m.def("enable_layout_autotune",
        [] { return egr::Controller::Instance().EnableLayoutAutoTune(); });
2852

2853 2854
  m.def("disable_layout_autotune",
        [] { return egr::Controller::Instance().DisableLayoutAutoTune(); });
2855

2856 2857
  m.def("use_layout_autotune",
        [] { return egr::Controller::Instance().UseLayoutAutoTune(); });
2858 2859 2860
  // Add the api for nan op debug
  m.def("set_nan_inf_debug_path",
        &paddle::framework::details::SetNanInfDebugPath);
2861

D
dongdaxiang 已提交
2862
  BindFleetWrapper(&m);
2863
  BindIO(&m);
2864 2865 2866
  BindParallelExecutor(m);
  BindPlace(m);
  BindTensor(m);
T
Thunderbrook 已提交
2867

T
Thunderbrook 已提交
2868
#if defined(PADDLE_WITH_PSLIB) && !defined(PADDLE_WITH_HETERPS)
T
Thunderbrook 已提交
2869
  BindHeterWrapper(&m);
2870
  BindMetrics(&m);
T
Thunderbrook 已提交
2871
#endif
T
Thunderbrook 已提交
2872
#ifdef PADDLE_WITH_HETERPS
T
Thunderbrook 已提交
2873
  BindPSGPUWrapper(&m);
T
Thunderbrook 已提交
2874 2875 2876
#ifdef PADDLE_WITH_PSLIB
  BindAfsWrapper(&m);
#endif
T
Thunderbrook 已提交
2877
#endif
2878
  BindGlooWrapper(&m);
H
hutuxian 已提交
2879
  BindBoxHelper(&m);
H
hutuxian 已提交
2880 2881 2882
#ifdef PADDLE_WITH_BOX_PS
  BindBoxWrapper(&m);
#endif
2883
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
D
dongdaxiang 已提交
2884
  BindNCCLWrapper(&m);
2885 2886 2887
#endif
#ifdef PADDLE_WITH_GLOO
  BindGlooContext(&m);
W
wopeizl 已提交
2888
#endif
F
flame 已提交
2889 2890
  BindGraph(&m);
  BindNode(&m);
2891
  BindPass(&m);
F
flame 已提交
2892
  BindInferenceApi(&m);
2893
  BindCompatible(&m);
2894
  BindDataset(&m);
Y
yaoxuefeng 已提交
2895
  BindGenerator(&m);
2896
#ifndef PADDLE_NO_PYTHON
2897 2898
  BindDistributed(&m);
#endif
2899 2900 2901
#ifdef PADDLE_WITH_ASCEND
  BindAscendWrapper(&m);
  BindAscendGraph(&m);
2902
  BindAscendDevice(&m);
2903
#endif
Y
Yanghello 已提交
2904 2905 2906
#ifdef PADDLE_WITH_CRYPTO
  BindCrypto(&m);
#endif
T
tangwei12 已提交
2907

T
tangwei12 已提交
2908
#if defined PADDLE_WITH_PSCORE
T
tangwei12 已提交
2909 2910
  BindDistFleetWrapper(&m);
  BindPSHost(&m);
2911
  BindCommunicatorContext(&m);
T
tangwei12 已提交
2912 2913
  BindDistCommunicator(&m);
  BindHeterClient(&m);
S
seemingwang 已提交
2914 2915 2916 2917 2918
  BindGraphPyFeatureNode(&m);
  BindGraphNode(&m);
  BindGraphPyService(&m);
  BindGraphPyServer(&m);
  BindGraphPyClient(&m);
1
123malin 已提交
2919 2920 2921 2922
  BindIndexNode(&m);
  BindTreeIndex(&m);
  BindIndexWrapper(&m);
  BindIndexSampler(&m);
2923
#ifdef PADDLE_WITH_HETERPS
2924 2925
  BindNodeQueryResult(&m);
  BindNeighborSampleQuery(&m);
2926 2927 2928
  BindNeighborSampleResult(&m);
  BindGraphGpuWrapper(&m);
#endif
2929
#endif
X
Xinger 已提交
2930
#if defined(PADDLE_WITH_RPC)
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
  BindWorkerInfo(&m);
  BindFuture(&m);
  InitAndSetAgentInstance(&m);
  InvokeRpc(&m);
  StartWorker(&m);
  StartClient(&m);
  StopWorker(&m);
  GetWorkerInfo(&m);
  GetWorkerInfoByRank(&m);
  GetCurrentWorkerInfo(&m);
  GetAllWorkerInfos(&m);
#endif
L
Luo Tao 已提交
2943
}
2944
}  // namespace pybind
2945
}  // namespace paddle