• 文档 >
  • torch >
  • torch.from_dlpack
快捷键

torch.from_dlpack ¶ 从 dlpack 转换张量

torch.from_dlpack(ext_tensor) → Tensor[source][source] ¶ torch.from_dlpack(扩展张量) → 张量[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])

© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源