【问题标题】:PyTorch custom forward function does not work with DataParallelPyTorch 自定义转发功能不适用于 DataParallel
【发布时间】:2021-09-21 10:55:25
【问题描述】:

编辑:我试过 PyTorch 1.6.0 和 1.7.1,都给我同样的错误。

我有一个模型,可以让用户在不同的架构 A 和 B 之间轻松切换。两种架构的转发功能也不同,所以我有以下模型类:

附注我这里只是用一个非常简单的例子来演示我的问题,实际模型要复杂得多。

class Net(nn.Module):
    def __init__(self, condition):
        super().__init__()
        self.linear = nn.Linear(10, 1)
        
        if condition == 'A':
            self.forward = self.forward_A
        elif condition == 'B':
            self.linear2 = nn.Linear(10, 1)
            self.forward = self.forward_B
            
    def forward_A(self, x):
        return self.linear(x)
    
    def forward_B(self, x1, x2):
        return self.linear(x1) + self.linear2(x2)
    

它在单个 GPU 情况下运行良好。然而,在多 GPU 的情况下,它会抛出一个错误。

device= 'cuda:0'
x = torch.randn(8,10).to(device)

model = Net('B')
model = model.to(device)
model = nn.DataParallel(model)

model(x, x)

RuntimeError: 期望所有张量都在同一个设备上,但发​​现 至少有两个设备,cuda:0 和 cuda:1! (在检查参数时 方法 wrapper_addmm 中的参数 mat1)

如何使这个模型类与nn.DataParallel一起工作?

【问题讨论】:

    标签: python-3.x deep-learning pytorch multiple-gpu


    【解决方案1】:

    您强制输入 x 和模型在 'cuda:0' 设备上,但在多个 GPU 上工作时,您不应指定任何特定设备。
    试试:

    x = torch.randn(8,10)  
    model = Net('B')
    model =  nn.DataParallel(model, device-ids=[0, 1]).cuda()  # assuming 2 GPUs
    pred = model(x, x)
    

    【讨论】:

    • 对不起,它也不起作用,我有这个错误。 “RuntimeError:模块必须在设备 cuda:0 (device_ids[0]) 上有其参数和缓冲区,但在设备上找到其中之一:cpu”。我正在使用torch 1.6.0,我不确定它是否是这个特定版本的错误
    • 我已经尝试过 PyTorch 1.6.0 和 1.7.1。两个版本都给了我相同的结果。
    • 现在错误变为:“RuntimeError: Caught RuntimeError in replica 1 on device 1.”
    • @RavenCheuk 你有更具体的错误吗? RuntimeError 到底是什么?您能否仅在一台设备上运行nn.DataParallel 并查看是否能得到更详细的错误描述?
    • 完整错误是“RuntimeError: Expected tensor for 'out' to have the same device as tensor for argument #2 'mat1'; 但设备 0 不等于 1(在检查 addmm 的参数时) " 如果我​​只使用一台设备运行 nn.DataParallel,则不会出现错误。
    猜你喜欢
    • 2021-12-09
    • 2021-01-11
    • 1970-01-01
    • 2017-02-09
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多