Skip to content
Closed
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
15399e4
Add English explanation
SCUcookie Nov 14, 2024
8986f04
Merge branch 'PaddlePaddle:develop' into develop
SCUcookie Nov 15, 2024
17bbaeb
Merge branch 'PaddlePaddle:develop' into develop
SCUcookie Nov 15, 2024
773e954
Merge branch 'PaddlePaddle:develop' into develop
SCUcookie Nov 18, 2024
09fe571
Merge branch 'PaddlePaddle:develop' into develop
SCUcookie Nov 18, 2024
d20ae97
Merge branch 'PaddlePaddle:develop' into develop
SCUcookie Nov 18, 2024
18349c5
modify code
SCUcookie Nov 18, 2024
34d57d5
Merge branch 'PaddlePaddle:develop' into develop
SCUcookie Nov 18, 2024
2461584
add __rand__
SCUcookie Nov 18, 2024
72fc12d
cancel update
SCUcookie Nov 18, 2024
6d4addc
add __rand__
SCUcookie Nov 18, 2024
eeb07ec
delete superfluous code
SCUcookie Nov 18, 2024
48e14ac
recover code
SCUcookie Nov 18, 2024
ae0a24b
Merge branch 'PaddlePaddle:develop' into Origin
SCUcookie Nov 18, 2024
82c622c
develop
SCUcookie Nov 18, 2024
73bb823
recover
SCUcookie Nov 18, 2024
cf81a6d
Merge branch 'PaddlePaddle:develop' into develop
SCUcookie Nov 18, 2024
376e452
add __rand__
SCUcookie Nov 18, 2024
777324f
Merge branch 'develop' of github.com:SCUcookie/Paddle into MyTensor
SCUcookie Nov 18, 2024
43a4d5c
Merge branch 'Origin' of github.com:SCUcookie/Paddle into MyTensor
SCUcookie Nov 18, 2024
214b64c
finish
SCUcookie Nov 18, 2024
b1a12a2
modify v1
SCUcookie Nov 19, 2024
3bb3cdd
question
SCUcookie Nov 21, 2024
c99d929
try
SCUcookie Nov 21, 2024
a456dbe
precommit
SCUcookie Nov 21, 2024
fddc3c2
modifying
SCUcookie Nov 21, 2024
c8e6a5f
upstream
SCUcookie Nov 25, 2024
024397d
try
SCUcookie Nov 25, 2024
9348366
modify
SCUcookie Nov 25, 2024
a79bad9
modify
SCUcookie Nov 26, 2024
0b65ceb
modify
SCUcookie Nov 26, 2024
6976b37
remove prototype
SCUcookie Nov 26, 2024
4e6dc05
finish
SCUcookie Nov 27, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions paddle/fluid/pybind/tensor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,28 @@ void BindTensor(pybind11::module &m) { // NOLINT
});
return capsule;
})
.def(
"__dlpack__",
[](phi::DenseTensor &self) {
DLManagedTensor *dlMTensor = framework::toDLPack(self);
return pybind11::capsule(
dlMTensor,
"dltensor",
[](PyObject *capsule) {
DLManagedTensor *managedTensor =
reinterpret_cast<DLManagedTensor *>(
PyCapsule_GetPointer(capsule, "dltensor"));
if (managedTensor && managedTensor->deleter) {
managedTensor->deleter(managedTensor);
}
});
},
R"DOC(
Encode the tensor to a DLPack capsule.

Returns:
PyCapsule: The DLPack representation of the tensor.
)DOC")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个复用 paddle.to_dlpack即可,不用写C++代码,可以参考:https://github.com/pytorch/pytorch/blob/main/torch/_tensor.py#L1565

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好的谢谢老师

.def("_set_float_element", TensorSetElement<float>)
.def("_get_float_element", TensorGetElement<float>)
.def("_set_double_element", TensorSetElement<double>)
Expand Down
2 changes: 2 additions & 0 deletions python/paddle/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,7 @@
from .utils.dlpack import (
from_dlpack,
to_dlpack,
__dlpack__,
)

# CINN has to set a flag to include a lib
Expand Down Expand Up @@ -1212,6 +1213,7 @@
'positive',
'from_dlpack',
'to_dlpack',
'__dlpack__',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__dlpack__是Tensor的方法,不是paddle模块下的函数

'inf',
'newaxis',
'nan',
Expand Down
1 change: 1 addition & 0 deletions python/paddle/tensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,7 @@
var,
)
from .to_string import set_printoptions # noqa: F401
from paddle.utils.dlpack import __dlpack__

