Tensor Attributes

每个torch.Tensor都有torch.dtype, torch.device,和torch.layout

torch.dtype

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

Data type dtype Tensor types
32-bit floating point torch.float32 or torch.float torch.*.FloatTensor
64-bit floating point torch.float64 or torch.double torch.*.DoubleTensor
16-bit floating point torch.float16 or torch.half torch.*.HalfTensor
8-bit integer (unsigned) torch.uint8 torch.*.ByteTensor
8-bit integer (signed) torch.int8 torch.*.CharTensor
16-bit integer (signed) torch.int16 or torch.short torch.*.ShortTensor
32-bit integer (signed) torch.int32 or torch.int torch.*.IntTensor
64-bit integer (signed) torch.int64 or torch.long torch.*.LongTensor

使用方法:

  1. >>> x = torch.Tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
  2. >>> print x.type()
  3. torch.FloatTensor

torch.device

torch.device代表将torch.Tensor分配到的设备的对象。

torch.device包含一个设备类型('cpu''cuda'设备类型)和可选的设备的序号。如果设备序号不存在,则为当前设备; 例如,torch.Tensor用设备构建'cuda'的结果等同于'cuda:X',其中Xtorch.cuda.current_device()的结果。

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

构造torch.device可以通过字符串/字符串和设备编号。

通过一个字符串:

  1. >>> torch.device('cuda:0')
  2. device(type='cuda', index=0)
  3. >>> torch.device('cpu')
  4. device(type='cpu')
  5. >>> torch.device('cuda') # current cuda device
  6. device(type='cuda')

通过字符串和设备序号:

  1. >>> torch.device('cuda', 0)
  2. device(type='cuda', index=0)
  3. >>> torch.device('cpu', 0)
  4. device(type='cpu', index=0)

注意torch.device函数中的参数通常可以用一个字符串替代。这允许使用代码快速构建原型。

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

注意出于传统原因,可以通过单个设备序号构建设备,将其视为cuda设备。这匹配Tensor.get_device(),它为cuda张量返回一个序数,并且不支持cpu张量。

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

注意指定设备的方法可以使用(properly formatted)字符串或(legacy)整数型设备序数,即以下示例均等效:

  1. >> torch.randn((2,3), device=torch.device('cuda:1'))
  2. >> torch.randn((2,3), device='cuda:1')
  3. >> torch.randn((2,3), device=1) # legacy

torch.layout

torch.layout表示torch.Tensor内存布局的对象。目前,我们支持torch.strided(dense Tensors)并为torch.sparse_coo(sparse COO Tensors)提供实验支持。

torch.strided代表密集张量,是最常用的内存布局。每个strided张量都会关联 一个torch.Storage,它保存着它的数据。这些张力提供了多维度, 存储的strided视图。Strides是一个整数型列表:k-th stride表示在张量的第k维从一个元素跳转到下一个元素所需的内存。这个概念使得可以有效地执行多张量。

例:

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

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

译者署名

用户名 头像 职能 签名
Song Tensor Attributes - 图1 翻译 人生总要追求点什么