eager.cc 48.0 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 15 16 17 18
#include <Python.h>

#include <string>
#include <vector>

19
#include "paddle/fluid/eager/accumulation/accumulation_node.h"
20 21 22
#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/autograd_meta.h"
#include "paddle/fluid/eager/utils.h"
23
#include "paddle/fluid/framework/convert_utils.h"
24 25 26 27
#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"
28 29 30
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/dense_tensor.h"
31
#include "pybind11/detail/internals.h"
32 33
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
34
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
35
#include "paddle/fluid/framework/python_headers.h"
36
#include "paddle/fluid/pybind/eager_op_function_impl.h"
37
#include "paddle/fluid/pybind/tensor_py.h"
38
#include "paddle/phi/api/lib/utils/tensor_utils.h"
J
Jack Zhou 已提交
39
#include "paddle/phi/core/string_tensor.h"
40 41 42 43 44
namespace paddle {
namespace pybind {

namespace py = ::pybind11;

45
PyTypeObject* p_tensor_type;
J
Jack Zhou 已提交
46
PyTypeObject* p_string_tensor_type;  // For StringTensor
47
extern PyTypeObject* g_vartype_pytype;
48
extern PyTypeObject* g_framework_tensor_pytype;
49

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

384
// initialize Tensor by Tensor or framework::Tensor (mix args and
385
// kwargs) automatically.
386 387
void AutoInitTensorByTensor(TensorObject* py_tensor_ptr,
                            std::unordered_map<std::string, PyObject*> kws_map,
388 389
                            PyObject* args,
                            bool flag_kwargs,
390 391 392
                            Py_ssize_t args_num,
                            bool init_by_egr_tensor = true) {
  // The first argument of the Tensor constructor is Tensor or
393
  // framework Tensor,
394
  // there are 3 arguments to construct the new Tensor,
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  // 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) {
410
    paddle::experimental::Tensor src_tensor;
411
    if (kw_order_map["value"] <= args_num) {
412 413 414
      src_tensor =
          CastPyArg2Tensor(PyTuple_GET_ITEM(args, kw_order_map["value"] - 1),
                           kw_order_map["value"] - 1);
415 416
    } else {
      if (flag_kwargs && kws_map["value"] != NULL) {
417
        src_tensor = CastPyArg2Tensor(kws_map["value"], 0);
418 419
      } else {
        PADDLE_THROW(platform::errors::InvalidArgument(
420 421
            "The first expected kwargs is {value: Tensor}, "
            "but could not parse the first argument {value: Tensor} "
422 423 424 425 426
            "successfully. "
            "Please check your input first and make sure you are on the right "
            "way."));
      }
    }
427
    InitTensorWithTensor(py_tensor_ptr, src_tensor, place, act_name);
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  } else {
    // init by framework tensor
    framework::Tensor src_tensor;
    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(
            "The first expected arguments is {value: framework::Tensor}, "
            "but could not parse the first argument {value: framework::Tensor} "
            "successfully. "
            "Please check your input first and make sure you are on the right "
            "way."));
      }
    }
447
    InitTensorWithFrameworkTensor(py_tensor_ptr, src_tensor, place, act_name);
448 449 450
  }
}

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

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

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

527
/** We should have init function with signature:
528 529 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
 * 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)
 *  **/
567
int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) {
0
0x45f 已提交
568
  EAGER_TRY
569 570 571 572 573 574 575 576 577
  // 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;

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

  // the keywords argument
586 587 588 589 590 591 592 593 594 595
  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};
596 597 598 599 600 601 602

  // '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.
603 604 605 606 607 608 609 610 611 612 613 614 615
  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);
616 617 618 619 620 621 622 623 624 625 626 627 628

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

629 630
  PADDLE_ENFORCE_EQ(flag_,
                    true,
631 632 633 634 635 636 637 638
                    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)"));

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

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

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

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

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

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

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

0
0x45f 已提交
894 895
  return -1;
  EAGER_CATCH_AND_THROW_RETURN_NEG
896 897
}