# this list used in math_op_patch.py for _binary_creator_
tensor_method_func = [
Expand Down
1 change: 1 addition & 0 deletions python/paddle/tensor/tensor.prototype.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ class AbstractTensor:
def _grad_ivar(self) -> Tensor | None: ...

# annotation: ${tensor_alias}
def __dlpack__(self) -> Any: ...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个返回的是Any吗?应该是CapsuleType,参考Paddle/python/paddle/utils/dlpack.py


class Tensor(AbstractTensor, AbstractEagerParamBase):
# annotation: ${tensor_docstring}
Expand Down
40 changes: 40 additions & 0 deletions python/paddle/utils/dlpack.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不应该改动这个文件

Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
__all__ = [
'to_dlpack',
'from_dlpack',
'__dlpack__'
]

_T_contra = TypeVar("_T_contra", contravariant=True)
Expand Down Expand Up @@ -221,3 +222,42 @@ def from_dlpack(
out: Tensor = paddle.Tensor(out, place=out._place())

return out


def __dlpack__(tensor: paddle.Tensor, stream: int | None = None):
"""
Export a Paddle Tensor to a DLPack capsule for data interchange.

Args:
tensor (paddle.Tensor): The input tensor.
stream (int | None): An optional stream for synchronization.

Returns:
CapsuleType: A PyCapsule object representing the tensor in DLPack format.
"""
if not isinstance(tensor, paddle.Tensor):
raise TypeError(f"Expected a paddle.Tensor, but got {type(tensor)}.")

if tensor.stop_gradient is False:
raise RuntimeError(
"Tensors that require gradients cannot be exported. "
"Call `detach()` before exporting."
)
if tensor.layout != paddle.strided:
raise RuntimeError(
"Only strided tensors can be exported to DLPack."
)

if stream is not None:
if not isinstance(stream, int):
raise TypeError("The `stream` argument must be an int or None.")
if tensor.place.is_gpu_place():
current_stream = paddle.device.cuda.current_stream()
if stream != 1 and stream != current_stream.cuda_stream:
event = paddle.device.cuda.Event()
event.record(current_stream)
sync_stream = paddle.device.cuda.ExternalStream(stream)
sync_stream.wait_event(event)

return paddle.utils.dlpack.to_dlpack(tensor)

56 changes: 56 additions & 0 deletions test/legacy_test/test_dlpack.py

@HydrogenSulfate HydrogenSulfate Nov 26, 2024

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__dlpack__作为Tensor的类方法,和__cuda_array_interface__是类似的:

def __cuda_array_interface__(self):
参考这个PR写一下就行:#68192

Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,62 @@ def test_to_dlpack_from_zero_size(self):
np.testing.assert_array_equal(x.numpy(), y1.numpy())
np.testing.assert_array_equal(x.numpy(), y2.numpy())

def test__dlpack_basic(self):
with dygraph_guard():
tensor = paddle.to_tensor(np.array([1, 2, 3, 4]).astype("int"))
dlpack_from_method = tensor.__dlpack__()
out_from_dlpack = paddle.utils.dlpack.from_dlpack(dlpack_from_method)

self.assertTrue(isinstance(out_from_dlpack, paddle.base.core.eager.Tensor))
self.assertEqual(str(tensor.place), str(out_from_dlpack.place))
np.testing.assert_array_equal(
out_from_dlpack.numpy(), np.array([1, 2, 3, 4]).astype("int")
)

def test__dlpack_consistency_with_to_dlpack(self):
with dygraph_guard():
tensor = paddle.to_tensor(np.random.rand(4, 5).astype("float32"))
dlpack_via_method = tensor.__dlpack__()
dlpack_via_func = paddle.to_dlpack(tensor)

self.assertEqual(dlpack_via_method.__dlpack_device__, dlpack_via_func.__dlpack_device__)
self.assertEqual(dlpack_via_method.__dlpack_dtype__, dlpack_via_func.__dlpack_dtype__)

out_from_method = paddle.from_dlpack(dlpack_via_method)
out_from_func = paddle.from_dlpack(dlpack_via_func)

np.testing.assert_allclose(out_from_method.numpy(), out_from_func.numpy(), rtol=1e-05)

def test__dlpack_on_special_cases(self):
with dygraph_guard():
zero_dim_tensor = paddle.to_tensor(1.0)
dlpack = zero_dim_tensor.__dlpack__()
out_from_dlpack = paddle.from_dlpack(dlpack)
self.assertEqual(out_from_dlpack.shape, [])
np.testing.assert_array_equal(zero_dim_tensor.numpy(), out_from_dlpack.numpy())

empty_tensor = paddle.zeros([0, 10])
dlpack = empty_tensor.__dlpack__()
out_from_dlpack = paddle.from_dlpack(dlpack)
self.assertEqual(out_from_dlpack.shape, [0, 10])
np.testing.assert_array_equal(empty_tensor.numpy(), out_from_dlpack.numpy())

def test__dlpack_on_different_devices_and_dtypes(self):
with dygraph_guard():
dtypes = ["float32", "int32", "bool"]
places = [base.CPUPlace()]
if paddle.is_compiled_with_cuda():
places.append(base.CUDAPlace(0))

for dtype in dtypes:
for place in places:
tensor = paddle.ones([3, 4], dtype=dtype)
dlpack = tensor.__dlpack__()
out = paddle.from_dlpack(dlpack)
self.assertEqual(str(tensor.place), str(out.place))
self.assertEqual(tensor.dtype, out.dtype)
np.testing.assert_array_equal(tensor.numpy(), out.numpy())


class TestRaiseError(unittest.TestCase):
def test_to_dlpack_raise_type_error(self):
Expand Down
2 changes: 1 addition & 1 deletion third_party/pybind

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不需要改pybind

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个submodule不要修改

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个文件记得还原回去

Submodule pybind updated 178 files