天天看點

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

來源:讀芯術

文章來源:微信公衆号 資料派THU

本文為大家介紹9個使用Pytorch訓練解決神經網絡的技巧

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

圖檔來源:unsplash.com/@dulgier

事實上,你的模型可能還停留在石器時代的水準。估計你還在用32位精度或GASP(一般活動仿真語言)訓練,甚至可能隻在單GPU上訓練。如果市面上有99個加速指南,但你可能隻看過1個?(沒錯,就是這樣)。但這份終極指南,會一步步教你清除模型中所有的(GP模型)。

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

不要讓你的神經網絡變成這樣。(圖檔來源:Monsters U)

這份指南的介紹從簡單到複雜,一直介紹到你可以完成大多數PITA修改,以充分利用你的網絡。例子中會包括一些Pytorch代碼和相關标記,可以在 Pytorch-Lightning訓練器中用,以防大家不想自己敲碼!

這份指南針對的是誰? 任何用Pytorch研究非瑣碎的深度學習模型的人,比如工業研究人員、博士生、學者等等……這些模型可能要花費幾天,甚至幾周、幾個月的時間來訓練。

Pytorch-Lightning

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

文中讨論的各種優化,都可以在名為Pytorch-Lightning(

https://github.com/williamFalcon/pytorch-lightning?source=post_page---------------------------

) 的Pytorch圖書館中找到。

Lightning是基于Pytorch的一個光包裝器,它可以幫助研究人員自動訓練模型,但關鍵的模型部件還是由研究人員完全控制。

參照此篇教程,獲得更有力的範例(

https://github.com/williamFalcon/pytorch-lightning/blob/master/examples/new_project_templates/single_gpu_node_template.py?source=post_page---------------------------

)。

Lightning采用最新、最尖端的方法,将犯錯的可能性降到最低。

MNIST定義的Lightning模型(

https://github.com/williamFalcon/pytorch-lightning/blob/master/examples/new_project_templates/lightning_module_template.py?source=post_page---------------------------

),可适用于訓練器。

from pytorch-lightning import Trainer

model = LightningModule(…)trainer = Trainer()
trainer.fit(model)           

1. DataLoader

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

這可能是最容易提速的地方。靠儲存h5py或numpy檔案來加速資料加載的日子已經一去不複返了。用 Pytorch dataloader (

https://pytorch.org/tutorials/beginner/data_loading_tutorial.html?source=post_page---------------------------

)加載圖像資料非常簡單。

(關于NLP資料,請參照TorchText:

https://torchtext.readthedocs.io/en/latest/datasets.html?source=post_page---------------------------)
dataset = MNIST(root=self.hparams.data_root, train=train, download=True)

loader = DataLoader(dataset, batch_size=32, shuffle=True)

for batch in loader: x, y = batchmodel.training_step(x, y)...           

在Lightning中,你無需指定一個訓練循環,隻需定義dataLoaders,訓練器便會在需要時調用它們。

https://github.com/williamFalcon/pytorch-lightning/blob/master/examples/new_project_templates/lightning_module_template.py?source=post_page---------------------------#L163-L217
  1. DataLoaders中的程序數
送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

加快速度的第二個秘訣在于允許批量并行加載。是以,你可以一次加載許多批量,而不是一次加載一個。

# slowloader = DataLoader(dataset, batch_size=32, shuffle=True)
# fast (use 10 workers)loader = DataLoader(dataset, batch_size=32, shuffle=True, num_workers=10)           

3. 批尺寸

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

在開始下一步優化步驟之前,将批量大小調高到CPU記憶體或GPU記憶體允許的最大值。

接下來的部分将着重于減少記憶體占用,這樣就可以繼續增加批尺寸。

記住,你很可能需要再次更新學習率。如果将批尺寸增加一倍,最好将學習速度也提高一倍。

4. 累積梯度

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

假如已經最大限度地使用了計算資源,而批尺寸仍然太低(假設為8),那我們則需為梯度下降模拟更大的批尺寸,以供精準估計。

假設想讓批尺寸達到128。然後,在執行單個優化器步驟前,将執行16次前向和後向傳播(批量大小為8)。

# clear last stepoptimizer.zero_grad()

# 16 accumulated gradient stepsscaled_loss = 0for accumulated_step_i in range(16):      out = model.forward()     loss = some_loss(out,y)         loss.backward()

       scaled_loss += loss.item()

# update weights after 8 steps. effective batch = 8*16optimizer.step()

# loss is now scaled up by the number of accumulated batchesactual_loss = scaled_loss / 16           

而在Lightning中,這些已經自動執行了。隻需設定标記:

https://williamfalcon.github.io/pytorch-lightning/Trainer/Training%20Loop/?source=post_page---------------------------#accumulated-gradients

trainer = Trainer(accumulate_grad_batches=16)

trainer.fit(model)

5. 保留計算圖

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

撐爆記憶體很簡單,隻要不釋放指向計算圖形的指針,比如……為記錄日志儲存loss。

losses = []
...losses.append(loss)

print(f'current loss: {torch.mean(losses)'})           

