eager_utils.cc 45.9 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 13
#include "paddle/fluid/pybind/eager_utils.h"

14 15 16 17 18 19 20
#include <Python.h>

#include <string>
#include <vector>

#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/autograd_meta.h"
J
Jiabin Yang 已提交
21
#include "paddle/fluid/framework/convert_utils.h"
0
0x45f 已提交
22
#include "paddle/fluid/framework/scope.h"
J
Jiabin Yang 已提交
23
#include "paddle/fluid/framework/scope_guard.h"
24 25
#include "paddle/fluid/jit/executor_function.h"
#include "paddle/fluid/jit/pe_function.h"
26
#include "paddle/fluid/memory/allocation/allocator.h"
27
#include "paddle/fluid/operators/py_func_op.h"
J
Jiabin Yang 已提交
28
#include "paddle/fluid/operators/utils.h"
29 30
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/pybind/eager.h"
31
#include "paddle/fluid/pybind/op_function_common.h"
32
#include "paddle/fluid/pybind/tensor_py.h"
33
#include "paddle/phi/api/ext/op_meta_info.h"
34 35 36
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/dense_tensor.h"
H
hong 已提交
37

38 39 40
namespace paddle {
namespace pybind {

41
extern PyTypeObject* p_tensor_type;
J
Jack Zhou 已提交
42
extern PyTypeObject* p_string_tensor_type;
43

0
0x45f 已提交
44
extern PyTypeObject* g_framework_scope_pytype;
J
Jiabin Yang 已提交
45
extern PyTypeObject* g_vartype_pytype;
46 47 48 49 50 51
extern PyTypeObject* g_place_pytype;
extern PyTypeObject* g_cudaplace_pytype;
extern PyTypeObject* g_cpuplace_pytype;
extern PyTypeObject* g_xpuplace_pytype;
extern PyTypeObject* g_npuplace_pytype;
extern PyTypeObject* g_cudapinnedplace_pytype;
52
extern PyTypeObject* g_customplace_pytype;
53
extern PyTypeObject* g_framework_tensor_pytype;
54
extern PyTypeObject* g_framework_lodtensorarray_pytype;
55
extern PyTypeObject* g_custom_op_kernel_ctx_pytype;
56
extern PyTypeObject* g_executor_function_pytype;
57
extern PyTypeObject* g_pe_function_pytype;
58

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

95 96 97 98 99 100 101 102 103 104 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 141
bool PyObject_CheckLongOrConvertToLong(PyObject** obj) {
  if ((PyLong_Check(*obj) && !PyBool_Check(*obj))) {
    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
                   // test case pass in None.
  } 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",
142 143
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
144 145 146 147 148 149 150 151 152 153
  }
}

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",
154 155
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
156 157 158 159 160 161 162 163 164 165
  }
}

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",
166 167
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
168 169 170
  }
}

W
wanghuancoder 已提交
171 172 173 174 175 176 177
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",
178 179
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
W
wanghuancoder 已提交
180 181 182
  }
}

183 184 185 186 187 188 189
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",
190 191
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
192 193 194 195 196 197 198 199 200 201 202 203 204
  }
}

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",
205 206
        arg_pos + 1,
        (reinterpret_cast<PyTypeObject*>(obj->ob_type))->tp_name));
207 208 209 210
    return "";
  }
}

W
wanghuancoder 已提交
211 212 213 214
bool IsEagerTensor(PyObject* obj) {
  return PyObject_IsInstance(obj, reinterpret_cast<PyObject*>(p_tensor_type));
}

215
paddle::experimental::Tensor CastPyArg2Tensor(PyObject* obj, ssize_t arg_pos) {
J
Jack Zhou 已提交
216 217 218
  if (PyObject_IsInstance(obj, reinterpret_cast<PyObject*>(p_tensor_type)) ||
      PyObject_IsInstance(obj,
                          reinterpret_cast<PyObject*>(p_string_tensor_type))) {
219
    return reinterpret_cast<TensorObject*>(obj)->tensor;
220 221 222
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
223
        "Tensor, but got %s",
224 225
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
226 227 228
  }
}

