eager.cc 48.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
#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"
44 45 46 47 48
namespace paddle {
namespace pybind {

namespace py = ::pybind11;

49 50
extern PyTypeObject* p_tensor_type;
extern PyTypeObject* p_string_tensor_type;  // For StringTensor
51
extern PyTypeObject* g_vartype_pytype;
52
extern PyTypeObject* g_framework_tensor_pytype;
53

54
PyObject* TensorNew(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
55 56
  PyObject* obj = type->tp_alloc(type, 0);
  if (obj) {
57
    auto v = reinterpret_cast<TensorObject*>(obj);
58
    new (&(v->tensor)) paddle::Tensor();
59 60 61 62
  }
  return obj;
}

63
// TODO(jiabin): Overload this once we need more constructor in Python
64 65
void EmptyTensorInitializer(TensorObject* self,
                            const std::string& name,
66
                            const paddle::platform::Place& place,
67 68
                            bool persistable = false,
                            int stop_gradient = -1,
69 70
                            framework::proto::VarType::Type dtype =
                                paddle::framework::proto::VarType::FP32,
71
                            const std::vector<int>& dims = {0},
72 73
                            framework::proto::VarType::Type var_type =
                                paddle::framework::proto::VarType::LOD_TENSOR) {
74
  auto ddims = phi::make_ddim(dims);
75 76
  self->tensor.set_name(name);
  auto autograd_meta = egr::EagerUtils::autograd_meta(&(self->tensor));
77
  autograd_meta->SetPersistable(persistable);
78 79 80
  if (stop_gradient != -1) {
    autograd_meta->SetStopGradient(static_cast<bool>(stop_gradient));
  }
81 82
  if (var_type == paddle::framework::proto::VarType::LOD_TENSOR) {
    // TODO(jiabin): Maybe support LOD later
83
    std::shared_ptr<phi::DenseTensor> dense_tensor = nullptr;
84
    if (dims.size() == 1 && dims[0] == 0) {
85 86 87 88 89 90 91 92
      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 已提交
93
          std::make_shared<phi::Allocation>(),
94 95 96
          phi::DenseTensorMeta(paddle::framework::TransToPhiDataType(dtype),
                               ddims));
    }
97
    self->tensor.set_impl(dense_tensor);
98 99 100 101
  } 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);
102 103 104
  }

  if (!autograd_meta->GetMutableGradNode()) {
105 106
    autograd_meta->SetGradNode(
        std::make_shared<egr::GradNodeAccumulation>(autograd_meta));
107 108 109
    VLOG(3) << "Tensor(" << name
            << ") have not GradNode, add GradNodeAccumulation"
            << autograd_meta->GradNode() << " for it.";
110 111 112
  }
}

113 114
void EmptyStringTensorInitializer(TensorObject* self,
                                  const std::string& name,
J
Jack Zhou 已提交
115 116 117 118 119 120 121
                                  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
122
  paddle::experimental::DefaultAllocator string_allocator(actual_place);
J
Jack Zhou 已提交
123
  std::shared_ptr<phi::StringTensor> string_tensor =
124 125
      std::make_shared<phi::StringTensor>(&string_allocator,
                                          phi::StringTensorMeta{ddims});
J
Jack Zhou 已提交
126 127 128 129 130 131
  if (phi::product(ddims) > 0) {
    string_tensor->mutable_data(actual_place);
  }
  self->tensor.set_impl(string_tensor);
}

132 133
void InitTensorWithNumpyValue(TensorObject* self,
                              const py::object& array,
134
                              const paddle::platform::Place& place,
135
                              bool zero_copy = false) {
136
  PADDLE_ENFORCE_EQ(
137 138
      self->tensor.defined(),
      true,
139
      paddle::platform::errors::Fatal(
140 141
          "Calling InitTensorWithNumpyValue of Eager Tensor without "
          "EmptyTensorInitializer is "
142 143
          "forbidden. Please check your code and make sure you new a "
          "eager tensor before init it with NumPy."));
144 145
  phi::DenseTensor* impl_ptr =
      static_cast<phi::DenseTensor*>(self->tensor.impl().get());
146
  if (platform::is_cpu_place(place)) {
147
    SetTensorFromPyArray<platform::CPUPlace>(impl_ptr, array, place, zero_copy);
148
  } else if (platform::is_xpu_place(place)) {
149
    SetTensorFromPyArray<platform::XPUPlace>(impl_ptr, array, place, zero_copy);
150
  } else if (platform::is_gpu_place(place)) {
151 152
    SetTensorFromPyArray<platform::CUDAPlace>(
        impl_ptr, array, place, zero_copy);
153
  } else if (platform::is_cuda_pinned_place(place)) {
154 155
    SetTensorFromPyArray<platform::CUDAPinnedPlace>(
        impl_ptr, array, place, zero_copy);
156
  } else if (platform::is_custom_place(place)) {
157 158
    SetTensorFromPyArray<platform::CustomPlace>(
        impl_ptr, array, place, zero_copy);
159 160 161
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Place should be one of "
张春乔 已提交
162
        "CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace/CustomPlace"));
