Hugging Face 详解 ZeRO 显存优化技术

原标题:Fit More and Train Faster With ZeRO via DeepSpeed and FairScale
45AI 研判分

Hugging Face 发布博客,深入解析 ZeRO(零冗余优化器)如何通过 DeepSpeed 和 FairScale 实现大模型训练中的显存节省与加速。文章介绍了 ZeRO 的核心原理及其在解决 GPU 内存瓶颈方面的应用,旨在帮助开发者更高效地训练大规模机器学习模型。

报道正文

本文目录9 个章节

返回文章列表

借助 DeepSpeed 和 FairScale 的 ZeRO 技术,实现更大模型适配与更快训练

发布于 2021 年 1 月 19 日 在 GitHub 上更新 点赞 6

Stas Bekman stas 客座作者

由 Hugging Face Fellow Stas Bekman 撰写的客座博客文章

随着近期机器学习模型的规模增长速度远超新发布 GPU 显存容量的提升速度,许多用户发现无法在自己的硬件上训练甚至加载这些巨型模型。尽管业界一直在努力通过蒸馏技术将部分大模型压缩到更易管理的尺寸,但这一进程尚未能足够快地产出体积足够小的模型。

2019 年秋季,Samyam Rajbhandari、Jeff Rasley、Olatunji Ruwase 和 Yuxiong He 发表了一篇论文:ZeRO: Memory Optimizations Toward Training Trillion Parameter Models,其中提出了大量巧妙的新思路,展示了如何让硬件突破以往被认为不可能的极限。不久之后,DeepSpeed 发布,为社区提供了该论文中大部分核心思想的开源实现(少数想法仍在开发中);与此同时,Facebook 的一个团队发布了 FairScale,也实现了 ZeRO 论文中的部分核心思想。

如果你使用 Hugging Face Trainer,从 transformers v4.2.0 版本开始,你已获得对 DeepSpeed 和 FairScale 中 ZeRO 特性的实验性支持。新的 --sharded_ddp 和 --deepspeed 命令行 Trainer 参数分别提供了对 FairScale 和 DeepSpeed 的集成。以下是完整文档。

本博客文章将介绍无论你拥有一块还是多块 GPU,如何都能从 ZeRO 技术中受益。

在多 GPU 配置下实现巨大加速

让我们做一个小型微调实验,任务是翻译,使用 t5-large 模型以及 finetune_trainer.py 脚本,该脚本可在 transformers GitHub 仓库的 examples/seq2seq 目录下找到。

我们拥有 2 块 24GB(Titan RTX)GPU 用于测试。

这只是一个概念验证(proof of concept)基准测试,因此肯定还有进一步改进的空间。为了进行比较,我们将使用一个小样本进行基准测试:训练集 2000 个条目,评估集 500 个条目。默认情况下,评估过程会执行大小为 4 的 beam search,因此其速度比相同样本数量的训练要慢,这也是为什么在这些测试中评估条目数量仅为训练条目的四分之一。

以下是我们基线配置的关键命令行参数:

BASH
export BS=16
python -m torch.distributed.launch --nproc_per_node=2 ./finetune_trainer.py \
--model_name_or_path t5-large --n_train 2000 --n_val 500 \
--per_device_eval_batch_size $BS --per_device_train_batch_size $BS \
--task translation_en_to_ro [...]

对于基线性能提升,我们仅使用了 DistributedDataParallel (DDP),没有采用其他技术。在遇到 Out of Memory (OOM) 错误之前,我能够将 batch size (BS) 设置为 16。

请注意,为了简化演示并使其更易于理解,我只展示了与此演示相关的命令行参数。完整的命令行可以在此帖子中找到。

接下来,我们将重新运行基准测试,每次添加以下其中一项优化:

  1. --fp16
  2. --sharded_ddp (fairscale)
  3. --sharded_ddp --fp16 (fairscale)
  4. --deepspeed(不带 CPU offloading)
  5. --deepspeed(带 CPU offloading)

由于这里的核心优化在于每种技术都能更高效地利用 GPU RAM,我们将尝试持续增加 batch size,并期望训练和评估能更快完成(同时保持指标稳定甚至有所改善,但此处我们不重点关注这些指标)。

