eager.cc 54.8 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
#include "paddle/fluid/pybind/eager.h"

14
#include <Python.h>
15 16 17 18
// Avoid a problem with copysign defined in pyconfig.h on Windows.
#ifdef copysign
#undef copysign
#endif
19 20 21 22

#include <string>
#include <vector>

23
#include "paddle/fluid/eager/accumulation/accumulation_node.h"
24 25 26
#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/autograd_meta.h"
#include "paddle/fluid/eager/utils.h"
27
#include "paddle/fluid/framework/convert_utils.h"
28 29 30 31
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/pybind/eager_utils.h"
32 33 34
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/dense_tensor.h"
35
#include "pybind11/detail/internals.h"
36 37
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
38
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
39
#include "paddle/fluid/framework/phi_utils.h"
40
#include "paddle/fluid/framework/python_headers.h"
41
#include "paddle/fluid/pybind/exception.h"
42
#include "paddle/fluid/pybind/tensor_py.h"
J
Jack Zhou 已提交
43
#include "paddle/phi/core/string_tensor.h"
L
LiYuRio 已提交
44 45 46 47 48 49 50 51

#ifdef PADDLE_WITH_DISTRIBUTE
#include "paddle/phi/core/distributed/auto_parallel/dist_attr.h"
#include "paddle/phi/core/distributed/auto_parallel/dist_tensor.h"
using phi::distributed::auto_parallel::DistTensor;
using phi::distributed::auto_parallel::TensorDistAttr;
#endif

52 53 54 55 56
namespace paddle {
namespace pybind {

namespace py = ::pybind11;

57 58
extern PyTypeObject* p_tensor_type;
extern PyTypeObject* p_string_tensor_type;  // For StringTensor
59
extern PyTypeObject* g_vartype_pytype;
60
extern PyTypeObject* g_framework_tensor_pytype;
61

62
PyObject* TensorNew(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
63 64
  PyObject* obj = type->tp_alloc(type, 0);
  if (obj) {
65
    auto v = reinterpret_cast<TensorObject*>(obj);
66
    new (&(v->tensor)) paddle::Tensor();
67 68 69 70
  }
  return obj;
}

L
LiYuRio 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
#ifdef PADDLE_WITH_DISTRIBUTE
void EmptyDistTensorInitializer(
    TensorObject* self,
    const std::string& name,
    const paddle::platform::Place& place,
    const std::shared_ptr<TensorDistAttr>& dist_attr,
    bool persistable = false,
    int stop_gradient = -1,
    framework::proto::VarType::Type dtype =
        paddle::framework::proto::VarType::FP32,
    const std::vector<int>& dims = {0}) {
  auto ddims = phi::make_ddim(dims);
  self->tensor.set_name(name);
  auto autograd_meta = egr::EagerUtils::autograd_meta(&(self->tensor));
  autograd_meta->SetPersistable(persistable);
  if (stop_gradient != -1) {
    autograd_meta->SetStopGradient(static_cast<bool>(stop_gradient));
  }

  std::shared_ptr<DistTensor> dist_tensor = nullptr;
  if (dims.size() == 1 && dims[0] == 0) {
    std::shared_ptr<phi::Allocation> allocation_ptr = nullptr;
    dist_tensor = std::make_shared<DistTensor>(
        allocation_ptr,
        phi::DenseTensorMeta(paddle::framework::TransToPhiDataType(dtype),
                             ddims),
        dist_attr);
  } else {
    dist_tensor = std::make_shared<DistTensor>(
        std::make_shared<phi::Allocation>(),
        phi::DenseTensorMeta(paddle::framework::TransToPhiDataType(dtype),
                             ddims),
        dist_attr);
  }
  self->tensor.set_impl(dist_tensor);

  if (!autograd_meta->GetMutableGradNode()) {
    autograd_meta->SetGradNode(
        std::make_shared<egr::GradNodeAccumulation>(autograd_meta));
    VLOG(3) << "Tensor(" << name
            << ") have not GradNode, add GradNodeAccumulation"
            << autograd_meta->GradNode() << " for it.";
  }
}
#endif

117
// TODO(jiabin): Overload this once we need more constructor in Python
118 119
void EmptyTensorInitializer(TensorObject* self,
                            const std::string& name,
120
                            const paddle::platform::Place& place,
121 122
                            bool persistable = false,
                            int stop_gradient = -1,
123 124
                            framework::proto::VarType::Type dtype =
                                paddle::framework::proto::VarType::FP32,
125
                            const std::vector<int>& dims = {0},
126 127
                            framework::proto::VarType::Type var_type =
                                paddle::framework::proto::VarType::LOD_TENSOR) {
128
  auto ddims = phi::make_ddim(dims);
129 130
  self->tensor.set_name(name);
  auto autograd_meta = egr::EagerUtils::autograd_meta(&(self->tensor));
131
  autograd_meta->SetPersistable(persistable);
132 133 134
  if (stop_gradient != -1) {
    autograd_meta->SetStopGradient(static_cast<bool>(stop_gradient));
  }
135 136
  if (var_type == paddle::framework::proto::VarType::LOD_TENSOR) {
    // TODO(jiabin): Maybe support LOD later
137
    std::shared_ptr<phi::DenseTensor> dense_tensor = nullptr;
138
    if (dims.size() == 1 && dims[0] == 0) {
139 140 141 142 143 144 145 146
      std::shared_ptr<phi::Allocation> allocation_ptr = nullptr;
      dense_tensor = std::make_shared<phi::DenseTensor>(
          allocation_ptr,
          phi::DenseTensorMeta(paddle::framework::TransToPhiDataType(dtype),
                               ddims));
    } else {
      // TODO(dev): we need enhance check for ddims.
      dense_tensor = std::make_shared<phi::DenseTensor>(
Z
zyfncg 已提交
147
          std::make_shared<phi::Allocation>(),
148 149 150
          phi::DenseTensorMeta(paddle::framework::TransToPhiDataType(dtype),
                               ddims));
    }
151
    self->tensor.set_impl(dense_tensor);
152 153 154 155
  } else if (var_type == paddle::framework::proto::VarType::SELECTED_ROWS) {
    std::shared_ptr<phi::SelectedRows> tensor =
        std::make_shared<phi::SelectedRows>();
    self->tensor.set_impl(tensor);
156 157 158
  }

  if (!autograd_meta->GetMutableGradNode()) {
159 160
    autograd_meta->SetGradNode(
        std::make_shared<egr::GradNodeAccumulation>(autograd_meta));
161 162 163
    VLOG(3) << "Tensor(" << name
            << ") have not GradNode, add GradNodeAccumulation"
            << autograd_meta->GradNode() << " for it.";
164 165 166
  }
}

167 168
void EmptyStringTensorInitializer(TensorObject* self,
                                  const std::string& name,
J
Jack Zhou 已提交
169 170 171 172 173 174 175
                                  const paddle::platform::Place& place,
                                  const std::vector<int>& dims = {}) {
  auto ddims = phi::make_ddim(dims);
  self->tensor.set_name(name);
  // Note(zhoushunjie): Only support CPUPlace when create StringTensor
  auto actual_place = platform::CPUPlace();
  // Allocate memory
176
  paddle::experimental::DefaultAllocator string_allocator(actual_place);
J
Jack Zhou 已提交
177
  std::shared_ptr<phi::StringTensor> string_tensor =
178 179
      std::make_shared<phi::StringTensor>(&string_allocator,
                                          phi::StringTensorMeta{ddims});
J
Jack Zhou 已提交
180 181 182 183 184 185
  if (phi::product(ddims) > 0) {
    string_tensor->mutable_data(actual_place);
  }
  self->tensor.set_impl(string_tensor);
}

L
LiYuRio 已提交
186 187 188 189 190 191 192 193
#ifdef PADDLE_WITH_DISTRIBUTE
void InitDistTensorWithNumpyValue(TensorObject* self,
                                  const py::object& array,
                                  const paddle::platform::Place& place,
                                  bool zero_copy = false) {
  PADDLE_ENFORCE_EQ(
      self->tensor.defined(),
      true,
194
      paddle::platform::errors::Unavailable(
L
LiYuRio 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
          "Calling InitDistTensorWithNumpyValue of Eager Tensor without "
          "EmptyDistTensorInitializer is "
          "forbidden. Please check your code and make sure you new a "
          "eager tensor before init it with NumPy."));
  DistTensor* dist_tensor_ptr =
      static_cast<DistTensor*>(self->tensor.impl().get());
  phi::DenseTensor* impl_ptr =
      static_cast<phi::DenseTensor*>(dist_tensor_ptr->mutable_value());

  if (platform::is_cpu_place(place)) {
    SetTensorFromPyArray<platform::CPUPlace>(impl_ptr, array, place, zero_copy);
  } else if (platform::is_xpu_place(place)) {
    SetTensorFromPyArray<platform::XPUPlace>(impl_ptr, array, place, zero_copy);
  } else if (platform::is_gpu_place(place)) {
    SetTensorFromPyArray<platform::CUDAPlace>(
        impl_ptr, array, place, zero_copy);
  } else if (platform::is_cuda_pinned_place(place)) {
    SetTensorFromPyArray<platform::CUDAPinnedPlace>(
        impl_ptr, array, place, zero_copy);
  } else if (platform::is_custom_place(place)) {
    SetTensorFromPyArray<platform::CustomPlace>(
        impl_ptr, array, place, zero_copy);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Place should be one of "
        "CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace/CustomPlace"));
  }

