eager_utils.cc 61.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

12
#include "paddle/fluid/pybind/eager_utils.h"
13
#include <Python.h>
14
#include "paddle/ir/core/value.h"
15 16 17 18
// Avoid a problem with copysign defined in pyconfig.h on Windows.
#ifdef copysign
#undef copysign
#endif
19 20 21 22 23 24

#include <string>
#include <vector>

#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/autograd_meta.h"
25
#include "paddle/fluid/eager/hooks.h"
J
Jiabin Yang 已提交
26
#include "paddle/fluid/framework/convert_utils.h"
0
0x45f 已提交
27
#include "paddle/fluid/framework/scope.h"
J
Jiabin Yang 已提交
28
#include "paddle/fluid/framework/scope_guard.h"
29
#include "paddle/fluid/jit/function.h"
30
#include "paddle/fluid/memory/allocation/allocator.h"
31
#include "paddle/fluid/operators/py_func_op.h"
J
Jiabin Yang 已提交
32
#include "paddle/fluid/operators/utils.h"
33 34
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/pybind/eager.h"
35
#include "paddle/fluid/pybind/op_function_common.h"
36
#include "paddle/fluid/pybind/tensor_py.h"
37
#include "paddle/phi/api/ext/op_meta_info.h"
38 39 40
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/dense_tensor.h"
41 42 43
#include "paddle/phi/core/flags.h"

PHI_DECLARE_bool(check_nan_inf);
44
PHI_DECLARE_int32(check_nan_inf_level);
45 46 47
namespace paddle {
namespace pybind {

48
extern PyTypeObject* p_tensor_type;
J
Jack Zhou 已提交
49
extern PyTypeObject* p_string_tensor_type;
50

0
0x45f 已提交
51
extern PyTypeObject* g_framework_scope_pytype;
52
extern PyTypeObject* g_ir_opresult_pytype;
J
Jiabin Yang 已提交
53
extern PyTypeObject* g_vartype_pytype;
54 55 56 57 58
extern PyTypeObject* g_place_pytype;
extern PyTypeObject* g_cudaplace_pytype;
extern PyTypeObject* g_cpuplace_pytype;
extern PyTypeObject* g_xpuplace_pytype;
extern PyTypeObject* g_cudapinnedplace_pytype;
59
extern PyTypeObject* g_customplace_pytype;
60
extern PyTypeObject* g_framework_tensor_pytype;
61
extern PyTypeObject* g_framework_lodtensorarray_pytype;
62
extern PyTypeObject* g_jit_function_pytype;
L
LiYuRio 已提交
63 64 65
#ifdef PADDLE_WITH_DISTRIBUTE
extern PyTypeObject* g_tensor_dist_attr_pytype;
#endif
66

67
int TensorDtype2NumpyDtype(phi::DataType dtype) {
68
  switch (dtype) {
69
    case phi::DataType::BOOL:
70
      return pybind11::detail::npy_api::NPY_BOOL_;
71
    case phi::DataType::INT8:
72
      return pybind11::detail::npy_api::NPY_INT8_;
73
    case phi::DataType::UINT8:
74
      return pybind11::detail::npy_api::NPY_UINT8_;
75
    case phi::DataType::INT16:
76
      return pybind11::detail::npy_api::NPY_INT16_;
77
    case phi::DataType::INT32:
78
      return pybind11::detail::npy_api::NPY_INT32_;
79
    case phi::DataType::INT64:
80
      return pybind11::detail::npy_api::NPY_INT64_;
H
hong 已提交
81 82
    case phi::DataType::BFLOAT16:
      return pybind11::detail::NPY_UINT16_;
83
    case phi::DataType::FLOAT16:
84
      return pybind11::detail::NPY_FLOAT16_;
85
    case phi::DataType::FLOAT32:
86
      return pybind11::detail::npy_api::NPY_FLOAT_;
87
    case phi::DataType::FLOAT64:
88
      return pybind11::detail::npy_api::NPY_DOUBLE_;
89
    case phi::DataType::COMPLEX64:
90
      return pybind11::detail::NPY_COMPLEX64;
91
    case phi::DataType::COMPLEX128:
92
      return pybind11::detail::NPY_COMPLEX128;
J
Jack Zhou 已提交
93 94
    case phi::DataType::PSTRING:
      return pybind11::detail::npy_api::NPY_UNICODE_;
95 96
    default:
      PADDLE_THROW(paddle::platform::errors::InvalidArgument(
97
          "Unknow phi::DataType, the int value = %d.",
98 99 100 101 102
          static_cast<int>(dtype)));
      return 0;
  }
}

103
bool PyObject_CheckLongOrConvertToLong(PyObject** obj) {
104
  if (PyLong_Check(*obj) && !PyBool_Check(*obj)) {
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    return true;
  }

  if (std::string((reinterpret_cast<PyTypeObject*>((*obj)->ob_type))->tp_name)
          .find("numpy") != std::string::npos) {
    auto to = PyNumber_Long(*obj);
    if (to) {
      *obj = to;
      return true;
    }
  }

  return false;
}

bool PyObject_CheckFloatOrConvertToFloat(PyObject** obj) {
  // sometimes users provide PyLong or numpy.int64 but attr is float
  if (PyFloat_Check(*obj) || PyLong_Check(*obj)) {
    return true;
  }
  if (std::string((reinterpret_cast<PyTypeObject*>((*obj)->ob_type))->tp_name)
          .find("numpy") != std::string::npos) {
    auto to = PyNumber_Float(*obj);
    if (to) {
      *obj = to;
      return true;
    }
  }
  return false;
}

bool PyObject_CheckStr(PyObject* obj) { return PyUnicode_Check(obj); }

bool CastPyArg2AttrBoolean(PyObject* obj, ssize_t arg_pos) {
  if (obj == Py_None) {
    return false;  // To be compatible with QA integration testing. Some
141
                   // test cases pass in None.
142 143 144 145 146 147 148 149
  } else if (obj == Py_True) {
    return true;
  } else if (obj == Py_False) {
    return false;
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "bool, but got %s",
150 151
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
152 153 154 155 156 157 158 159 160 161
  }
}

int CastPyArg2AttrInt(PyObject* obj, ssize_t arg_pos) {
  if (PyObject_CheckLongOrConvertToLong(&obj)) {
    return static_cast<int>(PyLong_AsLong(obj));
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "int, but got %s",
162 163
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
164 165 166 167 168 169 170 171 172 173
  }
}

int64_t CastPyArg2AttrLong(PyObject* obj, ssize_t arg_pos) {
  if (PyObject_CheckLongOrConvertToLong(&obj)) {
    return (int64_t)PyLong_AsLong(obj);  // NOLINT
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "long, but got %s",
174 175
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
176 177 178
  }
}

W
wanghuancoder 已提交
179 180 181 182 183 184 185
size_t CastPyArg2AttrSize_t(PyObject* obj, ssize_t arg_pos) {
  if (PyObject_CheckLongOrConvertToLong(&obj)) {
    return PyLong_AsSize_t(obj);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "long, but got %s",
186 187
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
W
wanghuancoder 已提交
188 189 190
  }
}

191 192 193 194 195 196 197
float CastPyArg2AttrFloat(PyObject* obj, ssize_t arg_pos) {
  if (PyObject_CheckFloatOrConvertToFloat(&obj)) {
    return static_cast<float>(PyFloat_AsDouble(obj));
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "float, but got %s",
198 199
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
200 201 202 203 204 205 206 207 208 209 210 211 212
  }
}

std::string CastPyArg2AttrString(PyObject* obj, ssize_t arg_pos) {
  if (PyObject_CheckStr(obj)) {
    Py_ssize_t size;
    const char* data;
    data = PyUnicode_AsUTF8AndSize(obj, &size);
    return std::string(data, static_cast<size_t>(size));
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "str, but got %s",
213 214
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
215 216 217 218
    return "";
  }
}

J
Jiabin Yang 已提交
219 220 221 222 223
std::shared_ptr<imperative::VarBase> CastPyArg2VarBase(PyObject* obj,
                                                       ssize_t arg_pos) {
  return py::cast<std::shared_ptr<imperative::VarBase>>(obj);
}

224
void SetPythonStack() {
225
  if (FLAGS_check_nan_inf && FLAGS_check_nan_inf_level == 0) {
226
    VLOG(4) << "this is SetPythonStack";
227 228 229 230 231 232 233 234 235 236 237 238 239
    pybind11::gil_scoped_acquire gil;
    PyObject* mod = PyImport_ImportModule("traceback");
    PyObject* traceback_list = PyObject_CallMethod(mod, "format_stack", "");
    std::string str = "";
    for (Py_ssize_t i = 0; i < PyList_Size(traceback_list); i++) {
      PyObject* line = PyList_GetItem(traceback_list, i);
      str += py::str(PyUnicode_AsUTF8(line));
    }
    std::string last = str + egr::Controller::Instance().GetPythonStack();
    egr::Controller::Instance().SetPythonStack(last);
  }
}

240 241
std::shared_ptr<jit::Function> CastPyArg2JitFunction(PyObject* obj,
                                                     ssize_t arg_pos) {
242
  if (PyObject_TypeCheck(obj, g_jit_function_pytype)) {
243
    return ::pybind11::handle(obj).cast<std::shared_ptr<jit::Function>>();
244 245 246
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
247
        "BaseEngine, but got %s",
248 249 250 251 252
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
}

253 254 255
std::vector<paddle::Tensor> CastPyArg2VectorOfTensor(PyObject* obj,
                                                     ssize_t arg_pos) {
  std::vector<paddle::Tensor> result;
256 257 258 259 260
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyList_GetItem(obj, i);
261
      if (PyObject_TypeCheck(item, p_tensor_type)) {
262
        result.emplace_back(reinterpret_cast<TensorObject*>(item)->tensor);
263 264 265
      } else if (item == Py_None) {
        // emplace empty Tensor for None
        result.emplace_back();
266 267 268
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
269
            "list of Tensor, but got %s at pos %d",
270
            arg_pos + 1,
271 272
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
273 274 275 276 277 278 279
      }
    }
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyTuple_GetItem(obj, i);
280
      if (PyObject_TypeCheck(item, p_tensor_type)) {
281
        result.emplace_back(reinterpret_cast<TensorObject*>(item)->tensor);
282 283 284
      } else if (item == Py_None) {
        // emplace empty Tensor for None
        result.emplace_back();
285 286 287
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
288
            "list of Tensor, but got %s at pos %d",
289
            arg_pos + 1,
290 291
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
292 293
      }
    }
294 295
  } else if (obj == Py_None) {
    return {};
296
  } else if (PyObject_TypeCheck(obj, p_tensor_type)) {
297
    return {reinterpret_cast<TensorObject*>(obj)->tensor};
298 299 300 301
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list or tuple, but got %s",
302 303
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
304 305 306 307 308 309 310 311 312 313
  }
  return result;
}