请记住,训练阶段和评估阶段彼此差异很大。因为在训练期间,模型权重会被修改,梯度会被计算,并且优化器状态会被存储。而在评估期间,上述操作都不会发生。但在翻译这一特定任务中,模型需要搜索最佳假设,因此实际上需要进行多次运行才能满足要求。这就是为什么评估速度不快,尤其是当模型较大时。

让我们看看这六次测试运行的结果:

Methodmax BStrain timeeval time
baseline1630.945856.3310
fp162021.494353.4675
sharded_ddp3025.908547.5589
sharded_ddp+fp163017.383845.6593
deepspeed w/o cpu offload4010.400734.9289
deepspeed w/ cpu offload5020.970632.1409

It's easy to see that both FairScale and DeepSpeed provide great improvements over the baseline, in the total train and evaluation time, but also in the batch size. DeepSpeed implements more magic as of this writing and seems to be the short term winner, but Fairscale is easier to deploy. For DeepSpeed you need to write a simple configuration file and change your command line's launcher, with Fairscale you only need to add the --sharded_ddp command line argument, so you may want to try it first as it's the most low-hanging fruit.

Following the 80:20 rule, I have only spent a few hours on these benchmarks and I haven't tried to squeeze every MB and second by refining the command line arguments and configuration, since it's pretty obvious from the simple table what you'd want to try next. When you will face a real project that will be running for hours and perhaps days, definitely spend more time to make sure you use the most optimal hyper-parameters to get your job done faster and at a minimal cost.

If you would like to experiment with this benchmark yourself or want to know more details about the hardware and software used to run it, please, refer to this post.

Fitting A Huge Model Onto One GPU

While Fairscale gives us a boost only with multiple GPUs, DeepSpeed has a gift even for those of us with a single GPU.

Let's try the impossible - let's train t5-3b on a 24GB RTX-3090 card.

First let's try to finetune the huge t5-3b using the normal single GPU setup:

BASH
export BS=1
CUDA_VISIBLE_DEVICES=0 ./finetune_trainer.py \
--model_name_or_path t5-3b --n_train 60 --n_val 10 \
--per_device_eval_batch_size $BS --per_device_train_batch_size $BS \
--task translation_en_to_ro --fp16 [...]

No cookie, even with BS=1 we get:

文本
RuntimeError: CUDA out of memory. Tried to allocate 64.00 MiB (GPU 0; 23.70 GiB total capacity;
21.37 GiB already allocated; 45.69 MiB free; 22.05 GiB reserved in total by PyTorch)

Note, as earlier I'm showing only the important parts and the full command line arguments can be found here.

Now update your transformers to v4.2.0 or higher, then install DeepSpeed:

BASH
pip install deepspeed

and let's try again, this time adding DeepSpeed to the command line:

BASH
export BS=20
CUDA_VISIBLE_DEVICES=0 deepspeed --num_gpus=1 ./finetune_trainer.py \
--model_name_or_path t5-3b --n_train 60 --n_val 10 \
--per_device_eval_batch_size $BS --per_device_train_batch_size $BS \
--task translation_en_to_ro --fp16 --deepspeed ds_config_1gpu.json [...]

et voila! We get a batch size of 20 trained just fine. I could probably push it even further. The program failed with OOM at BS=30.

Here are the relevant results:

文本
2021-01-12 19:06:31 | INFO | __main__ |   train_n_objs = 60
2021-01-12 19:06:31 | INFO | __main__ |   train_runtime = 8.8511
2021-01-12 19:06:35 | INFO | __main__ |   val_n_objs = 10
2021-01-12 19:06:35 | INFO | __main__ |   val_runtime = 3.5329

We can't compare these to the baseline, since the baseline won't even start and immediately failed with OOM.

Simply amazing!

I used only a tiny sample since I was primarily interested in being able to train and evaluate with this huge model that normally won't fit onto a 24GB GPU.

If you would like to experiment with this benchmark yourself or want to know more details about the hardware and software used to run it, please, refer to this post.

The Magic Behind ZeRO

Since transformers only integrated these fabulous solutions and wasn't part of their invention I will share the resources where you can discover all the details for yourself. But here are a few quick insights that may help understand how ZeRO manages these amazing feats.