163 164 165
  }
}

J
Jack Zhou 已提交
166 167
void InitStringTensorWithNumpyValue(TensorObject* self, const py::object& obj) {
  PADDLE_ENFORCE_EQ(
168 169
      self->tensor.defined(),
      true,
J
Jack Zhou 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
      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()));
  }
}

189
void InitTensorWithTensor(TensorObject* self,
190
                          const paddle::Tensor& src,
191 192
                          const paddle::platform::Place& place,
                          const std::string& name) {
193
  self->tensor.set_name(name);
C
Chen Weihang 已提交
194
  if (place == src.place()) {
195
    self->tensor.set_impl(src.impl());
196 197
    VLOG(4) << "Same place, do ShareDataWith";
  } else {
198
    self->tensor.set_impl(src.copy_to(place, true).impl());
199 200 201
    VLOG(4) << "Different place, do TensorCopy";
  }
  if (src.get_autograd_meta()) {
202
    egr::EagerUtils::autograd_meta(&(self->tensor))
203 204 205
        ->SetPersistable(
            egr::EagerUtils::unsafe_autograd_meta(src)->Persistable());
  } else {
206
    egr::EagerUtils::autograd_meta(&(self->tensor))->SetPersistable(false);
207 208 209
  }
}

210
void InitTensorWithFrameworkTensor(TensorObject* self,
211
                                   const phi::DenseTensor& src,
212 213
                                   const paddle::platform::Place& place,
                                   const std::string& name) {
214
  self->tensor.set_name(name);
215
  if (place == src.place()) {
216
    self->tensor.set_impl(std::make_shared<phi::DenseTensor>(src));
217 218
    VLOG(4) << "Same place, do ShareDataWith";
  } else {
219
    auto temp = paddle::Tensor(std::make_shared<phi::DenseTensor>(src));
220
    self->tensor.set_impl(temp.copy_to(place, true).impl());
221 222
    VLOG(4) << "Different place, do TensorCopy";
  }
223
  egr::EagerUtils::autograd_meta(&(self->tensor))->SetPersistable(false);
224
}
225

J
Jack Zhou 已提交
226
void InitStringTensorWithStringTensor(TensorObject* self,
227
                                      const paddle::Tensor& src,
J
Jack Zhou 已提交
228 229 230 231 232 233 234 235 236
                                      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";
}

237 238
py::object ParsePyArray(
    std::unordered_map<std::string, PyObject*> kws_map,
239 240 241 242
    std::unordered_map<std::string, Py_ssize_t> kw_order_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  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,
265 266 267 268
    std::unordered_map<std::string, Py_ssize_t> kw_order_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
  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;
}

// boolean arguments: zero_copy, stop_gradient, persistable
287 288 289
int ParseBooleanArgs(std::string key,
                     std::unordered_map<std::string, PyObject*> kws_map,
                     std::unordered_map<std::string, Py_ssize_t> kw_order_map,
290 291 292
                     PyObject* args,
                     bool flag_kwargs,
                     Py_ssize_t args_num) {
293
  int res = -1;
294 295

  if (kw_order_map[key] <= args_num) {
296 297
    res = static_cast<int>(CastPyArg2AttrBoolean(
        PyTuple_GET_ITEM(args, kw_order_map[key] - 1), kw_order_map[key] - 1));
298 299
  } else {
    if (flag_kwargs && kws_map[key] != NULL) {
300
      res = static_cast<int>(CastPyArg2AttrBoolean(kws_map[key], 0));
301 302 303 304 305 306 307
    }
  }
  return res;
}

