评价此页

Tensor 属性#

创建于:2018年4月21日 | 最后更新于:2025年6月27日

每个 torch.Tensor 都有一个 torch.dtypetorch.devicetorch.layout

torch.dtype#

class torch.dtype#

一个 torch.dtype 是一个表示 torch.Tensor 数据类型的对象。PyTorch 有几种不同的数据类型

浮点数 dtype

dtype

描述

torch.float32torch.float

32 位浮点数,定义在 https://en.wikipedia.org/wiki/IEEE_754

torch.float64torch.double

64 位浮点数,定义在 https://en.wikipedia.org/wiki/IEEE_754

torch.float16torch.half

16 位浮点数,定义在 https://en.wikipedia.org/wiki/IEEE_754,S-E-M 1-5-10

torch.bfloat16

16 位浮点数,有时也称为 Brain 浮点数,S-E-M 1-8-7

torch.complex32torch.chalf

32 位复数,包含两个 float16 分量

torch.complex64torch.cfloat

64 位复数,包含两个 float32 分量

torch.complex128torch.cdouble

128 位复数,包含两个 float64 分量

torch.float8_e4m3fn [shell], 1

8 位浮点数,S-E-M 1-4-3,来自 https://arxiv.org/abs/2209.05433

torch.float8_e5m2 [shell]

8 位浮点数,S-E-M 1-5-2,来自 https://arxiv.org/abs/2209.05433

torch.float8_e4m3fnuz [shell], 1

8 位浮点数,S-E-M 1-4-3,来自 https://arxiv.org/pdf/2206.02915

torch.float8_e5m2fnuz [shell], 1

8 位浮点数,S-E-M 1-5-2,来自 https://arxiv.org/pdf/2206.02915

torch.float8_e8m0fnu [shell], 1

8 位浮点数,S-E-M 0-8-0,来自 https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf

torch.float4_e2m1fn_x2 [shell], 1

打包的 4 位浮点数,S-E-M 1-2-1,来自 https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf

整数 dtype

dtype

描述

torch.uint8

8 位整数(无符号)

torch.int8

8 位整数(有符号)

torch.uint16 [shell], 2

16 位整数(无符号)

torch.int16torch.short

16 位整数(有符号)

torch.uint32 [shell], 2

32 位整数(无符号)

torch.int32torch.int

32 位整数(有符号)

torch.uint64 [shell], 2

64 位整数(无符号)

torch.int64torch.long

64 位整数(有符号)

torch.bool

布尔

shell(1,2,3,4,5,6,7,8,9)

shell dtype 是一种特殊的 dtype,具有有限的操作和后端支持。具体来说,支持那些不查看数据元素的操作(例如 torch.empty, torch.fill, torch.zeros)和不查看数据元素的操作(例如 torch.cat, torch.view, torch.reshape)。查看数据元素的操作,例如类型转换、矩阵乘法、NaN/Inf 检查,仅在具体情况下支持,取决于硬件加速内核的成熟度和可用性以及既定的用例。

1(1,2,3,4,5)

“fn”、“fnu”和“fnuz”dtype 后缀的含义是:“f” - 仅限有限值编码,无无穷大;“n” - NaN 值编码与 IEEE 规范不同;“uz” - 仅“无符号零”,即没有负零编码

2(1,2,3)

除了 uint8 之外的无符号类型目前仅计划在 eager 模式下提供有限支持(它们主要用于协助 torch.compile 的使用);如果您需要 eager 支持且不需要额外范围,我们建议使用它们的有符号变体。有关更多详细信息,请参阅 pytorch/pytorch#58734

注意:旧的构造函数,如 torch.*.FloatTensor, torch.*.DoubleTensor, torch.*.HalfTensor, torch.*.BFloat16Tensor, torch.*.ByteTensor, torch.*.CharTensor, torch.*.ShortTensor, torch.*.IntTensor, torch.*.LongTensor, torch.*.BoolTensor,仅为向后兼容而保留,不应再使用。

要确定一个 torch.dtype 是否为浮点数数据类型,可以使用属性 is_floating_point,它在数据类型是浮点数数据类型时返回 True

要确定一个 torch.dtype 是否为复数数据类型,可以使用属性 is_complex,它在数据类型是复数数据类型时返回 True

当算术运算(addsubdivmul)的输入 dtype 不同时,我们会通过找到满足以下规则的最小 dtype 来进行提升

  • 如果标量操作数的类型比张量操作数(其中 complex > floating > integral > boolean)的类别更高,则将其提升到具有足够大小以容纳该类别所有标量操作数的类型。

  • 如果零维张量操作数的类别比有维度操作数高,则将其提升到具有足够大小和类别以容纳该类别所有零维张量操作数的类型。

  • 如果不存在更高类别的零维操作数,则将其提升到具有足够大小和类别以容纳所有有维度操作数的类型。