  // TODO(dev): dist_tensor meta is not equal to dense tensor meta
  dist_tensor_ptr->set_meta(impl_ptr->meta());
}
#endif

228 229
void InitTensorWithNumpyValue(TensorObject* self,
                              const py::object& array,
230
                              const paddle::platform::Place& place,
231
                              bool zero_copy = false) {
232
  PADDLE_ENFORCE_EQ(
233 234
      self->tensor.defined(),
      true,
235
      paddle::platform::errors::Unavailable(
236 237
          "Calling InitTensorWithNumpyValue of Eager Tensor without "
          "EmptyTensorInitializer is "
238 239
          "forbidden. Please check your code and make sure you new a "
          "eager tensor before init it with NumPy."));
240 241
  phi::DenseTensor* impl_ptr =
      static_cast<phi::DenseTensor*>(self->tensor.impl().get());
L
LiYuRio 已提交
242

243
  if (platform::is_cpu_place(place)) {
244
    SetTensorFromPyArray<platform::CPUPlace>(impl_ptr, array, place, zero_copy);
245
  } else if (platform::is_xpu_place(place)) {
246
    SetTensorFromPyArray<platform::XPUPlace>(impl_ptr, array, place, zero_copy);
247
  } else if (platform::is_gpu_place(place)) {
248 249
    SetTensorFromPyArray<platform::CUDAPlace>(
        impl_ptr, array, place, zero_copy);
250
  } else if (platform::is_cuda_pinned_place(place)) {
251 252
    SetTensorFromPyArray<platform::CUDAPinnedPlace>(
        impl_ptr, array, place, zero_copy);
253
  } else if (platform::is_custom_place(place)) {
254 255
    SetTensorFromPyArray<platform::CustomPlace>(
        impl_ptr, array, place, zero_copy);
256 257 258
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Place should be one of "
张春乔 已提交
259
        "CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace/CustomPlace"));
260 261 262
  }
}

J
Jack Zhou 已提交
263 264
void InitStringTensorWithNumpyValue(TensorObject* self, const py::object& obj) {
  PADDLE_ENFORCE_EQ(
265 266
      self->tensor.defined(),
      true,
J
Jack Zhou 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
      paddle::platform::errors::Fatal(
          "Calling InitStringTensorWithNumpyValue of Eager StringTensor "
          "without "
          "EmptyStringTensorInitializer is "
          "forbidden. Please check your code and make sure you new a "
          "eager tensor before init it with NumPy."));
  phi::StringTensor* impl_ptr =
      static_cast<phi::StringTensor*>(self->tensor.impl().get());
  paddle::platform::Place place = impl_ptr->place();
  auto array = obj.cast<py::array>();
  if (platform::is_cpu_place(place)) {
    SetStringTensorFromPyArray<platform::CPUPlace>(impl_ptr, array, place);
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "StringTensor only support CPUPlace now, but receive %s",
        place.DebugString()));
  }
}

L
LiYuRio 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
#ifdef PADDLE_WITH_DISTRIBUTE
void InitDistTensorWithTensor(
    TensorObject* self,
    const paddle::Tensor& src,
    const paddle::platform::Place& place,
    const std::string& name,
    const std::shared_ptr<TensorDistAttr>& dist_attr) {
  PADDLE_ENFORCE(src.is_dense_tensor(),
                 paddle::platform::errors::InvalidArgument(
                     "DistTensor can only initialize by DenseTensor"));
  self->tensor.set_name(name);
  if (place == src.place()) {
    std::shared_ptr<phi::DenseTensor> tensor =
        std::static_pointer_cast<phi::DenseTensor>(src.impl());
    self->tensor.set_impl(std::make_shared<DistTensor>(tensor, dist_attr));
    VLOG(4) << "Same place, do ShareDataWith";
  } else {
    std::shared_ptr<phi::DenseTensor> tensor =
        std::static_pointer_cast<phi::DenseTensor>(
            src.copy_to(place, true).impl());
    self->tensor.set_impl(std::make_shared<DistTensor>(tensor, dist_attr));
    VLOG(4) << "Different place, do TensorCopy";
  }
  if (src.get_autograd_meta()) {
    egr::EagerUtils::autograd_meta(&(self->tensor))
        ->SetPersistable(
            egr::EagerUtils::unsafe_autograd_meta(src)->Persistable());
  } else {
    egr::EagerUtils::autograd_meta(&(self->tensor))->SetPersistable(false);
  }
}
#endif

319
void InitTensorWithTensor(TensorObject* self,
320
                          const paddle::Tensor& src,
321 322
                          const paddle::platform::Place& place,
                          const std::string& name) {
323
  self->tensor.set_name(name);
C
Chen Weihang 已提交
324
  if (place == src.place()) {
325
    self->tensor.set_impl(src.impl());
326 327
    VLOG(4) << "Same place, do ShareDataWith";
  } else {
328
    self->tensor.set_impl(src.copy_to(place, true).impl());
329 330 331
    VLOG(4) << "Different place, do TensorCopy";
  }
  if (src.get_autograd_meta()) {
332
    egr::EagerUtils::autograd_meta(&(self->tensor))
333 334 335
        ->SetPersistable(
            egr::EagerUtils::unsafe_autograd_meta(src)->Persistable());
  } else {
336
    egr::EagerUtils::autograd_meta(&(self->tensor))->SetPersistable(false);
337 338 339
  }
}

