[分布式訓練] 單機多卡的正確打開方式:PyTorch

[分布式訓練] 單機多卡的正確打開方式:PyTorch

轉自:https://fyubang.com/2019/07/23/distributed-training3/

PyTorch的數據并行相對于TensorFlow而言,要簡單的多,主要分成兩個API:

  • DataParallel(DP):Parameter Server模式,一張卡位reducer,實現也超級簡單,一行代碼。
  • DistributedDataParallel(DDP):All-Reduce模式,本意是用來分布式訓練,但是也可用于單機多卡。

1. DataParallel

DataParallel是基于Parameter server的算法,負載不均衡的問題比較嚴重,有時在模型較大的時候(比如bert-large),reducer的那張卡會多出3-4g的顯存占用。

先簡單定義一下數據流和模型。

import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import osinput_size = 5
output_size = 2
batch_size = 30
data_size = 30class RandomDataset(Dataset):def __init__(self, size, length):self.len = lengthself.data = torch.randn(length, size)def __getitem__(self, index):return self.data[index]def __len__(self):return self.lenrand_loader = DataLoader(dataset=RandomDataset(input_size, data_size),batch_size=batch_size, shuffle=True)class Model(nn.Module):# Our modeldef __init__(self, input_size, output_size):super(Model, self).__init__()self.fc = nn.Linear(input_size, output_size)def forward(self, input):output = self.fc(input)print("  In Model: input size", input.size(),"output size", output.size())return output
model = Model(input_size, output_size)if torch.cuda.is_available():model.cuda()if torch.cuda.device_count() > 1:print("Let's use", torch.cuda.device_count(), "GPUs!")# 就這一行model = nn.DataParallel(model)for data in rand_loader:if torch.cuda.is_available():input_var = Variable(data.cuda())else:input_var = Variable(data)output = model(input_var)print("Outside: input size", input_var.size(), "output_size", output.size())

2. DistributedDataParallel

官方建議用新的DDP,采用all-reduce算法,本來設計主要是為了多機多卡使用,但是單機上也能用,使用方法如下:

初始化使用nccl后端:

torch.distributed.init_process_group(backend="nccl")

模型并行化:

model=torch.nn.parallel.DistributedDataParallel(model)

需要注意的是:DDP并不會自動shard數據

  1. 如果自己寫數據流,得根據torch.distributed.get_rank()去shard數據,獲取自己應用的一份

  2. 如果用Dataset API,則需要在定義Dataloader的時候用 DistributedSampler 去shard:

    sampler = DistributedSampler(dataset) # 這個sampler會自動分配數據到各個gpu上
    DataLoader(dataset, batch_size=batch_size, sampler=sampler)
    

完整的例子:

import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import os
from torch.utils.data.distributed import DistributedSampler
# 1) 初始化
torch.distributed.init_process_group(backend="nccl")input_size = 5
output_size = 2
batch_size = 30
data_size = 90# 2) 配置每個進程的gpu
local_rank = torch.distributed.get_rank()
torch.cuda.set_device(local_rank)
device = torch.device("cuda", local_rank)class RandomDataset(Dataset):def __init__(self, size, length):self.len = lengthself.data = torch.randn(length, size).to('cuda')def __getitem__(self, index):return self.data[index]def __len__(self):return self.lendataset = RandomDataset(input_size, data_size)
# 3)使用DistributedSampler
rand_loader = DataLoader(dataset=dataset,batch_size=batch_size,sampler=DistributedSampler(dataset))class Model(nn.Module):def __init__(self, input_size, output_size):super(Model, self).__init__()self.fc = nn.Linear(input_size, output_size)def forward(self, input):output = self.fc(input)print("  In Model: input size", input.size(),"output size", output.size())return outputmodel = Model(input_size, output_size)# 4) 封裝之前要把模型移到對應的gpu
model.to(device)if torch.cuda.device_count() > 1:print("Let's use", torch.cuda.device_count(), "GPUs!")# 5) 封裝model = torch.nn.parallel.DistributedDataParallel(model,device_ids=[local_rank],output_device=local_rank)for data in rand_loader:if torch.cuda.is_available():input_var = dataelse:input_var = dataoutput = model(input_var)print("Outside: input size", input_var.size(), "output_size", output.size())

需要通過命令行啟動:

CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch --nproc_per_node=2 torch_ddp.py

結果:

Let's use 2 GPUs!
Let's use 2 GPUs!In Model: input size torch.Size([30, 5]) output size torch.Size([30, 2])
Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2])In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2])
Outside: input size torch.Size([15, 5]) output_size torch.Size([15, 2])In Model: input size torch.Size([30, 5]) output size torch.Size([30, 2])
Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2])In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2])
Outside: input size torch.Size([15, 5]) output_size torch.Size([15, 2])

可以看到有兩個進程,log打印了兩遍

torch.distributed.launch 會給模型分配一個 args.local_rank 的參數,也可以通過torch.distributed.get_rank() 獲取進程id。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/532703.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/532703.shtml
英文地址,請注明出處:http://en.pswp.cn/news/532703.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

上學期C語言復習

C語言&#xff1a;面向過程例&#xff1a;完成兩個單元內容的交換 &#xff1a; #include<stdio.h> //定義一個完成兩個數據交換的函數 //void swap(int m,int n) void swap(int*m,int* n) { int temp;//臨時單元 temp*m; *m*n; *ntemp; } int main() {int a5,b10; print…

[分布式訓練] 單機多卡的正確打開方式:Horovod

[分布式訓練] 單機多卡的正確打開方式&#xff1a;Horovod 轉自&#xff1a;https://fyubang.com/2019/07/26/distributed-training4/ 講完了單機多卡的分布式訓練的理論、TensorFlow和PyTorch分別的實現后&#xff0c;今天瓦礫講一個強大的第三方插件&#xff1a;Horovod。 …

【c語言數據結構筆記】1.2 數據結構

1.2數據結構 數據元素并獨立 結構實體關系 形式定義&#xff08;D&#xff0c;S&#xff09; 其中D是數據元素的有限集&#xff0c;S是D上關系的有限集 eg&#xff1a;12位數&#xff1a;132423451233 分成三組四位數 次序關系<a1,a2><a2,a3> 遵守次序關系 eg&…

使用Apex進行混合精度訓練

使用Apex進行混合精度訓練 轉自&#xff1a;https://fyubang.com/2019/08/26/fp16/ 你想獲得雙倍訓練速度的快感嗎&#xff1f; 你想讓你的顯存空間瞬間翻倍嗎&#xff1f; 如果我告訴你只需要三行代碼即可實現&#xff0c;你信不&#xff1f; 在這篇博客里&#xff0c;瓦礫…

【數據結構1.3筆記】研究內容

1.3研究內容 數據結構&#xff08;D&#xff0c;S&#xff09; {邏輯結構&#xff1a; {物理結構&#xff08;存儲結構&#xff09; {數據的運算 1.邏輯結構 1 集合&#xff1a;集合&#xff0c;沒有邏輯關系 2 線性結構 “一對一” 3樹形結構 層次關系 4圖形結構 練習&…

Linux下的LD_PRELOAD環境變量與庫打樁

Linux下的LD_PRELOAD環境變量與庫打樁 LD_PRELOAD是Linux系統的一個環境變量&#xff0c;它可以影響程序的運行時的鏈接&#xff08;Runtime linker&#xff09;&#xff0c;它允許你定義在程序運行前優先加載的動態鏈接庫&#xff0c;一方面&#xff0c;我們可以以此功能來使…

2019年藍橋杯第一題

第一題 標題&#xff1a;組隊&#xff08;本題總分&#xff1a;5 分&#xff09; 作為籃球隊教練&#xff0c;你需要從以下名單中選出 1 號位至 5 號位各一名球員&#xff0c; 組成球隊的首發陣容。 每位球員擔任 1 號位至 5 號位時的評分如下表所示。請你計算首發陣容 1 號位…

深度學習編譯:MLIR初步

深度學習編譯MLIR初步 深度模型的推理引擎 目前深度模型的推理引擎按照實現方式大體分為兩類&#xff1a;解釋型推理引擎和編譯型推理引擎。 解釋型推理引擎 一般包含模型解析器&#xff0c;模型解釋器&#xff0c;模型優化器。 模型解析器負責讀取和解析模型文件&#xff…

深入淺出LLVM

深入淺出LLVM 轉自&#xff1a;https://www.jianshu.com/p/1367dad95445 什么是LLVM&#xff1f; LLVM項目是模塊化、可重用的編譯器以及工具鏈技術的集合。 美國計算機協會 (ACM) 將其2012 年軟件系統獎項頒給了LLVM&#xff0c;之前曾經獲得此獎項的軟件和技術包括:Java、A…

藍橋杯真題訓練 2019.2題