std::vector<int> CastPyArg2VectorOfInt(PyObject* obj, size_t arg_pos) {
  std::vector<int> result;
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
314
      item = PyList_GET_ITEM(obj, i);
315 316 317 318 319 320 321
      if (PyObject_CheckLongOrConvertToLong(&item)) {
        result.emplace_back(static_cast<int>(PyLong_AsLong(item)));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of int, but got %s at pos %d",
            arg_pos + 1,
322 323
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
324 325 326 327 328 329
      }
    }
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
330
      item = PyTuple_GET_ITEM(obj, i);
331 332
      if (PyObject_CheckLongOrConvertToLong(&item)) {
        result.emplace_back(static_cast<int>(PyLong_AsLong(item)));
333 334 335
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
336
            "list of int, but got %s at pos %d",
337
            arg_pos + 1,
338 339
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
340 341
      }
    }
342 343
  } else if (obj == Py_None) {
    return {};
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
  } else if (PyObject_CheckLongOrConvertToLong(&obj)) {
    return {static_cast<int>(PyLong_AsLong(obj))};
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list or tuple, but got %s",
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
  return result;
}

std::vector<int64_t> CastPyArg2VectorOfInt64(PyObject* obj, size_t arg_pos) {
  std::vector<int64_t> result;
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyList_GET_ITEM(obj, i);
      if (PyObject_CheckLongOrConvertToLong(&item)) {
        result.emplace_back(static_cast<int64_t>(PyLong_AsLong(item)));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of int, but got %s at pos %d",
            arg_pos + 1,
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
      }
    }
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyTuple_GET_ITEM(obj, i);
      if (PyObject_CheckLongOrConvertToLong(&item)) {
        result.emplace_back(static_cast<int64_t>(PyLong_AsLong(item)));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of int, but got %s at pos %d",
            arg_pos + 1,
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
      }
    }
  } else if (obj == Py_None) {
    return {};
  } else if (PyObject_CheckLongOrConvertToLong(&obj)) {
    return {static_cast<int64_t>(PyLong_AsLong(obj))};
394 395 396 397
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list or tuple, but got %s",
398 399
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
400 401 402 403
  }
  return result;
}

W
wanghuancoder 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417
std::vector<size_t> CastPyArg2VectorOfSize_t(PyObject* obj, size_t arg_pos) {
  std::vector<size_t> result;
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyList_GetItem(obj, i);
      if (PyObject_CheckLongOrConvertToLong(&item)) {
        result.emplace_back(PyLong_AsSize_t(item));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of int, but got %s at pos %d",
            arg_pos + 1,
418 419
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
W
wanghuancoder 已提交
420 421
      }
    }
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyTuple_GET_ITEM(obj, i);
      if (PyObject_CheckLongOrConvertToLong(&item)) {
        result.emplace_back(PyLong_AsSize_t(item));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of size_t, but got %s at pos %d",
            arg_pos + 1,
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
      }
    }
  } else if (obj == Py_None) {
    return {};
  } else if (PyObject_CheckLongOrConvertToLong(&obj)) {
    return {PyLong_AsSize_t(obj)};
W
wanghuancoder 已提交
442 443 444
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
445
        "list of size_t, but got %s",
446 447
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
W
wanghuancoder 已提交
448 449 450 451
  }
  return result;
}

452 453 454 455 456 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
std::vector<float> CastPyArg2VectorOfFloat(PyObject* obj, size_t arg_pos) {
  std::vector<float> result;
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyList_GetItem(obj, i);
      if (PyObject_CheckFloatOrConvertToFloat(&item)) {
        result.emplace_back(static_cast<float>(PyFloat_AsDouble(item)));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of float, but got %s at pos %d",
            arg_pos + 1,
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
      }
    }
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyTuple_GET_ITEM(obj, i);
      if (PyObject_CheckFloatOrConvertToFloat(&item)) {
        result.emplace_back(static_cast<float>(PyFloat_AsDouble(item)));
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of float, but got %s at pos %d",
            arg_pos + 1,
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
      }
    }
  } else if (obj == Py_None) {
    return {};
  } else if (PyObject_CheckFloatOrConvertToFloat(&obj)) {
    return {static_cast<float>(PyFloat_AsDouble(obj))};
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list of float, but got %s",
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
  return result;
}

W
wanghuancoder 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512 513
std::vector<std::vector<size_t>> CastPyArg2VectorOfVectorOfSize_t(
    PyObject* obj, size_t arg_pos) {
  std::vector<std::vector<size_t>> result;
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyList_GetItem(obj, i);
      result.emplace_back(CastPyArg2VectorOfSize_t(item, arg_pos));
    }
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list but got %s",
514 515
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
W
wanghuancoder 已提交
516 517 518 519
  }
  return result;
}