340
void InitTensorWithFrameworkTensor(TensorObject* self,
341
                                   const phi::DenseTensor& src,
342 343
                                   const paddle::platform::Place& place,
                                   const std::string& name) {
344
  self->tensor.set_name(name);
345
  if (place == src.place()) {
346
    self->tensor.set_impl(std::make_shared<phi::DenseTensor>(src));
347 348
    VLOG(4) << "Same place, do ShareDataWith";
  } else {
349
    auto temp = paddle::Tensor(std::make_shared<phi::DenseTensor>(src));
350
    self->tensor.set_impl(temp.copy_to(place, true).impl());
351 352
    VLOG(4) << "Different place, do TensorCopy";
  }
353
  egr::EagerUtils::autograd_meta(&(self->tensor))->SetPersistable(false);
354
}
355

J
Jack Zhou 已提交
356
void InitStringTensorWithStringTensor(TensorObject* self,
357
                                      const paddle::Tensor& src,
J
Jack Zhou 已提交
358 359 360 361 362 363 364 365 366
                                      const paddle::platform::Place& place,
                                      const std::string& name) {
  self->tensor.set_name(name);
  auto impl = std::static_pointer_cast<phi::StringTensor>(src.impl());
  self->tensor.set_impl(impl);
  VLOG(4)
      << "Do ShareDataWith when using StringTensor to initialize StringTensor";
}

367 368
py::object ParsePyArray(
    std::unordered_map<std::string, PyObject*> kws_map,
369 370 371 372
    std::unordered_map<std::string, Py_ssize_t> kw_order_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  py::object numpy_value = py::object();

  if (kw_order_map["value"] <= args_num) {
    numpy_value = py::object(
        py::handle(PyTuple_GET_ITEM(args, kw_order_map["value"] - 1)), true);
  } else {
    if (flag_kwargs && kws_map["value"] != NULL) {
      numpy_value = py::object(py::handle(kws_map["value"]), true);
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "The first expected arguments is {value: PyArray}, "
          "but could not parse the first argument {value: PyArray} "
          "successfully. "
          "Please check your input first and make sure you are on the right "
          "way."));
    }
  }
  return numpy_value;
}

paddle::platform::Place ParsePlace(
    std::unordered_map<std::string, PyObject*> kws_map,
395 396 397 398
    std::unordered_map<std::string, Py_ssize_t> kw_order_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
  paddle::platform::Place place =
      egr::Controller::Instance().GetExpectedPlace();

  if (kw_order_map["place"] <= args_num) {
    place = CastPyArg2Place(PyTuple_GET_ITEM(args, kw_order_map["place"] - 1),
                            kw_order_map["place"] - 1);
  } else {
    if (flag_kwargs && kws_map["place"] != NULL) {
      place = CastPyArg2Place(kws_map["place"], 0);
    } else {
      // default
      return place;
    }
  }
  return place;
}

L
LiYuRio 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
#ifdef PADDLE_WITH_DISTRIBUTE
std::shared_ptr<TensorDistAttr> ParseDistAttrArgs(
    std::unordered_map<std::string, PyObject*> kws_map,
    std::unordered_map<std::string, Py_ssize_t> kw_order_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
  std::shared_ptr<TensorDistAttr> dist_attr = nullptr;
  if (kw_order_map["dist_attr"] <= args_num) {
    dist_attr = CastPyArg2DistAttr(
        PyTuple_GET_ITEM(args, kw_order_map["dist_attr"] - 1),
        kw_order_map["dist_attr"] - 1);
  } else if (flag_kwargs && kws_map["dist_attr"] != NULL) {
    dist_attr = CastPyArg2DistAttr(kws_map["dist_attr"], 0);
  }
  return dist_attr;
}
#endif

435
// boolean arguments: zero_copy, stop_gradient, persistable
436 437 438
int ParseBooleanArgs(std::string key,
                     std::unordered_map<std::string, PyObject*> kws_map,
                     std::unordered_map<std::string, Py_ssize_t> kw_order_map,
439 440 441
                     PyObject* args,
                     bool flag_kwargs,
                     Py_ssize_t args_num) {
442
  int res = -1;
443 444

  if (kw_order_map[key] <= args_num) {
445 446
    res = static_cast<int>(CastPyArg2AttrBoolean(
        PyTuple_GET_ITEM(args, kw_order_map[key] - 1), kw_order_map[key] - 1));
447 448
  } else {
    if (flag_kwargs && kws_map[key] != NULL) {
449
      res = static_cast<int>(CastPyArg2AttrBoolean(kws_map[key], 0));
450 451 452 453 454 455 456
    }
  }
  return res;
}

std::string ParseName(std::unordered_map<std::string, PyObject*> kws_map,
                      std::unordered_map<std::string, Py_ssize_t> kw_order_map,
457 458 459
                      PyObject* args,
                      bool flag_kwargs,
                      Py_ssize_t args_num,
J
Jack Zhou 已提交
460
                      std::string unique_name_prefix = "generated_tensor") {
461 462 463 464 465
  std::string act_name = "";
  if (kw_order_map["name"] <= args_num) {
    PyObject* name_obj = PyTuple_GET_ITEM(args, kw_order_map["name"] - 1);
    if (name_obj == Py_None) {
      act_name =
J
Jack Zhou 已提交
466
          egr::Controller::Instance().GenerateUniqueName(unique_name_prefix);
467 468 469 470 471
    } else {
      act_name = CastPyArg2AttrString(name_obj, kw_order_map["name"] - 1);
    }
  } else {
    if (flag_kwargs) {
J
Jiabin Yang 已提交
472
      if ((kws_map["name"] == NULL) || (kws_map["name"] == Py_None)) {
473
        act_name =
J
Jack Zhou 已提交
474
            egr::Controller::Instance().GenerateUniqueName(unique_name_prefix);
475 476 477 478 479
      } else {
        act_name = CastPyArg2AttrString(kws_map["name"], 0);
      }
    } else {
      act_name =
J
Jack Zhou 已提交
480
          egr::Controller::Instance().GenerateUniqueName(unique_name_prefix);
481 482 483 484 485
    }
  }
  return act_name;
}

486
// initialize Tensor by PyArray(first argument is PyArray,
487
// mix args and kwargs) automatically.
488 489
void AutoInitTensorByPyArray(TensorObject* py_tensor_ptr,
                             std::unordered_map<std::string, PyObject*> kws_map,
490 491
                             PyObject* args,
                             bool flag_kwargs,
492 493 494
                             Py_ssize_t args_num) {
  // The first argument of the Tensor constructor is PyArray,
  // there are 6 arguments to construct the new Tensor,
495 496 497 498
  // kw_order_map's key is every arguments of the constructor,
  // kw_order_map's value is the position of the arguments respectively.
  // If u want to update this constructor with new arguments,
  // need to update this map and to add or change related code.
L
LiYuRio 已提交
499 500 501 502 503 504 505
  std::unordered_map<std::string, Py_ssize_t> kw_order_map{{"value", 1},
                                                           {"place", 2},
                                                           {"persistable", 3},
                                                           {"zero_copy", 4},
                                                           {"name", 5},
                                                           {"stop_gradient", 6},
                                                           {"dist_attr", 7}};
506 507 508 509 510 511 512

  py::object numpy_value = py::object();
  paddle::platform::Place place =
      egr::Controller::Instance().GetExpectedPlace();
  bool persistable = false;
  bool zero_copy = false;
  std::string act_name = "";
513
  int stop_gradient = -1;
514 515 516 517

  numpy_value =
      ParsePyArray(kws_map, kw_order_map, args, flag_kwargs, args_num);
  place = ParsePlace(kws_map, kw_order_map, args, flag_kwargs, args_num);
518 519 520 521 522 523 524 525
  persistable =
      (1 ==
       ParseBooleanArgs(
           "persistable", kws_map, kw_order_map, args, flag_kwargs, args_num));
  zero_copy =
      (1 ==
       ParseBooleanArgs(
           "zero_copy", kws_map, kw_order_map, args, flag_kwargs, args_num));
526
  act_name = ParseName(kws_map, kw_order_map, args, flag_kwargs, args_num);
527 528
  stop_gradient = ParseBooleanArgs(
      "stop_gradient", kws_map, kw_order_map, args, flag_kwargs, args_num);
529

L
LiYuRio 已提交
530 531 532 533 534 535 536 537 538 539 540 541
#ifdef PADDLE_WITH_DISTRIBUTE
  std::shared_ptr<TensorDistAttr> dist_attr =
      ParseDistAttrArgs(kws_map, kw_order_map, args, flag_kwargs, args_num);

  if (dist_attr) {
    EmptyDistTensorInitializer(
        py_tensor_ptr, act_name, place, dist_attr, persistable, stop_gradient);
    InitDistTensorWithNumpyValue(py_tensor_ptr, numpy_value, place, zero_copy);
    return;
  }
#endif

542 543
  EmptyTensorInitializer(
      py_tensor_ptr, act_name, place, persistable, stop_gradient);
544
  InitTensorWithNumpyValue(py_tensor_ptr, numpy_value, place, zero_copy);
545 546
}

