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

本文转载自:https://ptorch.com/news/187.html

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

Tensor Attributes

每个torch.Tensor都有torch.dtypetorch.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


原创文章,转载请注明 :pytorch使用torch.dtype、torch.device和torch.layout管理数据类型属性 - pytorch中文网
原文出处: https://ptorch.com/news/187.html

使用 PyTorch 时,若遇到 `AttributeError: 'torch.dtype' object has no attribute 'device'` 错误,通常是因为代码中尝试访问了 `dtype` 对象的 `device` 属性,而该属性并不存在。这种错误常见于旧版本的 PyTorch 中,尤其是在从较新版本迁移至旧版本(如 v1.5.1 或更早)时,某些 API 的行为或可用性可能发生变化[^2]。 ### 常见原因 1. **版本兼容性问题** 某些方法或属性在新版本中被引入,在旧版本中则不可用。例如,`torch.dtype` 类型对象在较新版本中可能支持 `.device` 属性,但在旧版本中并未实现。因此,如果代码依赖于这些特性,则需要确保使用PyTorch 版本支持它们[^2]。 2. **不正确的类型操作** 当试图对 `torch.dtype` 实例调用 `.device` 方法时,实际上应检查是否应该直接作用于张量本身。每个张量实例具有 `device` 属性,可用于查询其所在设备(CPU 或 GPU)。而 `dtype` 只表示数据类型,与设备无关[^4]。 3. **混合使用 NumPy PyTorch 张量** 如果在计算过程中将 `torch.Tensor` 转换为 NumPy 数组,并尝试再次利用 `np.mean()` 等函数处理包含 `torch.dtype` 的对象,则可能导致此类错误。建议改用 `torch.mean(torch.stack(...))` 来替代 `np.mean()`,以保持数据一致性[^4]。 ### 解决方案 - **升级 PyTorch 到最新稳定版** 若当前项目允许更新依赖库版本,可考虑将 PyTorch 升级至最新稳定版本。这有助于避免因 API 差异导致的问题,并享受性能优化新功能支持。可通过以下命令完成安装: ```bash pip install --upgrade torch ``` - **检查并修改代码逻辑** 确认所有涉及 `dtype` 的地方是否真的需要访问 `device`。如果不是必要操作,应移除相关代码;如果是获取张量所在设备的需求,请改用如下方式: ```python x = torch.randn(3, 4) print(x.device) # 正确获取张量所在的设备 ``` - **转换张量为 NumPy 数组前进行预处理** 在将 `torch.Tensor` 转换为 NumPy 数组之前,建议先将其移动到 CPU 上,并显式调用 `.numpy()` 方法。这样可以避免潜在的类型冲突: ```python tensor_cpu = some_tensor.data.cpu() numpy_array = tensor_cpu.numpy() result = np.mean(numpy_array) ``` - **重构涉及聚合操作的部分** 如需对多个张量执行平均等统计操作,推荐使用 `torch.stack()` 结合 `torch.mean()` 替代 `np.mean()`,从而保证输出仍为张量形式,便于后续梯度传播或其他张量运算: ```python losses = [loss1, loss2, loss3] # 假设 loss1~3 均为 torch.Tensor 类型 mean_loss = torch.mean(torch.stack(losses)) ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值