pytorch DataParallel 多GPU使用

今天药忘吃喽~ 2023-05-29 03:30 85阅读 0赞
  1. import torch
  2. import torch.nn as nn
  3. from torch.utils.data import Dataset, DataLoader
  4. # Parameters and DataLoaders
  5. input_size = 5
  6. output_size = 2
  7. batch_size = 30
  8. data_size = 100
  9. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  10. print(device)
  11. class RandomDataset(Dataset):
  12. def __init__(self, size, length):
  13. self.len = length
  14. self.data = torch.randn(length, size)
  15. def __getitem__(self, index):
  16. return self.data[index]
  17. def __len__(self):
  18. return self.len
  19. rand_loader = DataLoader(dataset=RandomDataset(input_size, data_size), batch_size=batch_size, shuffle=True)
  20. class Model(nn.Module):
  21. # Our model
  22. def __init__(self, input_size, output_size):
  23. super(Model, self).__init__()
  24. self.fc = nn.Linear(input_size, output_size)
  25. def forward(self, input):
  26. output = self.fc(input)
  27. print("\tIn Model: input size", input.size(),
  28. "output size", output.size())
  29. return output
  30. model = Model(input_size, output_size)
  31. if torch.cuda.device_count() > 1:
  32. print("Let's use", torch.cuda.device_count(), "GPUs!")
  33. # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
  34. model = nn.DataParallel(model)
  35. model.to(device)
  36. for data in rand_loader:
  37. input = data.to(device)
  38. output = model(input)
  39. print("Outside: input size", input.size(),
  40. "output_size", output.size())

核心:

首先,确定使用GPU还是使用CPU, 设置device

  1. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

其次,我们需要制作一个模型实例,并检查是否有多个GPU。 如果我们有多个GPU,则可以使用nn.DataParallel包装模型。 然后我们可以通过model.to(device)将我们的模型放在GPU上

  1. model = Model(input_size, output_size)
  2. if torch.cuda.device_count() > 1:
  3. print("Let's use", torch.cuda.device_count(), "GPUs!")
  4. # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
  5. model = nn.DataParallel(model)
  6. model.to(device)

注意:

  1. mytensor = my_tensor.to(device)

仅调用my_tensor.to(device)即可在GPU上返回my_tensor的新副本,而不是重写my_tensor。 您需要将其分配给新的张量,并在GPU上使用该张量。

链接:

OPTIONAL: DATA PARALLELISM

发表评论

表情:
评论列表 (有 0 条评论,85人围观)

还没有评论,来说两句吧...

相关阅读