std::string ParseName(std::unordered_map<std::string, PyObject*> kws_map,
                      std::unordered_map<std::string, Py_ssize_t> kw_order_map,
308 309 310
                      PyObject* args,
                      bool flag_kwargs,
                      Py_ssize_t args_num,
J
Jack Zhou 已提交
311
                      std::string unique_name_prefix = "generated_tensor") {
312 313 314 315 316
  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 已提交
317
          egr::Controller::Instance().GenerateUniqueName(unique_name_prefix);
318 319 320 321 322
    } else {
      act_name = CastPyArg2AttrString(name_obj, kw_order_map["name"] - 1);
    }
  } else {
    if (flag_kwargs) {
J
Jiabin Yang 已提交
323
      if ((kws_map["name"] == NULL) || (kws_map["name"] == Py_None)) {
324
        act_name =
J
Jack Zhou 已提交
325
            egr::Controller::Instance().GenerateUniqueName(unique_name_prefix);
326 327 328 329 330
      } else {
        act_name = CastPyArg2AttrString(kws_map["name"], 0);
      }
    } else {
      act_name =
J
Jack Zhou 已提交
331
          egr::Controller::Instance().GenerateUniqueName(unique_name_prefix);
332 333 334 335 336
    }
  }
  return act_name;
}

337
// initialize Tensor by PyArray(first argument is PyArray,
338
// mix args and kwargs) automatically.
339 340
void AutoInitTensorByPyArray(TensorObject* py_tensor_ptr,
                             std::unordered_map<std::string, PyObject*> kws_map,
341 342
                             PyObject* args,
                             bool flag_kwargs,
343 344 345
                             Py_ssize_t args_num) {
  // The first argument of the Tensor constructor is PyArray,
  // there are 6 arguments to construct the new Tensor,
346 347 348 349 350
  // 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{
351 352 353 354 355 356
      {"value", 1},
      {"place", 2},
      {"persistable", 3},
      {"zero_copy", 4},
      {"name", 5},
      {"stop_gradient", 6}};
357 358 359 360 361 362 363

  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 = "";
364
  int stop_gradient = -1;
365 366 367 368

  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);
369 370 371 372 373 374 375 376
  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));
377
  act_name = ParseName(kws_map, kw_order_map, args, flag_kwargs, args_num);
378 379
  stop_gradient = ParseBooleanArgs(
      "stop_gradient", kws_map, kw_order_map, args, flag_kwargs, args_num);
380

381 382
  EmptyTensorInitializer(
      py_tensor_ptr, act_name, place, persistable, stop_gradient);
383
  InitTensorWithNumpyValue(py_tensor_ptr, numpy_value, place, zero_copy);
384 385
}

386
// initialize Tensor by Tensor or phi::DenseTensor (mix args and
387
// kwargs) automatically.
388 389
void AutoInitTensorByTensor(TensorObject* py_tensor_ptr,
                            std::unordered_map<std::string, PyObject*> kws_map,
390 391
                            PyObject* args,
                            bool flag_kwargs,
392 393 394
                            Py_ssize_t args_num,
                            bool init_by_egr_tensor = true) {
  // The first argument of the Tensor constructor is Tensor or
395
  // framework Tensor,
396
  // there are 3 arguments to construct the new Tensor,
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
  // 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}, {"place", 2}, {"name", 3}};

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

  if (init_by_egr_tensor) {
412
    paddle::Tensor src_tensor;
413
    if (kw_order_map["value"] <= args_num) {
414 415 416
      src_tensor =
          CastPyArg2Tensor(PyTuple_GET_ITEM(args, kw_order_map["value"] - 1),
                           kw_order_map["value"] - 1);
417 418
    } else {
      if (flag_kwargs && kws_map["value"] != NULL) {
419
        src_tensor = CastPyArg2Tensor(kws_map["value"], 0);
420 421
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
422 423
            "The first expected kwargs is {value: Tensor}, "
            "but could not parse the first argument {value: Tensor} "
424 425 426 427 428
            "successfully. "
            "Please check your input first and make sure you are on the right "
            "way."));
      }
    }
429
    InitTensorWithTensor(py_tensor_ptr, src_tensor, place, act_name);
430 431
  } else {
    // init by framework tensor
432
    phi::DenseTensor src_tensor;
433 434 435 436 437 438 439 440 441
    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(
442 443
            "The first expected arguments is {value: phi::DenseTensor}, "
            "but could not parse the first argument {value: phi::DenseTensor} "
444 445 446 447 448
            "successfully. "
            "Please check your input first and make sure you are on the right "
            "way."));
      }
    }
