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

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

18
#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

#include <string>
25
#include <unordered_map>
26 27 28 29 30 31
#include <vector>

#include "paddle/fluid/eager/accumulation/accumulation_node.h"
#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/autograd_meta.h"
#include "paddle/fluid/eager/backward.h"
32
#include "paddle/fluid/eager/custom_operator/custom_operator_node.h"
33
#include "paddle/fluid/eager/utils.h"
34
#include "paddle/fluid/framework/convert_utils.h"
35
#include "paddle/fluid/framework/custom_operator.h"
36
#include "paddle/fluid/framework/custom_operator_utils.h"
37
#include "paddle/fluid/framework/phi_utils.h"
38
#include "paddle/fluid/framework/python_headers.h"
39 40
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/memory/memcpy.h"
W
wanghuancoder 已提交
41
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
42
#include "paddle/fluid/platform/dynload/dynamic_loader.h"
43 44 45 46
#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"
47
#include "paddle/fluid/pybind/op_function_common.h"
48
#include "paddle/fluid/pybind/tensor_py.h"
49
#include "paddle/phi/api/ext/op_meta_info.h"
50
#include "paddle/phi/api/include/api.h"
51 52 53 54
#include "paddle/phi/api/lib/utils/allocator.h"
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/dense_tensor.h"
55 56
#include "paddle/phi/core/sparse_coo_tensor.h"
#include "paddle/phi/core/sparse_csr_tensor.h"
57
#include "paddle/utils/string/string_helper.h"
58 59
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
60

L
Leo Chen 已提交
61 62 63 64
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
#include "paddle/fluid/pybind/cuda_streams_py.h"
#endif

65
#include "paddle/phi/api/include/operants_manager.h"
66
#include "paddle/phi/api/include/tensor_operants.h"
67
#include "paddle/phi/core/flags.h"
68

69
PHI_DECLARE_string(tensor_operants_mode);
70

71 72 73 74 75
namespace paddle {
namespace pybind {

namespace py = ::pybind11;

76
extern PyTypeObject* p_tensor_type;
77 78
extern PyTypeObject* g_multidevicefeedreader_pytype;
extern PyTypeObject* g_orderedmultidevicefeedreader_pytype;
79 80 81 82 83 84 85 86 87 88 89

size_t PyArray_Size_(PyObject* numpy_data) {
  size_t res = 1;
  auto dims = pybind11::detail::array_proxy(numpy_data)->dimensions;
  auto nd = pybind11::detail::array_proxy(numpy_data)->nd;
  while (nd--) {
    res *= (*dims++);
  }
  return res;
}

90
class EagerNumpyAllocation : public phi::Allocation {
91
 public:
92
  explicit EagerNumpyAllocation(PyObject* numpy_data, phi::DataType dtype)
93 94
      : Allocation(
            static_cast<void*>(pybind11::detail::array_proxy(numpy_data)->data),
95
            phi::SizeOf(dtype) * PyArray_Size_(numpy_data),
96 97
            paddle::platform::CPUPlace()),
        arr_(numpy_data) {
98 99 100 101
    PADDLE_ENFORCE_NOT_NULL(
        arr_,
        platform::errors::InvalidArgument("The underlying PyObject pointer of "
                                          "numpy array cannot be nullptr"));
102
    PADDLE_ENFORCE_NE(
103 104
        arr_,
        Py_None,
105 106 107 108 109 110 111 112 113 114 115 116 117
        platform::errors::PreconditionNotMet(
            "The underlying PyObject pointer of numpy array cannot be None"));
    Py_INCREF(arr_);
  }
  ~EagerNumpyAllocation() override {
    py::gil_scoped_acquire gil;
    Py_DECREF(arr_);
  }

 private:
  PyObject* arr_;
};

118 119
static PyObject* eager_api_scale(PyObject* self,
                                 PyObject* args,
120 121 122
                                 PyObject* kwargs) {
  EAGER_TRY
  // TODO(jiabin): Sync Tensor and Variable here when we support
W
wanghuancoder 已提交
123 124 125 126 127 128 129

  auto& tensor =
      reinterpret_cast<TensorObject*>(PyTuple_GET_ITEM(args, 0))->tensor;
  float scale = CastPyArg2AttrFloat(PyTuple_GET_ITEM(args, 1), 1);
  float bias = CastPyArg2AttrFloat(PyTuple_GET_ITEM(args, 2), 2);
  bool bias_after_scale = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 3), 3);
  bool trace_backward = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 4), 4);
130
  paddle::Tensor ret;
W
wanghuancoder 已提交
131 132 133 134
  {
    eager_gil_scoped_release guard;
    ret = egr::scale(tensor, scale, bias, bias_after_scale, trace_backward);
  }
135 136 137 138
  return ToPyObject(ret);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

139 140
static PyObject* eager_api_run_backward(PyObject* self,
                                        PyObject* args,
141 142
                                        PyObject* kwargs) {
  EAGER_TRY
143 144
  auto tensors = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 0), 0);
  auto grad_tensors = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 1), 1);
W
wanghuancoder 已提交
145
  bool retain_graph = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 2), 2);
146 147
  {
    eager_gil_scoped_release guard;
W
wanghuancoder 已提交
148
    egr::Backward(tensors, grad_tensors, retain_graph);
149
  }
150
  RETURN_PY_NONE
151 152 153
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

154 155
static PyObject* eager_api_run_partial_grad(PyObject* self,
                                            PyObject* args,
156 157 158 159 160 161 162 163 164 165
                                            PyObject* kwargs) {
  EAGER_TRY
  auto tensors = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 0), 0);
  auto inputs = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 1), 1);
  auto grad_tensors = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 2), 2);
  auto retain_graph = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 3), 3);
  auto create_graph = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 4), 4);
  auto only_inputs = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 5), 5);
  auto allow_unused = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 6), 6);
  auto no_grad_vars = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 7), 7);
166
  std::vector<paddle::Tensor> result;
167 168 169 170 171 172 173 174 175 176
  {
    eager_gil_scoped_release guard;
    result = egr::Grad(tensors,
                       inputs,
                       grad_tensors,
                       retain_graph,
                       create_graph,
                       only_inputs,
                       allow_unused,
                       no_grad_vars);
L
Leo Chen 已提交
177
    VLOG(4) << " in eager_api_run_partial_grad, after runing egr::Grad";
178
  }
179 180 181 182
  return ToPyObject(result, true /* return_py_none_if_not_initialize */);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

183 184
static PyObject* eager_api_tensor_copy(PyObject* self,
                                       PyObject* args,
185 186
                                       PyObject* kwargs) {
  EAGER_TRY
187
  paddle::Tensor& src =
188
      reinterpret_cast<TensorObject*>(PyTuple_GET_ITEM(args, 0))->tensor;
189
  paddle::Tensor& dst =
190
      reinterpret_cast<TensorObject*>(PyTuple_GET_ITEM(args, 1))->tensor;
191 192 193
  auto place = CastPyArg2Place(PyTuple_GET_ITEM(args, 2), 2);
  bool blocking = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 3), 3);

W
wanghuancoder 已提交
194 195 196 197 198 199 200 201
  {
    eager_gil_scoped_release guard;
    dst = src.copy_to(place, blocking);
    egr::EagerUtils::autograd_meta(&dst)->SetStopGradient(
        egr::EagerUtils::autograd_meta(&(src))->StopGradient());
    egr::EagerUtils::autograd_meta(&dst)->SetPersistable(
        egr::EagerUtils::autograd_meta(&(src))->Persistable());
  }
202
  RETURN_PY_NONE
203 204 205
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

206 207 208 209 210 211
PyObject* eager_api_get_all_grads(PyObject* self,
                                  PyObject* args,
                                  PyObject* kwargs) {
  EAGER_TRY
  auto tensor_list = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 0), 0);

212
  std::vector<paddle::Tensor> ret;
213 214 215 216
  for (auto& tensor : tensor_list) {
    VLOG(6) << "Get grad for tensor: " << tensor.name();
    auto meta = egr::EagerUtils::nullable_autograd_meta(tensor);
    if (!meta || meta->StopGradient()) {
217
      ret.emplace_back(paddle::Tensor());
218 219 220 221 222
      continue;
    }
    if (meta && meta->Grad().initialized()) {
      ret.emplace_back(meta->Grad());
    } else {
223
      ret.emplace_back(paddle::Tensor());
224 225 226 227 228 229
    }
  }
  return ToPyObject(ret, true);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