547
// initialize Tensor by Tensor or phi::DenseTensor (mix args and
548
// kwargs) automatically.
549 550
void AutoInitTensorByTensor(TensorObject* py_tensor_ptr,
                            std::unordered_map<std::string, PyObject*> kws_map,
551 552
                            PyObject* args,
                            bool flag_kwargs,
553 554 555
                            Py_ssize_t args_num,
                            bool init_by_egr_tensor = true) {
  // The first argument of the Tensor constructor is Tensor or
556
  // framework Tensor,
557
  // there are 3 arguments to construct the new Tensor,
558 559 560 561 562
  // kw_order_map's key is every arguments of the constructor,
  // kw_order_map's value is the position of the arguments respectively.
  // If u want to update this constructor with new arguments,
  // need to update this map and to add or change related code.
  std::unordered_map<std::string, Py_ssize_t> kw_order_map{
L
LiYuRio 已提交
563
      {"value", 1}, {"place", 2}, {"name", 3}, {"dist_attr", 4}};
564 565 566 567 568 569 570 571

  paddle::platform::Place place =
      egr::Controller::Instance().GetExpectedPlace();
  std::string act_name = "";

  place = ParsePlace(kws_map, kw_order_map, args, flag_kwargs, args_num);
  act_name = ParseName(kws_map, kw_order_map, args, flag_kwargs, args_num);

L
LiYuRio 已提交
572 573 574 575 576
#ifdef PADDLE_WITH_DISTRIBUTE
  std::shared_ptr<TensorDistAttr> dist_attr =
      ParseDistAttrArgs(kws_map, kw_order_map, args, flag_kwargs, args_num);
#endif

577
  if (init_by_egr_tensor) {
578
    paddle::Tensor src_tensor;
579
    if (kw_order_map["value"] <= args_num) {
580 581 582
      src_tensor =
          CastPyArg2Tensor(PyTuple_GET_ITEM(args, kw_order_map["value"] - 1),
                           kw_order_map["value"] - 1);
583 584
    } else {
      if (flag_kwargs && kws_map["value"] != NULL) {
585
        src_tensor = CastPyArg2Tensor(kws_map["value"], 0);
586 587
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
588 589
            "The first expected kwargs is {value: Tensor}, "
            "but could not parse the first argument {value: Tensor} "
590 591 592 593 594
            "successfully. "
            "Please check your input first and make sure you are on the right "
            "way."));
      }
    }
L
LiYuRio 已提交
595 596 597 598 599 600 601 602
#ifdef PADDLE_WITH_DISTRIBUTE
    if (dist_attr) {
      InitDistTensorWithTensor(
          py_tensor_ptr, src_tensor, place, act_name, dist_attr);
    } else {
      InitTensorWithTensor(py_tensor_ptr, src_tensor, place, act_name);
    }
#else
603
    InitTensorWithTensor(py_tensor_ptr, src_tensor, place, act_name);
L
LiYuRio 已提交
604
#endif
605 606
  } else {
    // init by framework tensor
607
    phi::DenseTensor src_tensor;
608 609 610 611 612 613 614 615 616
    if (kw_order_map["value"] <= args_num) {
      src_tensor = CastPyArg2FrameworkTensor(
          PyTuple_GET_ITEM(args, kw_order_map["value"] - 1),
          kw_order_map["value"] - 1);
    } else {
      if (flag_kwargs && kws_map["value"] != NULL) {
        src_tensor = CastPyArg2FrameworkTensor(kws_map["value"], 0);
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
617 618
            "The first expected arguments is {value: phi::DenseTensor}, "
            "but could not parse the first argument {value: phi::DenseTensor} "
619 620 621 622 623
            "successfully. "
            "Please check your input first and make sure you are on the right "
            "way."));
      }
    }
624
    InitTensorWithFrameworkTensor(py_tensor_ptr, src_tensor, place, act_name);
625 626 627
  }
}

J
Jack Zhou 已提交
628 629
void AutoInitStringTensorByPyArray(
    TensorObject* py_tensor_ptr,
630 631 632 633
    std::unordered_map<std::string, PyObject*> kws_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
J
Jack Zhou 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  // The first argument of the StringTensor constructor is PyArray,
  // there are 4 arguments to construct the new StringTensor,
  // kw_order_map's key is every arguments of the constructor,
  // kw_order_map's value is the position of the arguments respectively.
  // If u want to update this constructor with new arguments,
  // need to update this map and to add or change related code.
  std::unordered_map<std::string, Py_ssize_t> kw_order_map{{"value", 1},
                                                           {"name", 2}};
  py::object numpy_value = py::object();
  paddle::platform::Place place =
      egr::Controller::Instance().GetExpectedPlace();
  std::string act_name = "";

  numpy_value =
      ParsePyArray(kws_map, kw_order_map, args, flag_kwargs, args_num);
649 650 651 652 653
  act_name = ParseName(kws_map,
                       kw_order_map,
                       args,
                       flag_kwargs,
                       args_num,
J
Jack Zhou 已提交
654 655 656 657 658 659 660
                       "generated_string_tensor");
  EmptyStringTensorInitializer(py_tensor_ptr, act_name, place);
  InitStringTensorWithNumpyValue(py_tensor_ptr, numpy_value);
}

void AutoInitStringTensorByStringTensor(
    TensorObject* py_tensor_ptr,
661 662 663 664
    std::unordered_map<std::string, PyObject*> kws_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
J
Jack Zhou 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677
  // The first argument of the Tensor constructor is StringTensor,
  // there are 3 arguments to construct the new StringTensor,
  // kw_order_map's key is every arguments of the constructor,
  // kw_order_map's value is the position of the arguments respectively.
  // If u want to update this constructor with new arguments,
  // need to update this map and to add or change related code.
  std::unordered_map<std::string, Py_ssize_t> kw_order_map{{"value", 1},
                                                           {"name", 2}};

  paddle::platform::Place place =
      egr::Controller::Instance().GetExpectedPlace();
  std::string act_name = "";

678 679 680 681 682
  act_name = ParseName(kws_map,
                       kw_order_map,
                       args,
                       flag_kwargs,
                       args_num,
J
Jack Zhou 已提交
683
                       "generated_string_tensor");
684
  paddle::Tensor src_tensor;
J
Jack Zhou 已提交
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
  if (kw_order_map["value"] <= args_num) {
    src_tensor =
        CastPyArg2Tensor(PyTuple_GET_ITEM(args, kw_order_map["value"] - 1),
                         kw_order_map["value"] - 1);
  } else {
    if (flag_kwargs && kws_map["value"] != NULL) {
      src_tensor = CastPyArg2Tensor(kws_map["value"], 0);
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "The first expected kwargs is {value: Tensor}, "
          "but could not parse the first argument {value: Tensor} "
          "successfully. "
          "Please check your input first and make sure you are on the right "
          "way."));
    }
  }
  InitStringTensorWithStringTensor(py_tensor_ptr, src_tensor, place, act_name);
}

