from_dlpack¶
- paddle. from_dlpack ( dlpack: SupportDLPack | CapsuleType ) Tensor [source]
-
Decodes a DLPack to a tensor. The returned Paddle tensor will share the memory with the tensor from given dlpack.
- Parameters
-
dlpack (SupportDLPack | CapsuleType) –
A PyCapsule object with the dltensor, or that implements ‘__dlpack__’ and ‘__dlpack_device__’ methods.
If dlpack is a tensor (or ndarray) object, it must support the __dlpack__ protocol (i.e., have a dlpack.__dlpack__ method). Otherwise dlpack may be a DLPack capsule, which is an opaque PyCapsule instance, typically produced by a to_dlpack function or method.
- Returns
-
- A tensor decoded from DLPack. The data type of returned tensor
-
can be one of:
int32
,int64
,float16
,float32
andfloat64
. The device of returned tensor can be one of:CPU
,CUDAPlace
,CUDAPinnedPlace
.
- Return type
-
out (Tensor)
Examples
>>> import paddle >>> # From DLPack capsule >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], ... [0.1, 0.2, 0.6, 0.7]], place="cpu") >>> dlpack = paddle.utils.dlpack.to_dlpack(x) >>> y = paddle.utils.dlpack.from_dlpack(dlpack) >>> # dlpack capsule will be renamed to 'used_dltensor' after decoded >>> print(dlpack) >>> <capsule object "used_dltensor" at 0x7f6103c681b0> >>> print(y) Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True, [[0.20000000, 0.30000001, 0.50000000, 0.89999998], [0.10000000, 0.20000000, 0.60000002, 0.69999999]]) >>> # data of tensor x is shared with tensor y >>> y[0, 0] = 10.0 >>> print(x) Tensor(shape=[2, 4], dtype=float32, place=Place(gpu:0), stop_gradient=True, [[10. , 0.30000001, 0.50000000, 0.89999998], [0.10000000, 0.20000000, 0.60000002, 0.69999999]])
>>> # Directly from external tensor that implements '__dlpack__' and '__dlpack_device__' methods >>> import paddle >>> import numpy as np >>> x = np.array([[0.2, 0.3, 0.5, 0.9], ... [0.1, 0.2, 0.6, 0.7]]) >>> y = paddle.utils.dlpack.from_dlpack(x) >>> y[0, 0] = 10.0 >>> # data of tensor x is shared with tensor y >>> print(x) [[10. 0.3 0.5 0.9] [ 0.1 0.2 0.6 0.7]]