J
Jiabin Yang 已提交
229 230 231 232 233
std::shared_ptr<imperative::VarBase> CastPyArg2VarBase(PyObject* obj,
                                                       ssize_t arg_pos) {
  return py::cast<std::shared_ptr<imperative::VarBase>>(obj);
}

234 235 236 237 238 239
std::shared_ptr<jit::BaseFunction> CastPyArg2BaseFunction(PyObject* obj,
                                                          ssize_t arg_pos) {
  if (PyObject_IsInstance(
          obj, reinterpret_cast<PyObject*>(g_executor_function_pytype))) {
    return ::pybind11::handle(obj)
        .cast<std::shared_ptr<jit::ExecutorFunction>>();
240 241 242
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(g_pe_function_pytype))) {
    return ::pybind11::handle(obj).cast<std::shared_ptr<jit::PEFunction>>();
243 244 245 246 247 248 249 250 251
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "BaseFunction, but got %s",
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
}

252 253 254
std::vector<paddle::experimental::Tensor> CastPyArg2VectorOfTensor(
    PyObject* obj, ssize_t arg_pos) {
  std::vector<paddle::experimental::Tensor> result;
255 256 257 258 259
  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);
260 261 262
      if (PyObject_IsInstance(item,
                              reinterpret_cast<PyObject*>(p_tensor_type))) {
        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 281 282
      if (PyObject_IsInstance(item,
                              reinterpret_cast<PyObject*>(p_tensor_type))) {
        result.emplace_back(reinterpret_cast<TensorObject*>(item)->tensor);
283 284 285
      } else if (item == Py_None) {
        // emplace empty Tensor for None
        result.emplace_back();
286 287 288
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
289
            "list of Tensor, but got %s at pos %d",
290
            arg_pos + 1,
291 292
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
293 294
      }
    }
295 296
  } else if (obj == Py_None) {
    return {};
297 298 299 300
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list or tuple, but got %s",
301 302
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  }
  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++) {
      item = PyList_GetItem(obj, i);
      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,
321 322
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
323 324 325 326 327 328 329 330 331
      }
    }
  } 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);
      if (PyObject_CheckLongOrConvertToLong(&item)) {
        result.emplace_back(static_cast<int>(PyLong_AsLong(item)));
332 333 334 335 336
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of bool, but got %s at pos %d",
            arg_pos + 1,
337 338
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
339 340
      }
    }
341 342
  } else if (obj == Py_None) {
    return {};
343 344 345 346
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list or tuple, but got %s",
347 348
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
349 350 351 352
  }
  return result;
}

W
wanghuancoder 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366
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,
367 368
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
W
wanghuancoder 已提交
369 370 371 372 373 374
      }
    }
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list, but got %s",
375 376
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
W
wanghuancoder 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  }
  return result;
}

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",
395 396
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
W
wanghuancoder 已提交
397 398 399 400
  }
  return result;
}

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
platform::Place CastPyArg2Place(PyObject* obj, ssize_t arg_pos) {
  platform::Place place;
  if (PyObject_IsInstance(obj, reinterpret_cast<PyObject*>(g_place_pytype))) {
    place = ::pybind11::handle(obj).cast<platform::Place>();
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(g_cudaplace_pytype))) {
    place = ::pybind11::handle(obj).cast<platform::CUDAPlace>();
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(g_cpuplace_pytype))) {
    place = ::pybind11::handle(obj).cast<platform::CPUPlace>();
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(g_xpuplace_pytype))) {
    place = ::pybind11::handle(obj).cast<platform::XPUPlace>();
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(g_npuplace_pytype))) {
    place = ::pybind11::handle(obj).cast<platform::NPUPlace>();
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(g_cudapinnedplace_pytype))) {
    place = ::pybind11::handle(obj).cast<platform::CUDAPinnedPlace>();
420 421 422
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(g_customplace_pytype))) {
    place = ::pybind11::handle(obj).cast<platform::CustomPlace>();
423 424 425
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
426 427 428
        "one "
        "of(Place,CUDAPlace,CPUPlace,XPUPlace,NPUPlace,CUDAPinnedPlace,"
        "CustomPlace), "
429
        "but got %s",
430 431
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
432 433 434 435
  }
  return place;
}

