【问题标题】:pytorch .cuda() can't get the tensor to cudapytorch .cuda() 无法获得 cuda 的张量
【发布时间】:2020-07-09 00:02:14
【问题描述】:

我尝试将我的数据放到 gpu 上,但它不起作用;

在我的 train.py 中

if __name__ == '__main__':
ten = torch.FloatTensor(2)
ten = ten.cuda()
print(ten)

args = config()
train_net(args, args.train_net, loss_config=net_loss_config[args.train_net])

当它运行时,它会打印出来

tensor([0., 0.])

张量不在 cuda 上

但在 test.py 中

import torch
ten=torch.FloatTensor(2)
ten=ten.cuda()
print(ten)

打印出来

tensor([1.4013e-45, 0.0000e+00], device='cuda:0')

现在张量在 cuda 上

【问题讨论】:

  • 在每个脚本之前运行 torch.cuda.is_available() 并在此处打印结果

标签: python pytorch gpu


【解决方案1】:

该错误意味着您模型中的十个变量的类型为 torch.FloatTensor (CPU),而您提供给模型的输入类型为 torch.cuda.FloatTensor (GPU)。

最可能的情况是您在模型的__init__() 方法中定义了nn.Parameter 或其他模块,例如nn.Conv2d,并在模型的forward() 方法中定义了其他权重或层。

此时forward()方法中定义的层不是模型的模块,调用cuda()时不会映射到GPU。

如果您希望使用梯度下降更新参数,您还需要将参数显式添加到优化器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2019-01-10
    • 2020-10-06
    • 2021-02-27
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多