eager_math_op_patch.cc 67.7 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 111 112 113 114 115 116
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"));
  }
}

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 143 144
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);
145
    VLOG(6) << "CurrentDeviceId: " << phi::backends::gpu::GetCurrentDeviceId()
146 147 148 149 150 151 152 153 154 155
            << " 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);
156
    VLOG(6) << "CurrentDeviceId: "
157 158 159 160 161 162 163 164 165 166 167 168
            << 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.
169 170 171 172
paddle::Tensor CallScalarFuction(const paddle::Tensor& self_tensor,
                                 double other,
                                 std::string op_type) {
  paddle::Tensor ret;
173 174 175 176 177 178 179
  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);
180 181
  } else if (op_type == "mul") {
    ret = scale_ad_func(self_tensor, phi::Scalar(other), 0.0, true);
182 183
  } else if (op_type == "div") {
    ret = scale_ad_func(self_tensor, phi::Scalar(1.0 / other), 0.0, true);
184 185
  } else if (op_type == "pow") {
    ret = pow_ad_func(self_tensor, other);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  }

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

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

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
212
    double other = 0.0;
213
    if (PyFloat_Check(other_obj)) {
214
      other = CastPyArg2Double(other_obj, "__add__", 0);
215 216 217 218 219 220
      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)) {
221
      other = CastPyArg2Double(other_obj, "__add__", 0);
222 223 224 225 226 227 228 229 230 231
    }

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

  // 2. create or get tensor for other_obj
232
  paddle::Tensor other_tensor;
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);
237
    other_tensor = paddle::Tensor(place);
238 239
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
240 241 242 243
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__add__", 0);
    {
      eager_gil_scoped_release guard;
244 245
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    }
  }

  // 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 {
271 272 273 274
      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;
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
      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);

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

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);
  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
314
    double other = 0.0;
315
    if (PyFloat_Check(other_obj)) {
316
      other = CastPyArg2Double(other_obj, "__sub__", 0);
317 318 319 320 321 322
      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)) {
323
      other = CastPyArg2Double(other_obj, "__sub__", 0);
324 325 326 327 328 329 330 331 332
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "sub");
    }

    return ToPyObject(ret);
  }
  // 2. create or get tensor for other_obj
333
  paddle::Tensor other_tensor;
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);
338
    other_tensor = paddle::Tensor(place);
339 340
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
341 342 343 344
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__sub__", 0);
    {
      eager_gil_scoped_release guard;
345 346
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    }
  }

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

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

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

  // 1. scalar exists cases
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
411
    double other = 0.0;
412
    if (PyFloat_Check(other_obj)) {
413
      other = CastPyArg2Double(other_obj, "__rsub__", 0);
414 415 416 417 418 419
      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)) {
420
      other = CastPyArg2Double(other_obj, "__rsub__", 0);
421 422 423 424 425 426 427 428 429
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "rsub");
    }
    return ToPyObject(ret);
  }

  // 2. create or get tensor for other_obj
430
  paddle::Tensor other_tensor;
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);
435
    other_tensor = paddle::Tensor(place);
436 437
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
438 439 440 441
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__rsub__", 0);
    {
      eager_gil_scoped_release guard;
442 443
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    }
  }

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

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

502 503
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
504 505 506 507

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

  // 1. scalar exists cases
508 509
  if (PyFloat_Check(other_obj) || PyCheckInteger(other_obj) ||
      IsNumpyType(other_obj)) {
510
    double other = 0.0;
511
    if (PyFloat_Check(other_obj)) {
512
      other = CastPyArg2Double(other_obj, "__mul__", 0);
513 514 515 516 517 518
      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)) {
519
      other = CastPyArg2Double(other_obj, "__mul__", 0);
520 521 522 523 524 525 526 527 528
    }
    {
      eager_gil_scoped_release guard;
      ret = CallScalarFuction(self_tensor, other, "mul");
    }
    return ToPyObject(ret);
  }

  // 2. create or get tensor for other_obj
529
  paddle::Tensor other_tensor;
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);
534
    other_tensor = paddle::Tensor(place);
535 536
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
537 538 539 540
    paddle::experimental::Scalar value =
        CastPyArg2Scalar(other_obj, "__mul__", 0);
    if (PyComplex_Check(other_obj)) {
      eager_gil_scoped_release guard;
541 542
      other_tensor = full_ad_func(
          self_tensor.shape(), value, DataType::COMPLEX64, self_tensor.place());
543 544
    } else {
      eager_gil_scoped_release guard;
545 546
      other_tensor = full_ad_func(
          self_tensor.shape(), value, self_tensor.dtype(), self_tensor.place());
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    }
  }

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

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

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

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

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

  // 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 {
678 679 680 681
      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;
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
      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);

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

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

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

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

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

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

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

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

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

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

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

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

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

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

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

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

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

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

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

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

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

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

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

  PyObject* other_obj = PyTuple_GET_ITEM(args, 0);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

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

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

  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
1427
  paddle::Tensor other_tensor;
W
Weilong Wu 已提交
1428 1429 1430 1431 1432 1433
  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());
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);
1438
    other_tensor = paddle::Tensor(place);
1439 1440
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
W
Weilong Wu 已提交
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 1478 1479
    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
}

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

1495 1496
  paddle::Tensor ret;
  paddle::Tensor self_tensor = self->tensor;
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521

  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
1522
  paddle::Tensor other_tensor;
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);
1527
    other_tensor = paddle::Tensor(place);
1528 1529
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
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
    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);

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

  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
1608
  paddle::Tensor other_tensor;
1609 1610 1611 1612 1613 1614
  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());
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);
1619
    other_tensor = paddle::Tensor(place);
1620 1621
    InitTensorWithNumpyValue(numpy_value, place, &other_tensor);
  } else {
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 1656 1657
    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
}

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

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

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

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

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

  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
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},
1855 1856 1857 1858 1859 1860 1861 1862
    {"__mul__",
     (PyCFunction)(void (*)(void))tensor__mul__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__rmul__",
     (PyCFunction)(void (*)(void))tensor__mul__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
    {"__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 已提交
1879 1880 1881 1882
    {"__floordiv__",
     (PyCFunction)(void (*)(void))tensor__floordiv__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1883 1884 1885 1886 1887 1888 1889 1890
    {"__pow__",
     (PyCFunction)(void (*)(void))tensor__pow__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__rpow__",
     (PyCFunction)(void (*)(void))tensor__rpow__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1891 1892 1893 1894 1895 1896 1897 1898
    {"__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 已提交
1899 1900 1901 1902 1903 1904 1905 1906
    {"__gt__",
     (PyCFunction)(void (*)(void))tensor__gt__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__ge__",
     (PyCFunction)(void (*)(void))tensor__ge__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1907 1908 1909 1910 1911 1912 1913 1914
    {"__lt__",
     (PyCFunction)(void (*)(void))tensor__lt__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
    {"__le__",
     (PyCFunction)(void (*)(void))tensor__le__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1915 1916 1917 1918
    {"__eq__",
     (PyCFunction)(void (*)(void))tensor__eq__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1919 1920 1921 1922
    {"__ne__",
     (PyCFunction)(void (*)(void))tensor__ne__method,
     METH_VARARGS | METH_KEYWORDS,
     NULL},
1923 1924 1925 1926
    {NULL, NULL, 0, NULL}};

}  // namespace pybind
}  // namespace paddle