436 437 438 439 440 441 442
framework::Tensor CastPyArg2FrameworkTensor(PyObject* obj, ssize_t arg_pos) {
  if (PyObject_IsInstance(
          obj, reinterpret_cast<PyObject*>(g_framework_tensor_pytype))) {
    return ::pybind11::handle(obj).cast<framework::Tensor>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
443
        "DenseTensor, but got %s",
444 445
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
446 447 448
  }
}

449 450
std::vector<framework::Tensor> CastPyArg2VectorOfTensorBase(PyObject* obj,
                                                            ssize_t arg_pos) {
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  std::vector<framework::LoDTensor> 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_IsInstance(
              item, reinterpret_cast<PyObject*>(g_framework_tensor_pytype))) {
        result.emplace_back(
            ::pybind11::handle(item).cast<framework::LoDTensor>());
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of LoDTensor, but got %s at pos %d",
            arg_pos + 1,
466 467
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
      }
    }
  } 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);
      if (PyObject_IsInstance(
              item, reinterpret_cast<PyObject*>(g_framework_tensor_pytype))) {
        result.emplace_back(
            ::pybind11::handle(item).cast<framework::LoDTensor>());
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument (position %d) must be "
            "list of LoDTensor, but got %s at pos %d",
            arg_pos + 1,
484 485
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
486 487
      }
    }
488 489 490
  } else if (PyObject_IsInstance(obj,
                                 reinterpret_cast<PyObject*>(
                                     g_framework_lodtensorarray_pytype))) {
491 492 493 494 495 496 497
    return ::pybind11::handle(obj).cast<framework::LoDTensorArray>();
  } else if (obj == Py_None) {
    return {};
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "list or tuple, but got %s",
498 499
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
500 501 502 503
  }
  return result;
}

J
Jiabin Yang 已提交
504 505 506 507 508 509 510 511 512 513 514
paddle::framework::proto::VarType::Type CastPyArg2ProtoType(PyObject* obj,
                                                            ssize_t arg_pos) {
  paddle::framework::proto::VarType::Type dtype;
  if (PyObject_IsInstance(obj, reinterpret_cast<PyObject*>(g_vartype_pytype))) {
    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",
515 516
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
J
Jiabin Yang 已提交
517 518 519 520
  }
  return dtype;
}

521 522 523 524 525 526 527
std::unordered_map<std::wstring, int> CastPyArg2Vocab(PyObject* obj,
                                                      ssize_t arg_pos) {
  if (PyDict_Check(obj)) {
    return ::pybind11::handle(obj)
        .cast<std::unordered_map<std::wstring, int>>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
528 529
        "argument (position %d) must be dict, but got %s",
        arg_pos + 1,
530 531 532 533 534 535 536 537 538
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
}

std::vector<std::string> CastPyArg2Strings(PyObject* obj, ssize_t arg_pos) {
  if (PyList_Check(obj)) {
    return ::pybind11::handle(obj).cast<std::vector<std::string>>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
539 540
        "argument (position %d) must be list, but got %s",
        arg_pos + 1,
541 542 543 544
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
}

545 546 547 548 549 550 551 552 553 554
paddle::CustomOpKernelContext CastPyArg2CustomOpKernelContext(PyObject* obj,
                                                              ssize_t arg_pos) {
  if (PyObject_IsInstance(
          obj, reinterpret_cast<PyObject*>(g_custom_op_kernel_ctx_pytype))) {
    return ::pybind11::handle(obj).cast<paddle::CustomOpKernelContext>();
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument (position %d) must be "
        "one of(Place,CUDAPlace,CPUPlace,XPUPlace,NPUPlace,CUDAPinnedPlace), "
        "but got %s",
555 556
        arg_pos + 1,
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
557 558
  }
}
559 560 561 562 563 564 565 566 567 568 569 570
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); }

