eager_math_op_patch.cc 67.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* 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>
19 20 21 22
// Avoid a problem with copysign defined in pyconfig.h on Windows.
#ifdef copysign
#undef copysign
#endif
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 72 73 74 75

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

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
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_custom_place(place)) {
    SetTensorFromPyArray<platform::CustomPlace>(
        impl_ptr, array, place, zero_copy);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Place should be one of "
张春乔 已提交
111
        "CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace/CustomPlace"));
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 142
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);
143
    VLOG(6) << "CurrentDeviceId: " << phi::backends::gpu::GetCurrentDeviceId()
144 145 146 147 148 149 150 151 152 153
            << " 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);
154
    VLOG(6) << "CurrentDeviceId: "
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.
167 168 169 170
paddle::Tensor CallScalarFuction(const paddle::Tensor& self_tensor,
                                 double other,
                                 std::string op_type) {
  paddle::Tensor ret;
171 172 173 174 175 176 177
  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);
178 179
  } else if (op_type == "mul") {
    ret = scale_ad_func(self_tensor, phi::Scalar(other), 0.0, true);
180 181
  } else if (op_type == "div") {
    ret = scale_ad_func(self_tensor, phi::Scalar(1.0 / other), 0.0, true);
182 183
  } else if (op_type == "pow") {
    ret = pow_ad_func(self_tensor, other);
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
  }

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

203 204
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
205 206 207 208 209
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
210
    double other = 0.0;
211
    if (PyFloat_Check(other_obj)) {
212
      other = CastPyArg2Double(other_obj, "__add__", 0);
213 214 215 216 217 218
      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)) {
219
      other = CastPyArg2Double(other_obj, "__add__", 0);
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
230
  paddle::Tensor other_tensor;
231 232 233 234
  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);
235
    other_tensor = paddle::Tensor(place);
236 237
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
238 239 240 241
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__add__", 0);
    {
      eager_gil_scoped_release guard;
242 243
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    }
  }

  // 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 {
269 270 271 272
      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;
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
      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);

305 306
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
307 308 309 310 311

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);
  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
312
    double other = 0.0;
313
    if (PyFloat_Check(other_obj)) {
314
      other = CastPyArg2Double(other_obj, "__sub__", 0);
315 316 317 318 319 320
      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)) {
321
      other = CastPyArg2Double(other_obj, "__sub__", 0);
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
331
  paddle::Tensor other_tensor;
332 333 334 335
  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);
336
    other_tensor = paddle::Tensor(place);
337 338
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
339 340 341 342
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__sub__", 0);
    {
      eager_gil_scoped_release guard;
343 344
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
    }
  }

  // 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 {
368 369 370 371
      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;
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
      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 已提交
396
  VLOG(4) << "Running Eager tensor__rsub__method";
397 398 399 400 401

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

402 403
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
404 405 406 407 408
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
409
    double other = 0.0;
410
    if (PyFloat_Check(other_obj)) {
411
      other = CastPyArg2Double(other_obj, "__rsub__", 0);
412 413 414 415 416 417
      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)) {
418
      other = CastPyArg2Double(other_obj, "__rsub__", 0);
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
428
  paddle::Tensor other_tensor;
429 430 431 432
  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);
433
    other_tensor = paddle::Tensor(place);
434 435
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
436 437 438 439
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__rsub__", 0);
    {
      eager_gil_scoped_release guard;
440 441
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    }
  }

  // 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 {
465 466 467 468
      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;
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
      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
}

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
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);

500 501
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
502 503 504 505

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
506 507
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
508
    double other = 0.0;
509
    if (PyFloat_Check(other_obj)) {
510
      other = CastPyArg2Double(other_obj, "__mul__", 0);
511 512 513 514 515 516
      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)) {
517
      other = CastPyArg2Double(other_obj, "__mul__", 0);
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
527
  paddle::Tensor other_tensor;
528 529 530 531
  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);
532
    other_tensor = paddle::Tensor(place);
533 534
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
535 536 537 538
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__mul__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
539 540
      other_tensor = full_ad_func(
          self_tensor.shape(), value, DataType::COMPLEX64, self_tensor.place());
541 542
    } else {
      eager_gil_scoped_release guard;
543 544
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    }
  }

  // 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 {