520 521
platform::Place CastPyArg2Place(PyObject* obj, ssize_t arg_pos) {
  platform::Place place;
522
  if (PyObject_TypeCheck(obj, g_place_pytype)) {
523
    place = ::pybind11::handle(obj).cast<platform::Place>();
524
  } else if (PyObject_TypeCheck(obj, g_cudaplace_pytype)) {
525
    place = ::pybind11::handle(obj).cast<platform::CUDAPlace>();
526
  } else if (PyObject_TypeCheck(obj, g_cpuplace_pytype)) {
527
    place = ::pybind11::handle(obj).cast<platform::CPUPlace>();
528
  } else if (PyObject_TypeCheck(obj, g_xpuplace_pytype)) {
529
    place = ::pybind11::handle(obj).cast<platform::XPUPlace>();
530
  } else if (PyObject_TypeCheck(obj, g_cudapinnedplace_pytype)) {
531
    place = ::pybind11::handle(obj).cast<platform::CUDAPinnedPlace>();
532
  } else if (PyObject_TypeCheck(obj, g_customplace_pytype)) {
533
    place = ::pybind11::handle(obj).cast<platform::CustomPlace>();
534 535 536
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
537
        "one "
张春乔 已提交
538
        "of(Place,CUDAPlace,CPUPlace,XPUPlace,CUDAPinnedPlace,"
539
        "CustomPlace), "
540
        "but got %s",
541 542
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
543 544 545 546
  }
  return place;
}

L
LiYuRio 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
#ifdef PADDLE_WITH_DISTRIBUTE
using phi::distributed::auto_parallel::TensorDistAttr;
std::shared_ptr<TensorDistAttr> CastPyArg2DistAttr(PyObject* obj,
                                                   ssize_t arg_pos) {
  if (PyObject_IsInstance(
          obj, reinterpret_cast<PyObject*>(g_tensor_dist_attr_pytype))) {
    return ::pybind11::handle(obj).cast<std::shared_ptr<TensorDistAttr>>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "TensorDistAttr, but got %s",
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
}
#endif

564
phi::DenseTensor CastPyArg2FrameworkTensor(PyObject* obj, ssize_t arg_pos) {
565
  if (PyObject_TypeCheck(obj, g_framework_tensor_pytype)) {
566
    return ::pybind11::handle(obj).cast<phi::DenseTensor>();
567 568 569
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
570
        "DenseTensor, but got %s",
571 572
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
573 574 575
  }
}

576 577
std::vector<phi::DenseTensor> CastPyArg2VectorOfTensorBase(PyObject* obj,
                                                           ssize_t arg_pos) {
578
  std::vector<phi::DenseTensor> result;
579 580 581 582 583
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyList_GetItem(obj, i);
584
      if (PyObject_TypeCheck(item, g_framework_tensor_pytype)) {
585
        result.emplace_back(::pybind11::handle(item).cast<phi::DenseTensor>());
586 587 588 589 590
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of LoDTensor, but got %s at pos %d",
            arg_pos + 1,
591 592
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
593 594 595 596 597 598 599
      }
    }
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyTuple_GetItem(obj, i);
600
      if (PyObject_TypeCheck(item, g_framework_tensor_pytype)) {
601
        result.emplace_back(::pybind11::handle(item).cast<phi::DenseTensor>());
602 603 604 605 606
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of LoDTensor, but got %s at pos %d",
            arg_pos + 1,
607 608
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
609 610
      }
    }
611
  } else if (PyObject_TypeCheck(obj, g_framework_lodtensorarray_pytype)) {
612 613 614 615
    for (auto& tensor :
         (::pybind11::handle(obj).cast<framework::LoDTensorArray>())) {
      result.emplace_back(tensor);
    }
616 617
  } else if (obj == Py_None) {
    return {};
618
  } else if (PyObject_TypeCheck(obj, g_framework_tensor_pytype)) {
619
    return {::pybind11::handle(obj).cast<phi::DenseTensor>()};
620 621 622 623
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list or tuple, but got %s",
624 625
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
626 627 628 629
  }
  return result;
}

J
Jiabin Yang 已提交
630 631 632
paddle::framework::proto::VarType::Type CastPyArg2ProtoType(PyObject* obj,
                                                            ssize_t arg_pos) {
  paddle::framework::proto::VarType::Type dtype;
633
  if (PyObject_TypeCheck(obj, g_vartype_pytype)) {
J
Jiabin Yang 已提交
634 635 636 637 638 639 640
    dtype =
        ::pybind11::handle(obj).cast<paddle::framework::proto::VarType::Type>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "one of core.VarDesc.VarType, "
        "but got %s",
641 642
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
J
Jiabin Yang 已提交
643 644 645 646
  }
  return dtype;
}

647
paddle::framework::Vocab CastPyArg2Vocab(PyObject* obj, ssize_t arg_pos) {
648
  if (PyDict_Check(obj)) {
649 650 651 652
    paddle::framework::Vocab vocab;
    vocab = ::pybind11::handle(obj)
                .cast<std::unordered_map<std::wstring, std::int32_t>>();
    return vocab;
653 654
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
655 656
        "argument (position %d) must be dict, but got %s",
        arg_pos + 1,
657 658 659 660
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
}

661 662
std::vector<std::string> CastPyArg2VectorOfString(PyObject* obj,
                                                  ssize_t arg_pos) {
663 664 665 666
  if (PyList_Check(obj)) {
    return ::pybind11::handle(obj).cast<std::vector<std::string>>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
667 668
        "argument (position %d) must be list, but got %s",
        arg_pos + 1,
669 670 671 672
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
}

673 674 675 676 677 678 679 680 681 682 683 684
PyObject* ToPyObject(bool value) {
  if (value) {
    Py_INCREF(Py_True);
    return Py_True;
  } else {
    Py_INCREF(Py_False);
    return Py_False;
  }
}

PyObject* ToPyObject(int value) { return PyLong_FromLong(value); }

685 686
PyObject* ToPyObject(uint32_t value) { return PyLong_FromUnsignedLong(value); }

687 688
PyObject* ToPyObject(int64_t value) { return PyLong_FromLongLong(value); }

W
wanghuancoder 已提交
689 690
PyObject* ToPyObject(size_t value) { return PyLong_FromSize_t(value); }

691 692 693 694 695 696 697 698 699 700
PyObject* ToPyObject(float value) { return PyLong_FromDouble(value); }

PyObject* ToPyObject(double value) { return PyLong_FromDouble(value); }

PyObject* ToPyObject(const char* value) { return PyUnicode_FromString(value); }

PyObject* ToPyObject(const std::string& value) {
  return PyUnicode_FromString(value.c_str());
}

701
PyObject* ToPyObject(const paddle::Tensor& value,
702
                     PyObject* args,
703 704 705 706 707 708 709 710 711
                     const std::map<ssize_t, ssize_t>& inplace_var_idx_map) {
  if (!inplace_var_idx_map.empty() && inplace_var_idx_map.count(0)) {
    return ToPyObject(args, inplace_var_idx_map.at(0));
  } else {
    return ToPyObject(value);
  }
}

PyObject* ToPyObject(PyObject* args, ssize_t arg_idx) {
712 713 714 715 716 717 718 719 720 721
  // For inplace op, directly return the input PyObject of the inplace tensor.
  // [Parameter]
  // args: Input PyObject.
  // arg_idx: Index of inplace PyObject in input args. Used to find the input
  // inplace PyObject.
  PyObject* obj = PyTuple_GET_ITEM(args, arg_idx);
  Py_INCREF(obj);
  return obj;
}

722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
PyObject* ToPyObject(const std::vector<bool>& value) {
  PyObject* result = PyList_New((Py_ssize_t)value.size());

  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), ToPyObject(value[i]));
  }

  return result;
}

PyObject* ToPyObject(const std::vector<int>& value) {
  PyObject* result = PyList_New((Py_ssize_t)value.size());

  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), ToPyObject(value[i]));
  }

  return result;
}

PyObject* ToPyObject(const std::vector<int64_t>& value) {
  PyObject* result = PyList_New((Py_ssize_t)value.size());

  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, (Py_ssize_t)i, ToPyObject(value[i]));
  }

  return result;
}