571 572
PyObject* ToPyObject(uint32_t value) { return PyLong_FromUnsignedLong(value); }

573 574
PyObject* ToPyObject(int64_t value) { return PyLong_FromLongLong(value); }

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

577 578 579 580 581 582 583 584 585 586
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());
}

W
wanghuancoder 已提交
587 588 589
PyObject* ToPyObject(const paddle::experimental::Tensor& value,
                     bool return_py_none_if_not_initialize) {
  if (return_py_none_if_not_initialize && !value.initialized()) {
590
    RETURN_PY_NONE
W
wanghuancoder 已提交
591
  }
J
Jack Zhou 已提交
592 593 594 595 596 597 598 599
  PyObject* obj = nullptr;
  if (value.initialized() && value.is_string_tensor()) {
    // In order to return the core.eager.StringTensor, there is need
    // to use p_string_tensor_type to create a python obj.
    obj = p_string_tensor_type->tp_alloc(p_string_tensor_type, 0);
  } else {
    obj = p_tensor_type->tp_alloc(p_tensor_type, 0);
  }
600
  if (obj) {
601 602 603
    auto v = reinterpret_cast<TensorObject*>(obj);
    new (&(v->tensor)) paddle::experimental::Tensor();
    v->tensor = value;
604 605 606 607 608 609 610
  } else {
    PADDLE_THROW(platform::errors::Fatal(
        "tp_alloc return null, can not new a PyObject."));
  }
  return obj;
}

611
PyObject* ToPyObject(const paddle::experimental::Tensor& value,
612
                     PyObject* args,
613 614 615 616 617 618 619 620 621
                     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) {
622 623 624 625 626 627 628 629 630 631
  // 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;
}

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
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 已提交
662 663 664 665 666 667 668 669 670 671
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;
}

672 673 674 675 676 677 678 679 680 681 682 683 684
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 已提交
685 686 687 688 689 690 691 692 693 694
  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());

695 696 697 698 699 700 701
  for (size_t i = 0; i < value.size(); i++) {
    PyList_SET_ITEM(result, static_cast<Py_ssize_t>(i), ToPyObject(value[i]));
  }

  return result;
}

702 703
PyObject* ToPyObject(const std::vector<paddle::experimental::Tensor>& value,
                     bool return_py_none_if_not_initialize) {
704 705 706
  PyObject* result = PyList_New((Py_ssize_t)value.size());

  for (size_t i = 0; i < value.size(); i++) {
707 708 709
    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);
710
    } else {
711 712 713 714 715 716 717 718 719 720
      PyObject* obj = p_tensor_type->tp_alloc(p_tensor_type, 0);
      if (obj) {
        auto v = reinterpret_cast<TensorObject*>(obj);
        new (&(v->tensor)) paddle::experimental::Tensor();
        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);
721 722 723 724 725 726 727 728 729 730 731 732
    }
  }

  return result;
}

PyObject* ToPyObject(const platform::Place& value) {
  auto obj = ::pybind11::cast(value);
  obj.inc_ref();
  return obj.ptr();
}

J
Jiabin Yang 已提交
733 734 735 736 737 738
PyObject* ToPyObject(const paddle::framework::proto::VarType::Type& dtype) {
  auto obj = ::pybind11::cast(dtype);
  obj.inc_ref();
  return obj.ptr();
}

739 740 741 742 743 744 745
PyObject* ToPyObject(const paddle::framework::proto::VarType& type) {
  auto obj = ::pybind11::cast(type);
  obj.inc_ref();
  return obj.ptr();
}