570 571 572 573
      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;
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
      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
}

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
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);

606 607
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
608 609 610 611 612 613

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
614
    double other = 0.0;
615
    if (PyFloat_Check(other_obj)) {
616
      other = CastPyArg2Double(other_obj, "__div__", 0);
617
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
618
      other = CastPyArg2Double(other_obj, "__div__", 0);
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
633
  paddle::Tensor other_tensor;
634 635 636 637
  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);
638
    other_tensor = paddle::Tensor(place);
639 640
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
641 642 643 644
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__div__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
645 646
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
647 648
    } else {
      eager_gil_scoped_release guard;
649 650
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    }
  }

  // 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 {
676 677 678 679
      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;
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
      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);

721 722
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
723 724 725 726 727

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar_div function for __rdiv__ and __rtruediv__
728 729
  double other_double = 0.0;
  bool has_other_double = false;
730 731 732
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
733 734
      other_double = CastPyArg2Double(other_obj, "__rdiv__", 0);
      has_other_double = true;
735
    } else if (PyCheckInteger(other_obj) || IsNumpyType(other_obj)) {
736 737
      other_double = CastPyArg2Double(other_obj, "__rdiv__", 0);
      has_other_double = true;
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
747
  paddle::Tensor other_tensor;
748
  if (has_other_double) {
749 750
    eager_gil_scoped_release guard;
    other_tensor = full_ad_func(self_tensor.shape(),
751
                                phi::Scalar(other_double),
752 753
                                self_tensor.dtype(),
                                place);
754 755 756 757
  } 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);
758
    other_tensor = paddle::Tensor(place);
759 760
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
761 762 763 764
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__rdiv__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
765 766
      other_tensor =
          full_ad_func({1}, value, DataType::COMPLEX64, self_tensor.place());
767 768
    } else {
      eager_gil_scoped_release guard;
769 770
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    }
  }

  // 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 {
796 797 798 799
      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;
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
      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 已提交
825 826 827 828 829 830 831 832 833
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 已提交
834
  VLOG(4) << "Running Eager tensor__gt__method";
W
Weilong Wu 已提交
835 836 837 838 839

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

840 841
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
W
Weilong Wu 已提交
842 843 844 845
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __gt__ now
846 847
  double other_double = 0.0;
  bool has_other_double = false;
W
Weilong Wu 已提交
848 849 850
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
851 852
      other_double = CastPyArg2Double(other_obj, "__gt__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
853 854 855 856 857 858
      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)) {
859 860
      other_double = CastPyArg2Double(other_obj, "__gt__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
861 862 863 864
    }
  }

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

  // 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) {
896 897 898 899
    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 已提交
900 901 902 903 904 905 906 907
    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;
908
    ret = greater_than_ad_func(self_tensor, other_tensor);
W
Weilong Wu 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  }

  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 已提交
924
  VLOG(4) << "Running Eager tensor__ge__method";
W
Weilong Wu 已提交
925 926 927 928 929

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

930 931
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
W
Weilong Wu 已提交
932 933 934 935
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __ge__ now
936 937
  double other_double = 0.0;
  bool has_other_double = false;
W
Weilong Wu 已提交
938 939 940
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
941 942
      other_double = CastPyArg2Double(other_obj, "__ge__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
943 944 945 946 947 948
      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)) {
949 950
      other_double = CastPyArg2Double(other_obj, "__ge__", 0);
      has_other_double = true;
W
Weilong Wu 已提交
951 952 953 954
    }
  }

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

  // 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) {
986 987 988 989
    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 已提交
990 991 992 993 994 995 996 997
    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;
998
    ret = greater_equal_ad_func(self_tensor, other_tensor);
W
Weilong Wu 已提交
999 1000 1001 1002 1003 1004
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
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);

1020 1021
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
1022 1023 1024 1025 1026

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar_mod function for __mod__ now
1027 1028
  float other_double = 0.0;
  bool has_other_double = false;
1029 1030 1031
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1032 1033
      other_double = CastPyArg2Double(other_obj, "__mod__", 0);
      has_other_double = true;
1034 1035 1036 1037 1038 1039
      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)) {
1040 1041
      other_double = CastPyArg2Double(other_obj, "__mod__", 0);
      has_other_double = true;
1042 1043 1044 1045
    }
  }

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

  // 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);

