pytorch中關(guān)于distributedsampler函數(shù)的使用
關(guān)于distributedsampler函數(shù)的使用
1.如何使用這個(gè)分布式采樣器
在使用distributedsampler函數(shù)時(shí),觀察loss發(fā)現(xiàn)loss收斂有規(guī)律,發(fā)現(xiàn)是按順序讀取數(shù)據(jù),未進(jìn)行shuffle。
問題的解決方式就是懷疑 seed 有問題,參考源碼 DistributedSampler,發(fā)現(xiàn) shuffle 的結(jié)果依賴 g.manual_seed(self.epoch) 中的 self.epoch。
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
if self.shuffle:
indices = torch.randperm(len(self.dataset), generator=g).tolist()
else:
indices = list(range(len(self.dataset)))
# add extra samples to make it evenly divisible
indices += indices[:(self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank:self.total_size:self.num_replicas]
assert len(indices) == self.num_samples
return iter(indices)而 self.epoch 初始默認(rèn)是 0
self.dataset = dataset
self.num_replicas = num_replicas
self.rank = rank
self.epoch = 0
self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas))
self.total_size = self.num_samples * self.num_replicas
self.shuffle = shuffle但是 DistributedSampler 也提供了一個(gè) set 函數(shù)來改變 self.epoch
def set_epoch(self, epoch):
self.epoch = epoch所以在運(yùn)行的時(shí)候要不斷調(diào)用這個(gè) set_epoch 函數(shù)。只要把我的代碼中的
# sampler.set_epoch(e)
全部代碼如下:
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
torch.distributed.init_process_group(backend="nccl")
input_size = 5
output_size = 2
batch_size = 2
data_size = 16
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, local_rank):
self.len = length
self.data = torch.stack([torch.ones(5), torch.ones(5)*2,
torch.ones(5)*3,torch.ones(5)*4,
torch.ones(5)*5,torch.ones(5)*6,
torch.ones(5)*7,torch.ones(5)*8,
torch.ones(5)*9, torch.ones(5)*10,
torch.ones(5)*11,torch.ones(5)*12,
torch.ones(5)*13,torch.ones(5)*14,
torch.ones(5)*15,torch.ones(5)*16]).to('cuda')
self.local_rank = local_rank
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.len
dataset = RandomDataset(input_size, data_size, local_rank)
sampler = DistributedSampler(dataset)
rand_loader = DataLoader(dataset=dataset,
batch_size=batch_size,
sampler=sampler)
e = 0
while e < 2:
t = 0
# sampler.set_epoch(e)
for data in rand_loader:
print(data)
e+=1運(yùn)行:
CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch --nproc_per_node=2 test.py
2.關(guān)于用不用這個(gè)采樣器的區(qū)別
多卡去訓(xùn)模型,嘗試著用DDP模式,而不是DP模式去加速訓(xùn)練(很容易出現(xiàn)負(fù)載不均衡的情況)。
遇到了一點(diǎn)關(guān)于DistributedSampler這個(gè)采樣器的一點(diǎn)疑惑,想試驗(yàn)下在DDP模式下,使用這個(gè)采樣器和不使用這個(gè)采樣器有什么區(qū)別。
實(shí)驗(yàn)代碼:
整個(gè)數(shù)據(jù)集大小為8,batch_size 為4,總共跑2個(gè)epoch。
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
torch.distributed.init_process_group(backend="nccl")
batch_size = 4
data_size = 8
local_rank = torch.distributed.get_rank()
print(local_rank)
torch.cuda.set_device(local_rank)
device = torch.device("cuda", local_rank)
class RandomDataset(Dataset):
def __init__(self, length, local_rank):
self.len = length
self.data = torch.stack([torch.ones(1), torch.ones(1)*2,torch.ones(1)*3,torch.ones(1)*4,torch.ones(1)*5,torch.ones(1)*6,torch.ones(1)*7,torch.ones(1)*8]).to('cuda')
self.local_rank = local_rank
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.len
dataset = RandomDataset(data_size, local_rank)
sampler = DistributedSampler(dataset)
#rand_loader =DataLoader(dataset=dataset,batch_size=batch_size,sampler=None,shuffle=True)
rand_loader = DataLoader(dataset=dataset,batch_size=batch_size,sampler=sampler)
epoch = 0
while epoch < 2:
sampler.set_epoch(epoch)
for data in rand_loader:
print(data)
epoch+=1運(yùn)行命令:
CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch --nproc_per_node=2 test.py
實(shí)驗(yàn)結(jié)果:

結(jié)論分析:上面的運(yùn)行結(jié)果來看,在一個(gè)epoch中,sampler相當(dāng)于把整個(gè)數(shù)據(jù)集 劃分成了nproc_per_node份,每個(gè)GPU每次得到batch_size的數(shù)量,也就是nproc_per_node 個(gè)GPU分一整份數(shù)據(jù)集,總數(shù)據(jù)量大小就為1個(gè)dataset。
如果不用它里面自帶的sampler,單純的還是按照我們一般的形式。Sampler=None,shuffle=True這種,那么結(jié)果將會(huì)是下面這樣的:
結(jié)果分析:沒用sampler的話,在一個(gè)epoch中,每個(gè)GPU各自維護(hù)著一份數(shù)據(jù),每個(gè)GPU每次得到的batch_size的數(shù)據(jù),總的數(shù)據(jù)量為2個(gè)dataset,

總結(jié)
一般的形式的dataset只能在同進(jìn)程中進(jìn)行采樣分發(fā),也就是為什么圖2只能單GPU維護(hù)自己的dataset,DDP中的sampler可以對(duì)不同進(jìn)程進(jìn)行分發(fā)數(shù)據(jù),圖1,可以夸不同進(jìn)程(GPU)進(jìn)行分發(fā)。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python request設(shè)置HTTPS代理代碼解析
這篇文章主要介紹了Python request設(shè)置HTTPS代理代碼解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
python實(shí)現(xiàn)圖片變亮或者變暗的方法
這篇文章主要介紹了python實(shí)現(xiàn)圖片變亮或者變暗的方法,涉及Python中Image模塊操作圖片的相關(guān)技巧,需要的朋友可以參考下2015-06-06
Numpy 將二維圖像矩陣轉(zhuǎn)換為一維向量的方法
今天小編就為大家分享一篇Numpy 將二維圖像矩陣轉(zhuǎn)換為一維向量的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06
關(guān)于數(shù)據(jù)分析之滾動(dòng)窗口pandas.DataFrame.rolling方法
Pandas庫(kù)中的rolling方法是數(shù)據(jù)處理中常用的功能,它允許用戶對(duì)數(shù)據(jù)進(jìn)行滾動(dòng)窗口(滑動(dòng)窗口)操作,通過指定窗口大小,可以使用不同的聚合函數(shù)對(duì)窗口內(nèi)的數(shù)據(jù)進(jìn)行計(jì)算,例如最大值、最小值、平均值、中位數(shù)等,此外,rolling方法還可以計(jì)算方差、標(biāo)準(zhǔn)差、偏度、峰度2024-09-09
Pygame坦克大戰(zhàn)游戲開發(fā)實(shí)戰(zhàn)詳解代碼
《坦克大戰(zhàn)》以二戰(zhàn)坦克為題材,既保留了射擊類游戲的操作性,也改進(jìn)了射擊類游戲太過于復(fù)雜難玩的高門檻特點(diǎn),集休閑與競(jìng)技于一身。經(jīng)典再度襲來,流暢的畫面,瘋狂的戰(zhàn)斗,讓玩家再次進(jìn)入瘋狂坦克的世界。玩家的目標(biāo)是控制坦克躲避危險(xiǎn),消滅掉所有的敵人即可進(jìn)入下一關(guān)2022-02-02

