tensor attributes
每一个torch.Tensor
都有一个 torch.dtype
,torch.device
,torch.layout
。
1、torch.dtype
torch.dtype
表示 torch.Tensor
的数据类型。PyTorch
共有9种数据类型,每种又分为CPU和GPU:
Data type | dtype | CPU tensor | GPU tensor |
---|---|---|---|
32-bit floating point | torch.float32 or torch.float | torch.FloatTensor | torch.cuda.FloatTensor |
64-bit floating point | torch.float64 or torch.double | torch.DoubleTensor | torch.cuda.DoubleTensor |
16-bit floating point | torch.float16 or torch.half | torch.HalfTensor | torch.cuda.HalfTensor |
8-bit integer (unsigned) | torch.uint8 | torch.ByteTensor | torch.cuda.ByteTensor |
8-bit integer (signed) | torch.int8 | torch.CharTensor | torch.cuda.CharTensor |
16-bit integer (signed) | torch.int16 or torch.short | torch.ShortTensor | torch.cuda.ShortTensor |
32-bit integer (signed) | torch.int32 or torch.int | torch.IntTensor | torch.cuda.IntTensor |
64-bit integer (signed) | torch.int64 or torch.long | torch.LongTensor | torch.cuda.LongTensor |
Boolean | torch.bool | torch.BoolTensor | torch.cuda.BoolTensor |
2、torch.decive
torch.device
表示分配torch.Tensor
的设备。
torch.device
包含设备类型(cpu或 cuda)和可选的设备序号。若设备序号不存在,则表示该类型当前设备,即使在调用 torch.cuda.set_device()
后也是如此。例如,在‘cuda’上构建 torch.Tensor
等价于'cuda:X'
,X为 torch.cuda.current_device()
返回的结果。
torch.Tensor
的device可以通过 Tensor.device
属性访问。
torch.device
可通过字符串或字符串和序号构建。
#字符串构建
>>> torch.device('cuda:0')
device(type='cuda', index=0)
>>> torch.device('cpu')
device(type='cpu')
>>> torch.device('cuda') # current cuda device
device(type='cuda')
#字符串和序号构建
>>> torch.device('cuda', 0)
device(type='cuda', index=0)
>>> torch.device('cpu', 0)
device(type='cpu', index=0)
注意
1.函数中的
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')
2.以
device
为参数的方法,通常接受一个字符串或是整型设备号作为参数。
下面三种表示方法等价:>> torch.randn((2,3), device=torch.device('cuda:1')) >> torch.randn((2,3), device='cuda:1') >> torch.randn((2,3), device=1) # legacy
3、torch.layout
torch.layout
表示 torch.Tensor
的内存布局。当前支持 torch.strided
(稠密tensor)并且实验性的支持 torch.sparse__coo
(稀疏COO tensor)。
torch.strided
表示稠密tensor,并且是最常用的内存布局。每个strided型的tensor都关联一个torch.Storage
,后者保存数据。torch.Storage
是单个数据类型的连续一维数组。 stride是一个整数列表,第k个值表示在tensor的第k维上,从一个元素到达下一个元素在内存中所需的跳数。该概念使得可以有效地执行许多tensor操作。
示例:
>>> x = torch.Tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
>>> x.stride()
(5, 1)
>>> x.t().stride()
(1, 5)