1110 1111
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
1112 1113 1114 1115 1116

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar_matmul function for __matmul__ now
1117 1118
  float other_double = 0.0;
  bool has_other_double = false;
1119 1120 1121
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1122 1123
      other_double = CastPyArg2Double(other_obj, "__matmul__", 0);
      has_other_double = true;
1124 1125 1126 1127 1128 1129
      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)) {
1130 1131
      other_double = CastPyArg2Double(other_obj, "__matmul__", 0);
      has_other_double = true;
1132 1133 1134 1135
    }
  }

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

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

1204 1205 1206 1207 1208 1209 1210 1211 1212
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 已提交
1213
  VLOG(4) << "Running Eager tensor__lt__method";
1214 1215 1216 1217 1218

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

1219 1220
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
1221 1222 1223 1224
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __lt__ now
1225 1226
  float other_double = 0.0;
  bool has_other_double = false;
1227 1228 1229
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1230 1231
      other_double = CastPyArg2Double(other_obj, "__lt__", 0);
      has_other_double = true;
1232 1233 1234 1235 1236 1237
      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)) {
1238 1239
      other_double = CastPyArg2Double(other_obj, "__lt__", 0);
      has_other_double = true;
1240 1241 1242 1243
    }
  }

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

  // 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) {
1275 1276 1277 1278
    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;
1279 1280 1281 1282 1283 1284 1285 1286
    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;
1287
    ret = less_than_ad_func(self_tensor, other_tensor);
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
  }

  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 已提交
1303
  VLOG(4) << "Running Eager tensor__le__method";
1304 1305 1306 1307 1308

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

1309 1310
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
1311 1312 1313 1314
  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
  // there is no scalar function for __le__ now
1315 1316
  float other_double = 0.0;
  bool has_other_double = false;
1317 1318 1319
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
    if (PyFloat_Check(other_obj)) {
1320 1321
      other_double = CastPyArg2Double(other_obj, "__le__", 0);
      has_other_double = true;
1322 1323 1324 1325 1326 1327
      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)) {
1328 1329
      other_double = CastPyArg2Double(other_obj, "__le__", 0);
      has_other_double = true;
1330 1331 1332 1333
    }
  }

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

  // 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) {
1365 1366 1367 1368
    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;
1369 1370 1371 1372 1373 1374 1375 1376
    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;
1377
    ret = less_equal_ad_func(self_tensor, other_tensor);
1378 1379 1380 1381 1382 1383
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
Weilong Wu 已提交
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
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);

1398 1399
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
W
Weilong Wu 已提交
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

  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
1425
  paddle::Tensor other_tensor;
W
Weilong Wu 已提交
1426 1427 1428 1429 1430 1431
  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());
1432 1433 1434 1435
  } 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);
1436
    other_tensor = paddle::Tensor(place);
1437 1438
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
W
Weilong Wu 已提交
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 1477
    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
}

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
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);

1493 1494
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
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

  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
1520
  paddle::Tensor other_tensor;
1521 1522 1523 1524
  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);
1525
    other_tensor = paddle::Tensor(place);
1526 1527
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
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
    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);

1579 1580
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
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

  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
1606
  paddle::Tensor other_tensor;
1607 1608 1609 1610 1611 1612
  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());
1613 1614 1615 1616
  } 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);
1617
    other_tensor = paddle::Tensor(place);
1618 1619
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
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 1655
    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
}

1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
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);

1671 1672
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
  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
1696
  paddle::Tensor other_tensor;
1697 1698 1699 1700 1701 1702
  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());
1703 1704 1705 1706
  } 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);
1707
    other_tensor = paddle::Tensor(place);
1708 1709
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
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 1738
    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;
1739
    ret = not_equal_ad_func(self_tensor, other_tensor);
1740 1741 1742 1743 1744 1745
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
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);

1761 1762
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
  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
1786
  paddle::Tensor other_tensor;
1787 1788 1789 1790 1791 1792
  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());
1793 1794 1795 1796
  } 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);
1797
    other_tensor = paddle::Tensor(place);
1798 1799
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
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 1828
    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;
1829
    ret = equal_ad_func(self_tensor, other_tensor);
1830 1831 1832 1833 1834 1835
  }

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

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

}  // namespace pybind
}  // namespace paddle