eager_math_op_patch.cc 68.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/* Copyright (c) 2022 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. */
// disable numpy compile error

#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif

#include <Python.h>

#include <string>
#include <unordered_map>
#include <vector>

#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/grad_node_info.h"
#include "paddle/fluid/eager/hooks.h"
#include "paddle/fluid/eager/utils.h"
#include "paddle/fluid/framework/convert_utils.h"
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/pybind/eager.h"
#include "paddle/fluid/pybind/eager_utils.h"
#include "paddle/fluid/pybind/exception.h"
#include "paddle/phi/api/include/api.h"
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/dense_tensor.h"
#include "pybind11/detail/internals.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#include "paddle/fluid/eager/api/generated/eager_generated/forwards/dygraph_functions.h"
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/python_headers.h"
#include "paddle/fluid/memory/allocation/mmap_allocator.h"
#include "paddle/fluid/pybind/op_function_common.h"
#include "paddle/fluid/pybind/tensor_py.h"
#include "paddle/phi/core/ddim.h"
#include "paddle/phi/kernels/funcs/math_function.h"

namespace paddle {
namespace pybind {

static bool PyCheckInteger(PyObject* obj) {
#if PY_VERSION_HEX < 0x03000000
  return (PyLong_Check(obj) || PyInt_Check(obj)) && !PyBool_Check(obj);
#else
  return PyLong_Check(obj) && !PyBool_Check(obj);
#endif
}

static bool IsNumpyType(PyObject* obj) {
  // It is not a good way to judge the type of obj by its type'name. Maybe using
  // `PyArray_IsScalar` will be better. However, this interface cannot be used
  // by including pybind11, and it needs to compile with numpy.
  auto type_name = std::string(Py_TYPE(obj)->tp_name);
  return type_name == "numpy.int64" || type_name == "numpy.longlong" ||
         type_name == "numpy.int32" || type_name == "numpy.int16";
}

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
static bool IsNumpyArray(PyObject* obj) {
  auto type_name = std::string(Py_TYPE(obj)->tp_name);
  return type_name == "numpy.ndarray";
}

void InitTensorWithNumpyValue(const py::object& array,
                              const paddle::platform::Place& place,
                              Tensor* self,
                              bool zero_copy = false) {
  PADDLE_ENFORCE_EQ(
      self->defined(),
      true,
      paddle::platform::errors::Fatal(
          "Calling InitTensorWithNumpyValue of Eager Tensor without "
          "EmptyTensorInitializer is "
          "forbidden. Please check your code and make sure you new a "
          "eager tensor before init it with NumPy."));
  phi::DenseTensor* impl_ptr =
      static_cast<phi::DenseTensor*>(self->impl().get());
  if (platform::is_cpu_place(place)) {
    SetTensorFromPyArray<platform::CPUPlace>(impl_ptr, array, place, zero_copy);
  } else if (platform::is_xpu_place(place)) {
    SetTensorFromPyArray<platform::XPUPlace>(impl_ptr, array, place, zero_copy);
  } else if (platform::is_gpu_place(place)) {
    SetTensorFromPyArray<platform::CUDAPlace>(
        impl_ptr, array, place, zero_copy);
  } else if (platform::is_cuda_pinned_place(place)) {
    SetTensorFromPyArray<platform::CUDAPinnedPlace>(
        impl_ptr, array, place, zero_copy);
  } else if (platform::is_npu_place(place)) {
    SetTensorFromPyArray<platform::NPUPlace>(impl_ptr, array, place, zero_copy);
  } else if (platform::is_custom_place(place)) {
    SetTensorFromPyArray<platform::CustomPlace>(
        impl_ptr, array, place, zero_copy);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Place should be one of "
        "CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace/NPUPlace/CustomPlace"));
  }
}

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
std::set<phi::DataType> _supported_int_dtype_{DataType::UINT8,
                                              DataType::INT8,
                                              DataType::INT16,
                                              DataType::INT32,
                                              DataType::INT64,
                                              DataType::BOOL};
std::set<phi::DataType> _complex_dtypes{
    DataType::COMPLEX64,
    DataType::COMPLEX128,
};

// _supported_promote_complex_types_
//     '__add__',
//     '__radd__',
//     '__sub__',
//     '__rsub__',
//     '__mul__',
//     '__rmul__',
//     '__div__',
//     '__truediv__',
//     '__rdiv__',
//     '__rtruediv__',
//     '__matmul__',