704
/** We should have init function with signature:
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
 * 1.
 * def __init__ ()
 * 2.
 * def __init__ (
 * ** dtype: paddle::framework::proto::VarType::Type,
 * ** dims: vector<int>,
 * ** name: std::string,
 * ** type: paddle::framework::proto::VarType::LodTensor,
 * ** persistable: bool)
 * 3. (multi-place)
 * (should have at least one parameter, one parameter equals to case 4, zero
 * parameter equals to case 1)
 * def __init__ (
 * ** value: ndarray,
 * ** place: paddle::platform::Place,
 * ** persistable: bool,
 * ** zero_copy: bool,
 * ** name: std::string,
L
LiYuRio 已提交
723 724
 * ** stop_gradient: bool,
 * ** dist_attr: phi::distributed::TensorDistAttr)
725 726 727 728 729 730 731 732 733 734 735 736
 * 4.
 * def __init__ (
 * ** value: ndarray)
 * 5.
 * def __init__ (
 * ** tensor: Tensor)
 * 6. (multi-place)
 * (should have at least one parameter, one parameter equals to case 5, zero
 * parameter equals to case 1.)
 * def __init__ (
 * ** tensor: Tensor,
 * ** place: paddle::platform::Place,
L
LiYuRio 已提交
737 738
 * ** name: std::string,
 * ** dist_attr: phi::distributed::TensorDistAttr)
739 740 741 742 743 744 745
 * 7. (multi-place) (should have at least one parameter, one parameter similar
 * to case 5, zero parameter equals to case 1.)
 * def __init__ (
 * ** tensor: FrameworkTensor,
 * ** place: paddle::platform::Place,
 * ** name: std::string)
 *  **/
746
int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) {
0
0x45f 已提交
747
  EAGER_TRY
748 749 750 751 752 753 754 755 756
  // set a flag to record use kwargs or not
  bool flag_kwargs = false;
  if (kwargs) flag_kwargs = true;

  // all kwargs
  PyObject* kw_zero_copy = NULL;
  PyObject* kw_persistable = NULL;
  PyObject* kw_stop_gradient = NULL;

757
  PyObject* kw_value = NULL;  // receive PyArray or Tensor
758 759 760 761 762
  PyObject* kw_place = NULL;
  PyObject* kw_name = NULL;
  PyObject* kw_dims = NULL;
  PyObject* kw_dtype = NULL;
  PyObject* kw_type = NULL;
L
LiYuRio 已提交
763
  PyObject* kw_dist_attr = NULL;
764 765

  // the keywords argument
766 767 768 769 770 771 772 773 774
  static char* kwlist[] = {const_cast<char*>("value"),
                           const_cast<char*>("place"),
                           const_cast<char*>("persistable"),
                           const_cast<char*>("zero_copy"),
                           const_cast<char*>("name"),
                           const_cast<char*>("stop_gradient"),
                           const_cast<char*>("dims"),
                           const_cast<char*>("dtype"),
                           const_cast<char*>("type"),
L
LiYuRio 已提交
775
                           const_cast<char*>("dist_attr"),
776
                           NULL};
777 778 779 780 781 782 783

  // 'O' Store a Python object (without any conversion) in a C object pointer,
  // '|' Indicates that the remaining arguments in the Python argument list are
  // optional.
  // PyArg_ParseTupleAndKeywords can Parse the parameters of a function that
  // takes both positional and keyword parameters into local variables,
  // which enhance case2, case3, case4, case5, case6, case7.
784 785
  bool flag_ = PyArg_ParseTupleAndKeywords(args,
                                           kwargs,
L
LiYuRio 已提交
786
                                           "|OOOOOOOOOO",
787 788 789 790 791 792 793 794 795
                                           kwlist,
                                           &kw_value,
                                           &kw_place,
                                           &kw_persistable,
                                           &kw_zero_copy,
                                           &kw_name,
                                           &kw_stop_gradient,
                                           &kw_dims,
                                           &kw_dtype,
L
LiYuRio 已提交
796 797
                                           &kw_type,
                                           &kw_dist_attr);
798 799 800 801 802 803 804 805 806 807 808

  // helper map
  std::unordered_map<std::string, PyObject*> kws_map{
      {"value", kw_value},
      {"place", kw_place},
      {"persistable", kw_persistable},
      {"zero_copy", kw_zero_copy},
      {"name", kw_name},
      {"stop_gradient", kw_stop_gradient},
      {"dims", kw_dims},
      {"dtype", kw_dtype},
L
LiYuRio 已提交
809 810
      {"type", kw_type},
      {"dist_attr", kw_dist_attr}};
811

812 813
  PADDLE_ENFORCE_EQ(flag_,
                    true,
814 815 816 817 818 819
                    paddle::platform::errors::PreconditionNotMet(
                        "Could not parse args and kwargs successfully, "
                        "please check your input first and make"
                        "sure you are on the right way. "
                        "The expected arguments as follow: ("
                        "value, place, persistable, zero_copy, "
L
LiYuRio 已提交
820
                        "name, stop_gradient, dims, dtype, type, dist_attr)"));
821

822
  PADDLE_ENFORCE_NOT_NULL(
823 824 825 826 827
      self,
      paddle::platform::errors::Fatal(
          "Calling __init__ of Eager Tensor without __new__ is "
          "forbidden. Please check your code and make sure you new a "
          "eager tensor before init it."));
828

829
  auto py_tensor_ptr = reinterpret_cast<TensorObject*>(self);
830 831

  Py_ssize_t args_num = PyTuple_Size(args);
832 833 834 835 836
  VLOG(6) << " args_num: " << args_num;

  // args_num = 0, means that there is no position arguments.
  if (args_num == (Py_ssize_t)0) {
    if (!flag_kwargs) {
837 838
      // case 1
      VLOG(6) << "Calling case1's initializer.";
839
      EmptyTensorInitializer(
840 841 842 843
          py_tensor_ptr,
          egr::Controller::Instance().GenerateUniqueName("generated_tensor"),
          egr::Controller::Instance().GetExpectedPlace());
      return 0;
844 845 846 847
    } else {  // no position args, all arguments are kwargs
      if (kw_value != NULL) {
        if (pybind11::detail::npy_api::get().PyArray_Check_(kw_value)) {
          VLOG(6) << "Calling case3's or case4's initializer";
848 849
          AutoInitTensorByPyArray(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
850
          return 0;
851
        } else if (PyObject_TypeCheck(kw_value, p_tensor_type)) {
852
          VLOG(6) << "Calling case5's or case6's initializer";
853 854
          AutoInitTensorByTensor(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
855
          return 0;
856
        } else if (PyObject_TypeCheck(kw_value, g_framework_tensor_pytype)) {
857
          VLOG(6) << "Calling case7's initializer.";
858 859 860 861
          AutoInitTensorByTensor(py_tensor_ptr,
                                 kws_map,
                                 args,
                                 flag_kwargs,
862 863
                                 args_num,
                                 /* false means not init by egr tensor*/ false);
864
          return 0;
865
        } else {
866 867 868
          PADDLE_THROW(platform::errors::InvalidArgument(
              "Could not parse the first keyword argument successfully, "
              "the first keyword argument is value, but it should be PyArray "
869
              "or Tensor or phi::DenseTensor. "
870 871
              "Please check your input first and make sure you are on the "
              "right way."));
872
        }
873
      } else if (kw_dtype != NULL &&
874
                 PyObject_TypeCheck(kw_dtype, g_vartype_pytype)) {
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
        VLOG(6) << "Calling case2's initializer";

        PADDLE_ENFORCE_NOT_NULL(
            kw_dims,
            paddle::platform::errors::InvalidArgument(
                "Calling __init__ of Eager Tensor with NULL dims is "
                "forbidden. Please check your code and make sure you new a "
                "dims before calling this constructor."));

        PADDLE_ENFORCE_NOT_NULL(
            kw_name,
            paddle::platform::errors::InvalidArgument(
                "Calling __init__ of Eager Tensor with NULL name is "
                "forbidden. Please check your code and make sure you new a "
                "name before calling this constructor."));

        PADDLE_ENFORCE_NOT_NULL(
            kw_dtype,
            paddle::platform::errors::InvalidArgument(
                "Calling __init__ of Eager Tensor with NULL dtype is "
                "forbidden. Please check your code and make sure you new a "
                "dtype before calling this constructor."));

        PADDLE_ENFORCE_NOT_NULL(
            kw_persistable,
            paddle::platform::errors::InvalidArgument(
                "Calling __init__ of Eager Tensor with NULL persistable is "
                "forbidden. Please check your code and make sure you new a "
                "persistable before calling this constructor."));

        paddle::framework::proto::VarType::Type dtype =
            CastPyArg2ProtoType(kw_dtype, 0);
        std::vector<int> dims = CastPyArg2VectorOfInt(kw_dims, 0);

909
        std::string act_name = "";
910
        if (kw_name == Py_None) {
911 912 913
          act_name = egr::Controller::Instance().GenerateUniqueName(
              "generated_tensor");
        } else {
914
          act_name = CastPyArg2AttrString(kw_name, 0);
915
        }
916 917 918 919 920

        paddle::framework::proto::VarType::Type var_type =
            CastPyArg2ProtoType(kw_type, 0);
        bool persistable = CastPyArg2AttrBoolean(kw_persistable, 0);

921 922
        EmptyTensorInitializer(py_tensor_ptr,
                               act_name,
923 924
                               egr::Controller::Instance().GetExpectedPlace(),
                               persistable,
925 926 927 928
                               /* stop_gradient */ -1,
                               dtype,
                               dims,
                               var_type);
929

930
        return 0;
931 932
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
933
            "We not only support construct Tensor from numpy value "
934
            "or tensor(Tensor or phi::DenseTensor) "
935
            "with python kwargs by this initializer, "
936
            "but also even support dtype to init a empty Tensor. "
937 938
            "Please check your input first and make sure you call the existed "
            "constructor."));
939
      }
940 941 942
    }
  } else if (args_num == (Py_ssize_t)1 || args_num == (Py_ssize_t)2 ||
             args_num == (Py_ssize_t)3) {
C
co63oc 已提交
943
    // 1 to 3 position args, remaining arguments are kwargs
944 945 946
    PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
    if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
      VLOG(6) << "Calling case3's or case4's initializer.";
947 948
      AutoInitTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
949
      return 0;
950
    } else if (PyObject_TypeCheck(arg0_ptr, p_tensor_type)) {
951
      VLOG(6) << "Calling case5's or case6's initializer.";
952 953
      AutoInitTensorByTensor(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
954
      return 0;
955
    } else if (PyObject_TypeCheck(arg0_ptr, g_framework_tensor_pytype)) {
956
      VLOG(6) << "Calling case7's initializer.";
957 958 959 960
      AutoInitTensorByTensor(py_tensor_ptr,
                             kws_map,
                             args,
                             flag_kwargs,
961 962
                             args_num,
                             /* false means not init by egr tensor*/ false);
963 964 965
      return 0;
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
966
          "We support construct Tensor from numpy value "
967
          "or tensor(Tensor or phi::DenseTensor) "
968
          "with python args and kwargs by this initializer, "
969
          "but the first argument should be PyArray or Tensor or "
970
          "phi::DenseTensor. "
971 972
          "Please check your input first and make sure you call the existed "
          "constructor."));
973
    }