2019第二題 標題&#xff1a;年號字串&#xff08;本題總分&#xff1a;5 分&#xff09; 小明用字母 A 對應數字 1&#xff0c;B 對應 2&#xff0c;以此類推&#xff0c;用 Z 對應 26。對于 27 以上的數字&#xff0c;小明用兩位或更長位的字符串來對應&#xff0c;例如 AA…

一分鐘系列:什么是虛擬內存?

一分鐘系列&#xff1a;什么是虛擬內存&#xff1f; 轉自&#xff1a;https://mp.weixin.qq.com/s/opMgZrXV-lfgOWrNUMKweg 注&#xff1a;一分鐘系列的篇幅都不長&#xff0c;適合吃飯蹲坑、地鐵公交上食用&#xff5e; 內存對于用戶來說就是一個字節數組&#xff0c;我們可…

藍橋杯真題訓練 2019.3題

標題&#xff1a;數列求值 &#xff08;本題總分&#xff1a;10 分&#xff09;### 給定數列 1, 1, 1, 3, 5, 9, 17, …&#xff0c;從第 4 項開始&#xff0c;每項都是前 3 項的和。求 第 20190324 項的最后 4 位數字。 【答案提交】 這是一道結果填空的題&#xff0c;你只需…

11-Kafka

1 Kafka Kafka是一個分布式流式數據平臺&#xff0c;它具有三個關鍵特性 Message System: Pub-Sub消息系統Availability & Reliability&#xff1a;以容錯及持久化的方式存儲數據記錄流Scalable & Real time 1.1 Kafka架構體系 Kafka系統中存在5個關鍵組件 Producer…

虛擬內存精粹

虛擬內存精粹 標題&#xff1a;虛擬內存精粹 作者&#xff1a;潘建鋒 原文&#xff1a;HTTPS://strikefreedom.top/memory-management–virtual-memory 導言 虛擬內存是當今計算機系統中最重要的抽象概念之一&#xff0c;它的提出是為了更加有效地管理內存并且降低內存出錯的概…

藍橋杯真題訓練 2019.4題

標題&#xff1a; 數的分解&#xff08;本題總分&#xff1a;10 分&#xff09; 【問題描述】 把 2019 分解成 3 個各不相同的正整數之和&#xff0c;并且要求每個正整數都不包 含數字 2 和 4&#xff0c;一共有多少種不同的分解方法&#xff1f; 注意交換 3 個整數的順序被視…

深度學習自動編譯和優化技術調研

深度學習自動編譯和優化技術調研 轉自&#xff1a;https://moqi.com.cn/blog/deeplearning/ 作者&#xff1a;墨奇科技全棧開發 在墨奇科技&#xff0c;我們需要將一些包含深度神經網絡&#xff08;DNN&#xff09;的 AI 算法移植到邊緣端的設備&#xff0c; 這些設備往往使用 …

三元組數據處理系統

include<stdio.h> include<stdlib.h> define OK 1 define ERROR 0 define OVERFLOW -2 typedef int Status; typedef float ElemType; typedef ElemType *Triplet; // 聲明Triplet為ElemType指針類型 //三元組的初始化 Status initTriplet(Triplet &T, E…

Copy-On-Write COW機制

Copy-On-Write COW機制 轉自&#xff1a;https://zhuanlan.zhihu.com/p/48147304 作者&#xff1a;Java3y 前言 只有光頭才能變強 在讀《Redis設計與實現》關于哈希表擴容的時候&#xff0c;發現這么一段話&#xff1a; 執行BGSAVE命令或者BGREWRITEAOF命令的過程中&#xff0c…

實驗報告:抽象數據類型的表現和實現

實驗報告&#xff1a;抽象數據類型的表現和實現 實驗內容 基本要求&#xff1a; 設計實現抽象數據類型“三元組”&#xff0c;要求動態分配內存。每個三元組由任意三個實數的序列構成&#xff0c;基本操作包括&#xff1a;創建一個三元組&#xff0c;取三元組的任意一個分量&…

關于x86、x86_64/x64、amd64和arm64/aarch64

關于x86、x86_64/x64、amd64和arm64/aarch64 轉自&#xff1a;https://www.jianshu.com/p/2753c45af9bf 為什么叫x86和x86_64和AMD64? 為什么大家叫x86為32位系統&#xff1f; 為什么軟件版本會注明 for amd64版本&#xff0c;不是intel64呢&#xff1f; x86是指intel的開…