微凉的衣柜 2023-07-28 13:27 采纳率: 63.9%
浏览 10
已结题

Hugging Face载入模型双卡训练报错

模型载入代码如下:

device = torch.device("cuda:0")
model6 = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny",
                                                       ignore_mismatched_sizes=True)  # /upernet-swin-large,upernet-convnext-tiny
model6 = nn.DataParallel(model6, device_ids = [0, 1])
model6 = model6.to(device)
x2 = torch.randn(4, 3, 256,256).to(device)
print(model6(x2).shape)

报错:

RuntimeError: Expected tensor for argument #1 'input' to have the same device as
tensor for argument #2 'weight'; but device 1 does not equal 0 (while checking 
arguments for cudnn_convolution)

请问如何解决?

  • 写回答

2条回答 默认 最新

  • TechLead KrisChang 人工智能领域优质创作者 2023-07-28 14:28
    关注

    模型的输入数据和模型权重必须在同一设备上。

    代码里模型移动到了GPU(device 0)上,执行 model6(x2) 时,输入数据 x2 却没有明确地分配到某一个GPU上。

    试试使用 nn.DataParallel 的 forward() 方法来解决这个问题。将 model6(x2) 更改为 model6.module.forward(x2),看看能否解决问题。这样会确保你的输入数据被分配到所有的GPU上。

    device = torch.device("cuda:0")
    model6 = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny",
                                                           ignore_mismatched_sizes=True)  # /upernet-swin-large,upernet-convnext-tiny
    model6 = nn.DataParallel(model6, device_ids=[0, 1])
    model6 = model6.to(device)
    x2 = torch.randn(4, 3, 256, 256).to(device)
    print(model6.module.forward(x2).shape)
    
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月6日
  • 创建了问题 7月28日

悬赏问题

  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档