230 231 232 233 234
PyObject* eager_api_get_grads_lists(PyObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  EAGER_TRY
  auto tensor_list = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 0), 0);
235
  // The order of the 3 vectors is: FP16_grads, BF16_grads, FP32_grads
236
  std::vector<std::vector<paddle::Tensor>> ret(3);
237 238 239 240 241 242 243

  for (auto& tensor : tensor_list) {
    VLOG(6) << "Get grad for tensor: " << tensor.name();
    auto meta = egr::EagerUtils::nullable_autograd_meta(tensor);
    if (meta && meta->Grad().initialized()) {
      auto& grad = meta->Grad();
      switch (grad.dtype()) {
244
        case phi::DataType::FLOAT16:
245 246
          ret[0].emplace_back(grad);
          break;
247
        case phi::DataType::BFLOAT16:
248 249
          ret[1].emplace_back(grad);
          break;
250
        case phi::DataType::FLOAT32:
251 252 253 254 255 256 257 258 259 260 261 262 263
          ret[2].emplace_back(grad);
          break;
        default:
          break;
      }
    }
  }

  return ToPyObject(ret);

  EAGER_CATCH_AND_THROW_RETURN_NULL
}

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
PyObject* eager_api_get_grads_types(PyObject* self,
                                    PyObject* args,
                                    PyObject* kwargs) {
  EAGER_TRY
  auto tensor_list = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 0), 0);

  std::vector<int> ret;

  for (auto& tensor : tensor_list) {
    VLOG(6) << "Get grad for tensor: " << tensor.name();
    auto meta = egr::EagerUtils::nullable_autograd_meta(tensor);
    if (!meta || meta->StopGradient()) {
      ret.emplace_back(-1);
      continue;
    }

    auto& grad = meta->Grad();
    if (meta && grad.initialized()) {
      if (grad.is_dense_tensor() &&
283 284 285
          (tensor.dtype() == phi::DataType::FLOAT32 ||
           tensor.dtype() == phi::DataType::FLOAT16 ||
           tensor.dtype() == phi::DataType::BFLOAT16)) {
286 287 288 289 290 291 292 293 294 295 296 297 298
        ret.emplace_back(
            paddle::framework::TransToProtoVarType(tensor.dtype()));
      }
    } else {
      ret.emplace_back(-1);
    }
  }

  return ToPyObject(ret);

  EAGER_CATCH_AND_THROW_RETURN_NULL
}

299 300
static PyObject* eager_api_read_next_tensor_list(PyObject* self,
                                                 PyObject* args,
301
                                                 PyObject* kwargs) {
302
  EAGER_TRY
303 304
  auto tensor_base_list =
      CastPyArg2VectorOfTensorBase(PyTuple_GET_ITEM(args, 0), 0);
305
  std::vector<paddle::Tensor> tensor_list;
306 307 308
  {
    eager_gil_scoped_release guard;
    tensor_list.reserve(tensor_base_list.size());
309
    auto func = [](phi::DenseTensor& tensor_base) {
310
      paddle::Tensor tensor(egr::Controller::Instance().GenerateUniqueName());
311 312 313 314 315 316 317 318 319
      auto autograd_meta = egr::EagerUtils::autograd_meta(&tensor);
      autograd_meta->SetPersistable(false);
      autograd_meta->SetStopGradient(true);
      tensor.set_impl(std::make_shared<phi::DenseTensor>(tensor_base));
      return tensor;
    };
    for (auto& tensor_base : tensor_base_list) {
      tensor_list.emplace_back(func(tensor_base));
    }
320
  }
321
  return ToPyObject(tensor_list);
322 323 324
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

325 326 327 328 329 330 331 332 333
static void ConstructFwdAndBwdMap(
    const std::vector<paddle::OpMetaInfo>& vec_map,
    const std::string& op_type) {
  auto& in_out_map = egr::Controller::Instance().GetCustomEdgesSlotMap();
  if (in_out_map.find(op_type) != in_out_map.end()) {
    VLOG(7) << "Find Exist CustomEdgesSlotMap Skip >>>> ";
    return;
  } else {
    VLOG(7) << "Construct CustomEdgesSlotMap ";
334 335 336 337 338 339
    auto inputs_names = paddle::OpMetaInfoHelper::GetInputs(vec_map[0]);
    auto outputs_names = paddle::OpMetaInfoHelper::GetOutputs(vec_map[0]);
    auto attrs_names = paddle::OpMetaInfoHelper::GetAttrs(vec_map[0]);
    auto grad_outputs_names = paddle::OpMetaInfoHelper::GetOutputs(vec_map[1]);
    auto grad_inputs_names = paddle::OpMetaInfoHelper::GetInputs(vec_map[1]);
    auto grad_attrs_names = paddle::OpMetaInfoHelper::GetAttrs(vec_map[1]);
340
    std::vector<std::unordered_map<int, int>> res(5);
341 342

    in_out_map.insert({op_type, {res}});
343 344 345
    // Prepare pos map for grad_outputs
    VLOG(7) << "Prepare pos map for grad_outputs";
    PADDLE_ENFORCE_LE(
346 347
        grad_outputs_names.size(),
        inputs_names.size(),
348 349 350 351 352
        paddle::platform::errors::InvalidArgument(
            "Grad outputs num should be less equal than forward inputs num."));
    for (size_t i = 0; i < grad_outputs_names.size(); i++) {
      size_t end = grad_outputs_names[i].find("@GRAD");
      PADDLE_ENFORCE_NE(
353 354
          end,
          std::string::npos,
355 356 357 358 359 360 361 362 363
          paddle::platform::errors::NotFound(
              "All Grad outputs should be grad and we got %s is not grad var, "
              "please check your op and change to fit the rule.",
              grad_outputs_names[i]));
      for (size_t j = 0; j < inputs_names.size(); j++) {
        if (grad_outputs_names[i].substr(0, end) == inputs_names[j]) {
          VLOG(7) << " ==== Custom Operator: " << op_type << "'s No." << j
                  << " inputs: " << inputs_names[j] << " related to No." << i
                  << " grad_outputs: " << grad_outputs_names[i];
364
          in_out_map[op_type][0][0][j] = i;
365 366 367 368 369 370 371 372 373 374 375 376
        }
      }
    }
    // Prepare pos map for grad_inputs
    for (size_t i = 0; i < grad_inputs_names.size(); i++) {
      size_t end = grad_inputs_names[i].find("@GRAD");
      if (end != std::string::npos) {
        for (size_t j = 0; j < outputs_names.size(); j++) {
          if (grad_inputs_names[i].substr(0, end) == outputs_names[j]) {
            VLOG(7) << " ==== Custom Operator: " << op_type << "'s No." << j
                    << " outputs: " << outputs_names[j] << " related to No."
                    << i << " grad_inputs's grad: " << grad_inputs_names[i];
377
            in_out_map[op_type][0][1][j] = i;
378 379 380
          }
        }
      } else {
381 382
        if (std::find(outputs_names.begin(),
                      outputs_names.end(),
383 384 385 386 387 388 389
                      grad_inputs_names[i]) != outputs_names.end()) {
          for (size_t j = 0; j < outputs_names.size(); j++) {
            if (grad_inputs_names[i] == outputs_names[j]) {
              VLOG(7) << " ==== Custom Operator: " << op_type << "'s No." << j
                      << " outputs: " << outputs_names[j] << " related to No."
                      << i
                      << " grad_inputs fwd outputs: " << grad_inputs_names[i];
390
              in_out_map[op_type][0][2][j] = i;
391 392 393 394 395 396 397 398 399
            }
          }
        } else {
          for (size_t j = 0; j < inputs_names.size(); j++) {
            if (grad_inputs_names[i] == inputs_names[j]) {
              VLOG(7) << " ==== Custom Operator: " << op_type << "'s No." << j
                      << " inputs: " << inputs_names[j] << " related to No."
                      << i
                      << " grad_inputs fwd inputs: " << grad_inputs_names[i];
400
              in_out_map[op_type][0][3][j] = i;
401 402 403 404 405 406 407 408
            }
          }
        }
      }
    }

    // Prepare pos map for grad attrs_
    for (size_t i = 0; i < grad_attrs_names.size(); i++) {
409 410 411 412
      auto end = std::find(
          attrs_names.begin(), attrs_names.end(), grad_attrs_names[i]);
      PADDLE_ENFORCE_NE(end,
                        attrs_names.end(),
413 414 415 416 417 418 419 420 421 422
                        paddle::platform::errors::NotFound(
                            "All Grad attrs should be one of forward attrs and "
                            "we got %s is not one of them, please check your "
                            "op and change to fit the rule.",
                            grad_attrs_names[i]));
      for (size_t j = 0; j < attrs_names.size(); j++) {
        if (grad_attrs_names[i] == attrs_names[j]) {
          VLOG(7) << " ==== Custom Operator: " << op_type << "'s No." << j
                  << " attrs: " << attrs_names[j] << " related to No." << i
                  << " grad_attrs: " << grad_attrs_names[i];
423
          in_out_map[op_type][0][4][j] = i;
424 425 426 427 428 429
        }
      }
    }
  }
}

430 431 432 433
static PyObject* eager_api_jit_function_call(PyObject* self,
                                             PyObject* args,
                                             PyObject* kwargs) {
  EAGER_TRY
434 435 436

  std::shared_ptr<jit::Function> function =
      CastPyArg2JitFunction(PyTuple_GET_ITEM(args, 0), 0);
437
  std::vector<paddle::Tensor> ins =
438
      CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 1), 1);