浮点数标量操作数的 dtype 为 torch.get_default_dtype(),无符号整数非布尔标量操作数的 dtype 为 torch.int64。与 numpy 不同,我们在确定操作数的最小 dtype 时不检查值。复数类型尚不支持。shell dtype 的提升未定义。

提升示例

>>> float_tensor = torch.ones(1, dtype=torch.float)
>>> double_tensor = torch.ones(1, dtype=torch.double)
>>> complex_float_tensor = torch.ones(1, dtype=torch.complex64)
>>> complex_double_tensor = torch.ones(1, dtype=torch.complex128)
>>> int_tensor = torch.ones(1, dtype=torch.int)
>>> long_tensor = torch.ones(1, dtype=torch.long)
>>> uint_tensor = torch.ones(1, dtype=torch.uint8)
>>> bool_tensor = torch.ones(1, dtype=torch.bool)
# zero-dim tensors
>>> long_zerodim = torch.tensor(1, dtype=torch.long)
>>> int_zerodim = torch.tensor(1, dtype=torch.int)

>>> torch.add(5, 5).dtype
torch.int64
# 5 is an int64, but does not have higher category than int_tensor so is not considered.
>>> (int_tensor + 5).dtype
torch.int32
>>> (int_tensor + long_zerodim).dtype
torch.int32
>>> (long_tensor + int_tensor).dtype
torch.int64
>>> (bool_tensor + long_tensor).dtype
torch.int64
>>> (bool_tensor + uint_tensor).dtype
torch.uint8
>>> (float_tensor + double_tensor).dtype
torch.float64
>>> (complex_float_tensor + complex_double_tensor).dtype
torch.complex128
>>> (bool_tensor + int_tensor).dtype
torch.int32
# Since long is a different kind than float, result dtype only needs to be large enough
# to hold the float.
>>> torch.add(long_tensor, float_tensor).dtype
torch.float32
当指定了算术运算的输出张量时,我们允许将其转换为其 dtype,但有一个例外:
  • 整数输出张量不能接受浮点数张量。

  • 布尔输出张量不能接受非布尔张量。

  • 非复数输出张量不能接受复数张量。

类型转换示例

# allowed:
>>> float_tensor *= float_tensor
>>> float_tensor *= int_tensor
>>> float_tensor *= uint_tensor
>>> float_tensor *= bool_tensor
>>> float_tensor *= double_tensor
>>> int_tensor *= long_tensor
>>> int_tensor *= uint_tensor
>>> uint_tensor *= int_tensor

# disallowed (RuntimeError: result type can't be cast to the desired output type):
>>> int_tensor *= float_tensor
>>> bool_tensor *= int_tensor
>>> bool_tensor *= uint_tensor
>>> float_tensor *= complex_float_tensor

torch.device#

class torch.device#

一个 torch.device 是一个对象,表示 torch.Tensor 所在或将要分配的设备。

torch.device 包含一个设备类型(最常见的是“cpu”或“cuda”,但也可能是 “mps”“xpu”“xla”“meta”)以及可选的设备序号。如果设备序号不存在,则此对象将始终表示设备类型的当前设备,即使在调用 torch.cuda.set_device() 之后也是如此;例如,用设备 'cuda' 构建的 torch.Tensor 等同于 'cuda:X',其中 X 是 torch.cuda.current_device() 的结果。

torch.Tensor 的设备可以通过 Tensor.device 属性访问。

torch.device 可以通过以下方式构造:

  • 设备字符串,即设备类型以及可选的设备序号的字符串表示。

  • 设备类型和设备序号。

  • 设备序号,将使用当前的 加速器 类型。

通过设备字符串

>>> torch.device('cuda:0')
device(type='cuda', index=0)

>>> torch.device('cpu')
device(type='cpu')

>>> torch.device('mps')
device(type='mps')

>>> torch.device('cuda')  # implicit index is the "current device index"
device(type='cuda')

通过设备类型和设备序号

>>> torch.device('cuda', 0)
device(type='cuda', index=0)

>>> torch.device('mps', 0)
device(type='mps', index=0)

>>> torch.device('cpu', 0)
device(type='cpu', index=0)

通过设备序号

注意

如果当前未检测到任何加速器,此方法将引发 RuntimeError。

