ida*_*ida 13 python gpu lstm pytorch
我正在尝试在pytorch中训练LSTM层。我正在使用4个GPU。初始化时,我添加了.cuda()函数将隐藏层移动到GPU。但是,当我使用多个GPU运行代码时,出现此运行时错误:
RuntimeError: Input and hidden tensors are not at the same device
Run Code Online (Sandbox Code Playgroud)
我试图通过在以下正向函数中使用.cuda()函数来解决此问题:
self.hidden = (self.hidden[0].type(torch.FloatTensor).cuda(), self.hidden[1].type(torch.FloatTensor).cuda())
Run Code Online (Sandbox Code Playgroud)
这条线似乎可以解决问题,但令我担心的是,是否在不同的GPU中看到了更新的隐藏层。我应该将向量在前进功能的末尾移回cpu进行批处理,还是有其他解决方法?
当您调用.cuda()张量时,Pytorch默认将其移动到当前 GPU 设备(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)
Run Code Online (Sandbox Code Playgroud)
您还需要CUDA_VISIBLE_DEVICES为多 GPU 设置相应地设置环境变量。
参考: