評價此頁

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