void SetDevice(paddle::platform::Place place) {
  if (paddle::platform::is_gpu_place(place)) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    phi::backends::gpu::SetDeviceId(place.device);
141
    VLOG(6) << "CurrentDeviceId: " << phi::backends::gpu::GetCurrentDeviceId()
142 143 144 145 146 147 148 149 150 151
            << " from " << static_cast<int>(place.device);
#else
    PADDLE_THROW(paddle::platform::errors::PreconditionNotMet(
        "PaddlePaddle should compile with GPU if use CUDAPlace."));
#endif
  }

  if (paddle::platform::is_custom_place(place)) {
#if defined(PADDLE_WITH_CUSTOM_DEVICE)
    phi::DeviceManager::SetDevice(place);
152
    VLOG(6) << "CurrentDeviceId: "
153 154 155 156 157 158 159 160 161 162 163 164 165 166
            << phi::DeviceManager::GetDevice(place.GetDeviceType()) << " from "
            << static_cast<int>(place.device);
#else
    PADDLE_THROW(paddle::platform::errors::PreconditionNotMet(
        "PaddlePaddle should compile with CUSTOM_DEVICE if use "
        "CustomPlace."));
#endif
  }
}

// scalar func only support add, radd, sub, rsub, mul, rmul, div, truediv.
// this function will update gradually.
paddle::experimental::Tensor CallScalarFuction(
    const paddle::experimental::Tensor& self_tensor,
167
    double other,
168 169 170 171 172 173 174 175 176
    std::string op_type) {
  paddle::experimental::Tensor ret;
  if (op_type == "add" || op_type == "radd") {
    ret = scale_ad_func(self_tensor, phi::Scalar(1.0), other, true);
  } else if (op_type == "sub") {
    ret = scale_ad_func(self_tensor, phi::Scalar(1.0), -other, true);

  } else if (op_type == "rsub") {
    ret = scale_ad_func(self_tensor, phi::Scalar(-1.0), other, true);
177 178
  } else if (op_type == "mul") {
    ret = scale_ad_func(self_tensor, phi::Scalar(other), 0.0, true);
179 180
  } else if (op_type == "div") {
    ret = scale_ad_func(self_tensor, phi::Scalar(1.0 / other), 0.0, true);
181 182
  } else if (op_type == "pow") {
    ret = pow_ad_func(self_tensor, other);
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
  }

  return ret;
}

static PyObject* tensor__add__method(TensorObject* self,
                                     PyObject* args,
                                     PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__add__ or __radd_ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
  VLOG(6) << "Running Eager tensor__add__method";
  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
209
    double other = 0.0;
210
    if (PyFloat_Check(other_obj)) {
211
      other = CastPyArg2Double(other_obj, "__add__", 0);
212 213 214 215 216 217
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
218
      other = CastPyArg2Double(other_obj, "__add__", 0);
219 220 221 222 223 224 225 226 227 228 229
    }

    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "add");
    }
    return ToPyObject(ret);
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
230 231 232 233 234 235 236
  if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