439
  std::vector<paddle::Tensor> outs;
W
wanghuancoder 已提交
440 441 442 443
  {
    eager_gil_scoped_release guard;
    outs = (*function)(ins);
  }
444 445 446 447
  return ToPyObject(outs);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
static PyObject* eager_api__get_custom_operator_inplace_reverse_idx(
    PyObject* self, PyObject* args, PyObject* kwargs) {
  EAGER_TRY
  std::string op_type = CastPyArg2AttrString(PyTuple_GET_ITEM(args, 0), 0);
  auto meta_info_map = egr::Controller::Instance().GetOpMetaInfoMap();
  PADDLE_ENFORCE_NE(meta_info_map.find(op_type),
                    meta_info_map.end(),
                    paddle::platform::errors::NotFound(
                        "Can't find %s in Eager OpMetaInfoMap which should be "
                        "created by LoadOpMetaInfoAndRegisterOp, please make "
                        "sure you registered your op first and try again. ",
                        op_type));

  const auto& inputs =
      paddle::OpMetaInfoHelper::GetInputs(meta_info_map.at(op_type)[0]);
  const auto& outputs =
      paddle::OpMetaInfoHelper::GetOutputs(meta_info_map.at(op_type)[0]);
  const auto& inplace_map =
      paddle::OpMetaInfoHelper::GetInplaceMap(meta_info_map.at(op_type)[0]);
  VLOG(7) << "Custom operator " << op_type
          << " get InplaceMap for python, inplace map size = "
          << inplace_map.size();

  std::unordered_map<int, int> inplace_idx_map;
  for (size_t in_idx = 0; in_idx < inputs.size(); ++in_idx) {
    auto& input = inputs[in_idx];
    if (inplace_map.find(input) == inplace_map.end()) {
      continue;
    }
    auto out_iter = find(outputs.begin(), outputs.end(), inplace_map.at(input));
    PADDLE_ENFORCE(
        out_iter != outputs.end(),
        phi::errors::NotFound("Can't find the mapped value of %s, please check "
                              "the input of `Inplace` again and make "
                              "sure you registered your op accurately. ",
                              input));
    inplace_idx_map[distance(outputs.begin(), out_iter)] = in_idx;
  }

  return ToPyObject(inplace_idx_map);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
// This function copies from function `EmptyTensorInitializer` with default
// parameters
static Tensor InitializedEmptyTensor() {
  auto ddims = phi::make_ddim({0});
  auto tensor = paddle::Tensor();
  tensor.set_name(
      egr::Controller::Instance().GenerateUniqueName("generated_tensor"));
  auto autograd_meta = egr::EagerUtils::autograd_meta(&tensor);
  autograd_meta->SetPersistable(false);
  std::shared_ptr<phi::DenseTensor> dense_tensor = nullptr;
  std::shared_ptr<phi::Allocation> allocation_ptr = nullptr;
  dense_tensor = std::make_shared<phi::DenseTensor>(
      allocation_ptr, phi::DenseTensorMeta(phi::DataType::FLOAT32, ddims));
  tensor.set_impl(dense_tensor);
  autograd_meta->SetGradNode(
      std::make_shared<egr::GradNodeAccumulation>(autograd_meta));
  return tensor;
}

H
HongyuJia 已提交
510
static PyObject* eager_api_run_custom_op(PyObject* self,
511
                                         PyObject* args,
512 513
                                         PyObject* kwargs) {
  EAGER_TRY
514
  FLAGS_tensor_operants_mode = "phi";
515 516
  if (paddle::OperantsManager::Instance().phi_operants.get() == nullptr) {
    paddle::OperantsManager::Instance().phi_operants.reset(
517 518 519 520
        new paddle::operants::PhiTensorOperants());
    VLOG(4) << "Initialize phi tensor operants successfully";
  }

521 522 523
  std::string op_type = CastPyArg2AttrString(PyTuple_GET_ITEM(args, 0), 0);
  VLOG(7) << "Get things from python for Custom Op: " << op_type;
  paddle::CustomOpKernelContext ctx;
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
  auto meta_info_map = egr::Controller::Instance().GetOpMetaInfoMap();
  PADDLE_ENFORCE_NE(meta_info_map.find(op_type),
                    meta_info_map.end(),
                    paddle::platform::errors::NotFound(
                        "Can't find %s in Eager OpMetaInfoMap which should be "
                        "created by LoadOpMetaInfoAndRegisterOp, please make "
                        "sure you registered your op first and try again. ",
                        op_type));
  const auto& vec_map = meta_info_map.at(op_type);
  const auto& inputs = paddle::OpMetaInfoHelper::GetInputs(vec_map[0]);
  const auto& attrs = paddle::OpMetaInfoHelper::GetAttrs(vec_map[0]);
  const auto& outputs = paddle::OpMetaInfoHelper::GetOutputs(vec_map[0]);
  const auto& inplace_map = paddle::OpMetaInfoHelper::GetInplaceMap(vec_map[0]);
  for (size_t i = 0; i < inputs.size(); ++i) {
    const auto& input = inputs.at(i);
    // Parse op_type first, so that use i + 1
    PyObject* obj = PyTuple_GET_ITEM(args, i + 1);
    // Emplace Py_None from python, this means optional inputs passed to C++,
    // use one un-initialized tensor to indicate both Tensor and
    // vector<Tensor> inputs.
    if (obj == Py_None) {
      VLOG(7) << "Custom operator add input " << input
              << " to CustomOpKernelContext. Add un-initialized tensor "
                 "because the optional input is None";
      ctx.EmplaceBackInput(std::move(paddle::Tensor()));
      continue;
550
    }
551 552 553 554 555 556 557 558 559
    if (paddle::framework::detail::IsDuplicableVar(input)) {
      ctx.EmplaceBackInputs(std::move(CastPyArg2VectorOfTensor(obj, i + 1)));
      VLOG(7) << "Custom operator add input " << input
              << " to CustomOpKernelContext. Add vector<Tensor> size = "
              << ctx.InputRangeAt(i).second - ctx.InputRangeAt(i).first;
    } else {
      ctx.EmplaceBackInput(std::move(CastPyArg2Tensor(obj, i + 1)));
      VLOG(7) << "Custom operator add input " << input
              << " to CustomOpKernelContext. Add Tensor for general case.";
560
    }
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
  }
  // Parse op_type and inputs first, so that use 1 + inputs.size() + i
  int attr_start_idx = 1 + inputs.size();
  for (size_t i = 0; i < attrs.size(); ++i) {
    const auto& attr = attrs.at(i);
    std::vector<std::string> attr_name_and_type = paddle::ParseAttrStr(attr);
    auto attr_type_str = attr_name_and_type[1];
    VLOG(7) << "Custom operator add attrs " << attr_name_and_type[0]
            << " to CustomOpKernelContext. Attribute type = " << attr_type_str;
    PyObject* obj = PyTuple_GET_ITEM(args, attr_start_idx + i);
    if (attr_type_str == "bool") {
      ctx.EmplaceBackAttr(CastPyArg2AttrBoolean(obj, attr_start_idx + i));
    } else if (attr_type_str == "int") {
      ctx.EmplaceBackAttr(CastPyArg2AttrInt(obj, attr_start_idx + i));
    } else if (attr_type_str == "float") {
      ctx.EmplaceBackAttr(CastPyArg2AttrFloat(obj, attr_start_idx + i));
    } else if (attr_type_str == "int64_t") {
      ctx.EmplaceBackAttr(CastPyArg2Long(obj, op_type, attr_start_idx + i));
    } else if (attr_type_str == "std::string") {
      ctx.EmplaceBackAttr(CastPyArg2AttrString(obj, attr_start_idx + i));
    } else if (attr_type_str == "std::vector<int>") {
      ctx.EmplaceBackAttr(CastPyArg2VectorOfInt(obj, attr_start_idx + i));
    } else if (attr_type_str == "std::vector<float>") {
      ctx.EmplaceBackAttr(CastPyArg2VectorOfFloat(obj, attr_start_idx + i));
    } else if (attr_type_str == "std::vector<int64_t>") {
      ctx.EmplaceBackAttr(CastPyArg2Longs(obj, op_type, attr_start_idx + i));
    } else if (attr_type_str == "std::vector<std::string>") {
      ctx.EmplaceBackAttr(CastPyArg2VectorOfString(obj, attr_start_idx + i));
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported `%s` type value as custom attribute now. "
          "Supported data types include `bool`, `int`, `float`, "
          "`int64_t`, `std::string`, `std::vector<int>`, "
          "`std::vector<float>`, `std::vector<int64_t>`, "
          "`std::vector<std::string>`, Please check whether "
          "the attribute data type and data type string are matched.",
          attr_type_str));
    }
  }
  {
    eager_gil_scoped_release guard;
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    ctx.ConstructInplaceIndex(inputs, outputs, inplace_map);
    const auto& inplace_reverse_idx_map = ctx.GetInplaceReverseIndexMap();
    for (size_t out_idx = 0; out_idx < outputs.size(); ++out_idx) {
      const auto& output = outputs.at(out_idx);
      // inplace special case
      if (inplace_reverse_idx_map.find(out_idx) !=
          inplace_reverse_idx_map.end()) {
        size_t in_idx = inplace_reverse_idx_map.at(out_idx);
        const auto& input_range = ctx.InputRangeAt(in_idx);
        const auto& input_tensor = ctx.InputAt(input_range.first);
        // inplace optional [Tensor or vector<Tensor>], un-initialized tensor.
        if (paddle::framework::detail::IsOptionalVar(output) &&
            !input_tensor.initialized()) {
          VLOG(7) << "Custom operator add output " << output
                  << " to CustomOpKernelContext. Add un-initialized tensor "
                     "because the inplace optional input is None";
          ctx.EmplaceBackOutput(std::move(paddle::Tensor()));
          continue;
        }
        /// inplace vector<Tensor>, initialized tensor.
        if (paddle::framework::detail::IsDuplicableVar(output)) {
          std::vector<paddle::Tensor> empty_tensors;
          size_t vector_size = input_range.second - input_range.first;
          empty_tensors.resize(vector_size);
          for (size_t i = 0; i < vector_size; ++i) {
            empty_tensors[i] = InitializedEmptyTensor();
          }
          VLOG(7) << "Custom operator add output " << output
                  << " to CustomOpKernelContext. Add vector<tensor> size = "
                  << empty_tensors.size();
          ctx.EmplaceBackOutputs(std::move(empty_tensors));
          continue;
        }
      }
      VLOG(7) << "Custom operator add output " << output
              << " to CustomOpKernelContext. Add initialized Tensor because "
                 "using general or inplace mechanism";
      // general Tensor or inplace Tensor, initialized tensor.
      ctx.EmplaceBackOutput(std::move(InitializedEmptyTensor()));
    }

643
    // handle inplace map
644 645
    ctx.UpdatePlainOutputs(inputs, outputs, inplace_map);
    VLOG(7) << "Run Kernel of Custom Op: " << op_type;
646
    (*paddle::OpMetaInfoHelper::GetKernelFn(vec_map[0]))(&ctx);
647
    ctx.AssignInplaceOutputs();
W
wanghuancoder 已提交
648

649 650 651
    // handle optional None output when construct backward graph
    for (size_t i = 0; i < ctx.OutputRange().size(); i++) {
      if (ctx.OutputRangeAt(i).first + 1 == ctx.OutputRangeAt(i).second) {
652 653
        paddle::Tensor* out_tensor =
            ctx.MutableOutputAt(ctx.OutputRangeAt(i).first);
654 655
        if (!out_tensor->initialized()) {
          PADDLE_ENFORCE(
656
              paddle::framework::detail::IsOptionalVar(outputs.at(i)),
657 658 659 660 661
              phi::errors::InvalidArgument(
                  "Custom operator's %d-th output is not initialized. "
                  "Please check your implementation again. If you are "
                  "using inplace optional output, then you must use "
                  "`paddle::Optional` to decorate this output",
662
                  i));
663 664 665 666 667 668
          // We can also consider using `autograd_meta` to tolerant nullptr.
          out_tensor->set_autograd_meta(std::make_shared<egr::AutogradMeta>());
        }
      }
    }

W
wanghuancoder 已提交
669
    VLOG(7) << "Get AutogradMeta for inputs and outputs for Custom Op";
670 671 672 673 674 675 676 677 678
    size_t slot_ins_num = ctx.InputRange().size();
    size_t slot_outs_num = ctx.OutputRange().size();
    VLOG(7) << "We got slot num of ins is: " << slot_ins_num;
    VLOG(7) << "We got slot num of outs is: " << slot_outs_num;
    std::vector<egr::AutogradMeta*> ins_auto_grad_metas =
        egr::EagerUtils::nullable_autograd_meta(*ctx.AllMutableInput());
    std::vector<egr::AutogradMeta*> outs_auto_grad_metas =
        egr::EagerUtils::unsafe_autograd_meta(*ctx.AllMutableOutput());

W
wanghuancoder 已提交
679
    bool require_any_grad = false;
680 681
    bool trace_backward = true;
    for (size_t i = 0; i < ins_auto_grad_metas.size(); ++i) {
W
wanghuancoder 已提交
682 683
      require_any_grad =
          require_any_grad || egr::EagerUtils::ComputeRequireGrad(
684
                                  trace_backward, ins_auto_grad_metas[i]);
685
    }
686

687
    // handle inplace map
688 689 690 691 692 693 694 695 696 697
    if (!inplace_map.empty()) {
      for (size_t i = 0; i < ctx.InputRange().size(); i++) {
        if (inplace_map.find(inputs[i]) == inplace_map.end()) {
          continue;
        }
        const auto& input_pair = ctx.InputRangeAt(i);
        for (size_t j = input_pair.first; j < input_pair.second; j++) {
          egr::EagerUtils::CheckInplace(
              ctx.InputAt(j), ins_auto_grad_metas[j], require_any_grad);
          if (ctx.MutableInputAt(j).defined()) {
698
            // Bump Inplace Version
699 700
            ctx.MutableInputAt(j).bump_inplace_version();
            VLOG(3) << "Custom operator: Tensor(" << ctx.InputAt(j).name()
701 702
                    << ") uses Inplace Strategy.";
          }
703 704 705 706
        }
      }
    }

W
wanghuancoder 已提交
707 708 709
    if (require_any_grad && (vec_map.size() > 1)) {
      VLOG(6) << " Construct Grad for Custom Op: " << op_type;
      ConstructFwdAndBwdMap(vec_map, op_type);
710 711
      for (auto& outs_auto_grad_meta : outs_auto_grad_metas) {
        egr::EagerUtils::PassStopGradient(false, outs_auto_grad_meta);
W
wanghuancoder 已提交
712
      }
713 714 715 716 717
      // Note(HongyuJia): In dygraph eager mode, CheckInplace makes sure leaf
      // nodes set stop_gradient=True. However, dygraph mode can also outputs
      // lead nodes' gradients (For example, we can get x.grad after x.add_(y)).
      // To be consistent with dygraph mode, we have to PassStopGradient for all
      // inplaced ins_auto_grad_metas.
718 719 720 721 722 723
      const auto& inplace_index_map = ctx.GetInplaceIndexMap();
      for (auto pair : inplace_index_map) {
        const auto& size_pair = ctx.InputRangeAt(pair.first);
        for (size_t i = size_pair.first; i < size_pair.second; ++i) {
          egr::EagerUtils::PassStopGradient(false, ins_auto_grad_metas[i]);
        }
724
      }
W
wanghuancoder 已提交
725
      auto grad_node = std::make_shared<egr::RunCustomOpNode>(
726 727
          slot_outs_num, slot_ins_num, op_type);
      const auto& slot_map =
W
wanghuancoder 已提交
728
          egr::Controller::Instance().GetCustomEdgesSlotMap().at(op_type);
729

W
wanghuancoder 已提交
730 731
      // Prepare Grad outputs
      size_t no_grad_cnt = 0;
732
      for (size_t i = 0; i < slot_ins_num; i++) {
733 734
        const std::vector<paddle::Tensor>& in_tensors = ctx.InputsBetween(
            ctx.InputRangeAt(i).first, ctx.InputRangeAt(i).second);
W
wanghuancoder 已提交
735 736

        if (slot_map[0][0].find(i) != slot_map[0][0].end()) {
737
          grad_node->SetGradOutMeta(in_tensors, slot_map[0][0].at(i));
W
wanghuancoder 已提交
738
        } else {
739
          grad_node->SetGradOutMeta(in_tensors, slot_ins_num - 1 - no_grad_cnt);
W
wanghuancoder 已提交
740 741 742 743
          no_grad_cnt++;
        }
      }
      // Prepare Grad inputs with grad of fwd outputs
744 745 746
      for (size_t i = 0; i < slot_outs_num; i++) {
        const auto& size_pair = ctx.OutputRangeAt(i);
        const std::vector<paddle::Tensor>& out_tensors =
C
co63oc 已提交
747
            ctx.OutputsBetween(size_pair.first, size_pair.second);
748 749 750 751 752 753
        for (size_t j = size_pair.first; j < size_pair.second; j++) {
          // SetOutRankWithSlot: slot_id = i, rank = j - size_pair.first
          outs_auto_grad_metas[j]->SetSingleOutRankWithSlot(
              i, j - size_pair.first);
          egr::EagerUtils::SetHistory(outs_auto_grad_metas[j], grad_node);
        }
W
wanghuancoder 已提交
754 755
        grad_node->SetGradInMeta(out_tensors, i);
      }
756

W
wanghuancoder 已提交
757
      // Prepare Grad inputs with fwd outputs
758 759 760 761
      for (auto item : slot_map[0][2]) {
        VLOG(7) << "Prepare fwd_outs: " << item.first
                << " to grad_inputs: " << item.second;
        grad_node->fwd_outs[item.second] =
W
wanghuancoder 已提交
762
            egr::RunCustomOpNode::ConstructTensorWrapper(
763 764
                ctx.OutputsBetween(ctx.OutputRangeAt(item.first).first,
                                   ctx.OutputRangeAt(item.first).second));
W
wanghuancoder 已提交
765
      }
766

W
wanghuancoder 已提交
767
      // Prepare Grad inputs with fwd inputs
768 769 770 771
      for (auto item : slot_map[0][3]) {
        VLOG(7) << "Prepare fwd_ins: " << item.first
                << " to grad_inputs: " << item.second;
        grad_node->fwd_ins[item.second] =
W
wanghuancoder 已提交
772
            egr::RunCustomOpNode::ConstructTensorWrapper(
773 774
                ctx.InputsBetween(ctx.InputRangeAt(item.first).first,
                                  ctx.InputRangeAt(item.first).second));
W
wanghuancoder 已提交
775
      }
776

777 778
      const std::vector<paddle::any>& res_attrs = ctx.Attrs();
      std::vector<paddle::any> attrs(res_attrs.size());
W
wanghuancoder 已提交
779
      // Prepare attrs for Grad node
780 781 782 783
      for (auto item : slot_map[0][4]) {
        VLOG(7) << "Prepare fwd attrs: " << item.first
                << " to grad_attrs: " << item.second;
        attrs[item.second] = res_attrs[item.first];
W
wanghuancoder 已提交
784 785
      }
      grad_node->SetAttrs(attrs);
786 787
    }
  }