449
    InitTensorWithFrameworkTensor(py_tensor_ptr, src_tensor, place, act_name);
450 451 452
  }
}

J
Jack Zhou 已提交
453 454
void AutoInitStringTensorByPyArray(
    TensorObject* py_tensor_ptr,
455 456 457 458
    std::unordered_map<std::string, PyObject*> kws_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
J
Jack Zhou 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  // 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);
474 475 476 477 478
  act_name = ParseName(kws_map,
                       kw_order_map,
                       args,
                       flag_kwargs,
                       args_num,
J
Jack Zhou 已提交
479 480 481 482 483 484 485
                       "generated_string_tensor");
  EmptyStringTensorInitializer(py_tensor_ptr, act_name, place);
  InitStringTensorWithNumpyValue(py_tensor_ptr, numpy_value);
}

void AutoInitStringTensorByStringTensor(
    TensorObject* py_tensor_ptr,
486 487 488 489
    std::unordered_map<std::string, PyObject*> kws_map,
    PyObject* args,
    bool flag_kwargs,
    Py_ssize_t args_num) {
J
Jack Zhou 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502
  // 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 = "";

503 504 505 506 507
  act_name = ParseName(kws_map,
                       kw_order_map,
                       args,
                       flag_kwargs,
                       args_num,
J
Jack Zhou 已提交
508
                       "generated_string_tensor");
509
  paddle::Tensor src_tensor;
J
Jack Zhou 已提交
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
  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);
}

529
/** We should have init function with signature:
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
 * 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,
 * ** stop_gradient: bool)
 * 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,
 * ** name: std::string)
 * 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)
 *  **/
569
int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) {
0
0x45f 已提交
570
  EAGER_TRY
571 572 573 574 575 576 577 578 579
  // 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;

580
  PyObject* kw_value = NULL;  // receive PyArray or Tensor
581 582 583 584 585 586 587
  PyObject* kw_place = NULL;
  PyObject* kw_name = NULL;
  PyObject* kw_dims = NULL;
  PyObject* kw_dtype = NULL;
  PyObject* kw_type = NULL;

  // the keywords argument
588 589 590 591 592 593 594 595 596 597
  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"),
                           NULL};
598 599 600 601 602 603 604

  // '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.
605 606 607 608 609 610 611 612 613 614 615 616 617
  bool flag_ = PyArg_ParseTupleAndKeywords(args,
                                           kwargs,
                                           "|OOOOOOOOO",
                                           kwlist,
                                           &kw_value,
                                           &kw_place,
                                           &kw_persistable,
                                           &kw_zero_copy,
                                           &kw_name,
                                           &kw_stop_gradient,
                                           &kw_dims,
                                           &kw_dtype,
                                           &kw_type);
618 619 620 621 622 623 624 625 626 627 628 629 630

  // 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},
      {"type", kw_type}};

631 632
  PADDLE_ENFORCE_EQ(flag_,
                    true,
633 634 635 636 637 638 639 640
                    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, "
                        "name, stop_gradient, dims, dtype, type)"));

641
  PADDLE_ENFORCE_NOT_NULL(
642 643 644 645 646
      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."));
647

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

  Py_ssize_t args_num = PyTuple_Size(args);
651 652 653 654 655
  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) {
656 657
      // case 1
      VLOG(6) << "Calling case1's initializer.";
658
      EmptyTensorInitializer(
659 660 661 662
          py_tensor_ptr,
          egr::Controller::Instance().GenerateUniqueName("generated_tensor"),
          egr::Controller::Instance().GetExpectedPlace());
      return 0;
663 664 665 666
    } 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";