237 238 239 240
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__add__", 0);
    {
      eager_gil_scoped_release guard;
241 242
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    // note: only op_type in _supported_promote_complex_types_ should promote
    // dtype
    if (_complex_dtypes.find(lhs_dtype) != _complex_dtypes.end() ||
        _complex_dtypes.find(rhs_dtype) != _complex_dtypes.end()) {
      phi::DataType promote_dtype =
          framework::TransToPhiDataType(framework::PromoteTypesIfComplexExists(
              framework::TransToProtoVarType(lhs_dtype),
              framework::TransToProtoVarType(rhs_dtype)));
      if (lhs_dtype != promote_dtype) {
        // cast
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, promote_dtype);
      }
      if (rhs_dtype != promote_dtype) {
        eager_gil_scoped_release guard;
        other_tensor = cast_ad_func(other_tensor, promote_dtype);
      }
    } else {
268 269 270 271
      VLOG(6) << "The dtype of left and right Tensor are not the same, left "
                 "dtype is "
              << lhs_dtype << ", but right dtype is " << rhs_dtype
              << ", the right dtype will convert to " << lhs_dtype;
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
      eager_gil_scoped_release guard;
      other_tensor = cast_ad_func(other_tensor, lhs_dtype);
    }
  }

  // 4. calculation
  VLOG(6) << "Calling add_ad_func in tensor__add__method";

  {
    eager_gil_scoped_release guard;
    ret = add_ad_func(self_tensor, other_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* tensor__sub__method(TensorObject* self,
                                     PyObject* args,
                                     PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__sub__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
  VLOG(6) << "Running Eager tensor__sub__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);
  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
311
    double other = 0.0;
312
    if (PyFloat_Check(other_obj)) {
313
      other = CastPyArg2Double(other_obj, "__sub__", 0);
314 315 316 317 318 319
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
320
      other = CastPyArg2Double(other_obj, "__sub__", 0);
321 322 323 324 325 326 327 328 329 330
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "sub");
    }

    return ToPyObject(ret);
  }
  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
331 332 333 334 335 336 337
  if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
338 339 340 341
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__sub__", 0);
    {
      eager_gil_scoped_release guard;
342 343
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    if (_complex_dtypes.find(lhs_dtype) != _complex_dtypes.end() ||
        _complex_dtypes.find(rhs_dtype) != _complex_dtypes.end()) {
      phi::DataType promote_dtype =
          framework::TransToPhiDataType(framework::PromoteTypesIfComplexExists(
              framework::TransToProtoVarType(lhs_dtype),
              framework::TransToProtoVarType(rhs_dtype)));
      if (lhs_dtype != promote_dtype) {
        // cast
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, promote_dtype);
      }
      if (rhs_dtype != promote_dtype) {
        eager_gil_scoped_release guard;
        other_tensor = cast_ad_func(other_tensor, promote_dtype);
      }
    } else {
367 368 369 370
      VLOG(6) << "The dtype of left and right Tensor are not the same, left "
                 "dtype is "
              << lhs_dtype << ", but right dtype is " << rhs_dtype
              << ", the right dtype will convert to " << lhs_dtype;
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
      eager_gil_scoped_release guard;
      other_tensor = cast_ad_func(other_tensor, lhs_dtype);
    }
  }
  // 4. calculation
  VLOG(6) << "Calling subtract_ad_func in tensor__sub__method";
  {
    eager_gil_scoped_release guard;
    ret = subtract_ad_func(self_tensor, other_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* tensor__rsub__method(TensorObject* self,
                                      PyObject* args,
                                      PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__rsub__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
L
Leo Chen 已提交
395
  VLOG(4) << "Running Eager tensor__rsub__method";
396 397 398 399 400 401 402 403 404 405 406 407

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
408
    double other = 0.0;
409
    if (PyFloat_Check(other_obj)) {
410
      other = CastPyArg2Double(other_obj, "__rsub__", 0);
411 412 413 414 415 416
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
417
      other = CastPyArg2Double(other_obj, "__rsub__", 0);
418 419 420 421 422 423 424 425 426 427
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "rsub");
    }
    return ToPyObject(ret);
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
428 429 430 431 432 433 434
  if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
435 436 437 438
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__rsub__", 0);
    {
      eager_gil_scoped_release guard;
439 440
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    if (_complex_dtypes.find(lhs_dtype) != _complex_dtypes.end() ||
        _complex_dtypes.find(rhs_dtype) != _complex_dtypes.end()) {
      phi::DataType promote_dtype =
          framework::TransToPhiDataType(framework::PromoteTypesIfComplexExists(
              framework::TransToProtoVarType(lhs_dtype),
              framework::TransToProtoVarType(rhs_dtype)));
      if (lhs_dtype != promote_dtype) {
        // cast
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, promote_dtype);
      }
      if (rhs_dtype != promote_dtype) {
        eager_gil_scoped_release guard;
        other_tensor = cast_ad_func(other_tensor, promote_dtype);
      }
    } else {
464 465 466 467
      VLOG(6) << "The dtype of left and right Tensor are not the same, left "
                 "dtype is "
              << lhs_dtype << ", but right dtype is " << rhs_dtype
              << ", the right dtype will convert to " << lhs_dtype;
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
      eager_gil_scoped_release guard;
      other_tensor = cast_ad_func(other_tensor, lhs_dtype);
    }
  }

  // 4. calculation
  VLOG(6) << "Calling subtract_ad_func in tensor__rsub__method";
  {
    eager_gil_scoped_release guard;
    ret = subtract_ad_func(other_tensor, self_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
static PyObject* tensor__mul__method(TensorObject* self,
                                     PyObject* args,
                                     PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__mul__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
  VLOG(6) << "Running Eager tensor__mul__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
505 506
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
507
    double other = 0.0;
508
    if (PyFloat_Check(other_obj)) {
509
      other = CastPyArg2Double(other_obj, "__mul__", 0);
510 511 512 513 514 515
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
516
      other = CastPyArg2Double(other_obj, "__mul__", 0);
517 518 519 520 521 522 523 524 525 526
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "mul");
    }
    return ToPyObject(ret);
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
527 528 529 530 531 532 533
  if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
534 535 536 537
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__mul__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
538 539
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
540 541
    } else {
      eager_gil_scoped_release guard;
542 543
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    // note: only op_type in _supported_promote_complex_types_ should promote
    // dtype
    if (_complex_dtypes.find(lhs_dtype) != _complex_dtypes.end() ||
        _complex_dtypes.find(rhs_dtype) != _complex_dtypes.end()) {
      phi::DataType promote_dtype =
          framework::TransToPhiDataType(framework::PromoteTypesIfComplexExists(
              framework::TransToProtoVarType(lhs_dtype),
              framework::TransToProtoVarType(rhs_dtype)));
      if (lhs_dtype != promote_dtype) {
        // cast
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, promote_dtype);
      }
      if (rhs_dtype != promote_dtype) {
        eager_gil_scoped_release guard;
        other_tensor = cast_ad_func(other_tensor, promote_dtype);
      }
    } else {
569 570 571 572
      VLOG(6) << "The dtype of left and right Tensor are not the same, left "
                 "dtype is "
              << lhs_dtype << ", but right dtype is " << rhs_dtype
              << ", the right dtype will convert to " << lhs_dtype;
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
      eager_gil_scoped_release guard;
      other_tensor = cast_ad_func(other_tensor, lhs_dtype);
    }
  }

  // 4. calculation
  VLOG(6) << "Calling multiply_ad_func in tensor__mul__method";
  {
    eager_gil_scoped_release guard;
    ret = multiply_ad_func(self_tensor, other_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
static PyObject* tensor__div__method(TensorObject* self,
                                     PyObject* args,
                                     PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__div__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY

  VLOG(6) << "Running Eager tensor__div__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
613
    double other = 0.0;
614
    if (PyFloat_Check(other_obj)) {
615
      other = CastPyArg2Double(other_obj, "__div__", 0);
616
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
617
      other = CastPyArg2Double(other_obj, "__div__", 0);
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    }
    if (_supported_int_dtype_.find(self_tensor.dtype()) !=
        _supported_int_dtype_.end()) {
      eager_gil_scoped_release guard;
      self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "div");
    }
    return ToPyObject(ret);
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
633 634 635 636 637 638 639
  if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
640 641 642 643
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__div__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
644 645
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
646 647
    } else {
      eager_gil_scoped_release guard;
648 649
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    // note: only op_type in _supported_promote_complex_types_ should promote
    // dtype
    if (_complex_dtypes.find(lhs_dtype) != _complex_dtypes.end() ||
        _complex_dtypes.find(rhs_dtype) != _complex_dtypes.end()) {
      phi::DataType promote_dtype =
          framework::TransToPhiDataType(framework::PromoteTypesIfComplexExists(
              framework::TransToProtoVarType(lhs_dtype),
              framework::TransToProtoVarType(rhs_dtype)));
      if (lhs_dtype != promote_dtype) {
        // cast
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, promote_dtype);
      }
      if (rhs_dtype != promote_dtype) {
        eager_gil_scoped_release guard;
        other_tensor = cast_ad_func(other_tensor, promote_dtype);
      }
    } else {
675 676 677 678
      VLOG(6) << "The dtype of left and right Tensor are not the same, left "
                 "dtype is "
              << lhs_dtype << ", but right dtype is " << rhs_dtype
              << ", the right dtype will convert to " << lhs_dtype;
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
      eager_gil_scoped_release guard;
      other_tensor = cast_ad_func(other_tensor, lhs_dtype);
    }
  }
  if (_supported_int_dtype_.find(self_tensor.dtype()) !=
      _supported_int_dtype_.end()) {
    eager_gil_scoped_release guard;
    self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
  }
  if (_supported_int_dtype_.find(other_tensor.dtype()) !=
      _supported_int_dtype_.end()) {
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, DataType::FLOAT32);
  }

  // 4. calculation
  VLOG(6) << "Calling divide_ad_func in tensor__div__method";
  {
    eager_gil_scoped_release guard;
    ret = divide_ad_func(self_tensor, other_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* tensor__rdiv__method(TensorObject* self,
                                      PyObject* args,
                                      PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__rdiv__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);
  EAGER_TRY

  VLOG(6) << "Running Eager tensor__rdiv__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar_div function for __rdiv__ and __rtruediv__
727 728
  double other_double = 0.0;
  bool has_other_double = false;
729 730 731
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
732 733
      other_double = CastPyArg2Double(other_obj, "__rdiv__", 0);
      has_other_double = true;
734
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
735 736
      other_double = CastPyArg2Double(other_obj, "__rdiv__", 0);
      has_other_double = true;
737 738 739 740 741 742 743 744 745 746
    }
    if (_supported_int_dtype_.find(self_tensor.dtype()) !=
        _supported_int_dtype_.end()) {
      eager_gil_scoped_release guard;
      self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
747
  if (has_other_double) {
748 749
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
750
                                phi::Scalar(other_double),
751 752
                                self_tensor.dtype(),
                                place);
753 754 755 756 757 758 759
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
760 761 762 763
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__rdiv__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
764 765
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
766 767
    } else {
      eager_gil_scoped_release guard;
768 769
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    // note: only op_type in _supported_promote_complex_types_ should promote
    // dtype
    if (_complex_dtypes.find(lhs_dtype) != _complex_dtypes.end() ||
        _complex_dtypes.find(rhs_dtype) != _complex_dtypes.end()) {
      phi::DataType promote_dtype =
          framework::TransToPhiDataType(framework::PromoteTypesIfComplexExists(
              framework::TransToProtoVarType(lhs_dtype),
              framework::TransToProtoVarType(rhs_dtype)));
      if (lhs_dtype != promote_dtype) {
        // cast
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, promote_dtype);
      }
      if (rhs_dtype != promote_dtype) {
        eager_gil_scoped_release guard;
        other_tensor = cast_ad_func(other_tensor, promote_dtype);
      }
    } else {
795 796 797 798
      VLOG(6) << "The dtype of left and right Tensor are not the same, left "
                 "dtype is "
              << lhs_dtype << ", but right dtype is " << rhs_dtype
              << ", the right dtype will convert to " << lhs_dtype;
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
      eager_gil_scoped_release guard;
      other_tensor = cast_ad_func(other_tensor, lhs_dtype);
    }
  }
  if (_supported_int_dtype_.find(self_tensor.dtype()) !=
      _supported_int_dtype_.end()) {
    eager_gil_scoped_release guard;
    self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
  }
  if (_supported_int_dtype_.find(other_tensor.dtype()) !=
      _supported_int_dtype_.end()) {
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, DataType::FLOAT32);
  }

  // 4. calculation
  VLOG(6) << "Calling divide_ad_func in tensor__rdiv__method";
  {
    eager_gil_scoped_release guard;
    ret = divide_ad_func(other_tensor, self_tensor);
  }
  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