>>> torch.device(0)  # the current accelerator is cuda
device(type='cuda', index=0)

>>> torch.device(1)  # the current accelerator is xpu
device(type='xpu', index=1)

>>> torch.device(0)  # no current accelerator detected
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Cannot access accelerator device when none is available.

设备对象也可以用作上下文管理器,以更改分配张量的默认设备

>>> with torch.device('cuda:1'):
...     r = torch.randn(2, 3)
>>> r.device
device(type='cuda', index=1)

如果工厂函数传递了显式的、非 None 的设备参数,此上下文管理器将不起作用。要全局更改默认设备,另请参阅 torch.set_default_device()

警告

此函数会对每次调用 torch API(不仅仅是工厂函数)产生轻微的性能开销。如果这给您带来了问题,请在 pytorch/pytorch#92701 上发表评论。

注意

函数中的 torch.device 参数通常可以用字符串代替。这使得代码能够快速原型化。

>>> # Example of a function that takes in a torch.device
>>> cuda1 = torch.device('cuda:1')
>>> torch.randn((2,3), device=cuda1)
>>> # You can substitute the torch.device with a string
>>> torch.randn((2,3), device='cuda:1')

注意

接受设备的函数通常会接受一个(格式正确的)字符串或一个整数设备序号,即以下所有方法都是等效的:

>>> torch.randn((2,3), device=torch.device('cuda:1'))
>>> torch.randn((2,3), device='cuda:1')
>>> torch.randn((2,3), device=1)  # equivalent to 'cuda:1' if the current accelerator is cuda

注意

张量从不自动在设备之间移动,需要用户显式调用。标量张量(tensor.dim()==0)是此规则的唯一例外,它们在需要时会自动从 CPU 传输到 GPU,因为此操作可以“免费”完成。示例:

>>> # two scalars
>>> torch.ones(()) + torch.ones(()).cuda()  # OK, scalar auto-transferred from CPU to GPU
>>> torch.ones(()).cuda() + torch.ones(())  # OK, scalar auto-transferred from CPU to GPU
>>> # one scalar (CPU), one vector (GPU)
>>> torch.ones(()) + torch.ones(1).cuda()  # OK, scalar auto-transferred from CPU to GPU
>>> torch.ones(1).cuda() + torch.ones(())  # OK, scalar auto-transferred from CPU to GPU
>>> # one scalar (GPU), one vector (CPU)
>>> torch.ones(()).cuda() + torch.ones(1)  # Fail, scalar not auto-transferred from GPU to CPU and non-scalar not auto-transferred from CPU to GPU
>>> torch.ones(1) + torch.ones(()).cuda()  # Fail, scalar not auto-transferred from GPU to CPU and non-scalar not auto-transferred from CPU to GPU

torch.layout#

class torch.layout#

警告

torch.layout 类处于 beta 阶段,可能会发生变化。

一个 torch.layout 是一个表示 torch.Tensor 内存布局的对象。目前,我们支持 torch.strided(密集张量)并对 torch.sparse_coo(稀疏 COO 张量)提供 beta 支持。

torch.strided 表示密集张量,是最常用的内存布局。每个 strided 张量都有一个关联的 torch.Storage,其中包含其数据。这些张量提供了存储的多维、跨步视图。跨步是一系列整数:第 k 个跨步表示要从张量第 k 个维度的一个元素移动到下一个元素时在内存中所需的跳跃。这个概念使得执行许多张量操作成为可能,并且非常高效。

示例

>>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
>>> x.stride()
(5, 1)

>>> x.t().stride()
(1, 5)

有关 torch.sparse_coo 张量的更多信息,请参阅 torch.sparse

torch.memory_format#

class torch.memory_format#

一个 torch.memory_format 是一个对象,表示 torch.Tensor 所在或将要分配的内存格式。

可能的值为:

  • torch.contiguous_format:张量在连续的、非重叠的内存中分配或将要分配。跨步值按递减顺序表示。

  • torch.channels_last:张量在连续的、非重叠的内存中分配或将要分配。跨步值表示为 strides[0] > strides[2] > strides[3] > strides[1] == 1,即 NHWC 顺序。

  • torch.channels_last_3d:张量在连续的、非重叠的内存中分配或将要分配。跨步值表示为 strides[0] > strides[2] > strides[3] > strides[4] > strides[1] == 1,即 NDHWC 顺序。

  • torch.preserve_format:在 clone 等函数中使用,以保留输入张量的内存格式。如果输入张量在连续的非重叠内存中分配,则输出张量的跨步将从输入张量复制。否则,输出跨步将遵循 torch.contiguous_format