上述的問題在于,loss仍然有一個圖形副本。在這種情況中,可用.item()來釋放它。

# badlosses.append(loss)

# goodlosses.append(loss.item())           

Lightning會特别注意,讓其無法保留圖形副本

(示例:

https://github.com/williamFalcon/pytorch-lightning/blob/master/pytorch_lightning/models/trainer.py?source=post_page---------------------------#L767-L768)

6. 轉至單GPU

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

一旦完成了前面的步驟,就可以進入GPU訓練了。GPU的訓練将對許多GPU核心上的數學計算進行并行處理。能加速多少取決于使用的GPU類型。個人使用的話,推薦使用2080Ti,公司使用的話可用V100。

剛開始你可能會覺得壓力很大,但其實隻需做兩件事: 1)将你的模型移動到GPU上;2)在用其運作資料時,把資料導至GPU中。

# put model on GPUmodel.cuda(0)

# put data on gpu (cuda on a variable returns a cuda copy)x = x.cuda(0)

# runs on GPU nowmodel(x)           

如果使用Lightning,則不需要對代碼做任何操作。隻需設定标記

https://williamfalcon.github.io/pytorch-lightning/Trainer/Distributed%20training/?source=post_page---------------------------#single-gpu

):

ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

在GPU進行訓練時,要注意限制CPU和GPU之間的傳輸量。

# expensivex = x.cuda(0)

# very expensivex = x.cpu()x = x.cuda(0)           

例如,如果耗盡了記憶體,不要為了省記憶體,将資料移回CPU。嘗試用其他方式優化代碼,或者在用這種方法之前先跨GPUs配置設定代碼。

此外還要注意進行強制GPUs同步的操作。例如清除記憶體緩存。

# really bad idea.Stops all the GPUs until they all catch uptorch.cuda.empty_cache()
           

但是如果使用Lightning,那麼隻有在定義Lightning子產品時可能會出現這種問題。Lightning特别注意避免此類錯誤。

7. 16位混合精度訓練

16位精度可以有效地削減一半的記憶體占用。大多數模型都是用32位精度數進行訓練的。然而最近的研究發現,使用16位精度,模型也可以很好地工作。混合精度指的是,用16位訓練一些特定的模型,而權值類的用32位訓練。

要想在Pytorch中用16位精度,先從NVIDIA中安裝 apex 圖書館并對你的模型進行這些更改。

# enable 16-bit on the model and the optimizermodel, optimizers = amp.initialize(model, optimizers, opt_level='O2')
# when doing .backward, let amp do it so it can scale the losswith amp.scale_loss(loss, optimizer) as scaled_loss:                           scaled_loss.backward()           

amp包會處理大部分事情。如果梯度爆炸或趨于零,它甚至會擴大loss。