PyObject* ToPyObject(const paddle::framework::LoDTensor* value) {
746
  auto obj = ::pybind11::cast(value, py::return_value_policy::reference);
747 748 749 750
  obj.inc_ref();
  return obj.ptr();
}

751 752 753 754 755 756
PyObject* ToPyObject(const phi::SelectedRows* value) {
  auto obj = ::pybind11::cast(value, py::return_value_policy::reference);
  obj.inc_ref();
  return obj.ptr();
}

W
wanghuancoder 已提交
757 758
PyObject* ToPyObject(const void* value) {
  if (value == nullptr) {
759
    RETURN_PY_NONE
W
wanghuancoder 已提交
760 761 762 763 764
  }
  PADDLE_THROW(
      platform::errors::Fatal("ToPyObject do not support void* with value."));
}

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
PyObject* ToPyObject(
    const std::unordered_map<std::string, std::vector<std::string>>& value) {
  PyObject* dict = PyDict_New();
  for (const auto map_iter : value) {
    // 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);
    for (const auto vector_iter : map_iter.second) {
      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 已提交
789
      Py_DECREF(val_string);
790 791 792 793 794 795
    }

    if (PyDict_SetItem(dict, key_string, py_list) != 0) {
      PADDLE_THROW(
          platform::errors::Fatal("Unable to set key:value for py_dict"));
    }
Y
YuanRisheng 已提交
796 797
    Py_DECREF(py_list);
    Py_DECREF(key_string);
798 799 800 801 802
  }

  return dict;
}

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
PyObject* ToPyObject(const std::unordered_map<std::wstring, int>& value) {
  PyObject* dict = PyDict_New();
  for (const auto map_iter : value) {
    // 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;
}

825 826
// For Final State Dygraph,
// We directly use paddle::optional(Tensor) as dispensable Tensor
827
paddle::optional<paddle::experimental::Tensor> GetOptionalTensorFromArgs(
828 829 830 831 832
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
833 834 835 836 837 838 839 840 841 842
  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",
843 844 845
          op_type,
          arg_name,
          arg_idx));
846
    }
H
hong 已提交
847
    return paddle::none;
848 849
  }

W
wanghuancoder 已提交
850
  if (PyObject_IsInstance(obj, reinterpret_cast<PyObject*>(p_tensor_type))) {
851
    return paddle::make_optional<paddle::experimental::Tensor>(
W
wanghuancoder 已提交
852 853 854
        reinterpret_cast<TensorObject*>(obj)->tensor);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
855 856 857 858
        "%s(): argument '%s' (position %d) must be Tensor, but got %s",
        op_type,
        arg_name,
        arg_idx,
W
wanghuancoder 已提交
859 860
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
861 862
}

863
static paddle::experimental::Tensor& GetTensorFromPyObject(
864 865 866 867 868
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* obj,
    ssize_t arg_idx,
    bool dispensable) {
869 870 871 872 873 874 875 876
  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",
877 878 879
          op_type,
          arg_name,
          arg_idx));
880
    }
881
    static paddle::experimental::Tensor emptytensor;
882 883 884
    return emptytensor;
  }

W
wanghuancoder 已提交
885 886
  if (PyObject_IsInstance(obj, reinterpret_cast<PyObject*>(p_tensor_type))) {
    return reinterpret_cast<TensorObject*>(obj)->tensor;
J
Jack Zhou 已提交
887 888 889
  } else if (PyObject_IsInstance(
                 obj, reinterpret_cast<PyObject*>(p_string_tensor_type))) {
    return reinterpret_cast<TensorObject*>(obj)->tensor;
W
wanghuancoder 已提交
890 891
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
892 893 894 895
        "%s(): argument '%s' (position %d) must be Tensor, but got %s",
        op_type,
        arg_name,
        arg_idx,
W
wanghuancoder 已提交
896 897
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
898 899
}