667 668
          AutoInitTensorByPyArray(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
669
          return 0;
670 671
        } else if (PyObject_IsInstance(
                       kw_value, reinterpret_cast<PyObject*>(p_tensor_type))) {
672
          VLOG(6) << "Calling case5's or case6's initializer";
673 674
          AutoInitTensorByTensor(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
675 676 677 678 679
          return 0;
        } else if (PyObject_IsInstance(kw_value,
                                       reinterpret_cast<PyObject*>(
                                           g_framework_tensor_pytype))) {
          VLOG(6) << "Calling case7's initializer.";
680 681 682 683
          AutoInitTensorByTensor(py_tensor_ptr,
                                 kws_map,
                                 args,
                                 flag_kwargs,
684 685
                                 args_num,
                                 /* false means not init by egr tensor*/ false);
686
          return 0;
687
        } else {
688 689 690
          PADDLE_THROW(platform::errors::InvalidArgument(
              "Could not parse the first keyword argument successfully, "
              "the first keyword argument is value, but it should be PyArray "
691
              "or Tensor or phi::DenseTensor. "
692 693
              "Please check your input first and make sure you are on the "
              "right way."));
694
        }
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
      } else if (kw_dtype != NULL &&
                 PyObject_IsInstance(
                     kw_dtype, reinterpret_cast<PyObject*>(g_vartype_pytype))) {
        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);

732
        std::string act_name = "";
733
        if (kw_name == Py_None) {
734 735 736
          act_name = egr::Controller::Instance().GenerateUniqueName(
              "generated_tensor");
        } else {
737
          act_name = CastPyArg2AttrString(kw_name, 0);
738
        }
739 740 741 742 743

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

744 745
        EmptyTensorInitializer(py_tensor_ptr,
                               act_name,
746 747
                               egr::Controller::Instance().GetExpectedPlace(),
                               persistable,
748 749 750 751
                               /* stop_gradient */ -1,
                               dtype,
                               dims,
                               var_type);
752

753
        return 0;
754 755
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
756
            "We not only support construct Tensor from numpy value "
757
            "or tensor(Tensor or phi::DenseTensor) "
758
            "with python kwargs by this initializer, "
759
            "but also even support dtype to init a empty Tensor. "
760 761
            "Please check your input first and make sure you call the existed "
            "constructor."));
762
      }
763 764 765
    }
  } else if (args_num == (Py_ssize_t)1 || args_num == (Py_ssize_t)2 ||
             args_num == (Py_ssize_t)3) {
C
co63oc 已提交
766
    // 1 to 3 position args, remaining arguments are kwargs
767 768 769
    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.";
770 771
      AutoInitTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
772
      return 0;
773 774
    } else if (PyObject_IsInstance(
                   arg0_ptr, reinterpret_cast<PyObject*>(p_tensor_type))) {
775
      VLOG(6) << "Calling case5's or case6's initializer.";
776 777
      AutoInitTensorByTensor(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
778
      return 0;
779 780 781
    } else if (PyObject_IsInstance(
                   arg0_ptr,
                   reinterpret_cast<PyObject*>(g_framework_tensor_pytype))) {
782
      VLOG(6) << "Calling case7's initializer.";
783 784 785 786
      AutoInitTensorByTensor(py_tensor_ptr,
                             kws_map,
                             args,
                             flag_kwargs,
787 788
                             args_num,
                             /* false means not init by egr tensor*/ false);
789 790 791
      return 0;
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
792
          "We support construct Tensor from numpy value "
793
          "or tensor(Tensor or phi::DenseTensor) "
794
          "with python args and kwargs by this initializer, "
795
          "but the first argument should be PyArray or Tensor or "
796
          "phi::DenseTensor. "
797 798
          "Please check your input first and make sure you call the existed "
          "constructor."));
799
    }
800
  } else if (args_num == (Py_ssize_t)4) {
C
co63oc 已提交
801
    // 4 position args, remaining arguments are kwargs
802 803 804
    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.";
805 806
      AutoInitTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
807
      return 0;
808 809 810
    } else {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Incompatible constructor arguments, "
C
co63oc 已提交
811
          "there are 4 position args and remaining arguments arg kwargs,"
812 813 814
          "but the first position args should be PyArray. "
          "Please check your code and make sure the first position args is "
          "PyArray."));
815
    }
816 817
  } else if (args_num == (Py_ssize_t)5) {
    if (!flag_kwargs) {
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
      PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
      if (PyObject_IsInstance(arg0_ptr,
                              reinterpret_cast<PyObject*>(g_vartype_pytype))) {
        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);
837 838
        EmptyTensorInitializer(py_tensor_ptr,
                               act_name,
839
                               egr::Controller::Instance().GetExpectedPlace(),
840 841 842 843 844
                               persistable,
                               -1,
                               dtype,
                               dims,
                               var_type);
845
        return 0;
846 847
      } else if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
        VLOG(6) << "Calling case3's initializer.";
848 849
        AutoInitTensorByPyArray(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
850 851 852
        return 0;
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
853 854 855 856 857
            "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."));
