torch.utils.dlpack¶
- torch.utils.dlpack.from_dlpack(ext_tensor) Tensor [source][source]¶
将外部库中的张量转换为
torch.Tensor
。返回的 PyTorch 张量将与输入张量共享内存(输入张量可能来自另一个库)。请注意,因此原地操作也将影响输入张量的数据。这可能会导致意外问题(例如,其他库可能有只读标志或不可变数据结构),因此用户只有在确定这样做没有问题的情况下才能这样做。
- 参数:
ext_tensor(具有
__dlpack__
属性的对象,或 DLPack 胶囊)-
要转换的张量或 DLPack 胶囊。如果
ext_tensor
是张量(或 ndarray)对象,它必须支持__dlpack__
协议(即具有ext_tensor.__dlpack__
方法)。否则ext_tensor
可能是一个 DLPack 胶囊,它是一个不透明的PyCapsule
实例,通常由to_dlpack
函数或方法生成。- 返回类型:
示例:
>>> 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[0] = -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
返回一个不可见对象(一个“DLPack 胶囊”),表示张量。
注意
to_dlpack
是一个遗留的 DLPack 接口。它返回的胶囊在 Python 中除了作为from_dlpack
的输入外,不能用于其他任何操作。DLPack 的更常用方法是直接在张量对象上调用from_dlpack
- 当该对象具有__dlpack__
方法时,这可以工作,现在 PyTorch 和大多数其他库确实都有这个方法。警告
每次使用
to_dlpack
产生的胶囊,只调用from_dlpack
一次。当胶囊被多次消费时的行为是未定义的。- 参数:
张量 – 要导出的张量
DLPack 胶囊共享张量的内存。