900 901 902 903
// For Intermediate State Dygraph,
// we use an uninitialized Tensor to represent dispensable Tensor
paddle::experimental::Tensor& GetTensorFromArgs(const std::string& op_type,
                                                const std::string& arg_name,
904 905
                                                PyObject* args,
                                                ssize_t arg_idx,
906 907 908 909 910
                                                bool dispensable) {
  PyObject* obj = PyTuple_GET_ITEM(args, arg_idx);
  return GetTensorFromPyObject(op_type, arg_name, obj, arg_idx, dispensable);
}

911
std::vector<paddle::experimental::Tensor> GetTensorListFromArgs(
912 913 914 915 916
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
917 918 919 920 921 922 923
  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",
924 925 926
          op_type,
          arg_name,
          arg_idx));
927 928 929 930
    }
    return {};
  }

931
  std::vector<paddle::experimental::Tensor> result;
932 933 934

  if (PyList_Check(list)) {
    Py_ssize_t len = PyList_Size(list);
935
    result.reserve(static_cast<size_t>(len));
936 937 938 939
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
940 941 942
          op_type,
          arg_name,
          arg_idx));
943 944 945
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
946
          reinterpret_cast<TensorObject*>(PyList_GetItem(list, i))->tensor);
947 948 949
    }
  } else if (PyTuple_Check(list)) {
    Py_ssize_t len = PyTuple_Size(list);
950
    result.reserve(static_cast<size_t>(len));
951 952 953 954
    if (len == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "%s(): argument '%s' (position %d) must be list of Tensors, but got "
          "empty list",
955 956 957
          op_type,
          arg_name,
          arg_idx));
958 959 960
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
961
          reinterpret_cast<TensorObject*>(PyTuple_GetItem(list, i))->tensor);
962
    }
963 964
  } else if (list == Py_None) {
    return {};
965 966 967 968
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument '%s' (position %d) must be list of Tensors, but got "
        "%s",
969 970 971
        op_type,
        arg_name,
        arg_idx,
972 973 974 975 976 977
        (reinterpret_cast<PyTypeObject*>(list->ob_type))->tp_name));
  }

  return result;
}

978 979 980 981 982
paddle::experimental::Tensor* GetTensorPtrFromArgs(const std::string& op_type,
                                                   const std::string& arg_name,
                                                   PyObject* args,
                                                   ssize_t arg_idx,
                                                   bool dispensable) {
983 984 985 986 987 988 989 990 991 992
  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",
993 994 995
          op_type,
          arg_name,
          arg_idx));
996
    }
997
    static paddle::experimental::Tensor emptytensor;
998 999 1000
    return &emptytensor;
  }

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

1013
std::vector<paddle::experimental::Tensor*> GetTensorPtrListFromArgs(
1014 1015 1016 1017 1018
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
1019 1020 1021 1022 1023 1024 1025
  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",
1026 1027 1028
          op_type,
          arg_name,
          arg_idx));
1029 1030 1031 1032
    }
    return {};
  }

1033
  std::vector<paddle::experimental::Tensor*> result;
1034 1035 1036 1037 1038 1039 1040

  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",
1041 1042 1043
          op_type,
          arg_name,
          arg_idx));
1044 1045 1046
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
1047
          &(reinterpret_cast<TensorObject*>(PyList_GetItem(list, i))->tensor));
1048 1049 1050 1051 1052 1053 1054
    }
  } 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",
1055 1056 1057
          op_type,
          arg_name,
          arg_idx));
1058 1059 1060
    }
    for (Py_ssize_t i = 0; i < len; i++) {
      result.emplace_back(
1061
          &(reinterpret_cast<TensorObject*>(PyTuple_GetItem(list, i))->tensor));
1062
    }