788
  return ToPyObject(*ctx.AllMutableOutput());
789 790 791
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

792 793
static PyObject* eager_api_sparse_coo_tensor(PyObject* self,
                                             PyObject* args,
794 795 796 797 798 799
                                             PyObject* kwargs) {
  EAGER_TRY
  auto non_zero_indices = CastPyArg2Tensor(PyTuple_GET_ITEM(args, 0), 0);
  auto non_zero_elements = CastPyArg2Tensor(PyTuple_GET_ITEM(args, 1), 1);
  auto dense_shape = CastPyArg2VectorOfInt(PyTuple_GET_ITEM(args, 2), 2);
  auto stop_gradient = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 3), 3);
800
  paddle::Tensor tensor;
W
wanghuancoder 已提交
801 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 827 828 829
  {
    eager_gil_scoped_release guard;
    PADDLE_ENFORCE(non_zero_indices.is_dense_tensor(),
                   paddle::platform::errors::Fatal(
                       "the non-zero indices must be a DenseTensor."));
    PADDLE_ENFORCE(non_zero_elements.is_dense_tensor(),
                   paddle::platform::errors::Fatal(
                       "the non-zero elements must be a DenseTensor."));
    auto dense_indices =
        std::dynamic_pointer_cast<phi::DenseTensor>(non_zero_indices.impl());
    auto dense_elements =
        std::dynamic_pointer_cast<phi::DenseTensor>(non_zero_elements.impl());
    // TODO(zhangkaihuo): After creating SparseCooTensor, call coalesced() to
    // sort and merge duplicate indices
    std::shared_ptr<phi::SparseCooTensor> coo_tensor =
        std::make_shared<phi::SparseCooTensor>(
            *dense_indices, *dense_elements, phi::make_ddim(dense_shape));
    tensor.set_impl(coo_tensor);
    auto name =
        egr::Controller::Instance().GenerateUniqueName("generated_tensor");
    tensor.set_name(name);
    auto autograd_meta = egr::EagerUtils::autograd_meta(&tensor);
    autograd_meta->SetStopGradient(static_cast<bool>(stop_gradient));
    if (!autograd_meta->GetMutableGradNode()) {
      VLOG(3) << "Tensor(" << name
              << ") doesn't have GradNode, add GradNodeAccumulation to it.";
      autograd_meta->SetGradNode(
          std::make_shared<egr::GradNodeAccumulation>(autograd_meta));
    }
830 831 832 833 834
  }
  return ToPyObject(tensor);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