W
wanghuancoder 已提交
752 753 754 755 756 757 758 759 760 761
PyObject* ToPyObject(const std::vector<size_t>& value) {
  PyObject* result = PyList_New((Py_ssize_t)value.size());

  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, (Py_ssize_t)i, ToPyObject(value[i]));
  }

  return result;
}

762 763 764 765 766 767 768 769 770 771 772 773 774
PyObject* ToPyObject(const std::vector<float>& value) {
  PyObject* result = PyList_New((Py_ssize_t)value.size());

  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), ToPyObject(value[i]));
  }

  return result;
}

PyObject* ToPyObject(const std::vector<double>& value) {
  PyObject* result = PyList_New((Py_ssize_t)value.size());

W
wanghuancoder 已提交
775 776 777 778 779 780 781 782 783 784
  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), ToPyObject(value[i]));
  }

  return result;
}

PyObject* ToPyObject(const std::vector<std::vector<size_t>>& value) {
  PyObject* result = PyList_New((Py_ssize_t)value.size());

785 786 787 788 789 790 791
  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), ToPyObject(value[i]));
  }

  return result;
}

792
PyObject* ToPyObject(const std::vector<paddle::Tensor>& value,
793
                     bool return_py_none_if_not_initialize) {
Y
Yuanle Liu 已提交
794 795 796
// NOTE(liuyuanle): I encountered a bug(access violation) in windows. ref to
// https://stackoverflow.com/questions/55598839/how-to-fix-access-violation-error-when-returning-pyobject-from-c-function-usin
#ifdef _WIN32
797
  PyGILState_STATE gstate = PyGILState_Ensure();
Y
Yuanle Liu 已提交
798
#endif
799
  PyObject* result = PyList_New((Py_ssize_t)value.size());
Y
Yuanle Liu 已提交
800
#ifdef _WIN32
801
  PyGILState_Release(gstate);
Y
Yuanle Liu 已提交
802
#endif
803 804

  for (size_t i = 0; i < value.size(); i++) {
805 806 807
    if (!value[i].initialized() && return_py_none_if_not_initialize) {
      Py_INCREF(Py_None);
      PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), Py_None);
808
    } else {
809 810 811
      PyObject* obj = p_tensor_type->tp_alloc(p_tensor_type, 0);
      if (obj) {
        auto v = reinterpret_cast<TensorObject*>(obj);
812
        new (&(v->tensor)) paddle::Tensor();
813 814 815 816 817 818
        v->tensor = value[i];
      } else {
        PADDLE_THROW(platform::errors::Fatal(
            "tp_alloc return null, can not new a PyObject."));
      }
      PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), obj);
819 820 821 822 823 824
    }
  }

  return result;
}

825 826
PyObject* ToPyObject(const std::vector<std::vector<paddle::Tensor>>& value,
                     bool return_py_none_if_not_initialize) {
827 828 829
  PyObject* result = PyList_New((Py_ssize_t)value.size());

  for (size_t i = 0; i < value.size(); i++) {
830 831 832
    PyList_SET_ITEM(result,
                    static_cast<Py_ssize_t>(i),
                    ToPyObject(value[i], return_py_none_if_not_initialize));
833 834 835 836 837
  }

  return result;
}

838 839 840 841 842 843
PyObject* ToPyObject(const platform::Place& value) {
  auto obj = ::pybind11::cast(value);
  obj.inc_ref();
  return obj.ptr();
}

J
Jiabin Yang 已提交
844 845 846 847 848 849
PyObject* ToPyObject(const paddle::framework::proto::VarType::Type& dtype) {
  auto obj = ::pybind11::cast(dtype);
  obj.inc_ref();
  return obj.ptr();
}

850 851 852 853 854 855
PyObject* ToPyObject(const paddle::framework::proto::VarType& type) {
  auto obj = ::pybind11::cast(type);
  obj.inc_ref();
  return obj.ptr();
}

856
PyObject* ToPyObject(const phi::DenseTensor* value) {
857
  auto obj = ::pybind11::cast(value, py::return_value_policy::reference);
858 859 860 861
  obj.inc_ref();
  return obj.ptr();
}

862 863 864 865 866 867
PyObject* ToPyObject(const ir::OpResult& value) {
  auto obj = ::pybind11::cast(value);
  obj.inc_ref();
  return obj.ptr();
}

L
LiYuRio 已提交
868
#ifdef PADDLE_WITH_DISTRIBUTE
869
PyObject* ToPyObject(const phi::distributed::DistTensor* value) {
L
LiYuRio 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882
  auto obj = ::pybind11::cast(value, py::return_value_policy::reference);
  obj.inc_ref();
  return obj.ptr();
}

PyObject* ToPyObject(
    const phi::distributed::auto_parallel::TensorDistAttr* value) {
  auto obj = ::pybind11::cast(value, py::return_value_policy::reference);
  obj.inc_ref();
  return obj.ptr();
}
#endif

883 884 885 886 887 888
PyObject* ToPyObject(const phi::SelectedRows* value) {
  auto obj = ::pybind11::cast(value, py::return_value_policy::reference);
  obj.inc_ref();
  return obj.ptr();
}

W
wanghuancoder 已提交
889 890
PyObject* ToPyObject(const void* value) {
  if (value == nullptr) {
891
    RETURN_PY_NONE
W
wanghuancoder 已提交
892 893 894 895 896
  }
  PADDLE_THROW(
      platform::errors::Fatal("ToPyObject do not support void* with value."));
}

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
PyObject* ToPyObject(const std::unordered_map<int, int>& value) {
  PyObject* dict = PyDict_New();
  for (const auto& map_iter : value) {
    // Convert Key
    PyObject* key = ToPyObject(map_iter.first);
    // Convert Value
    PyObject* value = ToPyObject(map_iter.second);

    if (!key || !value) {
      PADDLE_THROW(
          platform::errors::Fatal("Unable to convert int to PyObject"));
    }

    if (PyDict_SetItem(dict, key, value) != 0) {
      PADDLE_THROW(
          platform::errors::Fatal("Unable to set key:value for py_dict"));
    }
  }
  return dict;
}

918 919 920
PyObject* ToPyObject(
    const std::unordered_map<std::string, std::vector<std::string>>& value) {
  PyObject* dict = PyDict_New();
L
Leding Li 已提交
921
  for (const auto& map_iter : value) {
922 923 924 925 926 927 928 929 930
    // Convert Key
    PyObject* key_string = PyUnicode_FromString(map_iter.first.c_str());
    if (!key_string) {
      PADDLE_THROW(
          platform::errors::Fatal("Unable to convert std::string to PyObject"));
    }

    // Convert Val
    PyObject* py_list = PyList_New(0);
L
Leding Li 已提交
931
    for (const auto& vector_iter : map_iter.second) {
932 933 934 935 936 937 938 939 940 941
      PyObject* val_string = PyUnicode_FromString(vector_iter.c_str());
      if (!val_string) {
        PADDLE_THROW(platform::errors::Fatal(
            "Unable to convert std::string to PyObject"));
      }

      if (PyList_Append(py_list, val_string) != 0) {
        PADDLE_THROW(
            platform::errors::Fatal("Unable to append string to py_list"));
      }
Y
YuanRisheng 已提交
942
      Py_DECREF(val_string);
943 944 945 946 947 948
    }

    if (PyDict_SetItem(dict, key_string, py_list) != 0) {
      PADDLE_THROW(
          platform::errors::Fatal("Unable to set key:value for py_dict"));
    }
Y
YuanRisheng 已提交
949 950
    Py_DECREF(py_list);
    Py_DECREF(key_string);
951 952 953 954 955
  }

  return dict;
}