974
  } else if (args_num == (Py_ssize_t)4) {
C
co63oc 已提交
975
    // 4 position args, remaining arguments are kwargs
976 977 978
    PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
    if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
      VLOG(6) << "Calling case3's or case4's initializer.";
979 980
      AutoInitTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
981
      return 0;
982 983 984
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Incompatible constructor arguments, "
C
co63oc 已提交
985
          "there are 4 position args and remaining arguments arg kwargs,"
986 987 988
          "but the first position args should be PyArray. "
          "Please check your code and make sure the first position args is "
          "PyArray."));
989
    }
990 991
  } else if (args_num == (Py_ssize_t)5) {
    if (!flag_kwargs) {
992
      PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
993
      if (PyObject_TypeCheck(arg0_ptr, g_vartype_pytype)) {
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
        VLOG(6) << "Calling case2's initializer.";
        paddle::framework::proto::VarType::Type dtype =
            CastPyArg2ProtoType(PyTuple_GET_ITEM(args, 0), 0);
        std::vector<int> dims =
            CastPyArg2VectorOfInt(PyTuple_GET_ITEM(args, 1), 1);
        std::string act_name = "";
        PyObject* name_obj = PyTuple_GET_ITEM(args, 2);
        if (name_obj == Py_None) {
          act_name = egr::Controller::Instance().GenerateUniqueName(
              "generated_tensor");
        } else {
          act_name = CastPyArg2AttrString(PyTuple_GET_ITEM(args, 2), 2);
        }
        paddle::framework::proto::VarType::Type var_type =
            CastPyArg2ProtoType(PyTuple_GET_ITEM(args, 3), 3);
        bool persistable = CastPyArg2AttrBoolean(PyTuple_GET_ITEM(args, 4), 4);
1010 1011
        EmptyTensorInitializer(py_tensor_ptr,
                               act_name,
1012
                               egr::Controller::Instance().GetExpectedPlace(),
1013 1014 1015 1016 1017
                               persistable,
                               -1,
                               dtype,
                               dims,
                               var_type);
1018
        return 0;
1019 1020
      } else if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
        VLOG(6) << "Calling case3's initializer.";
1021 1022
        AutoInitTensorByPyArray(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
1023 1024 1025
        return 0;
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
1026 1027 1028 1029 1030
            "Incompatible constructor arguments, "
            "there are only 5 position args,"
            "but the first position args should be PyArray or dtype. "
            "Please check your code and make sure you call the existed "
            "constructor."));
1031
      }
C
co63oc 已提交
1032
    } else {  // five position args, remaining arguments are kwargs
1033
      PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
1034 1035
      if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
        VLOG(6) << "Calling case3's or case4's initializer";
1036 1037
        AutoInitTensorByPyArray(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
1038
        return 0;
1039
      } else {
1040 1041
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Incompatible constructor arguments, "
C
co63oc 已提交
1042
            "there are 5 position args and remaining arguments are kwargs,"
1043 1044 1045
            "but the first position args should be PyArray. "
            "Please check your code and make sure the first position args is "
            "PyArray."));
