- torch.utils.dlpack.from_dlpack(ext_tensor) Tensor ¶
Converts a tensor from an external library into a
The returned PyTorch tensor will share the memory with the input tensor (which may have come from another library). Note that in-place operations will therefore also affect the data of the input tensor. This may lead to unexpected issues (e.g., other libraries may have read-only flags or immutable data structures), so the user should only do this if they know for sure that this is fine.
ext_tensor (object with
__dlpack__attribute, or a DLPack capsule) –
The tensor or DLPack capsule to convert.
ext_tensoris a tensor (or ndarray) object, it must support the
__dlpack__protocol (i.e., have a
ext_tensormay be a DLPack capsule, which is an opaque
PyCapsuleinstance, typically produced by a
to_dlpackfunction or method.
- Return type:
>>> import torch.utils.dlpack >>> t = torch.arange(4) # Convert a tensor directly (supported in PyTorch >= 1.10) >>> t2 = torch.from_dlpack(t) >>> t2[:2] = -1 # show that memory is shared >>> t2 tensor([-1, -1, 2, 3]) >>> t tensor([-1, -1, 2, 3]) # The old-style DLPack usage, with an intermediate capsule object >>> capsule = torch.utils.dlpack.to_dlpack(t) >>> capsule <capsule object "dltensor" at ...> >>> t3 = torch.from_dlpack(capsule) >>> t3 tensor([-1, -1, 2, 3]) >>> t3 = -9 # now we're sharing memory between 3 tensors >>> t3 tensor([-9, -1, 2, 3]) >>> t2 tensor([-9, -1, 2, 3]) >>> t tensor([-9, -1, 2, 3])
- torch.utils.dlpack.to_dlpack(tensor) PyCapsule ¶
Returns an opaque object (a “DLPack capsule”) representing the tensor.
to_dlpackis a legacy DLPack interface. The capsule it returns cannot be used for anything in Python other than use it as input to
from_dlpack. The more idiomatic use of DLPack is to call
from_dlpackdirectly on the tensor object - this works when that object has a
__dlpack__method, which PyTorch and most other libraries indeed have now.
from_dlpackonce per capsule produced with
to_dlpack. Behavior when a capsule is consumed multiple times is undefined.
tensor – a tensor to be exported
The DLPack capsule shares the tensor’s memory.