J
Jack Zhou 已提交
898
/** We should have init function with signature:
899 900 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
 * 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 已提交
930 931 932 933 934 935 936 937 938 939 940 941 942
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
943 944 945 946 947
  static char* kwlist[] = {const_cast<char*>("value"),
                           const_cast<char*>("zero_copy"),
                           const_cast<char*>("name"),
                           const_cast<char*>("dims"),
                           NULL};
J
Jack Zhou 已提交
948 949 950 951 952 953
  // '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.
954 955 956 957 958 959 960 961
  bool flag_ = PyArg_ParseTupleAndKeywords(args,
                                           kwargs,
                                           "|OOOO",
                                           kwlist,
                                           &kw_value,
                                           &kw_zero_copy,
                                           &kw_name,
                                           &kw_dims);
J
Jack Zhou 已提交
962 963 964 965 966 967 968 969

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

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

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

1115
static void TensorDealloc(TensorObject* self) {
1116 1117
  if (self->weakrefs != NULL)
    PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
1118
  self->tensor.~Tensor();
1119 1120 1121 1122
  Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}

extern struct PyGetSetDef variable_properties[];
J
Jack Zhou 已提交
1123
extern struct PyGetSetDef string_tensor_variable_properties[];
1124 1125

extern PyMethodDef variable_methods[];
J
Jack Zhou 已提交
1126
extern PyMethodDef string_tensor_variable_methods[];
1127

W
wanghuancoder 已提交
1128 1129 1130 1131
PyNumberMethods number_methods;
PySequenceMethods sequence_methods;
PyMappingMethods mapping_methods;

1132 1133 1134
void BindEager(pybind11::module* module) {
  auto m = module->def_submodule("eager");

1135
  auto heap_type = reinterpret_cast<PyHeapTypeObject*>(
1136
      PyType_Type.tp_alloc(&PyType_Type, 0));
1137 1138
  heap_type->ht_name = ToPyObject("Tensor");
  heap_type->ht_qualname = ToPyObject("Tensor");
1139
  auto type = &heap_type->ht_type;
1140
  type->tp_name = "Tensor";
1141
  type->tp_basicsize = sizeof(TensorObject);
1142
  type->tp_dealloc = (destructor)TensorDealloc;
1143 1144 1145 1146 1147
  type->tp_as_number = &number_methods;
  type->tp_as_sequence = &sequence_methods;
  type->tp_as_mapping = &mapping_methods;
  type->tp_methods = variable_methods;
  type->tp_getset = variable_properties;
1148 1149
  type->tp_init = TensorInit;
  type->tp_new = TensorNew;
1150
  type->tp_weaklistoffset = offsetof(TensorObject, weakrefs);
1151 1152
  Py_INCREF(&PyBaseObject_Type);
  type->tp_base = reinterpret_cast<PyTypeObject*>(&PyBaseObject_Type);
1153 1154 1155 1156 1157
  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
1158
  p_tensor_type = type;
1159 1160

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

1166
  Py_INCREF(type);
1167 1168
  if (PyModule_AddObject(m.ptr(), "Tensor", reinterpret_cast<PyObject*>(type)) <
      0) {
1169
    Py_DECREF(type);
1170 1171
    Py_DECREF(m.ptr());
    PADDLE_THROW(platform::errors::Fatal(
1172
        "Init Paddle error in BindEager(PyModule_AddObject)."));
1173 1174 1175 1176
    return;
  }

  BindFunctions(m.ptr());
W
wanghuancoder 已提交
1177
  BindEagerPyLayer(m.ptr());
1178
  BindEagerOpFunctions(&m);
1179 1180
}

J
Jack Zhou 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
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);
1215 1216
  if (PyModule_AddObject(
          m.ptr(), "StringTensor", reinterpret_cast<PyObject*>(type)) < 0) {
J
Jack Zhou 已提交
1217 1218 1219 1220 1221 1222 1223 1224
    Py_DECREF(type);
    Py_DECREF(m.ptr());
    PADDLE_THROW(platform::errors::Fatal(
        "Init Paddle error in BindEagerStringTensor(PyModule_AddObject)."));
    return;
  }
}

1225 1226
}  // namespace pybind
}  // namespace paddle