1063 1064
  } else if (list == Py_None) {
    return {};
1065 1066 1067 1068
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument '%s' (position %d) must be list of Tensors, but got "
        "%s",
1069 1070 1071
        op_type,
        arg_name,
        arg_idx,
1072 1073 1074 1075 1076
        (reinterpret_cast<PyTypeObject*>(list->ob_type))->tp_name));
  }

  return result;
}
J
Jiabin Yang 已提交
1077

W
wanghuancoder 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
std::vector<paddle::experimental::Tensor*> GetTensorPtrListFromPyObject(
    PyObject* obj) {
  std::vector<paddle::experimental::Tensor*> result;

  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;
}

std::vector<paddle::experimental::Tensor> GetTensorListFromPyObject(
    PyObject* obj) {
  std::vector<paddle::experimental::Tensor> 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_IsInstance(item,
                              reinterpret_cast<PyObject*>(p_tensor_type))) {
        result.emplace_back(reinterpret_cast<TensorObject*>(item)->tensor);
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument must be "
            "list of Tensor, but got %s at pos %d",
1127 1128
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
W
wanghuancoder 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
      }
    }
  } 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);
      if (PyObject_IsInstance(item,
                              reinterpret_cast<PyObject*>(p_tensor_type))) {
        result.emplace_back(reinterpret_cast<TensorObject*>(item)->tensor);
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "argument must be "
            "list of Tensor, but got %s at pos %d",
1143 1144
            reinterpret_cast<PyTypeObject*>(item->ob_type)->tp_name,
            i));
W
wanghuancoder 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
      }
    }
  } 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;
}

paddle::experimental::Tensor& GetTensorFromPyObject(PyObject* obj) {
  if (!IsEagerTensor(obj)) {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "argument must be "
        "Tensor, but got %s",
        reinterpret_cast<PyTypeObject*>(obj->ob_type)->tp_name));
  }
  return reinterpret_cast<TensorObject*>(obj)->tensor;
}

1166 1167 1168 1169 1170 1171
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);
  VLOG(1) << "type_name: " << type_name;
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  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(
          "%s(): argument (position %d) is numpy.ndarry, the inner elements "
          "must be "
          "numpy.float32/float64 now, but got %s",
1183 1184 1185
          op_type,
          arg_pos + 1,
          type_name));  // NOLINT
1186 1187
    }
  } else if (type_name == "numpy.float64") {
1188 1189 1190 1191 1192 1193 1194 1195
    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);
  } else if (type_name == "numpy.int64") {
    int64_t value = CastPyArg2Long(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1196
  } else if (type_name == "numpy.int32" || type_name == "numpy.intc") {
1197 1198 1199 1200 1201 1202
    int value = CastPyArg2Int(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
        "numpy.float32/float64, numpy.int32/int64, but got %s",
1203 1204 1205
        op_type,
        arg_pos + 1,
        type_name));  // NOLINT
1206 1207 1208
  }
}

1209 1210 1211 1212 1213 1214
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 "
1215
        "int, float, bool or Tensor, but got %s",
1216 1217
        op_type,
        arg_pos + 1,