956
PyObject* ToPyObject(const paddle::framework::Vocab& value) {
957
  PyObject* dict = PyDict_New();
L
Leding Li 已提交
958
  for (const auto& map_iter : value) {
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    // Convert Key
    PyObject* key_string =
        PyUnicode_FromWideChar(map_iter.first.c_str(), map_iter.first.size());
    if (!key_string) {
      PADDLE_THROW(platform::errors::Fatal(
          "Unable to convert std::wstring to PyObject"));
    }

    // Convert Val
    PyObject* py_int = PyLong_FromLong(map_iter.second);

    if (PyDict_SetItem(dict, key_string, py_int) != 0) {
      PADDLE_THROW(
          platform::errors::Fatal("Unable to set key:value for py_dict"));
    }
  }
  return dict;
}

978 979
// For Final State Dygraph,
// We directly use paddle::optional(Tensor) as dispensable Tensor
980
paddle::optional<paddle::Tensor> GetOptionalTensorFromArgs(
981 982 983 984 985
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
986 987 988 989 990 991 992 993 994 995
  PyObject* obj = PyTuple_GET_ITEM(args, arg_idx);

  if (PyTuple_Check(obj)) {
    obj = PyTuple_GET_ITEM(obj, 0);
  }

  if (obj == nullptr || obj == Py_None) {
    if (!dispensable) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be Tensor, but got None",
996 997 998
          op_type,
          arg_name,
          arg_idx));
999
    }
H
hong 已提交
1000
    return paddle::none;
1001 1002
  }

1003
  if (PyObject_TypeCheck(obj, p_tensor_type)) {
1004
    return paddle::make_optional<paddle::Tensor>(
W
wanghuancoder 已提交
1005 1006 1007
        reinterpret_cast<TensorObject*>(obj)->tensor);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
1008 1009 1010 1011
        "%s(): argument '%s' (position %d) must be Tensor, but got %s",
        op_type,
        arg_name,
        arg_idx,
W
wanghuancoder 已提交
1012 1013
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
1014 1015
}

1016
PyObject* ToPyObject(std::shared_ptr<egr::GradNodeBase> grad_node) {
1017
  py::object py_obj = py::cast(grad_node, py::return_value_policy::reference);
1018
  PyObject* py_grad_node = py_obj.release().ptr();
1019 1020 1021 1022
  Py_INCREF(py_grad_node);
  return py_grad_node;
}

1023 1024 1025 1026 1027
static paddle::Tensor& GetTensorFromPyObject(const std::string& op_type,
                                             const std::string& arg_name,
                                             PyObject* obj,
                                             ssize_t arg_idx,
                                             bool dispensable) {
1028 1029 1030 1031 1032 1033 1034 1035
  if (PyTuple_Check(obj)) {
    obj = PyTuple_GET_ITEM(obj, 0);
  }

  if (obj == nullptr || obj == Py_None) {
    if (!dispensable) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be Tensor, but got None",
1036 1037 1038
          op_type,
          arg_name,
          arg_idx));
1039
    }
1040
    static paddle::Tensor emptytensor;
1041 1042 1043
    return emptytensor;
  }

1044
  if (PyObject_TypeCheck(obj, p_tensor_type)) {
W
wanghuancoder 已提交
1045
    return reinterpret_cast<TensorObject*>(obj)->tensor;
1046
  } else if (PyObject_TypeCheck(obj, p_string_tensor_type)) {
J
Jack Zhou 已提交
1047
    return reinterpret_cast<TensorObject*>(obj)->tensor;
W
wanghuancoder 已提交
1048 1049
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
1050 1051 1052 1053
        "%s(): argument '%s' (position %d) must be Tensor, but got %s",
        op_type,
        arg_name,
        arg_idx,
W
wanghuancoder 已提交
1054 1055
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
1056 1057
}

1058 1059
// For Intermediate State Dygraph,
// we use an uninitialized Tensor to represent dispensable Tensor
1060 1061 1062 1063 1064
paddle::Tensor& GetTensorFromArgs(const std::string& op_type,
                                  const std::string& arg_name,
                                  PyObject* args,
                                  ssize_t arg_idx,
                                  bool dispensable) {
1065 1066 1067 1068
  PyObject* obj = PyTuple_GET_ITEM(args, arg_idx);
  return GetTensorFromPyObject(op_type, arg_name, obj, arg_idx, dispensable);
}

1069 1070 1071 1072 1073
std::vector<paddle::Tensor> GetTensorListFromArgs(const std::string& op_type,
                                                  const std::string& arg_name,
                                                  PyObject* args,
                                                  ssize_t arg_idx,
                                                  bool dispensable) {
1074 1075 1076 1077 1078 1079 1080
  PyObject* list = PyTuple_GET_ITEM(args, arg_idx);

  if (list == nullptr) {
    if (!dispensable) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensor, but got "
          "None",
1081 1082 1083
          op_type,
          arg_name,
          arg_idx));
1084 1085 1086 1087
    }
    return {};
  }

1088
  std::vector<paddle::Tensor> result;
1089 1090 1091

  if (PyList_Check(list)) {
    Py_ssize_t len = PyList_Size(list);
1092
    result.reserve(static_cast<size_t>(len));
1093 1094 1095 1096
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
1097 1098 1099
          op_type,
          arg_name,
          arg_idx));
1100 1101 1102
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
1103
          reinterpret_cast<TensorObject*>(PyList_GetItem(list, i))->tensor);
1104 1105 1106
    }
  } else if (PyTuple_Check(list)) {
    Py_ssize_t len = PyTuple_Size(list);
1107
    result.reserve(static_cast<size_t>(len));
1108 1109 1110 1111
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
1112 1113 1114
          op_type,
          arg_name,
          arg_idx));
1115 1116 1117
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
1118
          reinterpret_cast<TensorObject*>(PyTuple_GetItem(list, i))->tensor);
1119
    }
1120 1121
  } else if (list == Py_None) {
    return {};
1122 1123 1124 1125
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument '%s' (position %d) must be list of Tensors, but got "
        "%s",
1126 1127 1128
        op_type,
        arg_name,
        arg_idx,
1129 1130 1131 1132 1133 1134
        (reinterpret_cast<PyTypeObject*>(list->ob_type))->tp_name));
  }

  return result;
}

1135 1136 1137 1138 1139 1140
paddle::optional<std::vector<paddle::Tensor>> GetOptionalTensorListFromArgs(
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
  PyObject* list = PyTuple_GET_ITEM(args, arg_idx);

  if (list == nullptr || list == Py_None) {
    if (!dispensable) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensor, but got "
          "None",
          op_type,
          arg_name,
          arg_idx));
    }
    return paddle::none;
  }

1155
  std::vector<paddle::Tensor> result;
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 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

  if (PyList_Check(list)) {
    Py_ssize_t len = PyList_Size(list);
    result.reserve(static_cast<size_t>(len));
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
          op_type,
          arg_name,
          arg_idx));
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
          reinterpret_cast<TensorObject*>(PyList_GetItem(list, i))->tensor);
    }
  } else if (PyTuple_Check(list)) {
    Py_ssize_t len = PyTuple_Size(list);
    result.reserve(static_cast<size_t>(len));
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
          op_type,
          arg_name,
          arg_idx));
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
          reinterpret_cast<TensorObject*>(PyTuple_GetItem(list, i))->tensor);
    }
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument '%s' (position %d) must be list of Tensors, but got "
        "%s",
        op_type,
        arg_name,
        arg_idx,
        (reinterpret_cast<PyTypeObject*>(list->ob_type))->tp_name));
  }

  return result;
}

1200 1201 1202 1203 1204
paddle::Tensor* GetTensorPtrFromArgs(const std::string& op_type,
                                     const std::string& arg_name,
                                     PyObject* args,
                                     ssize_t arg_idx,
                                     bool dispensable) {
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
  PyObject* obj = PyTuple_GET_ITEM(args, arg_idx);

  if (PyTuple_Check(obj)) {
    obj = PyTuple_GET_ITEM(obj, 0);
  }

  if (obj == nullptr || obj == Py_None) {
    if (!dispensable) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be Tensor, but got None",
1215 1216 1217
          op_type,
          arg_name,
          arg_idx));