1046 1047
      }
    }
1048 1049 1050 1051
  } else if (args_num == (Py_ssize_t)6) {
    if (!flag_kwargs) {
      // case 3
      VLOG(6) << "Calling case3's initializer.";
1052 1053
      AutoInitTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
1054
      return 0;
C
co63oc 已提交
1055
    } else {  // six position args, remaining arguments are kwargs, but this
1056 1057 1058
              // is not a right way
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Incompatible constructor arguments, "
C
co63oc 已提交
1059
          "there are 6 position args and the remaining arguments are kwargs. "
1060 1061
          "Please check your code and make sure the first position args is "
          "PyArray."));
1062
    }
1063 1064 1065 1066
  } else {
    PADDLE_THROW(platform::errors::Fatal(
        "Can't not find expected num of args, please check your call, and "
        "make sure u call the existed constructor."));
1067
  }
1068

0
0x45f 已提交
1069 1070
  return -1;
  EAGER_CATCH_AND_THROW_RETURN_NEG
1071 1072
}

J
Jack Zhou 已提交
1073
/** We should have init function with signature:
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
 * 1.
 * def __init__ ()
 *
 * 2.
 * def __init__ (
 * ** dims: vector<int>,
 * ** name: std::string)
 *
 * 3.
 * (should have at least one parameter, one parameter equals to case 4, zero
 * parameter equals to case 1)
 * def __init__ (
 * ** value: ndarray,
 * ** zero_copy: bool,
 * ** name: std::string)
 *
 * 4.
 * def __init__ (
 * ** value: ndarray)
 *
 * 5.
 * def __init__ (
 * ** tensor: Tensor)
 *
 * 6.
 * (should have at least one parameter, one parameter equals to case 5, zero
 * parameter equals to case 1.)
 * def __init__ (
 * ** tensor: Tensor,
 * ** name: std::string)
 * **/
J
Jack Zhou 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
int StringTensorInit(PyObject* self, PyObject* args, PyObject* kwargs) {
  // set a flag to record use kwargs or not
  bool flag_kwargs = false;
  if (kwargs) flag_kwargs = true;

  // all kwargs
  PyObject* kw_zero_copy = NULL;

  PyObject* kw_value = NULL;  // receive PyArray or Tensor
  PyObject* kw_name = NULL;
  PyObject* kw_dims = NULL;

  // the keywords argument
1118 1119 1120 1121 1122
  static char* kwlist[] = {const_cast<char*>("value"),
                           const_cast<char*>("zero_copy"),
                           const_cast<char*>("name"),
                           const_cast<char*>("dims"),
                           NULL};
J
Jack Zhou 已提交
1123 1124 1125 1126 1127 1128
  // 'O' Store a Python object (without any conversion) in a C object pointer,
  // '|' Indicates that the remaining arguments in the Python argument list are
  // optional.
  // PyArg_ParseTupleAndKeywords can Parse the parameters of a function that
  // takes both positional and keyword parameters into local variables,
  // which enhance case1, case2, case3, case4, case 5, case 6.
1129 1130 1131 1132 1133 1134 1135 1136
  bool flag_ = PyArg_ParseTupleAndKeywords(args,
                                           kwargs,
                                           "|OOOO",
                                           kwlist,
                                           &kw_value,
                                           &kw_zero_copy,
                                           &kw_name,
                                           &kw_dims);
J
Jack Zhou 已提交
1137 1138 1139 1140 1141 1142 1143 1144

  // helper map
  std::unordered_map<std::string, PyObject*> kws_map{
      {"value", kw_value},
      {"zero_copy", kw_zero_copy},
      {"name", kw_name},
      {"dims", kw_dims}};

1145 1146
  PADDLE_ENFORCE_EQ(flag_,
                    true,
J
Jack Zhou 已提交
1147 1148 1149 1150 1151 1152 1153 1154
                    paddle::platform::errors::PreconditionNotMet(
                        "Could not parse args and kwargs successfully, "
                        "please check your input first and make"
                        "sure you are on the right way. "
                        "The expected arguments as follow: ("
                        "value, zero_copy, name, dims)"));

  PADDLE_ENFORCE_NOT_NULL(
1155 1156 1157 1158 1159
      self,
      paddle::platform::errors::Fatal(
          "Calling __init__ of Eager Tensor without __new__ is "
          "forbidden. Please check your code and make sure you new a "
          "eager tensor before init it."));
J
Jack Zhou 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

  auto py_tensor_ptr = reinterpret_cast<TensorObject*>(self);

  Py_ssize_t args_num = PyTuple_Size(args);
  VLOG(6) << " args_num: " << args_num;
  // args_num = 0, means that there is no position arguments.
  if (args_num == (Py_ssize_t)0) {
    if (!flag_kwargs) {
      // case 1
      VLOG(6) << "Calling case1's string initializer.";
      EmptyStringTensorInitializer(
1171 1172 1173
          py_tensor_ptr,
          egr::Controller::Instance().GenerateUniqueName(
              "generated_string_tensor"),
J
Jack Zhou 已提交
1174 1175 1176 1177 1178 1179
          egr::Controller::Instance().GetExpectedPlace());
      return 0;
    } else {
      if (kw_value != NULL) {
        if (pybind11::detail::npy_api::get().PyArray_Check_(kw_value)) {
          VLOG(6) << "Calling case3's or case4's string initializer";
1180 1181
          AutoInitStringTensorByPyArray(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1182
          return 0;
1183
        } else if (PyObject_TypeCheck(kw_value, p_string_tensor_type)) {
J
Jack Zhou 已提交
1184
          VLOG(6) << "Calling case5's or case6's string initializer";
1185 1186
          AutoInitStringTensorByStringTensor(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
          return 0;
        } else {
          PADDLE_THROW(platform::errors::InvalidArgument(
              "Could not parse the first keyword argument successfully, "
              "the first keyword argument is value, but it should be PyArray "
              "or StringTensor."
              "Please check your input first and make sure you are on the "
              "right way."));
        }
      } else if (kw_dims != NULL) {
        VLOG(6) << "Calling case2's string initializer.";
        std::unordered_map<std::string, Py_ssize_t> kw_order_map{{"dims", 1},
                                                                 {"name", 2}};

        std::vector<int> dims = CastPyArg2VectorOfInt(kw_dims, 0);
1202 1203 1204 1205 1206 1207
        std::string act_name = ParseName(kws_map,
                                         kw_order_map,
                                         args,
                                         flag_kwargs,
                                         args_num,
                                         "generated_string_tensor");
J
Jack Zhou 已提交
1208
        EmptyStringTensorInitializer(
1209 1210 1211 1212
            py_tensor_ptr,
            act_name,
            egr::Controller::Instance().GetExpectedPlace(),
            dims);
J
Jack Zhou 已提交
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        return 0;
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "We not only support construct Tensor from numpy value "
            "or StringTensor with python kwargs by this initializer, "
            "but also even support dtype to init a empty StringTensor. "
            "Please check your input first and make sure you call the existed "
            "constructor."));
      }
    }
  } else if (args_num == (Py_ssize_t)1) {  // case 3 ~ 6
C
co63oc 已提交
1224
    // 1 position args, remaining arguments are kwargs
J
Jack Zhou 已提交
1225 1226 1227
    PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
    if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
      VLOG(6) << "Calling case3's or case4's string initializer.";
1228 1229
      AutoInitStringTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1230
      return 0;
1231
    } else if (PyObject_TypeCheck(arg0_ptr, p_string_tensor_type)) {
J
Jack Zhou 已提交
1232
      VLOG(6) << "Calling case5's or case6's string initializer.";
1233 1234
      AutoInitStringTensorByStringTensor(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
      return 0;
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Could not parse the first keyword argument successfully, "
          "the first keyword argument is value, but it should be PyArray "
          "or StringTensor."
          "Please check your input first and make sure you are on the "
          "right way."));
    }
  } else if (args_num == (Py_ssize_t)2) {  // case 2
    // 2 position args
    if (!flag_kwargs) {
      PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
1248
      if (PyObject_TypeCheck(arg0_ptr, p_string_tensor_type)) {
J
Jack Zhou 已提交
1249
        VLOG(6) << "Calling case6's string initializer.";
1250 1251
        AutoInitStringTensorByStringTensor(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1252 1253 1254
        return 0;
      } else if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
        VLOG(6) << "Calling case3's string initializer.";
1255 1256
        AutoInitStringTensorByPyArray(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
        return 0;
      } else {
        VLOG(6) << "Calling case2's string initializer.";
        std::vector<int> dims = CastPyArg2VectorOfInt(arg0_ptr, 0);
        std::string act_name = "";
        PyObject* name_obj = PyTuple_GET_ITEM(args, 1);
        if (name_obj == Py_None) {
          act_name = egr::Controller::Instance().GenerateUniqueName(
              "generated_string_tensor");
        } else {
          act_name = CastPyArg2AttrString(PyTuple_GET_ITEM(args, 1), 1);
        }
        EmptyStringTensorInitializer(
1270 1271 1272 1273
            py_tensor_ptr,
            act_name,
            egr::Controller::Instance().GetExpectedPlace(),
            dims);
J
Jack Zhou 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
        return 0;
      }
    } else {
      PADDLE_THROW(platform::errors::Fatal(
          "Can't not find expected num of args, please check your call, and "
          "make sure u call the existed constructor."));
    }
  }
  return 1;
}

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
void AddPyMethodDefs(std::vector<PyMethodDef>* vector, PyMethodDef* methods) {
  if (!vector->empty()) {
    // remove nullptr terminator
    vector->pop_back();
  }
  while (true) {
    vector->push_back(*methods);
    if (!methods->ml_name) {
      break;
    }
    methods++;
  }
}