835 836
static PyObject* eager_api_sparse_csr_tensor(PyObject* self,
                                             PyObject* args,
837 838 839 840 841 842 843
                                             PyObject* kwargs) {
  EAGER_TRY
  auto non_zero_crows = CastPyArg2Tensor(PyTuple_GET_ITEM(args, 0), 0);
  auto non_zero_cols = CastPyArg2Tensor(PyTuple_GET_ITEM(args, 1), 1);
  auto non_zero_elements = CastPyArg2Tensor(PyTuple_GET_ITEM(args, 2), 2);
  auto dense_shape = CastPyArg2VectorOfInt(PyTuple_GET_ITEM(args, 3), 3);
  auto stop_gradient = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 4), 4);
844
  paddle::Tensor tensor;
W
wanghuancoder 已提交
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
  {
    eager_gil_scoped_release guard;
    PADDLE_ENFORCE(non_zero_crows.is_dense_tensor(),
                   paddle::platform::errors::Fatal(
                       "the compressed non-zero rows must be a DenseTensor."));
    PADDLE_ENFORCE(non_zero_cols.is_dense_tensor(),
                   paddle::platform::errors::Fatal(
                       "the non-zero cols must be a DenseTensor."));
    PADDLE_ENFORCE(non_zero_elements.is_dense_tensor(),
                   paddle::platform::errors::Fatal(
                       "the non-zero elements must be a DenseTensor."));

    auto dense_crows =
        std::dynamic_pointer_cast<phi::DenseTensor>(non_zero_crows.impl());
    auto dense_cols =
        std::dynamic_pointer_cast<phi::DenseTensor>(non_zero_cols.impl());
    auto dense_elements =
        std::dynamic_pointer_cast<phi::DenseTensor>(non_zero_elements.impl());
    std::shared_ptr<phi::SparseCsrTensor> csr_tensor =
        std::make_shared<phi::SparseCsrTensor>(*dense_crows,
                                               *dense_cols,
                                               *dense_elements,
                                               phi::make_ddim(dense_shape));
    tensor.set_impl(csr_tensor);
    auto name =
        egr::Controller::Instance().GenerateUniqueName("generated_tensor");
    tensor.set_name(name);
    auto autograd_meta = egr::EagerUtils::autograd_meta(&tensor);
    autograd_meta->SetStopGradient(static_cast<bool>(stop_gradient));
    if (!autograd_meta->GetMutableGradNode()) {
      VLOG(3) << "Tensor(" << name
              << ") have not GradNode, add GradNodeAccumulation for it.";
      autograd_meta->SetGradNode(
          std::make_shared<egr::GradNodeAccumulation>(autograd_meta));
    }
880 881 882 883
  }
  return ToPyObject(tensor);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}