858
      }
C
co63oc 已提交
859
    } else {  // five position args, remaining arguments are kwargs
860
      PyObject* arg0_ptr = PyTuple_GET_ITEM(args, 0);
861 862
      if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
        VLOG(6) << "Calling case3's or case4's initializer";
863 864
        AutoInitTensorByPyArray(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
865
        return 0;
866
      } else {
867 868
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Incompatible constructor arguments, "
C
co63oc 已提交
869
            "there are 5 position args and remaining arguments are kwargs,"
870 871 872
            "but the first position args should be PyArray. "
            "Please check your code and make sure the first position args is "
            "PyArray."));
873 874
      }
    }
875 876 877 878
  } else if (args_num == (Py_ssize_t)6) {
    if (!flag_kwargs) {
      // case 3
      VLOG(6) << "Calling case3's initializer.";
879 880
      AutoInitTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
881
      return 0;
C
co63oc 已提交
882
    } else {  // six position args, remaining arguments are kwargs, but this
883 884 885
              // is not a right way
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Incompatible constructor arguments, "
C
co63oc 已提交
886
          "there are 6 position args and the remaining arguments are kwargs. "
887 888
          "Please check your code and make sure the first position args is "
          "PyArray."));
889
    }
890 891 892 893
  } 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."));
894
  }
895

0
0x45f 已提交
896 897
  return -1;
  EAGER_CATCH_AND_THROW_RETURN_NEG
898 899
}