1218
    }
1219
    static paddle::Tensor emptytensor;
1220 1221 1222
    return &emptytensor;
  }

1223
  if (PyObject_TypeCheck(obj, p_tensor_type)) {
W
wanghuancoder 已提交
1224 1225 1226
    return &(reinterpret_cast<TensorObject*>(obj)->tensor);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
1227 1228 1229 1230
        "%s(): argument '%s' (position %d) must be Tensor, but got %s",
        op_type,
        arg_name,
        arg_idx,
W
wanghuancoder 已提交
1231 1232
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
1233 1234
}

1235
std::vector<paddle::Tensor*> GetTensorPtrListFromArgs(
1236 1237 1238 1239 1240
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
1241 1242 1243 1244 1245 1246 1247
  PyObject* list = PyTuple_GET_ITEM(args, arg_idx);

  if (list == nullptr) {
    if (!dispensable) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensor, but got "
          "None",
1248 1249 1250
          op_type,
          arg_name,
          arg_idx));
1251 1252 1253 1254
    }
    return {};
  }

1255
  std::vector<paddle::Tensor*> result;
1256 1257 1258 1259 1260 1261 1262

  if (PyList_Check(list)) {
    Py_ssize_t len = PyList_Size(list);
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
1263 1264 1265
          op_type,
          arg_name,
          arg_idx));
1266 1267 1268
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
1269
          &(reinterpret_cast<TensorObject*>(PyList_GetItem(list, i))->tensor));
1270 1271 1272 1273 1274 1275 1276
    }
  } else if (PyTuple_Check(list)) {
    Py_ssize_t len = PyTuple_Size(list);
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
1277 1278 1279
          op_type,
          arg_name,
          arg_idx));
1280 1281 1282
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
1283
          &(reinterpret_cast<TensorObject*>(PyTuple_GetItem(list, i))->tensor));
1284
    }
1285 1286
  } else if (list == Py_None) {
    return {};
1287 1288 1289 1290
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument '%s' (position %d) must be list of Tensors, but got "
        "%s",
1291 1292 1293
        op_type,
        arg_name,
        arg_idx,
1294 1295 1296 1297 1298
        (reinterpret_cast<PyTypeObject*>(list->ob_type))->tp_name));
  }

  return result;
}
J
Jiabin Yang 已提交
1299

1300 1301
std::vector<paddle::Tensor*> GetTensorPtrListFromPyObject(PyObject* obj) {
  std::vector<paddle::Tensor*> result;
W
wanghuancoder 已提交
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332

  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    if (len == 0) {
      PADDLE_THROW(
          platform::errors::InvalidArgument("The list of Tensor is empty."));
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
          &(reinterpret_cast<TensorObject*>(PyList_GetItem(obj, i))->tensor));
    }
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    if (len == 0) {
      PADDLE_THROW(
          platform::errors::InvalidArgument("The tuple of Tensor is empty."));
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
          &(reinterpret_cast<TensorObject*>(PyTuple_GetItem(obj, i))->tensor));
    }
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "The PyObject must be list of Tensors, but got "
        "%s",
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
  }

  return result;
}

1333 1334
std::vector<paddle::Tensor> GetTensorListFromPyObject(PyObject* obj,
                                                      bool allow_none) {
1335
  std::vector<paddle::Tensor> result;
W
wanghuancoder 已提交
1336 1337 1338 1339 1340
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyList_GetItem(obj, i);
1341
      if (PyObject_TypeCheck(item, p_tensor_type)) {
W
wanghuancoder 已提交
1342
        result.emplace_back(reinterpret_cast<TensorObject*>(item)->tensor);
1343 1344 1345
      } else if (allow_none && (item == Py_None)) {
        VLOG(4) << "Got None in Tensor list: " << i;
        result.emplace_back();
W
wanghuancoder 已提交
1346 1347 1348 1349
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument must be "
            "list of Tensor, but got %s at pos %d",
1350 1351
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
W
wanghuancoder 已提交
1352 1353 1354 1355 1356 1357 1358
      }
    }
  } else if (PyTuple_Check(obj)) {
    Py_ssize_t len = PyTuple_Size(obj);
    PyObject* item = nullptr;
    for (Py_ssize_t i = 0; i < len; i++) {
      item = PyTuple_GetItem(obj, i);
1359
      if (PyObject_TypeCheck(item, p_tensor_type)) {
W
wanghuancoder 已提交
1360
        result.emplace_back(reinterpret_cast<TensorObject*>(item)->tensor);
1361 1362 1363
      } else if (allow_none && (item == Py_None)) {
        VLOG(4) << "Got None in Tensor list: " << i;
        result.emplace_back();
W
wanghuancoder 已提交
1364 1365 1366 1367
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument must be "
            "list of Tensor, but got %s at pos %d",
1368 1369
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
W
wanghuancoder 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
      }
    }
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument must be "
        "list or tuple, but got %s",
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
  return result;
}