884 885 886 887 888 889 890 891

static PyObject* eager_api_register_saved_tensors_hooks(PyObject* self,
                                                        PyObject* args,
                                                        PyObject* kwargs) {
  EAGER_TRY
  if (egr::Controller::Instance().HasGrad()) {
    auto pack_hook = PyTuple_GET_ITEM(args, 0);
    auto unpack_hook = PyTuple_GET_ITEM(args, 1);
892 893 894
    egr::SavedTensorsHooks::GetInstance().SetHooks(
        std::make_shared<PackHook>(pack_hook),
        std::make_shared<UnPackHook>(unpack_hook));
895 896 897 898 899 900 901 902 903 904 905 906 907 908
  }
  RETURN_PY_NONE
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

static PyObject* eager_api_reset_saved_tensors_hooks(PyObject* self,
                                                     PyObject* args,
                                                     PyObject* kwargs) {
  EAGER_TRY
  egr::SavedTensorsHooks::GetInstance().ResetHooks();
  RETURN_PY_NONE
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
909
#if defined(PADDLE_WITH_CUDA)
910 911
static PyObject* eager_api_async_read(PyObject* self,
                                      PyObject* args,
W
wanghuancoder 已提交
912 913 914 915 916 917 918 919
                                      PyObject* kwargs) {
  EAGER_TRY
  auto& src = GetTensorFromArgs("async_read", "src", args, 0, false);
  auto& dst = GetTensorFromArgs("async_read", "dst", args, 1, false);
  auto& index = GetTensorFromArgs("async_read", "index", args, 2, false);
  auto& buffer = GetTensorFromArgs("async_read", "buffer", args, 3, false);
  auto& offset = GetTensorFromArgs("async_read", "offset", args, 4, false);
  auto& count = GetTensorFromArgs("async_read", "count", args, 5, false);
W
wanghuancoder 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
  {
    eager_gil_scoped_release guard;
    PADDLE_ENFORCE_EQ(
        src.is_gpu_pinned(),
        true,
        platform::errors::InvalidArgument("Required `src` device should be "
                                          "CUDAPinnedPlace, but received %d.",
                                          src.place()));
    PADDLE_ENFORCE_EQ(
        dst.is_gpu(),
        true,
        platform::errors::InvalidArgument(
            "Required `dst` device should be CUDAPlace, but received %d.",
            dst.place()));
    PADDLE_ENFORCE_EQ(
        index.is_cpu(),
        true,
        platform::errors::InvalidArgument(
            "Required `index` device should be CPUPlace, but received %d.",
            index.place()));
    PADDLE_ENFORCE_EQ(buffer.is_gpu_pinned(),
                      true,
W
wanghuancoder 已提交
942
                      platform::errors::InvalidArgument(
W
wanghuancoder 已提交
943 944 945 946 947 948 949 950 951
                          "Required `buffer` device should be CUDAPinnedPlace, "
                          "but received %d.",
                          buffer.place()));
    PADDLE_ENFORCE_EQ(
        offset.is_cpu(),
        true,
        platform::errors::InvalidArgument(
            "Required `offset` device should be CPUPlace, but received %d.",
            offset.place()));
W
wanghuancoder 已提交
952
    PADDLE_ENFORCE_EQ(
W
wanghuancoder 已提交
953 954
        count.is_cpu(),
        true,
W
wanghuancoder 已提交
955
        platform::errors::InvalidArgument(
W
wanghuancoder 已提交
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            "Required `count` device should be CPUPlace, but received %d.",
            count.place()));

    auto& src_tensor = src;
    auto* dst_tensor = &dst;
    auto& index_tensor = index;
    auto* buffer_tensor = &buffer;
    auto& offset_tensor = offset;
    auto& count_tensor = count;
    auto* dst_data = dst_tensor->mutable_data<float>(dst.place());
    const auto& deviceId = paddle::platform::GetCurrentDeviceId();

    PADDLE_ENFORCE_EQ(src_tensor.dims().size(),
                      dst_tensor->dims().size(),
                      platform::errors::InvalidArgument(
                          "`src` and `dst` should have same tensor shape, "
                          "except for the first dimension."));
    PADDLE_ENFORCE_EQ(src_tensor.dims().size(),
                      buffer_tensor->dims().size(),
                      platform::errors::InvalidArgument(
                          "`src` and `buffer` should have same tensor shape, "
                          "except for the first dimension."));
    for (int i = 1; i < src_tensor.dims().size(); i++) {
      PADDLE_ENFORCE_EQ(
          src_tensor.dims()[i],
          dst_tensor->dims()[i],
          platform::errors::InvalidArgument(
              "`src` and `dst` should have the same tensor shape, "
              "except for the first dimension."));
      PADDLE_ENFORCE_EQ(
          src_tensor.dims()[i],
          buffer_tensor->dims()[i],
          platform::errors::InvalidArgument(
              "`src` and `buffer` should have the same tensor shape, "
              "except for the first dimension."));
    }
    PADDLE_ENFORCE_EQ(index_tensor.dims().size(),
                      1,
                      platform::errors::InvalidArgument(
                          "`index` tensor should be one-dimensional."));

    auto stream = paddle::platform::get_current_stream(deviceId)->raw_stream();

    int64_t numel = 0;  // total copy length
    int64_t copy_flag = offset_tensor.dims()[0];
    int64_t size = src_tensor.numel() / src_tensor.dims()[0];

    if (copy_flag != 0) {
      PADDLE_ENFORCE_EQ(offset_tensor.dims().size(),
                        1,
                        platform::errors::InvalidArgument(
                            "`offset` tensor should be one-dimensional."));
      PADDLE_ENFORCE_EQ(count_tensor.dims().size(),
                        1,
                        platform::errors::InvalidArgument(
                            "`count` tensor should be one-dimensional."));
      PADDLE_ENFORCE_EQ(offset_tensor.numel(),
                        count_tensor.numel(),
                        platform::errors::InvalidArgument(
                            "`offset` and `count` tensor size dismatch."));
      auto* offset_data = offset_tensor.data<int64_t>();
      auto* count_data = count_tensor.data<int64_t>();
      for (int64_t i = 0; i < count_tensor.numel(); i++) {
        numel += count_data[i];
      }
      PADDLE_ENFORCE_LE(numel + index_tensor.numel(),
                        buffer_tensor->dims()[0],
                        platform::errors::InvalidArgument(
                            "Buffer tensor size is too small."));
      PADDLE_ENFORCE_LE(numel + index_tensor.numel(),
                        dst_tensor->dims()[0],
                        platform::errors::InvalidArgument(
                            "Target tensor size is too small."));

      int64_t src_offset, dst_offset = 0, c;
      auto* src_data = src_tensor.data<float>();
      for (int64_t i = 0; i < offset_tensor.numel(); i++) {
        src_offset = offset_data[i], c = count_data[i];
        PADDLE_ENFORCE_LE(src_offset + c,
                          src_tensor.dims()[0],
                          platform::errors::InvalidArgument(
                              "Invalid offset or count index."));
        PADDLE_ENFORCE_LE(dst_offset + c,
                          dst_tensor->dims()[0],
                          platform::errors::InvalidArgument(
                              "Invalid offset or count index."));
        cudaMemcpyAsync(dst_data + (dst_offset * size),
                        src_data + (src_offset * size),
                        c * size * sizeof(float),
                        cudaMemcpyHostToDevice,
                        stream);
        dst_offset += c;
      }
    } else {
      PADDLE_ENFORCE_LE(index_tensor.numel(),
                        buffer_tensor->dims()[0],
                        platform::errors::InvalidArgument(
                            "Buffer tensor size is too small."));
    }

    // Select the index data to the buffer
1057 1058 1059
    auto index_select = [](const paddle::Tensor& src_tensor,
                           const paddle::Tensor& index_tensor,
                           paddle::Tensor* buffer_tensor) {
W
wanghuancoder 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
      auto* src_data = src_tensor.data<float>();
      auto* index_data = index_tensor.data<int64_t>();
      auto* buffer_data = buffer_tensor->data<float>();
      const int& slice_size = src_tensor.numel() / src_tensor.dims()[0];
      const int& copy_bytes = slice_size * sizeof(float);
      int64_t c = 0;
      for (int64_t i = 0; i < index_tensor.numel(); i++) {
        std::memcpy(buffer_data + c * slice_size,
                    src_data + index_data[i] * slice_size,
                    copy_bytes);
        c += 1;
      }
    };
    index_select(src_tensor, index_tensor, buffer_tensor);

    // Copy the data to device memory
    cudaMemcpyAsync(dst_data + (numel * size),
                    buffer_tensor->data<float>(),
                    index_tensor.numel() * size * sizeof(float),
                    cudaMemcpyHostToDevice,
                    stream);
W
wanghuancoder 已提交
1081
  }
W
wanghuancoder 已提交
1082 1083 1084
  RETURN_PY_NONE
  EAGER_CATCH_AND_THROW_RETURN_NULL
}
W
wanghuancoder 已提交
1085

W
wanghuancoder 已提交
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
static PyObject* eager_api_async_write(PyObject* self,
                                       PyObject* args,
                                       PyObject* kwargs) {
  EAGER_TRY
  auto& src = GetTensorFromArgs("async_write", "src", args, 0, false);
  auto& dst = GetTensorFromArgs("async_write", "dst", args, 1, false);
  auto& offset = GetTensorFromArgs("async_write", "offset", args, 2, false);
  auto& count = GetTensorFromArgs("async_write", "count", args, 3, false);
  {
    eager_gil_scoped_release guard;
    PADDLE_ENFORCE_EQ(
        src.is_gpu(),
        true,
        platform::errors::InvalidArgument(
            "Required `src` device should be CUDAPlace, but received %d. ",
            src.place()));
    PADDLE_ENFORCE_EQ(dst.is_gpu_pinned(),
                      true,
                      platform::errors::InvalidArgument(
                          "Required `dst` device should be CUDAPinnedPlace, "
                          "but received %d. ",
                          dst.place()));
    PADDLE_ENFORCE_EQ(
        offset.is_cpu(),
        true,
        platform::errors::InvalidArgument("Required `offset` device should "
                                          "be CPUPlace, but received %d. ",
                                          offset.place()));
    PADDLE_ENFORCE_EQ(
        count.is_cpu(),
        true,
        platform::errors::InvalidArgument(
            "Required `count` device should be CPUPlace, but received %d. ",
            count.place()));
W
wanghuancoder 已提交
1120

W
wanghuancoder 已提交
1121 1122 1123 1124 1125 1126 1127
    // TODO(daisiming): In future, add index as arguments following
    // async_read.
    auto& src_tensor = src;
    auto* dst_tensor = &dst;
    auto& offset_tensor = offset;
    auto& count_tensor = count;
    const auto& deviceId = paddle::platform::GetCurrentDeviceId();
W
wanghuancoder 已提交
1128

1129 1130
    PADDLE_ENFORCE_EQ(offset_tensor.dims().size(),
                      1,
W
wanghuancoder 已提交
1131 1132
                      platform::errors::InvalidArgument(
                          "`offset` tensor should be one-dimensional."));
1133 1134
    PADDLE_ENFORCE_EQ(count_tensor.dims().size(),
                      1,
W
wanghuancoder 已提交
1135 1136
                      platform::errors::InvalidArgument(
                          "`count` tensor should be one-dimensional."));
1137 1138
    PADDLE_ENFORCE_EQ(offset_tensor.numel(),
                      count_tensor.numel(),
W
wanghuancoder 已提交
1139 1140
                      platform::errors::InvalidArgument(
                          "`offset` and `count` tensor size dismatch."));
W
wanghuancoder 已提交
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    PADDLE_ENFORCE_EQ(src_tensor.dims().size(),
                      dst_tensor->dims().size(),
                      platform::errors::InvalidArgument(
                          "`src` and `dst` should have the same tensor shape, "
                          "except for the first dimension."));
    for (int i = 1; i < src_tensor.dims().size(); i++) {
      PADDLE_ENFORCE_EQ(
          src_tensor.dims()[i],
          dst_tensor->dims()[i],
          platform::errors::InvalidArgument(
              "`src` and `dst` should have the same tensor shape, "
              "except for the first dimension."));
W
wanghuancoder 已提交
1153 1154
    }

W
wanghuancoder 已提交
1155 1156 1157
    auto stream = paddle::platform::get_current_stream(deviceId)->raw_stream();

    int64_t size = src_tensor.numel() / src_tensor.dims()[0];
W
wanghuancoder 已提交
1158
    auto* src_data = src_tensor.data<float>();
W
wanghuancoder 已提交
1159 1160 1161 1162
    auto* dst_data = dst_tensor->data<float>();
    const int64_t* offset_data = offset_tensor.data<int64_t>();
    const int64_t* count_data = count_tensor.data<int64_t>();
    int64_t src_offset = 0, dst_offset, c;
W
wanghuancoder 已提交
1163
    for (int64_t i = 0; i < offset_tensor.numel(); i++) {
W
wanghuancoder 已提交
1164
      dst_offset = offset_data[i], c = count_data[i];
W
wanghuancoder 已提交
1165
      PADDLE_ENFORCE_LE(
1166 1167
          src_offset + c,
          src_tensor.dims()[0],
W
wanghuancoder 已提交
1168
          platform::errors::InvalidArgument("Invalid offset or count index"));
W
wanghuancoder 已提交
1169
      PADDLE_ENFORCE_LE(
1170 1171
          dst_offset + c,
          dst_tensor->dims()[0],
W
wanghuancoder 已提交
1172
          platform::errors::InvalidArgument("Invalid offset or count index"));
W
wanghuancoder 已提交
1173
      cudaMemcpyAsync(dst_data + (dst_offset * size),
1174 1175
                      src_data + (src_offset * size),
                      c * size * sizeof(float),
W
wanghuancoder 已提交
1176
                      cudaMemcpyDeviceToHost,
1177
                      stream);
W
wanghuancoder 已提交
1178
      src_offset += c;
W
wanghuancoder 已提交
1179 1180
    }
  }
1181
  RETURN_PY_NONE
W
wanghuancoder 已提交
1182 1183
  EAGER_CATCH_AND_THROW_RETURN_NULL
}
1184

1185 1186
static PyObject* eager_api_to_uva_tensor(PyObject* self,
                                         PyObject* args,
1187 1188 1189
                                         PyObject* kwargs) {
  EAGER_TRY
  VLOG(4) << "Running in eager_api_to_uva_tensor.";
1190 1191
  auto new_tensor = std::shared_ptr<paddle::Tensor>(
      new paddle::Tensor(egr::Controller::Instance().GenerateUniqueName()));
1192 1193 1194
  PyObject* obj = PyTuple_GET_ITEM(args, 0);
  auto array = py::cast<py::array>(py::handle(obj));

1195 1196 1197 1198 1199 1200 1201
  Py_ssize_t args_num = PyTuple_Size(args);
  int64_t device_id = 0;
  if (args_num > 1) {
    PyObject* Py_device_id = PyTuple_GET_ITEM(args, 1);
    if (Py_device_id) {
      device_id = CastPyArg2AttrLong(Py_device_id, 1);
    }
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
  }

  if (py::isinstance<py::array_t<int32_t>>(array)) {
    SetUVATensorFromPyArray<int32_t>(new_tensor, array, device_id);
  } else if (py::isinstance<py::array_t<int64_t>>(array)) {
    SetUVATensorFromPyArray<int64_t>(new_tensor, array, device_id);
  } else if (py::isinstance<py::array_t<float>>(array)) {
    SetUVATensorFromPyArray<float>(new_tensor, array, device_id);
  } else if (py::isinstance<py::array_t<double>>(array)) {
    SetUVATensorFromPyArray<double>(new_tensor, array, device_id);
  } else if (py::isinstance<py::array_t<int8_t>>(array)) {
    SetUVATensorFromPyArray<int8_t>(new_tensor, array, device_id);
  } else if (py::isinstance<py::array_t<int16_t>>(array)) {
    SetUVATensorFromPyArray<int16_t>(new_tensor, array, device_id);
  } else if (py::isinstance<py::array_t<paddle::platform::float16>>(array)) {
1217 1218
    SetUVATensorFromPyArray<paddle::platform::float16>(
        new_tensor, array, device_id);
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
  } else if (py::isinstance<py::array_t<bool>>(array)) {
    SetUVATensorFromPyArray<bool>(new_tensor, array, device_id);
  } else {
    // obj may be any type, obj.cast<py::array>() may be failed,
    // then the array.dtype will be string of unknown meaning.
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Input object type error or incompatible array data type. "
        "tensor.set() supports array with bool, float16, float32, "
        "float64, int8, int16, int32, int64,"
        "please check your input or input array data type."));
  }
  return ToPyObject(*(new_tensor.get()));
  EAGER_CATCH_AND_THROW_RETURN_NULL
}
W
wanghuancoder 已提交
1233
#endif
1234

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
static PyObject* eager_api__add_backward_final_hook(PyObject* self,
                                                    PyObject* args,
                                                    PyObject* kwargs) {
  EAGER_TRY
  PyObject* hook_func = PyTuple_GET_ITEM(args, 0);
  egr::Controller::Instance().RegisterBackwardFinalHook(
      std::make_shared<PyVoidHook>(hook_func));
  RETURN_PY_NONE
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1246 1247 1248 1249 1250 1251 1252 1253
static PyObject* eager_api_set_master_grads(PyObject* self,
                                            PyObject* args,
                                            PyObject* kwargs) {
  EAGER_TRY
  // tensor_list is a list of model parameters.
  auto tensor_list = CastPyArg2VectorOfTensor(PyTuple_GET_ITEM(args, 0), 0);
  for (auto& tensor : tensor_list) {
    VLOG(6) << "set master_grad for tensor: " << tensor.name();
1254
    if (!egr::EagerUtils::IsLeafTensor(tensor)) {
1255 1256
      continue;
    }
1257 1258 1259 1260
    paddle::Tensor* grad = egr::EagerUtils::mutable_grad(tensor);
    PADDLE_ENFORCE_NE(grad,
                      nullptr,
                      paddle::platform::errors::Fatal(
1261
                          "Detected nullptr grad"
1262 1263
                          "Please check if you have manually cleared"
                          "the grad inside autograd_meta"));
1264 1265
    if ((*grad).initialized() && ((*grad).dtype() == phi::DataType::FLOAT16 ||
                                  (*grad).dtype() == phi::DataType::BFLOAT16)) {
1266 1267 1268 1269
      auto master_grad =
          paddle::experimental::cast(*grad, phi::DataType::FLOAT32);
      grad->set_impl(master_grad.impl());
    }
1270
    VLOG(6) << "finish setting master_grad for tensor: " << tensor.name();
1271 1272 1273 1274 1275
  }
  RETURN_PY_NONE
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

1276
PyMethodDef variable_functions[] = {
1277
    // TODO(jiabin): Remove scale when we have final state tests
1278
    {"scale",
1279
     (PyCFunction)(void (*)())eager_api_scale,
1280
     METH_VARARGS | METH_KEYWORDS,
1281
     nullptr},
1282
    {"_add_backward_final_hook",
1283
     (PyCFunction)(void (*)())eager_api__add_backward_final_hook,
1284
     METH_VARARGS | METH_KEYWORDS,
1285
     nullptr},
1286
    {"run_backward",
1287
     (PyCFunction)(void (*)())eager_api_run_backward,
1288
     METH_VARARGS | METH_KEYWORDS,
1289
     nullptr},
1290
    {"run_partial_grad",
1291
     (PyCFunction)(void (*)())eager_api_run_partial_grad,
1292
     METH_VARARGS | METH_KEYWORDS,
1293
     nullptr},
1294 1295 1296 1297
    {"_get_custom_operator_inplace_map",
     (PyCFunction)(void (*)(
         void))eager_api__get_custom_operator_inplace_reverse_idx,
     METH_VARARGS | METH_KEYWORDS,
1298
     nullptr},
1299
    {"_run_custom_op",
1300
     (PyCFunction)(void (*)())eager_api_run_custom_op,
1301
     METH_VARARGS | METH_KEYWORDS,
1302
     nullptr},
1303
    {"tensor_copy",
1304
     (PyCFunction)(void (*)())eager_api_tensor_copy,
1305
     METH_VARARGS | METH_KEYWORDS,
1306
     nullptr},
1307
    {"get_all_grads",
1308
     (PyCFunction)(void (*)())eager_api_get_all_grads,
1309
     METH_VARARGS | METH_KEYWORDS,
1310
     nullptr},
1311
    {"get_grads_lists",
1312
     (PyCFunction)(void (*)())eager_api_get_grads_lists,
1313
     METH_VARARGS | METH_KEYWORDS,
1314
     nullptr},
1315
    {"get_grads_types",
1316
     (PyCFunction)(void (*)())eager_api_get_grads_types,
1317
     METH_VARARGS | METH_KEYWORDS,
1318
     nullptr},
1319
    {"read_next_tensor_list",
1320
     (PyCFunction)(void (*)())eager_api_read_next_tensor_list,
1321
     METH_VARARGS | METH_KEYWORDS,
1322
     nullptr},
1323
    {"jit_function_call",
1324
     (PyCFunction)(void (*)())eager_api_jit_function_call,
1325
     METH_VARARGS | METH_KEYWORDS,
1326
     nullptr},
1327 1328
    /**sparse functions**/
    {"sparse_coo_tensor",
1329
     (PyCFunction)(void (*)())eager_api_sparse_coo_tensor,
1330
     METH_VARARGS | METH_KEYWORDS,
1331
     nullptr},
1332
    {"sparse_csr_tensor",
1333
     (PyCFunction)(void (*)())eager_api_sparse_csr_tensor,
1334
     METH_VARARGS | METH_KEYWORDS,
1335
     nullptr},
1336
    {"register_saved_tensors_hooks",
1337
     (PyCFunction)(void (*)())eager_api_register_saved_tensors_hooks,
1338
     METH_VARARGS | METH_KEYWORDS,
1339
     nullptr},
1340
    {"reset_saved_tensors_hooks",
1341
     (PyCFunction)(void (*)())eager_api_reset_saved_tensors_hooks,
1342
     METH_VARARGS | METH_KEYWORDS,
1343
     nullptr},
1344 1345
    /**amp functions**/
    {"set_master_grads",
1346
     (PyCFunction)(void (*)())eager_api_set_master_grads,
1347
     METH_VARARGS | METH_KEYWORDS,
1348
     nullptr},
1349
/**sparse functions**/
W
wanghuancoder 已提交
1350
#if defined(PADDLE_WITH_CUDA)
1351
    {"async_read",
1352
     (PyCFunction)(void (*)())eager_api_async_read,
1353
     METH_VARARGS | METH_KEYWORDS,
1354
     nullptr},
1355
    {"async_write",
1356
     (PyCFunction)(void (*)())eager_api_async_write,
1357
     METH_VARARGS | METH_KEYWORDS,
1358
     nullptr},
1359
    {"to_uva_tensor",
1360
     (PyCFunction)(void (*)())eager_api_to_uva_tensor,
1361
     METH_VARARGS | METH_KEYWORDS,
1362
     nullptr},
W
wanghuancoder 已提交
1363
#endif
1364
    {nullptr, nullptr, 0, nullptr}};
1365 1366 1367 1368

void BindFunctions(PyObject* module) {
  if (PyModule_AddFunctions(module, variable_functions) < 0) {
    PADDLE_THROW(platform::errors::Fatal(
1369
        "Init Paddle error in BindFunctions(PyModule_AddFunctions)."));
1370 1371 1372 1373 1374 1375
    return;
  }
}

}  // namespace pybind
}  // namespace paddle