gpt4 book ai didi

python - 使用多个 GPU 运行 LSTM 得到 "Input and hidden tensors are not at the same device"

转载 作者:行者123 更新时间:2023-12-01 19:55:02 24 4
gpt4 key购买 nike

我正在尝试在 pytorch 中训练 LSTM 层。我使用 4 个 GPU。初始化时,我添加了 .cuda() 函数将隐藏层移动到 GPU。但是当我使用多个 GPU 运行代码时,我收到此运行时错误:

RuntimeError: Input and hidden tensors are not at the same device

我尝试通过在转发函数中使用 .cuda() 函数来解决问题,如下所示:

self.hidden = (self.hidden[0].type(torch.FloatTensor).cuda(), self.hidden[1].type(torch.FloatTensor).cuda()) 

这行代码似乎解决了问题,但它引起了我的担忧,即是否在不同的 GPU 中看到更新的隐藏层。我是否应该在批量的前向函数结束时将向量移回CPU,或者是否有其他方法来解决该问题。

最佳答案

当您在张量上调用 .cuda() 时,Pytorch 将其移动到 current GPU device默认情况下(GPU-0)。因此,由于数据并行性,您的数据位于不同的 GPU 中,而您的模型则位于另一个 GPU 中,这会导致您面临运行时错误。

循环神经网络实现数据并行的正确方法如下:

from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence

class MyModule(nn.Module):
# ... __init__, other methods, etc.

# padded_input is of shape [B x T x *] (batch_first mode) and contains
# the sequences sorted by lengths
# B is the batch size
# T is max sequence length
def forward(self, padded_input, input_lengths):
total_length = padded_input.size(1) # get the max sequence length
packed_input = pack_padded_sequence(padded_input, input_lengths,
batch_first=True)
packed_output, _ = self.my_lstm(packed_input)
output, _ = pad_packed_sequence(packed_output, batch_first=True,
total_length=total_length)
return output

m = MyModule().cuda()
dp_m = nn.DataParallel(m)

您还需要为多 GPU 设置相应地设置 CUDA_VISIBLE_DEVICES 环境变量。

引用文献:

关于python - 使用多个 GPU 运行 LSTM 得到 "Input and hidden tensors are not at the same device",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com