1299
static void TensorDealloc(TensorObject* self) {
1300 1301
  if (self->weakrefs != NULL)
    PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
1302
  self->tensor.~Tensor();
1303 1304 1305 1306
  Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}

extern struct PyGetSetDef variable_properties[];
J
Jack Zhou 已提交
1307
extern struct PyGetSetDef string_tensor_variable_properties[];
1308 1309

extern PyMethodDef variable_methods[];
1310
extern PyMethodDef math_op_patch_methods[];
J
Jack Zhou 已提交
1311
extern PyMethodDef string_tensor_variable_methods[];
1312

W
wanghuancoder 已提交
1313 1314 1315 1316
PyNumberMethods number_methods;
PySequenceMethods sequence_methods;
PyMappingMethods mapping_methods;

1317 1318 1319
void BindEager(pybind11::module* module) {
  auto m = module->def_submodule("eager");

1320 1321 1322 1323
  static std::vector<PyMethodDef> methods;
  AddPyMethodDefs(&methods, variable_methods);
  AddPyMethodDefs(&methods, math_op_patch_methods);

1324
  auto heap_type = reinterpret_cast<PyHeapTypeObject*>(
1325
      PyType_Type.tp_alloc(&PyType_Type, 0));
1326 1327
  heap_type->ht_name = ToPyObject("Tensor");
  heap_type->ht_qualname = ToPyObject("Tensor");
1328
  auto type = &heap_type->ht_type;
1329
  type->tp_name = "Tensor";
1330
  type->tp_basicsize = sizeof(TensorObject);
1331
  type->tp_dealloc = (destructor)TensorDealloc;
1332 1333 1334
  type->tp_as_number = &number_methods;
  type->tp_as_sequence = &sequence_methods;
  type->tp_as_mapping = &mapping_methods;
1335
  type->tp_methods = methods.data();
1336
  type->tp_getset = variable_properties;
1337 1338
  type->tp_init = TensorInit;
  type->tp_new = TensorNew;
1339
  type->tp_weaklistoffset = offsetof(TensorObject, weakrefs);
1340 1341
  Py_INCREF(&PyBaseObject_Type);
  type->tp_base = reinterpret_cast<PyTypeObject*>(&PyBaseObject_Type);
1342 1343 1344 1345 1346
  type->tp_flags |=
      Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
#if PY_VERSION_HEX >= 0x03050000
  type->tp_as_async = &heap_type->as_async;
#endif
1347
  p_tensor_type = type;
1348 1349

  if (PyType_Ready(type) < 0) {
1350
    PADDLE_THROW(platform::errors::Fatal(
1351
        "Init Paddle error in BindEager(PyType_Ready)."));
1352 1353 1354
    return;
  }

1355
  Py_INCREF(type);
1356 1357
  if (PyModule_AddObject(m.ptr(), "Tensor", reinterpret_cast<PyObject*>(type)) <
      0) {
1358
    Py_DECREF(type);
1359 1360
    Py_DECREF(m.ptr());
    PADDLE_THROW(platform::errors::Fatal(
1361
        "Init Paddle error in BindEager(PyModule_AddObject)."));
1362 1363 1364 1365
    return;
  }

  BindFunctions(m.ptr());
W
wanghuancoder 已提交
1366
  BindEagerPyLayer(m.ptr());
1367
  BindEagerOpFunctions(&m);
1368 1369
}

J
Jack Zhou 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
void BindEagerStringTensor(pybind11::module* module) {
  auto m = module->def_submodule("eager");

  auto heap_type = reinterpret_cast<PyHeapTypeObject*>(
      PyType_Type.tp_alloc(&PyType_Type, 0));
  heap_type->ht_name = ToPyObject("StringTensor");
  heap_type->ht_qualname = ToPyObject("StringTensor");
  auto type = &heap_type->ht_type;
  type->tp_name = "StringTensor";
  type->tp_basicsize = sizeof(TensorObject);
  type->tp_dealloc = (destructor)TensorDealloc;
  type->tp_as_number = &number_methods;
  type->tp_as_sequence = &sequence_methods;
  type->tp_as_mapping = &mapping_methods;
  type->tp_methods = string_tensor_variable_methods;
  type->tp_getset = string_tensor_variable_properties;
  type->tp_init = StringTensorInit;
  type->tp_new = TensorNew;
  Py_INCREF(&PyBaseObject_Type);
  type->tp_base = reinterpret_cast<PyTypeObject*>(&PyBaseObject_Type);
  type->tp_flags |=
      Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
#if PY_VERSION_HEX >= 0x03050000
  type->tp_as_async = &heap_type->as_async;
#endif
  p_string_tensor_type = type;

  if (PyType_Ready(type) < 0) {
    PADDLE_THROW(platform::errors::Fatal(
        "Init Paddle error in BindEager(PyType_Ready)."));
    return;
  }

  Py_INCREF(type);
1404 1405
  if (PyModule_AddObject(
          m.ptr(), "StringTensor", reinterpret_cast<PyObject*>(type)) < 0) {
J
Jack Zhou 已提交
1406 1407 1408 1409 1410 1411 1412 1413
    Py_DECREF(type);
    Py_DECREF(m.ptr());
    PADDLE_THROW(platform::errors::Fatal(
        "Init Paddle error in BindEagerStringTensor(PyModule_AddObject)."));
    return;
  }
}

1414 1415
}  // namespace pybind
}  // namespace paddle