1218 1219 1220 1221 1222 1223
        ((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);
1224
  VLOG(1) << "type_name: " << type_name;
1225 1226 1227 1228
  if (PyBool_Check(obj)) {
    bool value = CastPyArg2Boolean(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
  } else if (PyLong_Check(obj)) {
1229
    int64_t value = CastPyArg2Long(obj, op_type, arg_pos);
1230
    return paddle::experimental::Scalar(value);
1231
  } else if (PyFloat_Check(obj)) {
1232 1233
    float value = CastPyArg2Float(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1234
  } else if (IsEagerTensor(obj)) {
1235 1236 1237
    paddle::experimental::Tensor& value = GetTensorFromPyObject(
        op_type, "" /*arg_name*/, obj, arg_pos, false /*dispensable*/);
    return paddle::experimental::Scalar(value);
1238 1239
  } else if (type_name.find("numpy") != std::string::npos) {
    return CastNumpy2Scalar(obj, op_type, arg_pos);
1240 1241 1242
  } else if (PyObject_CheckLongOrToLong(&obj)) {
    int value = CastPyArg2Int(obj, op_type, arg_pos);
    return paddle::experimental::Scalar(value);
1243 1244 1245
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1246
        "int, float, bool or Tensor, but got %s",
1247 1248
        op_type,
        arg_pos + 1,
1249 1250 1251 1252 1253 1254 1255
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }

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

1256 1257 1258 1259
paddle::experimental::IntArray CastPyArg2IntArray(PyObject* obj,
                                                  const std::string& op_type,
                                                  ssize_t arg_pos) {
  // In case of IntArray, only two possible PyObjects:
1260 1261 1262 1263 1264
  // 1. list of int
  // 2. Tensor
  if (obj == Py_None) {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1265
        "list or Tensor, but got %s",
1266 1267
        op_type,
        arg_pos + 1,
1268 1269 1270 1271 1272 1273
        ((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);
1274 1275
  if (type_name == "list" || type_name == "tuple" ||
      type_name == "numpy.ndarray") {
1276
    std::vector<int> value = CastPyArg2Ints(obj, op_type, arg_pos);
1277
    return paddle::experimental::IntArray(value);
1278

H
hong 已提交
1279
  } else if (type_name == "paddle.Tensor" || type_name == "Tensor") {
1280 1281
    paddle::experimental::Tensor& value = GetTensorFromPyObject(
        op_type, "" /*arg_name*/, obj, arg_pos, false /*dispensable*/);
1282
    return paddle::experimental::IntArray(value);
1283 1284 1285 1286

  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "%s(): argument (position %d) must be "
1287
        "list or Tensor, but got %s",
1288 1289
        op_type,
        arg_pos + 1,
1290 1291 1292
        ((PyTypeObject*)obj->ob_type)->tp_name));  // NOLINT
  }

1293 1294
  // Fake a IntArray
  return paddle::experimental::IntArray({1});
1295 1296
}

0
0x45f 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
paddle::framework::Scope* CastPyArg2ScopePtr(PyObject* obj) {
  if (PyObject_IsInstance(
          obj, reinterpret_cast<PyObject*>(g_framework_scope_pytype))) {
    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(
1308 1309 1310 1311 1312
    const std::string& op_type,
    const std::string& arg_name,
    PyObject* args,
    ssize_t arg_idx,
    bool dispensable) {
0
0x45f 已提交
1313 1314 1315 1316 1317 1318
  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",
1319 1320 1321
          op_type,
          arg_name,
          arg_idx));
0
0x45f 已提交
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    }
  }

  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",
1332 1333 1334
          op_type,
          arg_name,
          arg_idx));
0
0x45f 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    }
    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",
1345 1346 1347
          op_type,
          arg_name,
          arg_idx));
0
0x45f 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
    }
    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",
1358 1359 1360
        op_type,
        arg_name,
        arg_idx,
0
0x45f 已提交
1361 1362 1363 1364 1365
        (reinterpret_cast<PyTypeObject*>(list->ob_type))->tp_name));
  }
  return result;
}

1366 1367
paddle::Place CastPyArg2Place(PyObject* obj,
                              const std::string& op_type,
1368
                              ssize_t arg_pos) {
1369
  return CastPyArg2Place(obj, arg_pos);
1370 1371
}

1372 1373
paddle::DataType CastPyArg2DataType(PyObject* obj,
                                    const std::string& op_type,
1374
                                    ssize_t arg_pos) {
1375
  if (obj == Py_None) {
1376
    return paddle::experimental::DataType::UNDEFINED;
1377 1378 1379 1380 1381
  }

  framework::proto::VarType::Type type = CastPyArg2ProtoType(obj, arg_pos);
  return framework::TransToPhiDataType(type);
}
1382 1383
}  // namespace pybind
}  // namespace paddle