pytorch中關于distributedsampler函數(shù)的使用
關于distributedsampler函數(shù)的使用
1.如何使用這個分布式采樣器
在使用distributedsampler函數(shù)時,觀察loss發(fā)現(xiàn)loss收斂有規(guī)律,發(fā)現(xiàn)是按順序讀取數(shù)據(jù),未進行shuffle。
問題的解決方式就是懷疑 seed 有問題,參考源碼 DistributedSampler,發(fā)現(xiàn) shuffle 的結果依賴 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 初始默認是 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 也提供了一個 set 函數(shù)來改變 self.epoch
def set_epoch(self, epoch):
self.epoch = epoch所以在運行的時候要不斷調用這個 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運行:
CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch --nproc_per_node=2 test.py
2.關于用不用這個采樣器的區(qū)別
多卡去訓模型,嘗試著用DDP模式,而不是DP模式去加速訓練(很容易出現(xiàn)負載不均衡的情況)。
遇到了一點關于DistributedSampler這個采樣器的一點疑惑,想試驗下在DDP模式下,使用這個采樣器和不使用這個采樣器有什么區(qū)別。
實驗代碼:
整個數(shù)據(jù)集大小為8,batch_size 為4,總共跑2個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運行命令:
CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch --nproc_per_node=2 test.py
實驗結果:

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

總結
一般的形式的dataset只能在同進程中進行采樣分發(fā),也就是為什么圖2只能單GPU維護自己的dataset,DDP中的sampler可以對不同進程進行分發(fā)數(shù)據(jù),圖1,可以夸不同進程(GPU)進行分發(fā)。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
關于數(shù)據(jù)分析之滾動窗口pandas.DataFrame.rolling方法
Pandas庫中的rolling方法是數(shù)據(jù)處理中常用的功能,它允許用戶對數(shù)據(jù)進行滾動窗口(滑動窗口)操作,通過指定窗口大小,可以使用不同的聚合函數(shù)對窗口內的數(shù)據(jù)進行計算,例如最大值、最小值、平均值、中位數(shù)等,此外,rolling方法還可以計算方差、標準差、偏度、峰度2024-09-09
Pygame坦克大戰(zhàn)游戲開發(fā)實戰(zhàn)詳解代碼
《坦克大戰(zhàn)》以二戰(zhàn)坦克為題材,既保留了射擊類游戲的操作性,也改進了射擊類游戲太過于復雜難玩的高門檻特點,集休閑與競技于一身。經典再度襲來,流暢的畫面,瘋狂的戰(zhàn)斗,讓玩家再次進入瘋狂坦克的世界。玩家的目標是控制坦克躲避危險,消滅掉所有的敵人即可進入下一關2022-02-02

