Hugging Face 教程:用 FSDP 加速大模型训练

原标题:Accelerate Large Model Training using PyTorch Fully Sharded Data Parallel
48AI 研判分

Hugging Face 发布技术博客,指导开发者利用 Accelerate 库集成 PyTorch FullyShardedDataParallel (FSDP) 以解决大模型显存瓶颈。文章通过对比 ZeRO 等方案,展示了如何在有限硬件上高效加载和训练大规模参数模型。

报道正文

本文目录10 个章节

返回文章列表

使用 PyTorch Fully Sharded Data Parallel 加速大模型训练

发布于 2022 年 5 月 2 日 在 GitHub 上更新 点赞 9

Sourab Mangrulkar smangrul Sylvain Gugger sgugger

本文也有简体中文版本 简体中文。

在这篇文章中,我们将探讨如何利用 Accelerate 库来训练大型模型,该库使用户能够利用 PyTorch FullyShardedDataParallel (FSDP) 的最新特性。

动机 🤗

随着机器学习(ML)模型的规模、大小和参数数量不断增加,从业者发现很难在硬件上训练甚至加载这些大型模型。 一方面,人们发现大型模型学习速度更快(数据和计算效率高),并且与小型模型相比性能显著更优 [1];另一方面,在大多数可用硬件上训练此类模型变得不切实际。

分布式训练是实现此类大型 ML 模型训练的关键。近年来,大规模分布式训练领域取得了重大进展。以下是一些最显著的进展:

  1. 使用 ZeRO - Zero Redundancy Optimizer 进行数据并行 [2]

  2. Stage 1:在数据并行工作进程/GPU 之间分片优化器状态

  3. Stage 2:在数据并行工作进程/GPU 之间分片优化器状态和梯度

  4. Stage 3:在数据并行工作进程/GPU 之间分片优化器状态、梯度和模型参数

  5. CPU Offload:基于 ZERO Stage 2,将梯度和优化器状态卸载到 CPU [3]

  6. Tensor Parallelism [4]:一种模型并行形式,通过巧妙的方式将具有大量参数的单个层的参数跨加速器/GPU 进行分片,以实现并行计算,同时避免昂贵的通信同步开销。

  7. Pipeline Parallelism [5]:一种模型并行形式,将模型的不同层分布到不同的加速器/GPU 上,并采用流水线技术以保持所有加速器同时运行。例如,第二个加速器/GPU 在处理第一个 micro-batch 时,第一个加速器/GPU 正在处理第二个 micro-batch。

  8. 3D parallelism [3]:结合使用基于 ZeRO 的数据并行、Tensor Parallelism 和 Pipeline Parallelism,以训练参数量达数千亿级别的超大模型。例如,BigScience 的 176B 参数语言模型就采用了这种方法 [6]。

在这篇文章中,我们将探讨基于 ZeRO 的数据并行,特别是 PyTorch 的最新特性 FullyShardedDataParallel (FSDP)。DeepSpeed 和 FairScale 已经实现了 ZeRO 论文的核心思想。这些功能已集成到 transformers Trainer 中,并配有优秀的博客文章 Fit More and Train Faster With ZeRO via DeepSpeed and FairScale [10]。PyTorch 最近将 Fairscale 的 FSDP 上游合并到了 PyTorch Distributed 中,并进行了额外的优化。

Accelerate 🚀:无需更改代码即可利用 PyTorch FSDP

我们将探讨使用 GPT-2 Large (762M) 和 XL (1.5B) 模型变体进行因果语言建模(Causal Language Modelling)的任务。

以下是用于预训练 GPT-2 模型的代码。它与官方的因果语言建模示例 此处 类似,但额外添加了两个参数 n_train(2000)和 n_val(500),以避免对完整数据集进行预处理/训练,从而快速完成概念验证基准测试。

run_clm_no_trainer.py

运行命令 accelerate config 后生成的 FSDP 配置示例:

BASH
compute_environment: LOCAL_MACHINE
deepspeed_config: {}
distributed_type: FSDP
fsdp_config:
  min_num_params: 2000
  offload_params: false
  sharding_strategy: 1
