PyTorch深度學習框架可以利用GPU加速網絡訓練,網絡太深,參數太多的話,很可能在利用GPU訓練網絡的時候導致GPU顯存不夠,無法繼續訓練。GPU的顯存大小几乎與其價格成正比,顯存越大,也就越貴。但是爲了利用GPU訓練深度學習網絡模型,可能需要大顯存的顯卡,比如直接買一個1080ti,顯存爲11G,但是也可以退而求其次,買兩個1070ti,總顯存爲16G,似乎更划算。那麼,單機多卡(一臺機器配置多個GPU)情況下,在PyTorch框架下怎樣訓練模型呢?在PyTorch 1.0之後,可以利用多GPU進行網絡模型訓練。
1. 第一種情況,利用單機多卡對模型進行並行GPU處理(本人當時的需求爲一個gtx 1070ti顯存爲8G,訓練模型時出現超出顯存的錯誤,所以又加裝了一個gtx 1070ti顯卡,這樣總顯存爲16G,夠用啦)。
model = torch.nn.DataParallel(model, device_ids=[0, 1]).cuda()
output = model(input)
class torch.nn.DataParallel(module, device_ids=None, output_device=None, dim=0),通過device_ids參數可以指定在哪些GPU上進行優化,output_device指定輸出到哪個GPU上。
DataParallel並行的方式,是將輸入一個batch的數據均分成多份,分別送到對應的GPU進行計算,各個GPU得到的梯度累加。與Module相關的所有數據也都會以淺複製的方式複製多份,在此需要注意,在module中屬性應該是隻讀的。
if torch.cuda.device_count() > 1:
model = nn.DataParallel(model)
if torch.cuda.is_available():
model.cuda()
2,。 第二種情況,利用多機多卡進行分佈式訓練。torch.nn.parallel.DistributedDataParallel可以實現單機多卡和多機多卡的分佈式訓練。對於單機多卡,利用torch.nn.parallel.DistributedDataParallel對模型進行訓練,每個GPU獨立執行一個BatchSize的數據,如果單卡顯存太小,仍然會出現顯存不夠的錯誤,導致模型無法繼續訓練。啓動方式如下:
torch.distributed.init_process_group(backend='nccl', world_size=4, rank=, init_method='...')
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[i], output_device=i)
下面是關於torch.nn.DataParallel與torch.nn.parallel.DistributedDataParallel的啓動對比:
if args.distributed:
# For multiprocessing distributed, DistributedDataParallel constructor
# should always set the single device scope, otherwise,
# DistributedDataParallel will use all available devices.
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
model.cuda(args.gpu)
# When using a single GPU per process and per
# DistributedDataParallel, we need to divide the batch size
# ourselves based on the total number of GPUs we have
args.batch_size = int(args.batch_size / ngpus_per_node)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
else:
model.cuda()
# DistributedDataParallel will divide and allocate batch_size to all
# available GPUs if device_ids are not set
model = torch.nn.parallel.DistributedDataParallel(model)
elif args.gpu is not None:
torch.cuda.set_device(args.gpu)
model = model.cuda(args.gpu)
else:
# DataParallel will divide and allocate batch_size to all available GPUs
if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
model.features = torch.nn.DataParallel(model.features)
model.cuda()
else:
model = torch.nn.DataParallel(model).cuda()
參考:
1. pytorch 多GPU訓練總結(DataParallel的使用)