在Lightning中, 使用16位很簡單(

https://williamfalcon.github.io/pytorch-lightning/Trainer/Distributed%20training/?source=post_page---------------------------#16-bit-mixed-precision

),不需對你的模型做任何修改,也不用完成上述操作。

trainer = Trainer(amp_level=’O2', use_amp=False)trainer.fit(model)           

8. 移至多GPU

現在,事情就變得有意思了。有3種(也許更多?)方式訓練多GPU。

分批量訓練

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

A在每個GPU上複制模型;B給每個GPU配置設定一部分批量。

第一種方法叫做分批量訓練。這一政策将模型複制到每個GPU上,而每個GPU會分到該批量的一部分。

# copy model on each GPU and give a fourth of the batch to eachmodel = DataParallel(model, devices=[0, 1, 2 ,3])

# out has 4 outputs (one for each gpu)out = model(x.cuda(0))           

在Lightning中,可以直接訓示訓練器增加GPU數量,而無需完成上述任何操作。

# ask lightning to use 4 GPUs for trainingtrainer = Trainer(gpus=[0, 1, 2, 3])trainer.fit(model)
           

分模型訓練

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

将模型的不同部分配置設定給不同的GPU,按順序配置設定批量

有時模型可能太大,記憶體不足以支撐。比如,帶有編碼器和解碼器的Sequence to Sequence模型在生成輸出時可能會占用20gb的記憶體。在這種情況下,我們希望把編碼器和解碼器放在單獨的GPU上。

# each model is sooo big we can't fit both in memory
encoder_rnn.cuda(0)
decoder_rnn.cuda(1)


# run input through encoder on GPU 0
out = encoder_rnn(x.cuda(0))


# run output through decoder on the next GPU
out = decoder_rnn(x.cuda(1))


# normally we want to bring all outputs back to GPU 0
out = out.cuda(0)
           

對于這種類型的訓練,無需将Lightning訓練器分到任何GPU上。與之相反,隻要把自己的子產品導入正确的GPU的Lightning子產品中:

class MyModule(LightningModule):

def __init__():         self.encoder = RNN(...)        self.decoder = RNN(...)

def forward(x):

    # models won't be moved after the first forward because         # they are already on the correct GPUs        self.encoder.cuda(0)        self.decoder.cuda(1)        out = self.encoder(x)        out = self.decoder(out.cuda(1))

# don't pass GPUs to trainermodel = MyModule()trainer = Trainer()trainer.fit(model)           

混合兩種訓練方法

在上面的例子中,編碼器和解碼器仍然可以從并行化每個操作中獲益。我們現在可以更具創造力了。

# change these linesself.encoder = RNN(...)self.decoder = RNN(...)

# to these# now each RNN is based on a different gpu setself.encoder = DataParallel(self.encoder, devices=[0, 1, 2, 3])self.decoder = DataParallel(self.encoder, devices=[4, 5, 6, 7])

# in forward...out = self.encoder(x.cuda(0))

# notice inputs on first gpu in devicesout = self.decoder(out.cuda(4))  # <--- the 4 here           

使用多GPUs時需注意的事項

如果該裝置上已存在model.cuda(),那麼它不會完成任何操作。

始終輸入到裝置清單中的第一個裝置上。

跨裝置傳輸資料非常昂貴,不到萬不得已不要這樣做。

優化器和梯度将存儲在GPU 0上。是以,GPU 0使用的記憶體很可能比其他處理器大得多。

9. 轉至多GPU階段(8+GPUs)

送你9個快速使用Pytorch訓練解決神經網絡的技巧(附代碼)ask lightning to use gpu 0 for trainingtrainer = Trainer(gpus=[0])trainer.fit(model)

每台機器上的各GPU都可擷取一份模型的副本。每台機器分得一部分資料,并僅針對該部分資料進行訓練。各機器彼此同步梯度。

做到了這一步,就可以在幾分鐘内訓練Imagenet資料集了! 這沒有想象中那麼難,但需要更多有關計算叢集的知識。這些指令假定你正在叢集上使用SLURM。

Pytorch在各個GPU上跨節點複制模型并同步梯度,進而實作多節點訓練。是以,每個模型都是在各GPU上獨立初始化的,本質上是在資料的一個分區上獨立訓練的,隻是它們都接收來自所有模型的梯度更新。

進階階段:

在各GPU上初始化一個模型的副本(確定設定好種子,使每個模型初始化到相同的權值,否則操作會失效)。

将資料集分成子集。每個GPU隻在自己的子集上訓練。

On .backward() 所有副本都會接收各模型梯度的副本。隻有此時,模型之間才會互相通信。

Pytorch有一個很好的抽象概念,叫做分布式資料并行處理,它可以為你完成這一操作。要使用DDP(分布式資料并行處理),需要做4件事:

def tng_dataloader():     d = MNIST()

     # 4: Add distributed sampler     # sampler sends a portion of tng data to each machine     dist_sampler = DistributedSampler(dataset)     dataloader = DataLoader(d, shuffle=False, sampler=dist_sampler)

def main_process_entrypoint(gpu_nb):      # 2: set up connections  between all gpus across all machines     # all gpus connect to a single GPU "root"     # the default uses env://

     world = nb_gpus * nb_nodes     dist.init_process_group("nccl", rank=gpu_nb, world_size=world)

     # 3: wrap model in DPP     torch.cuda.set_device(gpu_nb)     model.cuda(gpu_nb)     model = DistributedDataParallel(model, device_ids=[gpu_nb])

     # train your model now...

if  __name__ == '__main__':      # 1: spawn number of processes     # your cluster will call main for each machine     mp.spawn(main_process_entrypoint, nprocs=8)
           

Pytorch團隊對此有一份詳細的實用教程(

https://github.com/pytorch/examples/blob/master/imagenet/main.py?source=post_page---------------------------

然而,在Lightning中,這是一個自帶功能。隻需設定節點數标志,其餘的交給Lightning處理就好。

# train on 1024 gpus across 128 nodes
trainer = Trainer(nb_gpu_nodes=128, gpus=[0, 1, 2, 3, 4, 5, 6, 7])
           

Lightning還附帶了一個SlurmCluster管理器,可助你簡單地送出SLURM任務的正确細節。

示例:

https://github.com/williamFalcon/pytorch-lightning/blob/master/examples/new_project_templates/multi_node_cluster_template.py?source=post_page---------------------------#L103-L134

事實證明,分布式資料并行處理要比資料并行快得多,因為其唯一的通信是梯度同步。是以,最好用分布式資料并行處理替換資料并行,即使隻是在做單機訓練。

在Lightning中,通過将distributed_backend設定為ddp(分布式資料并行處理)并設定GPU的數量,這可以很容易實作。

# train on 4 gpus on the same machine MUCH faster than DataParallel
trainer = Trainer(distributed_backend='ddp', gpus=[0, 1, 2, 3])
           

10. 有關模型加速的思考和技巧

如何通過尋找瓶頸來思考問題?可以把模型分成幾個部分:

首先,確定資料加載中沒有瓶頸。為此,可以使用上述的現有資料加載方案,但是如果沒有适合你的方案,你可以把離線處理及超高速緩存作為高性能資料儲存,就像h5py一樣。

其次看看在訓練過程中該怎麼做。確定快速轉發,避免多餘的計算,并将CPU和GPU之間的資料傳輸最小化最後,避免降低GPU的速度(在本指南中有介紹)。

接下來,最大化批尺寸,通常來說,GPU的記憶體大小會限制批量大小。自此看來,這其實就是跨GPU分布,但要最小化延遲,有效使用大批次(例如在資料集中,可能會在多個GPUs上獲得8000+的有效批量大小)。

但是需要小心處理大批次。根據具體問題查閱文獻,學習一下别人是如何處理的!

編輯:王菁

校對:楊學俊

繼續閱讀