我使用这个命令来使用GPU。
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
但是,我想在 jupyter 中使用两个GPU,就像这样:
device = torch.device("cuda:0,1" if torch.cuda.is_available() else "cpu")
假设您想要在可用的GPU之间分配数据(如果您有批量大小为16且有2个GPU,则可能希望将8个样本提供给每个GPU),而不是将模型的部分分散到不同的GPU上。可以按以下方式完成:
如果您想要使用所有可用的GPU:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = CreateModel()
model= nn.DataParallel(model)
model.to(device)
如果你想使用特定的GPU: (例如,只使用4个GPU中的2个)
device = torch.device("cuda:1,3" if torch.cuda.is_available() else "cpu") ## specify the GPU id's, GPU id's start from 0.
model = CreateModel()
model= nn.DataParallel(model,device_ids = [1, 3])
model.to(device)
通过设置操作系统环境变量来使用特定的GPU:
在执行程序之前,按照以下方式设置CUDA_VISIBLE_DEVICES
变量:
export CUDA_VISIBLE_DEVICES=1,3
(假设您想选择第2个和第4个GPU)
然后,在程序内部,您可以像要使用所有GPU一样使用DataParallel()
(类似于第1种情况)。这里程序可用的GPU受到操作系统环境变量的限制。
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = CreateModel()
model= nn.DataParallel(model)
model.to(device)
X
和y
是数据:X.to(device)
y.to(device)
使用多个GPU就像将模型包装在DataParallel
中并增加批量大小一样简单。请查看这两个教程以进行快速入门:
如果你只想在特定的GPU上运行代码(例如,仅在GPU id 2和3上运行),则可以在从终端触发Python代码时使用CUDA_VISIBLE_DEVICES=2,3变量来指定。
CUDA_VISIBLE_DEVICES=2,3 python lstm_demo_example.py --epochs=30 --lr=0.001
在代码内部,保留如下:
device = torch.device("cuda" if torch.cuda.is_available() else 'cpu')
model = LSTMModel()
model = nn.DataParallel(model)
model = model.to(device)
来源: https://glassboxmedicine.com/2020/03/04/multi-gpu-training-in-pytorch-data-and-model-parallelism/
本文将介绍如何在PyTorch中使用多GPU进行数据和模型并行训练。对于大规模的深度学习任务,使用多个GPU可以显著提高训练速度。在本文中,我们将学习如何使用DataParallel和DistributedDataParallel两种方法实现多GPU训练。当我运行naiveinception_googlenet
时,上述方法对我无效。下面的方法解决了我的问题。
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0,3" # specify which GPU(s) to be used
torch.device("cuda:0,3")
返回device(type='cuda', index=0)
。如果您在nn.DataParallel(model,device_ids = [1, 3])
中指定了ids,那么运行这行代码有意义吗? - Igor给出字符串错误
- MAC