1381
paddle::Tensor& UnSafeGetTensorFromPyObject(PyObject* obj) {
W
wanghuancoder 已提交
1382 1383
  return reinterpret_cast<TensorObject*>(obj)->tensor;
}
1384 1385 1386 1387 1388
paddle::experimental::Scalar CastNumpy2Scalar(PyObject* obj,
                                              const std::string& op_type,
                                              ssize_t arg_pos) {
  PyTypeObject* type = obj->ob_type;
  auto type_name = std::string(type->tp_name);
L
Leo Chen 已提交
1389
  VLOG(4) << "type_name: " << type_name;
1390 1391 1392 1393 1394 1395 1396 1397
  if (type_name == "numpy.ndarray" && PySequence_Check(obj)) {
    PyObject* item = nullptr;
    item = PySequence_GetItem(obj, 0);
    if (PyObject_CheckFloatOrToFloat(&item)) {
      float value = static_cast<float>(PyFloat_AsDouble(item));
      return paddle::experimental::Scalar(value);
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
C
co63oc 已提交
1398
          "%s(): argument (position %d) is numpy.ndarray, the inner elements "
1399 1400
          "must be "
          "numpy.float32/float64 now, but got %s",
1401 1402 1403
          op_type,
          arg_pos + 1,
          type_name));  // NOLINT
1404 1405
    }
  } else if (type_name == "numpy.float64") {
1406 1407 1408 1409 1410
    double value = CastPyArg2Double(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
  } else if (type_name == "numpy.float32") {
    float value = CastPyArg2Float(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1411 1412 1413
  } else if (type_name == "numpy.float16") {
    float16 value = CastPyArg2Float16(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1414 1415 1416
  } else if (type_name == "numpy.int64") {
    int64_t value = CastPyArg2Long(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1417
  } else if (type_name == "numpy.int32" || type_name == "numpy.intc") {
1418 1419
    int value = CastPyArg2Int(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1420 1421 1422 1423 1424 1425 1426
  } else if (type_name == "numpy.complex64") {
    phi::dtype::complex<float> value = CastPyArg2Complex(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
  } else if (type_name == "numpy.complex128") {
    phi::dtype::complex<double> value =
        CastPyArg2Complex128(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1427 1428 1429
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1430 1431
        "numpy.float32/float64, numpy.int32/int64, numpy.complex64/complex128, "
        "but got %s",
1432 1433 1434
        op_type,
        arg_pos + 1,
        type_name));  // NOLINT
1435 1436 1437
  }
}

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
ir::OpResult CastPyArg2OpResult(const std::string& op_type,
                                PyObject* obj,
                                size_t arg_pos) {
  if (PyObject_TypeCheck(obj, g_ir_opresult_pytype)) {
    return ::pybind11::handle(obj).cast<ir::OpResult>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
        "OpResult, but got %s",
        op_type,
        arg_pos + 1,
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }
}

1453 1454 1455 1456 1457 1458
paddle::experimental::Scalar CastPyArg2Scalar(PyObject* obj,
                                              const std::string& op_type,
                                              ssize_t arg_pos) {
  if (obj == Py_None) {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1459
        "int, float, bool or Tensor, but got %s",
1460 1461
        op_type,
        arg_pos + 1,
1462 1463 1464 1465 1466 1467
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }

  // obj could be: int, float, bool, paddle.Tensor
  PyTypeObject* type = obj->ob_type;
  auto type_name = std::string(type->tp_name);
L
Leo Chen 已提交
1468
  VLOG(4) << "type_name: " << type_name;
1469 1470 1471 1472
  if (PyBool_Check(obj)) {
    bool value = CastPyArg2Boolean(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
  } else if (PyLong_Check(obj)) {
1473
    int64_t value = CastPyArg2Long(obj, op_type, arg_pos);
1474
    return paddle::experimental::Scalar(value);
1475
  } else if (PyFloat_Check(obj)) {
1476
    double value = CastPyArg2Double(obj, op_type, arg_pos);
1477
    return paddle::experimental::Scalar(value);
1478
  } else if (PyCheckTensor(obj)) {
1479
    paddle::Tensor& value = GetTensorFromPyObject(
1480 1481
        op_type, "" /*arg_name*/, obj, arg_pos, false /*dispensable*/);
    return paddle::experimental::Scalar(value);
1482 1483
  } else if (type_name.find("numpy") != std::string::npos) {
    return CastNumpy2Scalar(obj, op_type, arg_pos);
1484
  } else if (PyComplex_Check(obj)) {
1485
    auto value = CastPyArg2Complex128(obj, op_type, arg_pos);
1486
    return paddle::experimental::Scalar(value);
1487 1488 1489
  } else if (PyObject_CheckLongOrToLong(&obj)) {
    int value = CastPyArg2Int(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1490 1491 1492
  } else if (PyObject_CheckString(obj)) {
    std::string value = CastPyArg2String(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1493 1494 1495
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1496
        "int, float, bool or Tensor, but got %s",
1497 1498
        op_type,
        arg_pos + 1,
1499 1500 1501 1502 1503 1504 1505
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }

  // Fake a Scalar
  return paddle::experimental::Scalar(1.0);
}

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
std::vector<phi::Scalar> CastPyArg2ScalarArray(PyObject* obj,
                                               const std::string& op_type,
                                               ssize_t arg_pos) {
  if (obj == Py_None) {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
        "a list of int, float, or bool, but got %s",
        op_type,
        arg_pos + 1,
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }

  PyTypeObject* type = obj->ob_type;
  auto type_name = std::string(type->tp_name);
L
Leo Chen 已提交
1520
  VLOG(4) << "type_name: " << type_name;
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
  if (PyList_Check(obj)) {
    Py_ssize_t len = PyList_Size(obj);
    PyObject* item = nullptr;
    item = PyList_GetItem(obj, 0);
    if (PyObject_CheckFloatOrToFloat(&item)) {
      std::vector<phi::Scalar> value;
      for (Py_ssize_t i = 0; i < len; i++) {
        item = PyList_GetItem(obj, i);
        value.emplace_back(phi::Scalar{PyFloat_AsDouble(item)});
      }
      return value;
    } else if (PyObject_CheckLongOrToLong(&item)) {
      std::vector<phi::Scalar> value;
      for (Py_ssize_t i = 0; i < len; i++) {
        item = PyList_GetItem(obj, i);
        value.emplace_back(
            phi::Scalar{static_cast<int64_t>(PyLong_AsLong(item))});
      }
      return value;
1540 1541 1542 1543 1544 1545 1546 1547
    } else if (PyObject_CheckComplexOrToComplex(&item)) {
      std::vector<phi::Scalar> value;
      for (Py_ssize_t i = 0; i < len; i++) {
        item = PyList_GetItem(obj, i);
        Py_complex v = PyComplex_AsCComplex(item);
        value.emplace_back(phi::Scalar{std::complex<double>(v.real, v.imag)});
      }
      return value;
1548 1549 1550 1551
    }
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1552
        "a list of int, float, complex, or bool, but got %s",
1553 1554 1555 1556 1557 1558 1559 1560 1561
        op_type,
        arg_pos + 1,
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }

  // Fake a ScalarArray
  return std::vector<phi::Scalar>({phi::Scalar(1.0)});
}

1562 1563 1564
paddle::experimental::IntArray CastPyArg2IntArray(PyObject* obj,
                                                  const std::string& op_type,
                                                  ssize_t arg_pos) {
1565
  if (obj == Py_None) {
1566
    return paddle::experimental::IntArray({});
1567 1568 1569 1570 1571
  }

  // obj could be: int, float, bool, paddle.Tensor
  PyTypeObject* type = obj->ob_type;
  auto type_name = std::string(type->tp_name);
1572 1573
  if (type_name == "list" || type_name == "tuple" ||
      type_name == "numpy.ndarray") {
1574
    std::vector<int64_t> value = CastPyArg2Longs(obj, op_type, arg_pos);
1575
    return paddle::experimental::IntArray(value);
H
hong 已提交
1576
  } else if (type_name == "paddle.Tensor" || type_name == "Tensor") {
1577
    paddle::Tensor& value = GetTensorFromPyObject(
1578
        op_type, "" /*arg_name*/, obj, arg_pos, false /*dispensable*/);
1579
    return paddle::experimental::IntArray(value);
1580 1581 1582
  } else if (PyObject_CheckLongOrConvertToLong(&obj)) {
    return paddle::experimental::IntArray(
        {static_cast<int64_t>(PyLong_AsLong(obj))});
1583 1584 1585
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1586
        "list or int, but got %s",
1587 1588
        op_type,
        arg_pos + 1,
1589 1590 1591
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }

1592 1593
  // Fake a IntArray
  return paddle::experimental::IntArray({1});
1594 1595
}

0
0x45f 已提交
1596
paddle::framework::Scope* CastPyArg2ScopePtr(PyObject* obj) {
1597
  if (PyObject_TypeCheck(obj, g_framework_scope_pytype)) {
0
0x45f 已提交
1598 1599 1600 1601 1602 1603 1604 1605
    return ::pybind11::handle(obj).cast<paddle::framework::Scope*>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "PyObject can not be cast into framework::Scope"));
  }
}

std::vector<paddle::framework::Scope*> GetScopePtrListFromArgs(
1606 1607 1608 1609 1610
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
0
0x45f 已提交
1611 1612 1613 1614 1615 1616
  PyObject* list = PyTuple_GET_ITEM(args, arg_idx);
  if (list == nullptr) {
    if (!dispensable) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of scope, but got "
          "None",
1617 1618 1619
          op_type,
          arg_name,
          arg_idx));
0
0x45f 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    }
  }

  std::vector<paddle::framework::Scope*> result;
  if (PyList_Check(list)) {
    Py_ssize_t len = PyList_Size(list);
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of scope, but got "
          "empty list",
1630 1631 1632
          op_type,
          arg_name,
          arg_idx));
0
0x45f 已提交
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(CastPyArg2ScopePtr(PyList_GetItem(list, i)));
    }
  } else if (PyTuple_Check(list)) {
    Py_ssize_t len = PyTuple_Size(list);
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of scope, but got "
          "empty list",
1643 1644 1645
          op_type,
          arg_name,
          arg_idx));
0
0x45f 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(CastPyArg2ScopePtr(PyList_GetItem(list, i)));
    }
  } else if (list == Py_None) {
    return {};
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument '%s' (position %d) must be list of Tensors, but got "
        "%s",
1656 1657 1658
        op_type,
        arg_name,
        arg_idx,
0
0x45f 已提交
1659 1660 1661 1662 1663
        (reinterpret_cast<PyTypeObject*>(list->ob_type))->tp_name));
  }
  return result;
}

1664 1665
paddle::Place CastPyArg2Place(PyObject* obj,
                              const std::string& op_type,
1666
                              ssize_t arg_pos) {
1667
  return CastPyArg2Place(obj, arg_pos);
1668 1669
}

