eager_properties.cc 21.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/* 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
#include <Python.h>
13 14 15 16
// Avoid a problem with copysign defined in pyconfig.h on Windows.
#ifdef copysign
#undef copysign
#endif
17 18 19 20

#include <string>
#include <vector>

21
#include "paddle/fluid/eager/accumulation/accumulation_node.h"
22 23 24
#include "paddle/fluid/eager/api/all.h"
#include "paddle/fluid/eager/autograd_meta.h"
#include "paddle/fluid/eager/utils.h"
25
#include "paddle/fluid/imperative/op_base.h"
26 27 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.h"
#include "paddle/fluid/pybind/eager_utils.h"
#include "paddle/fluid/pybind/exception.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

36 37 38 39 40
#pragma GCC diagnostic ignored "-Wwrite-strings"

namespace paddle {
namespace pybind {

41
extern PyTypeObject* p_tensor_type;
42

W
wanghuancoder 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
PyDoc_STRVAR(tensor_name__doc__,
             R"DOC(name

Tensor's name.

Returns:
    str: Tensor's name.

Examples:
    .. code-block:: python

        import paddle

        x = paddle.to_tensor(1.)
        print(x.name)  # generated_tensor_0
        x.name = 'test_tensor_name'
        print(x.name)  # test_tensor_name
)DOC");

62 63
PyObject* tensor_properties_get_name(TensorObject* self, void* closure) {
  EAGER_TRY
C
co63oc 已提交
64 65
  // NOTE(dev): [why not use egr::Controller::Instance::GenerateUniqueName()?]
  // Because Controller must holder a tracer, but 'tensor.name' maybe called
66 67
  // everywhere such as static graph mode in @to_static, which means tracer is
  // None.
68 69 70 71
  static egr::UniqueNameGenerator name_generator;
  if (self->tensor.name().empty()) {
    self->tensor.set_name(name_generator.Generate());
  }
72
  return ToPyObject(self->tensor.name());
73 74 75
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
PyDoc_STRVAR(tensor_type__doc__,
             R"DOC(type

Tensor's type.

Returns:
    VarType: Tensor's type.

Examples:
    .. code-block:: python

        import paddle

        x = paddle.to_tensor(1.)
        print(x.type) # VarType.LOD_TENSOR
)DOC");

93 94
PyObject* tensor_properties_get_type(TensorObject* self, void* closure) {
  EAGER_TRY
95 96 97 98
  if (!self->tensor.defined()) {
    // be same to old dygraph
    return ToPyObject(paddle::framework::proto::VarType::LOD_TENSOR);
  }
99
  if (self->tensor.is_dense_tensor()) {
100
    return ToPyObject(paddle::framework::proto::VarType::LOD_TENSOR);
101 102
  } else if (self->tensor.is_selected_rows()) {
    return ToPyObject(paddle::framework::proto::VarType::SELECTED_ROWS);
103 104 105 106
  } else if (egr::IsVariableCompatTensor(self->tensor)) {
    return ToPyObject(static_cast<paddle::framework::proto::VarType::Type>(
        static_cast<const egr::VariableCompatTensor*>(self->tensor.impl().get())
            ->Type()));
107
  } else {
108
    RETURN_PY_NONE
109 110 111 112
  }
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

113
PyDoc_STRVAR(tensor_is_leaf__doc__,  // NOLINT
W
wanghuancoder 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
             R"DOC(is_leaf

Whether a Tensor is leaf Tensor.

For the Tensor whose stop_gradient is ``True`` , it will be leaf Tensor.

For the Tensor whose stop_gradient is ``False`` , it will be leaf Tensor too if it is created by user.

Returns:
    bool: Whether a Tensor is leaf Tensor.

Examples:
    .. code-block:: python

        import paddle

        x = paddle.to_tensor(1.)
        print(x.is_leaf) # True

        x = paddle.to_tensor(1., stop_gradient=True)
        y = x + 1
        print(x.is_leaf) # True
        print(y.is_leaf) # True

        x = paddle.to_tensor(1., stop_gradient=False)
        y = x + 1
        print(x.is_leaf) # True
        print(y.is_leaf) # False
)DOC");

W
wanghuancoder 已提交
144 145
PyObject* tensor_properties_is_leaf(TensorObject* self, void* closure) {
  EAGER_TRY
146
  return ToPyObject(egr::EagerUtils::IsLeafTensor(self->tensor));
W
wanghuancoder 已提交
147 148 149
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

150 151
int tensor_properties_set_name(TensorObject* self,
                               PyObject* value,
152 153
                               void* closure) {
  EAGER_TRY
154
  self->tensor.set_name(CastPyArg2AttrString(value, 0));
155
  return 0;
0
0x45f 已提交
156
  EAGER_CATCH_AND_THROW_RETURN_NEG
157 158
}

W
wanghuancoder 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
PyDoc_STRVAR(tensor_stop_gradient__doc__,
             R"DOC(stop_gradient

Tensor's stop_gradient.

Returns:
    bool: Tensor's stop_gradient.

Examples:
    .. code-block:: python

        import paddle

        x = paddle.to_tensor(1.)
        print(x.stop_gradient) # True
        x.stop_gradient = False
        print(x.stop_gradient) # False
)DOC");

178 179 180
PyObject* tensor_properties_get_stop_gradient(TensorObject* self,
                                              void* closure) {
  EAGER_TRY
181
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
182 183 184 185
  return ToPyObject(meta->StopGradient());
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
PyDoc_STRVAR(tensor_data__doc__,
             R"DOC(data

Tensor's self.

Returns:
    Tensor: self.

Examples:
    .. code-block:: python

        import paddle

        x = paddle.to_tensor(1.)
        print(x)
        print(x.data)
        x.data = paddle.to_tensor(2.)
        print(x)
        print(x.data)
)DOC");
W
wanghuancoder 已提交
206 207
PyObject* tensor_properties_get_data(TensorObject* self, void* closure) {
  EAGER_TRY
W
wanghuancoder 已提交
208
  Py_INCREF(self);
W
wanghuancoder 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  return reinterpret_cast<PyObject*>(self);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

int tensor_properties_set_data(TensorObject* self,
                               PyObject* value,
                               void* closure) {
  EAGER_TRY
  auto src = CastPyArg2Tensor(value, 0);
  self->tensor = src;
  phi::DenseTensor tmp;
  auto dense_tensor = static_cast<phi::DenseTensor*>(self->tensor.impl().get());
  if (dense_tensor) {
    dense_tensor->ShareInplaceVersionCounterWith(tmp);
  }
  return 0;
  EAGER_CATCH_AND_THROW_RETURN_NEG
}

W
wanghuancoder 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
PyDoc_STRVAR(tensor_grad__doc__,
             R"DOC(grad

Tensor's grad Tensor.

Returns:
    Tensor: grad Tensor.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor(1.0, stop_gradient=False)
      y = x**2
      y.backward()
      print(x.grad)
      x.grad = paddle.to_tensor(3.0)
      print(x.grad)
)DOC");
248 249
PyObject* tensor_properties_get_grad(TensorObject* self, void* closure) {
  EAGER_TRY
250 251
  VLOG(6) << "Get grad for tensor: " << self->tensor.name();
  auto meta = egr::EagerUtils::nullable_autograd_meta(self->tensor);
252
  VLOG(6) << meta << " initialized: " << meta->Grad().initialized();
253
  if (meta && meta->Grad().initialized()) {
254
    return ToPyObject(meta->Grad());
255
  } else {
256
    RETURN_PY_NONE
257
  }
258 259 260
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

261 262
int tensor_properties_set_grad(TensorObject* self,
                               PyObject* value,
263 264
                               void* closure) {
  EAGER_TRY
265
  auto src = CastPyArg2Tensor(value, 0);
266
  PADDLE_ENFORCE(
267
      egr::EagerUtils::IsLeafTensor(self->tensor),
268
      paddle::platform::errors::Fatal("Only leaf Tensor can be set grad."));
269

270
  paddle::Tensor* grad = egr::EagerUtils::mutable_grad(self->tensor);
271 272 273 274 275
  PADDLE_ENFORCE(grad != nullptr,
                 paddle::platform::errors::Fatal(
                     "Detected NULL grad"
                     "Please check if you have manually cleared"
                     "the grad inside autograd_meta"));
C
Chen Weihang 已提交
276
  grad->copy_(src, self->tensor.place(), true);
277
  return 0;
0
0x45f 已提交
278
  EAGER_CATCH_AND_THROW_RETURN_NEG
279 280
}

W
wanghuancoder 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
int tensor_properties_set_grad_(TensorObject* self,
                                PyObject* value,
                                void* closure) {
  EAGER_TRY
  auto src = CastPyArg2Tensor(value, 0);
  PADDLE_ENFORCE(
      egr::EagerUtils::IsLeafTensor(self->tensor),
      paddle::platform::errors::Fatal("Only leaf Tensor can be set grad."));

  paddle::Tensor* grad = egr::EagerUtils::mutable_grad(self->tensor);
  PADDLE_ENFORCE(grad != nullptr,
                 paddle::platform::errors::Fatal(
                     "Detected NULL grad"
                     "Please check if you have manually cleared"
                     "the grad inside autograd_meta"));
  *grad = src;
  return 0;
  EAGER_CATCH_AND_THROW_RETURN_NEG
}

301 302
int tensor_properties_set_stop_gradient(TensorObject* self,
                                        PyObject* value,
303 304
                                        void* closure) {
  EAGER_TRY
305
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
306
  meta->SetStopGradient(CastPyArg2AttrBoolean(value, 0));
307 308 309
  if (!meta->GradNode()) {
    meta->SetGradNode(std::make_shared<egr::GradNodeAccumulation>(meta));
  }
310
  return 0;
0
0x45f 已提交
311
  EAGER_CATCH_AND_THROW_RETURN_NEG
312 313
}

W
wanghuancoder 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
PyDoc_STRVAR(tensor_persistable__doc__,
             R"DOC(persistable

Tensor's persistable.

Returns:
    bool: persistable.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor(1.0, stop_gradient=False)
      print(x.persistable) # False
      x. persistable = True
      print(x.persistable) # True
)DOC");

333 334
PyObject* tensor_properties_get_persistable(TensorObject* self, void* closure) {
  EAGER_TRY
335
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
336 337 338 339
  return ToPyObject(meta->Persistable());
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

340 341
int tensor_properties_set_persistable(TensorObject* self,
                                      PyObject* value,
342 343
                                      void* closure) {
  EAGER_TRY
344
  auto meta = egr::EagerUtils::autograd_meta(&self->tensor);
345 346
  meta->SetPersistable(CastPyArg2AttrBoolean(value, 0));
  return 0;
0
0x45f 已提交
347
  EAGER_CATCH_AND_THROW_RETURN_NEG
348 349
}

L
LiYuRio 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
PyDoc_STRVAR(tensor_dist_attr__doc__,
             R"DOC(dist_attr

Get dist_attr property from shard tensor.

Returns:
    core.TensorDistAttr: the dist attr of shard tensor

Examples:
    .. code-block:: python

        import paddle
        import paddle.distributed as dist

        mesh = dist.ProcessMesh([[2, 4, 5], [0, 1, 3]], dim_names=["x", "y"])
        dist_attr = dist.DistAttr(mesh=mesh, sharding_specs=['x', 'y'])

        a = paddle.to_tensor([[1,2,3],
                              [5,6,7]])
        d_tensor = dist.shard_tensor(a, dist_attr=dist_attr)

        print(d_tensor.dist_attr)

)DOC");

L
LiYuRio 已提交
375 376 377 378
PyObject* tensor_properties_get_dist_attr(TensorObject* self, void* closure) {
  EAGER_TRY
  if (self->tensor.is_dist_tensor()) {
#ifdef PADDLE_WITH_DISTRIBUTE
379 380
    phi::distributed::DistTensor* dist_tensor =
        static_cast<phi::distributed::DistTensor*>(self->tensor.impl().get());
L
LiYuRio 已提交
381 382 383 384 385 386 387 388 389 390
    return ToPyObject(dist_tensor->dist_attr().get());
#else
    RETURN_PY_NONE
#endif
  } else {
    RETURN_PY_NONE
  }
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
PyDoc_STRVAR(tensor_shape__doc__,
             R"DOC(shape

Tensor's shape.

Returns:
    List: shape.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor(1.0, stop_gradient=False)
      print(x.shape)
)DOC");

408 409
PyObject* tensor_properties_get_shape(TensorObject* self, void* closure) {
  EAGER_TRY
410
  std::vector<int64_t> value;
411 412 413
  if (!self->tensor.defined()) {
    return ToPyObject(value);
  }
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  if (egr::IsVariableCompatTensor(self->tensor)) {
    auto* var_tensor = static_cast<const egr::VariableCompatTensor*>(
        self->tensor.impl().get());
    if (var_tensor->IsType<paddle::framework::Vocab>()) {
      value.emplace_back(static_cast<int64_t>(
          var_tensor->Get<paddle::framework::Vocab>().size()));
    } else if (var_tensor->IsType<paddle::framework::Strings>()) {
      value.emplace_back(static_cast<int64_t>(
          var_tensor->Get<paddle::framework::Strings>().size()));
    } else {
      PADDLE_THROW(paddle::platform::errors::Unavailable(
          "VariableCompatTensor only support get shape from Vocab or "
          "Strings."));
    }
  } else {
    auto ddim = self->tensor.shape();
    size_t rank = static_cast<size_t>(ddim.size());
    value.resize(rank);
    for (size_t i = 0; i < rank; i++) {
      value[i] = ddim[i];
    }
435
  }
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
  if (!egr::IsVariableCompatTensor(self->tensor)) {
    auto desired_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout();
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    bool change_dim =
        (desired_layout != default_layout &&
         self->tensor.layout() == desired_layout && value.size() == 4);
    VLOG(6) << "eager_properties 'Shape' method, layout autotune "
            << " desired_layout: " << desired_layout
            << " default_layout: " << default_layout
            << " tensor layout: " << self->tensor.layout()
            << " tensor's shape size is : " << value.size();
    std::vector<int64_t> dims = value;
    if (change_dim && phi::DataLayoutToString(desired_layout) == "NCHW") {
      // NCHW -> NHWC
      VLOG(6) << "layout autotune get Shape from NCHW -> NHWC " << value[0]
              << " " << value[1] << " " << value[2] << " " << value[3] << " to "
              << dims[0] << " " << dims[2] << " " << dims[3] << " " << dims[1];
      value[0] = dims[0];
      value[1] = dims[2];
      value[2] = dims[3];
      value[3] = dims[1];
    } else if (change_dim &&
               phi::DataLayoutToString(desired_layout) == "NHWC") {
      // NHWC -> NCHW
      VLOG(6) << "layout autotune get Shape from NHWC -> NCHW " << value[0]
              << " " << value[1] << " " << value[2] << " " << value[3] << " to "
              << dims[0] << " " << dims[3] << " " << dims[1] << " " << dims[2]
              << " " << dims[1];
      value[0] = dims[0];
      value[1] = dims[3];
      value[2] = dims[1];
      value[3] = dims[2];
    }
471 472
  }

473 474 475 476
  return ToPyObject(value);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
PyDoc_STRVAR(tensor_strides__doc__,
             R"DOC(strides

Tensor's strides.

Returns:
    List: strides.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor([1, 2, 3])
      y = x[1]
      print(y.strides)
)DOC");

W
wanghuancoder 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
PyObject* tensor_properties_get_strides(TensorObject* self, void* closure) {
  EAGER_TRY
  std::vector<int64_t> value;
  if (!self->tensor.defined() || !self->tensor.is_dense_tensor()) {
    return ToPyObject(value);
  }

  auto stride = self->tensor.strides();
  size_t rank = static_cast<size_t>(stride.size());
  value.resize(rank);

  for (size_t i = 0; i < rank; i++) {
    value[i] = stride[i];
  }

  return ToPyObject(value);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
PyDoc_STRVAR(tensor_offset__doc__,
             R"DOC(offset

The address of the first element relative to the offset of the video memory.

Returns:
    int: offset.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor([1, 2, 3])
      y = x[1]
      print(y.offset)
)DOC");
W
wanghuancoder 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
PyObject* tensor_properties_get_offset(TensorObject* self, void* closure) {
  EAGER_TRY
  if (!self->tensor.defined() || !self->tensor.is_dense_tensor()) {
    RETURN_PY_NONE;
  }

  auto dense_tensor =
      std::dynamic_pointer_cast<phi::DenseTensor>(self->tensor.impl());

  if (dense_tensor == nullptr) {
    RETURN_PY_NONE;
  } else {
    return ToPyObject(dense_tensor->offset());
  }

  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
PyDoc_STRVAR(tensor_layout__doc__,
             R"DOC(layout

Tensor's memory layout.

Returns:
    Layout: layout.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor([1, 2, 3])
      print(x.layout)
)DOC");
565 566 567 568 569 570 571 572 573 574 575
PyObject* tensor_properties_get_layout(TensorObject* self, void* closure) {
  EAGER_TRY
  std::string layout = "";
  if (!self->tensor.defined()) {
    return ToPyObject(layout);
  }

  if (egr::IsVariableCompatTensor(self->tensor)) {
    VLOG(3) << "VariableCompatTensor does not support `layout` method.";
    return ToPyObject(layout);
  } else {
576
    return ToPyObject(phi::DataLayoutToString(self->tensor.layout()));
577 578 579 580 581 582
  }

  return ToPyObject(layout);
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
PyDoc_STRVAR(tensor_place__doc__,
             R"DOC(place

The device Tensor's memory locate.

Returns:
    Place: place.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor([1, 2, 3])
      print(x.place)
)DOC");
599 600
PyObject* tensor_properties_get_place(TensorObject* self, void* closure) {
  EAGER_TRY
C
Chen Weihang 已提交
601
  return ToPyObject(self->tensor.place());
602 603 604
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

605 606
PyObject* tensor_properties_get_place_str(TensorObject* self, void* closure) {
  EAGER_TRY
607
  std::stringstream ostr;
C
Chen Weihang 已提交
608
  ostr << self->tensor.place();
609 610 611 612
  return ToPyObject(ostr.str());
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

W
wanghuancoder 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
PyDoc_STRVAR(tensor_dtype__doc__,
             R"DOC(dtype

Tensor's data type.

Returns:
    paddle dtype: dtype.

Examples:
    .. code-block:: python

      import paddle

      x = paddle.to_tensor([1, 2, 3])
      print(x.dtype)
)DOC");
629 630
PyObject* tensor_properties_get_dtype(TensorObject* self, void* closure) {
  EAGER_TRY
631 632 633 634
  if (!self->tensor.defined()) {
    // be same to old dygraph
    return ToPyObject(framework::proto::VarType::FP32);
  }
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  if (egr::IsVariableCompatTensor(self->tensor)) {
    auto* var_tensor = static_cast<const egr::VariableCompatTensor*>(
        self->tensor.impl().get());
    if (var_tensor->IsType<paddle::framework::Vocab>()) {
      return ToPyObject(framework::proto::VarType::RAW);
    } else if (var_tensor->IsType<paddle::framework::Strings>()) {
      return ToPyObject(framework::proto::VarType::STRING);
    } else {
      PADDLE_THROW(paddle::platform::errors::Unavailable(
          "VariableCompatTensor only support get shape from Vocab or "
          "Strings."));
    }
  } else {
    return ToPyObject(
        paddle::framework::TransToProtoVarType(self->tensor.type()));
  }
651 652 653
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
PyObject* tensor_properties_get_grad_fn(TensorObject* self, void* closure) {
  EAGER_TRY
  if (!self->tensor.defined()) {
    // Handle undefined tensors if necessary; otherwise, return nullptr or an
    // appropriate PyObject. In this case, I will return Py_None.
    Py_INCREF(Py_None);
    return Py_None;
  }

  // Get GradNode from the tensor
  auto meta = egr::EagerUtils::nullable_autograd_meta(
      self->tensor);  // If meta exists, get the GradNode

  if (meta) {
    // Get the GradNode from meta
669 670
    auto grad_node_ptr = meta->GetMutableGradNode();
    if (!grad_node_ptr) {
671 672 673 674
      Py_INCREF(Py_None);
      return Py_None;
    }

675
    PyObject* py_grad_node = ToPyObject(grad_node_ptr);
676 677

    return py_grad_node;
678

679 680 681 682 683 684 685 686 687
  } else {
    // If meta does not exist, return an appropriate Python object (e.g., None
    // or a special value).
    Py_INCREF(Py_None);
    return Py_None;
  }
  EAGER_CATCH_AND_THROW_RETURN_NULL
}

688
struct PyGetSetDef variable_properties[] = {  // NOLINT
W
wanghuancoder 已提交
689 690 691
    {"data",
     (getter)tensor_properties_get_data,
     (setter)tensor_properties_set_data,
W
wanghuancoder 已提交
692
     tensor_data__doc__,
W
wanghuancoder 已提交
693
     nullptr},
694 695 696
    {"grad",
     (getter)tensor_properties_get_grad,
     (setter)tensor_properties_set_grad,
W
wanghuancoder 已提交
697
     tensor_grad__doc__,
698
     nullptr},
W
wanghuancoder 已提交
699 700 701 702 703
    {"grad_",
     (getter)tensor_properties_get_grad,
     (setter)tensor_properties_set_grad_,
     nullptr,
     nullptr},
704 705 706
    {"name",
     (getter)tensor_properties_get_name,
     (setter)tensor_properties_set_name,
W
wanghuancoder 已提交
707
     tensor_name__doc__,
708 709 710 711
     nullptr},
    {"stop_gradient",
     (getter)tensor_properties_get_stop_gradient,
     (setter)tensor_properties_set_stop_gradient,
W
wanghuancoder 已提交
712
     tensor_stop_gradient__doc__,
713 714 715 716
     nullptr},
    {"persistable",
     (getter)tensor_properties_get_persistable,
     (setter)tensor_properties_set_persistable,
W
wanghuancoder 已提交
717 718 719 720
     tensor_persistable__doc__,
     nullptr},
    {"shape",
     (getter)tensor_properties_get_shape,
721
     nullptr,
W
wanghuancoder 已提交
722 723 724 725 726 727
     tensor_shape__doc__,
     nullptr},
    {"layout",
     (getter)tensor_properties_get_layout,
     nullptr,
     tensor_layout__doc__,
728
     nullptr},
W
wanghuancoder 已提交
729 730 731
    {"strides",
     (getter)tensor_properties_get_strides,
     nullptr,
W
wanghuancoder 已提交
732 733 734 735
     tensor_strides__doc__,
     nullptr},
    {"place",
     (getter)tensor_properties_get_place,
W
wanghuancoder 已提交
736
     nullptr,
W
wanghuancoder 已提交
737 738 739 740 741 742
     tensor_place__doc__,
     nullptr},
    {"offset",
     (getter)tensor_properties_get_offset,
     nullptr,
     tensor_offset__doc__,
W
wanghuancoder 已提交
743
     nullptr},
L
LiYuRio 已提交
744 745 746
    {"dist_attr",
     (getter)tensor_properties_get_dist_attr,
     nullptr,
L
LiYuRio 已提交
747
     tensor_dist_attr__doc__,
L
LiYuRio 已提交
748
     nullptr},
749 750 751 752
    {"_place_str",
     (getter)tensor_properties_get_place_str,
     nullptr,
     nullptr,
753
     nullptr},
W
wanghuancoder 已提交
754 755 756 757 758 759 760 761 762 763
    {"dtype",
     (getter)tensor_properties_get_dtype,
     nullptr,
     tensor_dtype__doc__,
     nullptr},
    {"type",
     (getter)tensor_properties_get_type,
     nullptr,
     tensor_type__doc__,
     nullptr},
W
wanghuancoder 已提交
764 765 766 767 768
    {"is_leaf",
     (getter)tensor_properties_is_leaf,
     nullptr,
     tensor_is_leaf__doc__,
     nullptr},
769 770 771 772 773
    {"grad_fn",
     (getter)tensor_properties_get_grad_fn,
     nullptr,
     nullptr,
     nullptr},
774 775
    {nullptr, nullptr, nullptr, nullptr, nullptr}};

J
Jack Zhou 已提交
776
// variable_properties for core.eager.StringTensor
777
struct PyGetSetDef string_tensor_variable_properties[] = {  // NOLINT
778 779 780 781 782
    {"name",
     (getter)tensor_properties_get_name,
     (setter)tensor_properties_set_name,
     nullptr,
     nullptr},
J
Jack Zhou 已提交
783
    {"shape", (getter)tensor_properties_get_shape, nullptr, nullptr, nullptr},
784
    {"layout", (getter)tensor_properties_get_layout, nullptr, nullptr, nullptr},
J
Jack Zhou 已提交
785
    {"place", (getter)tensor_properties_get_place, nullptr, nullptr, nullptr},
786 787 788 789
    {"_place_str",
     (getter)tensor_properties_get_place_str,
     nullptr,
     nullptr,
J
Jack Zhou 已提交
790 791 792
     nullptr},
    {nullptr, nullptr, nullptr, nullptr, nullptr}};

793 794
}  // namespace pybind
}  // namespace paddle