The key feature of ZeRO is adding distributed data storage to the quite familiar concept of data parallel training.

The computation on each GPU is exactly the same as data parallel training, but the parameter, gradients and optimizer states are stored in a distributed/partitioned fashion across all the GPUs and fetched only when needed.

The following diagram, coming from this blog post illustrates how this works:

[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]

ZeRO Partitioning

ZeRO's ingenious approach is to partition the params, gradients and optimizer states equally across all GPUs and give each GPU just a single partition (also referred to as a shard). This leads to zero overlap in data storage between GPUs. At runtime each GPU builds up each layer's data on the fly by asking participating GPUs to send the information it's lacking.

This idea could be difficult to grasp, and you will find my attempt at an explanation here.

As of this writing FairScale and DeepSpeed only perform Partitioning (Sharding) for the optimizer states and gradients. Model parameters sharding is supposedly coming soon in DeepSpeed and FairScale.

The other powerful feature is ZeRO-Offload (paper). This feature offloads some of the processing and memory needs to the host's CPU, thus allowing more to be fit onto the GPU. You saw its dramatic impact in the success at running t5-3b on a 24GB GPU.

One other problem that a lot of people complain about on pytorch forums is GPU memory fragmentation. One often gets an OOM error that may look like this:

文本
RuntimeError: CUDA out of memory. Tried to allocate 1.48 GiB (GPU 0; 23.65 GiB total capacity;
16.22 GiB already allocated; 111.12 MiB free; 22.52 GiB reserved in total by PyTorch)

The program wants to allocate ~1.5GB and the GPU still has some 6-7GBs of unused memory, but it reports to have only ~100MB of contiguous free memory and it fails with the OOM error. This happens as chunks of different size get allocated and de-allocated again and again, and over time holes get created leading to memory fragmentation, where there is a lot of unused memory but no contiguous chunks of the desired size. In the example above the program could probably allocate 100MB of contiguous memory, but clearly it can't get 1.5GB in a single chunk.

DeepSpeed attacks this problem by managing GPU memory by itself and ensuring that long term memory allocations don't mix with short-term ones and thus there is much less fragmentation. While the paper doesn't go into details, the source code is available, so it's possible to see how DeepSpeed accomplishes that.

As ZeRO stands for Zero Redundancy Optimizer, it's easy to see that it lives up to its name.

The Future

Besides the anticipated upcoming support for model params sharding in DeepSpeed, it already released new features that we haven't explored yet. These include DeepSpeed Sparse Attention and 1-bit Adam, which are supposed to decrease memory usage and dramatically reduce inter-GPU communication overhead, which should lead to an even faster training and support even bigger models.

I trust we are going to see new gifts from the FairScale team as well. I think they are working on ZeRO stage 3 as well.

Even more exciting, ZeRO is being integrated into pytorch.

Deployment

If you found the results shared in this blog post enticing, please proceed here for details on how to use DeepSpeed and FairScale with the transformers Trainer.

You can, of course, modify your own trainer to integrate DeepSpeed and FairScale, based on each project's instructions or you can "cheat" and see how we did it in the transformers Trainer. If you go for the latter, to find your way around grep the source code for deepspeed and/or sharded_ddp.

The good news is that ZeRO requires no model modification. The only required modifications are in the training code.

Issues

If you encounter any issues with the integration part of either of these projects please open an Issue in transformers.

But if you have problems with DeepSpeed and FairScale installation, configuration and deployment - you need to ask the experts in their domains, therefore, please, use DeepSpeed Issue or FairScale Issue instead.

Resources

While you don't really need to understand how any of these projects work and you can just deploy them via the transformers Trainer, should you want to figure out the whys and hows please refer to the following resources.

Gratitude

We were quite astonished at the amazing level of support we received from the FairScale and DeepSpeed developer teams while working on integrating those projects into transformers.

In particular I'd like to thank:

from the FairScale team and:

from the DeepSpeed team for your generous and caring support and prompt resolution of the issues we have encountered.

And HuggingFace for providing access to hardware the benchmarks were run on.

Sylvain Gugger @sgugger and Stas Bekman @stas00 worked on the integration of these projects.