Weilong Wu 已提交
824 825 826 827 828 829 830 831 832
static PyObject* tensor__gt__method(TensorObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__gt__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
L
Leo Chen 已提交
833
  VLOG(4) << "Running Eager tensor__gt__method";
W
Weilong Wu 已提交
834 835 836 837 838 839 840 841 842 843 844

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __gt__ now
845 846
  double other_double = 0.0;
  bool has_other_double = false;
W
Weilong Wu 已提交
847 848 849
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
850 851
      other_double = CastPyArg2Double(other_obj, "__gt__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
852 853 854 855 856 857
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
858 859
      other_double = CastPyArg2Double(other_obj, "__gt__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
860 861 862 863 864
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
865
  if (has_other_double) {
W
Weilong Wu 已提交
866 867
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
868
                                phi::Scalar(other_double),
W
Weilong Wu 已提交
869 870
                                self_tensor.dtype(),
                                place);
871 872 873 874 875 876 877
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
W
Weilong Wu 已提交
878 879 880 881
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__gt__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
882 883
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
W
Weilong Wu 已提交
884 885
    } else {
      eager_gil_scoped_release guard;
886 887
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
W
Weilong Wu 已提交
888 889 890 891 892 893 894
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
895 896 897 898
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
W
Weilong Wu 已提交
899 900 901 902 903 904 905 906
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling greater_than_ad_func in tensor__gt__method";
  {
    eager_gil_scoped_release guard;
907
    ret = greater_than_ad_func(self_tensor, other_tensor);
W
Weilong Wu 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* tensor__ge__method(TensorObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__ge__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
L
Leo Chen 已提交
923
  VLOG(4) << "Running Eager tensor__ge__method";
W
Weilong Wu 已提交
924 925 926 927 928 929 930 931 932 933 934

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __ge__ now
935 936
  double other_double = 0.0;
  bool has_other_double = false;
W
Weilong Wu 已提交
937 938 939
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
940 941
      other_double = CastPyArg2Double(other_obj, "__ge__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
942 943 944 945 946 947
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
948 949
      other_double = CastPyArg2Double(other_obj, "__ge__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
950 951 952 953 954
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
955
  if (has_other_double) {
W
Weilong Wu 已提交
956 957
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
958
                                phi::Scalar(other_double),
W
Weilong Wu 已提交
959 960
                                self_tensor.dtype(),
                                place);
961 962 963 964 965 966 967
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
W
Weilong Wu 已提交
968 969 970 971
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__ge__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
972 973
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
W
Weilong Wu 已提交
974 975
    } else {
      eager_gil_scoped_release guard;
976 977
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
W
Weilong Wu 已提交
978 979 980 981 982 983 984
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
985 986 987 988
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
W
Weilong Wu 已提交
989 990 991 992 993 994 995 996
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling greater_equal_ad_func in tensor__ge__method";
  {
    eager_gil_scoped_release guard;
997
    ret = greater_equal_ad_func(self_tensor, other_tensor);
W
Weilong Wu 已提交
998 999 1000 1001 1002 1003
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
static PyObject* tensor__mod__method(TensorObject* self,
                                     PyObject* args,
                                     PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__mod__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);
  EAGER_TRY

  VLOG(6) << "Running Eager tensor__mod__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar_mod function for __mod__ now
1026 1027
  float other_double = 0.0;
  bool has_other_double = false;
1028 1029 1030
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1031 1032
      other_double = CastPyArg2Double(other_obj, "__mod__", 0);
      has_other_double = true;
1033 1034 1035 1036 1037 1038
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
1039 1040
      other_double = CastPyArg2Double(other_obj, "__mod__", 0);
      has_other_double = true;
1041 1042 1043 1044 1045
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
1046
  if (has_other_double) {
1047 1048
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
1049
                                phi::Scalar(other_double),
1050
                                self_tensor.dtype(),
1051
                                self_tensor.place());
1052 1053 1054 1055 1056 1057 1058
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1059 1060 1061 1062
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__mod__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
1063 1064
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
1065 1066
    } else {
      eager_gil_scoped_release guard;
1067 1068
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
1069 1070 1071 1072 1073 1074 1075 1076 1077 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
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    VLOG(6) << "The  dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling remainder_ad_func in tensor__mod__method";
  {
    eager_gil_scoped_release guard;
    ret = remainder_ad_func(self_tensor, other_tensor);
  }
  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* tensor__matmul__method(TensorObject* self,
                                        PyObject* args,
                                        PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__matmul__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);
  EAGER_TRY

  VLOG(6) << "Running Eager tensor__matmul__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar_matmul function for __matmul__ now
1116 1117
  float other_double = 0.0;
  bool has_other_double = false;
1118 1119 1120
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1121 1122
      other_double = CastPyArg2Double(other_obj, "__matmul__", 0);
      has_other_double = true;
1123 1124 1125 1126 1127 1128
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
1129 1130
      other_double = CastPyArg2Double(other_obj, "__matmul__", 0);
      has_other_double = true;
1131 1132 1133 1134 1135
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
1136
  if (has_other_double) {
1137
    eager_gil_scoped_release guard;
1138
    other_tensor = full_ad_func({1},
1139
                                phi::Scalar(other_double),
1140 1141
                                self_tensor.dtype(),
                                self_tensor.place());
1142 1143 1144 1145 1146 1147 1148
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1149 1150 1151 1152
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__matmul__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
1153 1154
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
1155 1156
    } else {
      eager_gil_scoped_release guard;
1157 1158
      other_tensor =
          full_ad_func({1}, value, self_tensor.dtype(), self_tensor.place());
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 1200 1201 1202
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    // note: only op_type in _supported_promote_complex_types_ should promote
    // dtype
    if (_complex_dtypes.find(lhs_dtype) != _complex_dtypes.end() ||
        _complex_dtypes.find(rhs_dtype) != _complex_dtypes.end()) {
      phi::DataType promote_dtype =
          framework::TransToPhiDataType(framework::PromoteTypesIfComplexExists(
              framework::TransToProtoVarType(lhs_dtype),
              framework::TransToProtoVarType(rhs_dtype)));
      if (lhs_dtype != promote_dtype) {
        // cast
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, promote_dtype);
      }
      if (rhs_dtype != promote_dtype) {
        eager_gil_scoped_release guard;
        other_tensor = cast_ad_func(other_tensor, promote_dtype);
      }
    } else {
      VLOG(6) << "The dtype of left and right Tensor are not the same, left "
                 "dtype is "
              << lhs_dtype << ", but right dtype is " << rhs_dtype
              << ", the right dtype will convert to " << lhs_dtype;
      eager_gil_scoped_release guard;
      other_tensor = cast_ad_func(other_tensor, lhs_dtype);
    }
  }

  // 4. calculation
  VLOG(6) << "Calling matmul_ad_func in tensor__matmul__method";
  {
    eager_gil_scoped_release guard;
    ret = matmul_ad_func(self_tensor, other_tensor, false, false);
  }
  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1203 1204 1205 1206 1207 1208 1209 1210 1211
static PyObject* tensor__lt__method(TensorObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__lt__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
L
Leo Chen 已提交
1212
  VLOG(4) << "Running Eager tensor__lt__method";
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __lt__ now
1224 1225
  float other_double = 0.0;
  bool has_other_double = false;
1226 1227 1228
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1229 1230
      other_double = CastPyArg2Double(other_obj, "__lt__", 0);
      has_other_double = true;
1231 1232 1233 1234 1235 1236
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
1237 1238
      other_double = CastPyArg2Double(other_obj, "__lt__", 0);
      has_other_double = true;
1239 1240 1241 1242 1243
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
1244
  if (has_other_double) {
1245 1246
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
1247
                                phi::Scalar(other_double),
1248
                                self_tensor.dtype(),
1249
                                self_tensor.place());
1250 1251 1252 1253 1254 1255 1256
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1257 1258 1259 1260
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__lt__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
1261 1262
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
1263 1264
    } else {
      eager_gil_scoped_release guard;
1265 1266
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
1267 1268 1269 1270 1271 1272 1273
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
1274 1275 1276 1277
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
1278 1279 1280 1281 1282 1283 1284 1285
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling less_than_ad_func in tensor__lt__method";
  {
    eager_gil_scoped_release guard;
1286
    ret = less_than_ad_func(self_tensor, other_tensor);
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* tensor__le__method(TensorObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__le__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
L
Leo Chen 已提交
1302
  VLOG(4) << "Running Eager tensor__le__method";
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __le__ now
1314 1315
  float other_double = 0.0;
  bool has_other_double = false;
1316 1317 1318
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1319 1320
      other_double = CastPyArg2Double(other_obj, "__le__", 0);
      has_other_double = true;
1321 1322 1323 1324 1325 1326
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
1327 1328
      other_double = CastPyArg2Double(other_obj, "__le__", 0);
      has_other_double = true;
1329 1330 1331 1332 1333
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
1334
  if (has_other_double) {
1335 1336
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
1337
                                phi::Scalar(other_double),
1338
                                self_tensor.dtype(),
1339
                                self_tensor.place());
1340 1341 1342 1343 1344 1345 1346
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1347 1348 1349 1350
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__le__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
1351 1352
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
1353 1354
    } else {
      eager_gil_scoped_release guard;
1355 1356
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
1357 1358 1359 1360 1361 1362 1363
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
1364 1365 1366 1367
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
1368 1369 1370 1371 1372 1373 1374 1375
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling less_equal_ad_func in tensor__le__method";
  {
    eager_gil_scoped_release guard;
1376
    ret = less_equal_ad_func(self_tensor, other_tensor);
1377 1378 1379 1380 1381 1382
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
Weilong Wu 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
static PyObject* tensor__floordiv__method(TensorObject* self,
                                          PyObject* args,
                                          PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "floordiv pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);
  EAGER_TRY
  VLOG(6) << "Running Eager tensor__floordiv__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases or not
  // there is no scalar case for floordiv, but alse need to cast self_tensor
  // in need.
  double other_double = 0.0;
  bool has_other_double = false;
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__floordiv__", 0);
      has_other_double = true;
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__floordiv__", 0);
      has_other_double = true;
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
  if (has_other_double) {
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
                                phi::Scalar(other_double),
                                self_tensor.dtype(),
                                self_tensor.place());
1431 1432 1433 1434 1435 1436 1437
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
W
Weilong Wu 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__floordiv__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
    } else {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, self_tensor.dtype(), self_tensor.place());
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    // note: only op_type in _supported_promote_complex_types_ should promote
    // dtype, floordiv is not in _supported_promote_complex_types_, will not do
    // promote dtype
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling floor_divide_ad_func in tensor__floordiv__method";
  {
    eager_gil_scoped_release guard;
    ret = floor_divide_ad_func(self_tensor, other_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
static PyObject* tensor__pow__method(TensorObject* self,
                                     PyObject* args,
                                     PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "pow pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
  VLOG(6) << "Running Eager tensor__pow__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    double other = 0.0;
    if (PyFloat_Check(other_obj)) {
      other = CastPyArg2Double(other_obj, "__pow__", 0);
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
      other = CastPyArg2Double(other_obj, "__pow__", 0);
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "pow");
    }
    return ToPyObject(ret);
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
1520 1521 1522 1523 1524 1525 1526
  if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__pow__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
    } else {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, self_tensor.dtype(), self_tensor.place());
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling elementwise_pow_ad_func in tensor__pow__method";
  {
    eager_gil_scoped_release guard;
    ret = elementwise_pow_ad_func(self_tensor, other_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* tensor__rpow__method(TensorObject* self,
                                      PyObject* args,
                                      PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__rpow__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
  VLOG(6) << "Running Eager tensor__rpow__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases or not
  // there is no scalar case for rpow, but alse need to cast self_tensor in
  // need.
  double other_double = 0.0;
  bool has_other_double = false;
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__rpow__", 0);
      has_other_double = true;
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__rpow__", 0);
      has_other_double = true;
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
  if (has_other_double) {
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
                                phi::Scalar(other_double),
                                self_tensor.dtype(),
                                self_tensor.place());
1612 1613 1614 1615 1616 1617 1618
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__rpow__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
    } else {
      eager_gil_scoped_release guard;
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling elementwise_pow_ad_func in tensor__rpow__method";
  {
    eager_gil_scoped_release guard;
    ret = elementwise_pow_ad_func(other_tensor, self_tensor);
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
static PyObject* tensor__ne__method(TensorObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__ne__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
  VLOG(6) << "Running Eager tensor__ne__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __ne__ now
  double other_double = 0.0;
  bool has_other_double = false;
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__ne__", 0);
      has_other_double = true;
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__ne__", 0);
      has_other_double = true;
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
  if (has_other_double) {
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
                                phi::Scalar(other_double),
                                self_tensor.dtype(),
                                self_tensor.place());
1702 1703 1704 1705 1706 1707 1708
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__ne__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
    } else {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, self_tensor.dtype(), self_tensor.place());
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling not_equal_ad_func in tensor__ne__method";
  {
    eager_gil_scoped_release guard;
1738
    ret = not_equal_ad_func(self_tensor, other_tensor);
1739 1740 1741 1742 1743 1744
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 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
static PyObject* tensor__eq__method(TensorObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  paddle::platform::RecordEvent pythonc_record_event(
      "__eq__ pybind_patch_func",
      paddle::platform::TracerEventType::UserDefined,
      1);

  EAGER_TRY
  VLOG(6) << "Running Eager tensor__eq__method";

  // Set Device ID
  auto place = egr::Controller::Instance().GetExpectedPlace();
  SetDevice(place);

  paddle::experimental::Tensor ret;
  paddle::experimental::Tensor self_tensor = self->tensor;
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __eq__ now
  double other_double = 0.0;
  bool has_other_double = false;
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__eq__", 0);
      has_other_double = true;
      if (_supported_int_dtype_.find(self_tensor.dtype()) !=
          _supported_int_dtype_.end()) {
        eager_gil_scoped_release guard;
        self_tensor = cast_ad_func(self_tensor, DataType::FLOAT32);
      }
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
      other_double = CastPyArg2Double(other_obj, "__eq__", 0);
      has_other_double = true;
    }
  }

  // 2. create or get tensor for other_obj
  paddle::experimental::Tensor other_tensor;
  if (has_other_double) {
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
                                phi::Scalar(other_double),
                                self_tensor.dtype(),
                                self_tensor.place());
1792 1793 1794 1795 1796 1797 1798
  } else if (PyCheckTensor(other_obj)) {
    other_tensor = CastPyArg2Tensor(other_obj, 0);
  } else if (IsNumpyArray(other_obj)) {
    py::object numpy_value = py::object(py::handle(other_obj), true);
    other_tensor = paddle::experimental::Tensor(place);
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__eq__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
    } else {
      eager_gil_scoped_release guard;
      other_tensor =
          full_ad_func({1}, value, self_tensor.dtype(), self_tensor.place());
    }
  }

  // 3. promote types or unify right var type to left var
  phi::DataType lhs_dtype = self_tensor.dtype();
  phi::DataType rhs_dtype = other_tensor.dtype();
  if (lhs_dtype != rhs_dtype) {
    VLOG(6) << "The dtype of left and right Tensor are not the same, left "
               "dtype is "
            << lhs_dtype << ", but right dtype is " << rhs_dtype
            << ", the right dtype will convert to " << lhs_dtype;
    eager_gil_scoped_release guard;
    other_tensor = cast_ad_func(other_tensor, lhs_dtype);
  }

  // 4. calculation
  VLOG(6) << "Calling equal_ad_func in tensor__eq__method";
  {
    eager_gil_scoped_release guard;
1828
    ret = equal_ad_func(self_tensor, other_tensor);
1829 1830 1831 1832 1833 1834
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
PyMethodDef math_op_patch_methods[] = {
    {"__add__",
     (PyCFunction)(void (*)(void))tensor__add__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__radd__",
     (PyCFunction)(void (*)(void))tensor__add__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__sub__",
     (PyCFunction)(void (*)(void))tensor__sub__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__rsub__",
     (PyCFunction)(void (*)(void))tensor__rsub__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1852 1853 1854 1855 1856 1857 1858 1859
    {"__mul__",
     (PyCFunction)(void (*)(void))tensor__mul__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__rmul__",
     (PyCFunction)(void (*)(void))tensor__mul__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
    {"__div__",
     (PyCFunction)(void (*)(void))tensor__div__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__truediv__",
     (PyCFunction)(void (*)(void))tensor__div__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__rdiv__",
     (PyCFunction)(void (*)(void))tensor__rdiv__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__rtruediv__",
     (PyCFunction)(void (*)(void))tensor__rdiv__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
W
Weilong Wu 已提交
1876 1877 1878 1879
    {"__floordiv__",
     (PyCFunction)(void (*)(void))tensor__floordiv__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1880 1881 1882 1883 1884 1885 1886 1887
    {"__pow__",
     (PyCFunction)(void (*)(void))tensor__pow__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__rpow__",
     (PyCFunction)(void (*)(void))tensor__rpow__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1888 1889 1890 1891 1892 1893 1894 1895
    {"__mod__",
     (PyCFunction)(void (*)(void))tensor__mod__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__matmul__",
     (PyCFunction)(void (*)(void))tensor__matmul__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
W
Weilong Wu 已提交
1896 1897 1898 1899 1900 1901 1902 1903
    {"__gt__",
     (PyCFunction)(void (*)(void))tensor__gt__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__ge__",
     (PyCFunction)(void (*)(void))tensor__ge__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1904 1905 1906 1907 1908 1909 1910 1911
    {"__lt__",
     (PyCFunction)(void (*)(void))tensor__lt__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__le__",
     (PyCFunction)(void (*)(void))tensor__le__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1912 1913 1914 1915
    {"__eq__",
     (PyCFunction)(void (*)(void))tensor__eq__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1916 1917 1918 1919
    {"__ne__",
     (PyCFunction)(void (*)(void))tensor__ne__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1920 1921 1922 1923
    {NULL, NULL, 0, NULL}};

}  // namespace pybind
}  // namespace paddle