torch.utils.dlpack#
Created On: Jul 11, 2018 | Last Updated On: Jun 13, 2025
- torch.utils.dlpack.from_dlpack(ext_tensor)→Tensor[source]#
Converts a tensor from an external library into a
torch.Tensor.The returned PyTorch tensor will share the memory with the input tensor(which may have come from another library). Note that in-place operationswill therefore also affect the data of the input tensor. This may lead tounexpected issues (e.g., other libraries may have read-only flags orimmutable data structures), so the user should only do this if they knowfor sure that this is fine.
- Parameters:
ext_tensor (object with
__dlpack__attribute, or a DLPack capsule) –The tensor or DLPack capsule to convert.
If
ext_tensoris a tensor (or ndarray) object, it must supportthe__dlpack__protocol (i.e., have aext_tensor.__dlpack__method). Otherwiseext_tensormay be a DLPack capsule, which isan opaquePyCapsuleinstance, typically produced by ato_dlpackfunction or method.device (torch.device orstr orNone) – An optional PyTorch devicespecifying where to place the new tensor. If None (default), thenew tensor will be on the same device as
ext_tensor.copy (bool orNone) – An optional boolean indicating whether or not to copy
self. If None, PyTorch will copy only if necessary.
- Return type:
Examples:
>>>importtorch.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>>>t2tensor([-1, -1, 2, 3])>>>ttensor([-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)>>>t3tensor([-1, -1, 2, 3])>>>t3[0]=-9# now we're sharing memory between 3 tensors>>>t3tensor([-9, -1, 2, 3])>>>t2tensor([-9, -1, 2, 3])>>>ttensor([-9, -1, 2, 3])
- torch.utils.dlpack.to_dlpack(tensor)→PyCapsule#
Returns an opaque object (a “DLPack capsule”) representing the tensor.
Note
to_dlpackis a legacy DLPack interface. The capsule it returnscannot be used for anything in Python other than use it as input tofrom_dlpack. The more idiomatic use of DLPack is to callfrom_dlpackdirectly on the tensor object - this works when thatobject has a__dlpack__method, which PyTorch and most otherlibraries indeed have now.Warning
Only call
from_dlpackonce per capsule produced withto_dlpack.Behavior when a capsule is consumed multiple times is undefined.- Parameters:
tensor – a tensor to be exported
The DLPack capsule shares the tensor’s memory.