machine_rank: 0
main_process_ip: null
main_process_port: null
main_training_function: main
mixed_precision: 'no'
num_machines: 1
num_processes: 2
use_cpu: false

多 GPU FSDP

在此,我们在单节点多 GPU 设置下进行实验。我们比较了分布式数据并行(DDP)和 FSDP 在不同配置下的性能。首先,使用 GPT-2 Large(762M)模型,其中 DDP 在某些批量大小下可以正常工作而不会抛出内存不足(OOM)错误。接下来,使用 GPT-2 XL(1.5B)模型,其中 DDP 即使在批量大小为 1 时也会因 OOM 错误而失败。我们观察到,FSDP 使 GPT-2 Large 模型能够支持更大的批量大小,并且与 DDP 不同,它使得 GPT-2 XL 模型能够以合理的批量大小进行训练。

硬件设置:2 块 24GB NVIDIA Titan RTX GPU。

训练 GPT-2 Large 模型(762M 参数)的命令:

BASH
export BS=

time accelerate launch run_clm_no_trainer.py \
--model_name_or_path gpt2-large \
--dataset_name wikitext \
--dataset_config_name wikitext-2-raw-v1 \
--per_device_train_batch_size $BS 
--per_device_eval_batch_size $BS 
--num_train_epochs 1 
--block_size 12

FSDP 运行示例:Sample FSDP Run

方法最大批大小 ($BS)近似训练时间(分钟)备注
DDP (Distributed Data Parallel,分布式数据并行)715
DDP + FP1678
FSDP with SHARD_GRAD_OP1111
FSDP with min_num_params = 1M + FULL_SHARD1512
FSDP with min_num_params = 2K + FULL_SHARD1513
FSDP with min_num_params = 1M + FULL_SHARD + Offload to CPU2023
FSDP with min_num_params = 2K + FULL_SHARD + Offload to CPU2224

表 1:在 GPT-2 Large (762M) 模型上对 FSDP 进行基准测试

与 DDP 相比,从表 1 中我们可以观察到,FSDP 支持更大的批大小,在不使用和不使用 CPU offload 设置的情况下,分别可达到 2X-3X 的提升。就训练时间而言,采用混合精度的 DDP 最快,其次是分别使用 ZERO Stage 2 和 Stage 3 的 FSDP。由于因果语言建模任务始终具有固定的上下文序列长度 (--block_size),因此使用 FSDP 带来的训练时间加速并不显著。对于采用动态批处理的应用场景,FSDP 能够支持更大的批大小,这可能会在训练时间方面带来可观的加速。目前,FSDP 的混合精度支持在 transformer 中存在一些 问题。一旦这些问题得到解决,训练时间的加速效果将进一步显著提升。

通过 CPU Offloading 实现无法放入 GPU 显存的巨型模型训练

训练 GPT-2 XL 模型(1.5B 参数)的命令:

BASH
export BS=

time accelerate launch run_clm_no_trainer.py \
--model_name_or_path gpt2-xl \
--dataset_name wikitext \
--dataset_config_name wikitext-2-raw-v1 \
--per_device_train_batch_size $BS 
--per_device_eval_batch_size $BS 
--num_train_epochs 1 
--block_size 12

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

MethodBatch Size Max ($BS)Num GPUsApprox Train Time (Hours)Notes
DDP11NAOOM Error RuntimeError: CUDA out of memory. Tried to allocate 40.00 MiB (GPU 0; 23.65 GiB total capacity; 22.27 GiB already allocated; 20.31 MiB free; 22.76 GiB reserved in total by PyTorch)
DDP12NAOOM Error RuntimeError: CUDA out of memory. Tried to allocate 40.00 MiB (GPU 0; 23.65 GiB total capacity; 22.27 GiB already allocated; 20.31 MiB free; 22.76 GiB reserved in total by PyTorch)
DDP + FP1611NAOOM Error RuntimeError: CUDA out of memory. Tried to allocate 40.00 MiB (GPU 0; 23.65 GiB total capacity; 22.27 GiB already allocated; 20.31 MiB free; 22.76 GiB reserved in total by PyTorch)
FSDP with min_num_params = 2K520.6
FSDP with min_num_params = 2K + Offload to CPU1013
FSDP with min_num_params = 2K + Offload to CPU1421.16