1670 1671
paddle::DataType CastPyArg2DataType(PyObject* obj,
                                    const std::string& op_type,
1672
                                    ssize_t arg_pos) {
1673
  if (obj == Py_None) {
1674
    return phi::DataType::UNDEFINED;
1675 1676 1677 1678 1679
  }

  framework::proto::VarType::Type type = CastPyArg2ProtoType(obj, arg_pos);
  return framework::TransToPhiDataType(type);
}
1680

1681
paddle::Tensor PyTensorHook::operator()(const paddle::Tensor& var) {
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
  py::gil_scoped_acquire gil;
  VLOG(3) << "Call PyTensorHook for var " << var.name();

  PyObject* res = nullptr;
  try {
    PyObject* p_tmp_var = ToPyObject(var);
    res = PyObject_CallFunctionObjArgs(py_func_, p_tmp_var, nullptr);
    Py_DECREF(p_tmp_var);
  } catch (platform::EnforceNotMet& e) {
    throw std::move(e);
  } catch (std::exception& e) {
    PADDLE_THROW(platform::errors::Unavailable(
        "Hook function of Tensor raises an exception: %s.", e.what()));
  } catch (...) {
    PADDLE_THROW(platform::errors::Fatal(
        "Hook function of Tensor raises an unknown exception."));
  }

  PADDLE_ENFORCE_NOT_NULL(res,
1701 1702
                          paddle::platform::errors::External(
                              pybind11::detail::error_string().c_str()));
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
  if (res == Py_None) {
    return var;
  }
  auto res_tensor = reinterpret_cast<TensorObject*>(res)->tensor;
  Py_DECREF(res);
  return res_tensor;
}

void PyVoidHook::operator()() {
  py::gil_scoped_acquire gil;
  VLOG(3) << "Call PyVoidHook";

  try {
    PyObject_CallFunctionObjArgs(py_func_, nullptr);
  } catch (platform::EnforceNotMet& e) {
    throw std::move(e);
  } catch (std::exception& e) {
    PADDLE_THROW(platform::errors::Unavailable(
        "Hook function of Tensor raises an exception: %s.", e.what()));
  } catch (...) {
    PADDLE_THROW(platform::errors::Fatal(
        "Hook function of Tensor raises an unknown exception."));
  }
}

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
PyObjectHolder::PyObjectHolder(PyObject* ptr) { ptr_ = ptr; }

PyObjectHolder::~PyObjectHolder() {
  ::pybind11::gil_scoped_acquire gil;
  Py_XDECREF(ptr_);
}

void* PyObjectHolder::get() { return reinterpret_cast<void*>(ptr_); }

void PyObjectHolder::reset(void* ptr) {
  if (ptr_) {
    ::pybind11::gil_scoped_acquire gil;
    Py_XDECREF(ptr_);
  }
  ptr_ = reinterpret_cast<PyObject*>(ptr);
}

void PyObjectHolder::inc_ref() {
  ::pybind11::gil_scoped_acquire gil;
  Py_XINCREF(ptr_);
}
void PyObjectHolder::dec_ref() {
  ::pybind11::gil_scoped_acquire gil;
  Py_XDECREF(ptr_);
}

PackHook::PackHook(PyObject* hook) : hook_(hook) { Py_INCREF(hook_); }

PackHook::~PackHook() {
  ::pybind11::gil_scoped_acquire gil;
  Py_DECREF(hook_);
}

std::shared_ptr<egr::PyObjectHolderBase> PackHook::operator()(
1762
    const paddle::Tensor& tensor) {
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
  bool grad_tmp = egr::Controller::Instance().HasGrad();
  egr::Controller::Instance().SetHasGrad(false);
  ::pybind11::gil_scoped_acquire gil;
  auto args = PyTuple_New(1);
  PyTuple_SET_ITEM(args, 0, paddle::pybind::ToPyObject(tensor));
  PyObject* ret = PyObject_Call(hook_, args, nullptr);
  PADDLE_ENFORCE_NOT_NULL(ret,
                          paddle::platform::errors::External(
                              pybind11::detail::error_string().c_str()));
  Py_XDECREF(args);
  egr::Controller::Instance().SetHasGrad(grad_tmp);
  return std::make_shared<PyObjectHolder>(ret);
}

void* PackHook::operator()(void* py_tensor) {
  bool grad_tmp = egr::Controller::Instance().HasGrad();
  egr::Controller::Instance().SetHasGrad(false);
  ::pybind11::gil_scoped_acquire gil;
  auto args = PyTuple_New(1);
  Py_INCREF(reinterpret_cast<PyObject*>(py_tensor));
  PyTuple_SET_ITEM(args, 0, reinterpret_cast<PyObject*>(py_tensor));
  PyObject* ret = PyObject_Call(hook_, args, nullptr);
  PADDLE_ENFORCE_NOT_NULL(ret,
                          paddle::platform::errors::External(
                              pybind11::detail::error_string().c_str()));
  Py_XDECREF(args);
  egr::Controller::Instance().SetHasGrad(grad_tmp);
  return reinterpret_cast<void*>(ret);
}

UnPackHook::UnPackHook(PyObject* hook) : hook_(hook) { Py_INCREF(hook_); }

UnPackHook::~UnPackHook() {
  ::pybind11::gil_scoped_acquire gil;
  Py_DECREF(hook_);
}

1800
paddle::Tensor UnPackHook::operator()(
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
    std::shared_ptr<egr::PyObjectHolderBase> packed_value) {
  bool grad_tmp = egr::Controller::Instance().HasGrad();
  egr::Controller::Instance().SetHasGrad(false);
  ::pybind11::gil_scoped_acquire gil;
  auto args = PyTuple_New(1);
  Py_INCREF(reinterpret_cast<PyObject*>(packed_value->get()));
  PyTuple_SET_ITEM(args, 0, reinterpret_cast<PyObject*>(packed_value->get()));
  PyObject* ret = PyObject_Call(hook_, args, nullptr);
  PADDLE_ENFORCE_NOT_NULL(ret,
                          paddle::platform::errors::External(
                              pybind11::detail::error_string().c_str()));
  Py_XDECREF(args);
  egr::Controller::Instance().SetHasGrad(grad_tmp);

1815
  PADDLE_ENFORCE_EQ(paddle::pybind::PyCheckTensor(ret),
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
                    true,
                    paddle::platform::errors::InvalidArgument(
                        "paddle.autograd.saved_tensors_hooks only one pair "
                        "of hooks is allowed at a time."));

  auto tensor = reinterpret_cast<paddle::pybind::TensorObject*>(ret)->tensor;
  Py_XDECREF(ret);
  return tensor;
}

void* UnPackHook::operator()(void* packed_value, void* other) {
  bool grad_tmp = egr::Controller::Instance().HasGrad();
  egr::Controller::Instance().SetHasGrad(false);
  ::pybind11::gil_scoped_acquire gil;
  auto args = PyTuple_New(1);
  Py_INCREF(reinterpret_cast<PyObject*>(packed_value));
  PyTuple_SET_ITEM(args, 0, reinterpret_cast<PyObject*>(packed_value));
  PyObject* ret = PyObject_Call(hook_, args, nullptr);
  PADDLE_ENFORCE_NOT_NULL(ret,
                          paddle::platform::errors::External(
                              pybind11::detail::error_string().c_str()));
  Py_XDECREF(args);
  egr::Controller::Instance().SetHasGrad(grad_tmp);

1840
  PADDLE_ENFORCE_EQ(paddle::pybind::PyCheckTensor(ret),
1841 1842 1843 1844 1845 1846 1847 1848
                    true,
                    paddle::platform::errors::InvalidArgument(
                        "paddle.autograd.saved_tensors_hooks only one pair "
                        "of hooks is allowed at a time."));

  return reinterpret_cast<void*>(ret);
}

1849 1850
}  // namespace pybind
}  // namespace paddle