J
Jack Zhou 已提交
900
/** We should have init function with signature:
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
 * 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 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944
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
945 946 947 948 949
  static char* kwlist[] = {const_cast<char*>("value"),
                           const_cast<char*>("zero_copy"),
                           const_cast<char*>("name"),
                           const_cast<char*>("dims"),
                           NULL};
J
Jack Zhou 已提交
950 951 952 953 954 955
  // '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.
956 957 958 959 960 961 962 963
  bool flag_ = PyArg_ParseTupleAndKeywords(args,
                                           kwargs,
                                           "|OOOO",
                                           kwlist,
                                           &kw_value,
                                           &kw_zero_copy,
                                           &kw_name,
                                           &kw_dims);
J
Jack Zhou 已提交
964 965 966 967 968 969 970 971

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

972 973
  PADDLE_ENFORCE_EQ(flag_,
                    true,
J
Jack Zhou 已提交
974 975 976 977 978 979 980 981
                    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(
982 983 984 985 986
      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 已提交
987 988 989 990 991 992 993 994 995 996 997

  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(
998 999 1000
          py_tensor_ptr,
          egr::Controller::Instance().GenerateUniqueName(
              "generated_string_tensor"),
J
Jack Zhou 已提交
1001 1002 1003 1004 1005 1006
          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";
1007 1008
          AutoInitStringTensorByPyArray(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1009
          return 0;
1010 1011 1012
        } else if (PyObject_IsInstance(
                       kw_value,
                       reinterpret_cast<PyObject*>(p_string_tensor_type))) {
J
Jack Zhou 已提交
1013
          VLOG(6) << "Calling case5's or case6's string initializer";
1014 1015
          AutoInitStringTensorByStringTensor(
              py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
          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);
1031 1032 1033 1034 1035 1036
        std::string act_name = ParseName(kws_map,
                                         kw_order_map,
                                         args,
                                         flag_kwargs,
                                         args_num,
                                         "generated_string_tensor");
J
Jack Zhou 已提交
1037
        EmptyStringTensorInitializer(
1038 1039 1040 1041
            py_tensor_ptr,
            act_name,
            egr::Controller::Instance().GetExpectedPlace(),
            dims);
J
Jack Zhou 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
        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 已提交
1053
    // 1 position args, remaining arguments are kwargs
J
Jack Zhou 已提交
1054 1055 1056
    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.";
1057 1058
      AutoInitStringTensorByPyArray(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1059
      return 0;
1060 1061 1062
    } else if (PyObject_IsInstance(
                   arg0_ptr,
                   reinterpret_cast<PyObject*>(p_string_tensor_type))) {
J
Jack Zhou 已提交
1063
      VLOG(6) << "Calling case5's or case6's string initializer.";
1064 1065
      AutoInitStringTensorByStringTensor(
          py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
      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);
      if (PyObject_IsInstance(
              arg0_ptr, reinterpret_cast<PyObject*>(p_string_tensor_type))) {
        VLOG(6) << "Calling case6's string initializer.";
1082 1083
        AutoInitStringTensorByStringTensor(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1084 1085 1086
        return 0;
      } else if (pybind11::detail::npy_api::get().PyArray_Check_(arg0_ptr)) {
        VLOG(6) << "Calling case3's string initializer.";
1087 1088
        AutoInitStringTensorByPyArray(
            py_tensor_ptr, kws_map, args, flag_kwargs, args_num);
J
Jack Zhou 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        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(
1102 1103 1104 1105
            py_tensor_ptr,
            act_name,
            egr::Controller::Instance().GetExpectedPlace(),
            dims);
J
Jack Zhou 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
        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;
}

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
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++;
  }
}

1131
static void TensorDealloc(TensorObject* self) {
1132 1133
  if (self->weakrefs != NULL)
    PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
1134
  self->tensor.~Tensor();
1135 1136 1137 1138
  Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}

extern struct PyGetSetDef variable_properties[];
J
Jack Zhou 已提交
1139
extern struct PyGetSetDef string_tensor_variable_properties[];
1140 1141

extern PyMethodDef variable_methods[];
1142
extern PyMethodDef math_op_patch_methods[];
J
Jack Zhou 已提交
1143
extern PyMethodDef string_tensor_variable_methods[];
1144

W
wanghuancoder 已提交
1145 1146 1147 1148
PyNumberMethods number_methods;
PySequenceMethods sequence_methods;
PyMappingMethods mapping_methods;

1149 1150 1151
void BindEager(pybind11::module* module) {
  auto m = module->def_submodule("eager");

1152 1153 1154 1155
  static std::vector<PyMethodDef> methods;
  AddPyMethodDefs(&methods, variable_methods);
  AddPyMethodDefs(&methods, math_op_patch_methods);

1156
  auto heap_type = reinterpret_cast<PyHeapTypeObject*>(
1157
      PyType_Type.tp_alloc(&PyType_Type, 0));
1158 1159
  heap_type->ht_name = ToPyObject("Tensor");
  heap_type->ht_qualname = ToPyObject("Tensor");
1160
  auto type = &heap_type->ht_type;
1161
  type->tp_name = "Tensor";
1162
  type->tp_basicsize = sizeof(TensorObject);
1163
  type->tp_dealloc = (destructor)TensorDealloc;
1164 1165 1166
  type->tp_as_number = &number_methods;
  type->tp_as_sequence = &sequence_methods;
  type->tp_as_mapping = &mapping_methods;
1167
  type->tp_methods = methods.data();
1168
  type->tp_getset = variable_properties;
1169 1170
  type->tp_init = TensorInit;
  type->tp_new = TensorNew;
1171
  type->tp_weaklistoffset = offsetof(TensorObject, weakrefs);
1172 1173
  Py_INCREF(&PyBaseObject_Type);
  type->tp_base = reinterpret_cast<PyTypeObject*>(&PyBaseObject_Type);
1174 1175 1176 1177 1178
  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
1179
  p_tensor_type = type;
1180 1181

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

1187
  Py_INCREF(type);
1188 1189
  if (PyModule_AddObject(m.ptr(), "Tensor", reinterpret_cast<PyObject*>(type)) <
      0) {
1190
    Py_DECREF(type);
1191 1192
    Py_DECREF(m.ptr());
    PADDLE_THROW(platform::errors::Fatal(
1193
        "Init Paddle error in BindEager(PyModule_AddObject)."));
1194 1195 1196 1197
    return;
  }

  BindFunctions(m.ptr());
W
wanghuancoder 已提交
1198
  BindEagerPyLayer(m.ptr());
1199
  BindEagerOpFunctions(&m);
1200 1201
}

J
Jack Zhou 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
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);
1236 1237
  if (PyModule_AddObject(
          m.ptr(), "StringTensor", reinterpret_cast<PyObject*>(type)) < 0) {
J
Jack Zhou 已提交
1238 1239 1240 1241 1242 1243 1244 1245
    Py_DECREF(type);
    Py_DECREF(m.ptr());
    PADDLE_THROW(platform::errors::Fatal(
        "Init Paddle error in BindEagerStringTensor(PyModule_AddObject)."));
    return;
  }
}

1246 1247
}  // namespace pybind
}  // namespace paddle