Table 2: Benchmarking FSDP on GPT-2 XL (1.5B) model

From Table 2, we can observe that DDP (w and w/o fp16) isn’t even able to run with batch size of 1 and results in CUDA OOM error. FSDP with Zero-Stage 3 is able to be run on 2 GPUs with batch size of 5 (effective batch size =10 (5 X 2)). FSDP with CPU offload can further increase the max batch size to 14 per GPU when using 2 GPUs. FSDP with CPU offload enables training GPT-2 1.5B model on a single GPU with a batch size of 10. This enables ML practitioners with minimal compute resources to train such large models, thereby democratizing large model training.

Capabilities and limitations of the FSDP Integration

Let’s dive into the current support that Accelerate provides for FSDP integration and the known limitations.

Required PyTorch version for FSDP support: PyTorch Nightly (or 1.12.0 if you read this after it has been released) as the model saving with FSDP activated is only available with recent fixes.

Configuration through CLI:

  1. Sharding Strategy: [1] FULL_SHARD, [2] SHARD_GRAD_OP
  2. Min Num Params: FSDP's minimum number of parameters for Default Auto Wrapping.
  3. Offload Params: Decides Whether to offload parameters and gradients to CPU.

For more control, users can leverage the FullyShardedDataParallelPlugin wherein they can specify auto_wrap_policy, backward_prefetch and ignored_modules.

After creating an instance of this class, users can pass it when creating the Accelerator object.

For more information on these options, please refer to the PyTorch FullyShardedDataParallel code.

Next, we will see the importance of the min_num_params config. Below is an excerpt from [8] detailing the importance of FSDP Auto Wrap Policy.

Importance of FSDP Auto Wrap Policy

(Source: link)

When using the default_auto_wrap_policy, a layer is wrapped in FSDP module if the number of parameters in that layer is more than the min_num_params . The code for finetuning BERT-Large (330M) model on the GLUE MRPC task is the official complete NLP example outlining how to properly use FSDP feature with the addition of utilities for tracking peak memory usage.

fsdp_with_peak_mem_tracking.py

We leverage the tracking functionality support in Accelerate to log the train and evaluation peak memory usage along with evaluation metrics. Below is the snapshot of the plots from wandb run. Wandb Run

We can observe that the DDP takes twice as much memory as FSDP with auto wrap. FSDP without auto wrap takes more memory than FSDP with auto wrap but considerably less than that of DDP. FSDP with auto wrap with min_num_params=2k takes marginally less memory when compared to setting with min_num_params=1M. This highlights the importance of the FSDP Auto Wrap Policy and users should play around with the min_num_params to find the setting which considerably saves memory and isn’t resulting in lot of communication overhead. PyTorch team is working on auto tuning tool for this config as mentioned in [8].

Few caveats to be aware of

  • PyTorch FSDP auto wraps sub-modules, flattens the parameters and shards the parameters in place. Due to this, any optimizer created before model wrapping gets broken and occupies more memory. Hence, it is highly recommended and efficient to prepare model before creating optimizer. Accelerate will automatically wrap the model and create an optimizer for you in case of single model with a warning message.

FSDP Warning: When using FSDP, it is efficient and recommended to call prepare for the model before creating the optimizer

However, below is the recommended way to prepare model and optimizer while using FSDP:

DIFF
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+ model = accelerator.prepare(model)

optimizer = torch.optim.AdamW(params=model.parameters(), lr=lr)

- model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(model,
-        optimizer, train_dataloader, eval_dataloader, lr_scheduler
-    )

+ optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+         optimizer, train_dataloader, eval_dataloader, lr_scheduler
+        )
  • In case of a single model, if you have created optimizer with multiple parameter groups and called prepare with them together, then the parameter groups will be lost and the following warning is displayed:

FSDP Warning: When using FSDP, several parameter groups will be conflated into a single one due to nested module wrapping and parameter flattening.

