pytorch使用torch.dtype、torch.device和torch.layout管理数据类型属性

Song2350 次浏览0个评论2018年06月24日

pytorch0.4开始提出了Tensor Attributes,主要包含了torch.dtype,torch.device,torch.layoutpytorch可以使用他们管理数据类型属性。以下内容为pytorch0.4文档内容,具体可以查看Tensor Attributes

Tensor Attributes

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

torch.dtype

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

Data typedtypeTensor types
32-bit floating pointtorch.float32 or torch.floattorch.*.FloatTensor
64-bit floating pointtorch.float64 or torch.doubletorch.*.DoubleTensor
16-bit floating pointtorch.float16 or torch.halftorch.*.HalfTensor
8-bit integer (unsigned)torch.uint8torch.*.ByteTensor
8-bit integer (signed)torch.int8torch.*.CharTensor
16-bit integer (signed)torch.int16 or torch.shorttorch.*.ShortTensor
32-bit integer (signed)torch.int32 or torch.inttorch.*.IntTensor
64-bit integer (signed)torch.int64 or torch.longtorch.*.LongTensor

使用方法:

>>> x = torch.Tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
>>> print x.type()
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可以通过字符串/字符串和设备编号。

通过一个字符串:

>>> 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)

注意 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), 'cuda:1')

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

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

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

>> torch.randn((2,3), device=torch.device('cuda:1'))
>> torch.randn((2,3), device='cuda:1')
>> 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维从一个元素跳转到下一个元素所需的内存。这个概念使得可以有效地执行多张量。

例:

>>> 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

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文

    当前暂无更多相关好文推荐...