This is because parameter groups created before wrapping will have no meaning post wrapping due parameter flattening of nested FSDP modules into 1D arrays (which can consume many layers). For instance, below are the named parameters of FSDP model on GPU 0 (When using 2 GPUs. Around 55M (110M/2) params in 1D arrays as this will have the 1st shard of the parameters). Here, if one has applied no weight decay for [bias, LayerNorm.weight] named parameters of unwrapped BERT-Base model, it can’t be applied to the below FSDP wrapped model as there are no named parameters with either of those strings and the parameters of those layers are concatenated with parameters of various other layers. More details mentioned in this issue (The original model parameters' .grads are not set, meaning that they cannot be optimized separately (which is why we cannot support multiple parameter groups)).

文本

{ '_fsdp_wrapped_module.flat_param': torch.Size([494209]),

'_fsdp_wrapped_module._fpw_module.bert.embeddings.word_embeddings._fsdp_wrapped_module.flat_param': torch.Size([11720448]),

'_fsdp_wrapped_module._fpw_module.bert.encoder._fsdp_wrapped_module.flat_param': torch.Size([42527232]) }

文本
  • In case of multiple models, it is necessary to prepare the models before creating optimizers else it will throw an error.
  • Mixed precision is currently not supported with FSDP as we wait for PyTorch to fix support for it.

How it works 📝

FSDP Workflow

(Source: link)

The above workflow gives an overview of what happens behind the scenes when FSDP is activated. Let's first understand how DDP works and how FSDP improves it. In DDP, each worker/accelerator/GPU has a replica of the entire model parameters, gradients and optimizer states. Each worker gets a different batch of data, it goes through the forwards pass, a loss is computed followed by the backward pass to generate gradients. Now, an all-reduce operation is performed wherein each worker gets the gradients from the remaining workers and averaging is done. In this way, each worker now has the same global gradients which are used by the optimizer to update the model parameters. We can see that having full replicas consume a lot of redundant memory on each GPU, which limits the batch size as well as the size of the models.

FSDP precisely addresses this by sharding the optimizer states, gradients and model parameters across the data parallel workers. It further facilitates CPU offloading of all those tensors, thereby enabling loading large models which won't fit the available GPU memory. Similar to DDP, each worker gets a different batch of data. During the forward pass, if the CPU offload is enabled, the parameters of the local shard are first copied to the GPU/accelerator. Then, each worker performs all-gather operation for a given FSDP wrapped module/layer(s) to all get the needed parameters, computation is performed followed by releasing/emptying the parameter shards of other workers. This continues for all the FSDP modules. The loss gets computed after the forward pass and during the backward pass, again an all-gather operation is performed to get all the needed parameters for a given FSDP module, computation is performed to get local gradients followed by releasing the shards of other workers. Now, the local gradients are averaged and sharded to each relevant workers using reduce-scatter operation. This allows each worker to update the parameters of its local shard. If CPU offload is activated, the gradients are passed to CPU for updating parameters directly on CPU.

Please refer [7, 8, 9] for all the in-depth details on the workings of the PyTorch FSDP and the extensive experimentation carried out using this feature.

Issues

If you encounter any issues with the integration part of PyTorch FSDP, please open an Issue in accelerate.

But if you have problems with PyTorch FSDP configuration, and deployment - you need to ask the experts in their domains, therefore, please, open a PyTorch Issue instead.

References

[1] Train Large, Then Compress: Rethinking Model Size for Efficient Training and Inference of Transformers

[2] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models

[3] DeepSpeed: Extreme-scale model training for everyone - Microsoft Research

[4] Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism

[5] Introducing GPipe, an Open Source Library for Efficiently Training Large-scale Neural Network Models

[6] Which hardware do you need to train a 176B parameters model?

[7] Introducing PyTorch Fully Sharded Data Parallel (FSDP) API | PyTorch

[8] Getting Started with Fully Sharded Data Parallel(FSDP) — PyTorch Tutorials 1.11.0+cu102 documentation

[9] Training a 1 Trillion Parameter Model With PyTorch Fully Sharded Data Parallel on AWS | by PyTorch | PyTorch | Mar, 2022 | Medium

[10] Fit More and Train Faster With ZeRO via DeepSpeed and FairScale