Transformers documentation
DeepSpeed ZeRO
DeepSpeed ZeRO
DeepSpeed ZeRO(Zero Redundancy Optimizer,零冗余优化器)通过将优化器状态、梯度和参数分片到各个 GPU 上,消除了分布式训练中的内存冗余。ZeRO 分为三个阶段,每个阶段比上一阶段分片更多的状态。DeepSpeed 还支持将数据卸载到 CPU 或 NVMe 内存以进一步节省空间。每增加一个阶段或卸载级别,峰值内存都会降低,但代价是 GPU 间的通信量增加。
params grads opt states
┌──────────┐ ┌──────────┐ ┌──────────┐
ZeRO-1 │██████████│ │██████████│ │███░░░░░░░│ GPU 0
│██████████│ │██████████│ │░░░███░░░░│ GPU 1
│██████████│ │██████████│ │░░░░░░████│ GPU 2
└──────────┘ └──────────┘ └──────────┘
┌──────────┐ ┌──────────┐ ┌──────────┐
ZeRO-2 │██████████│ │███░░░░░░░│ │███░░░░░░░│ GPU 0
│██████████│ │░░░███░░░░│ │░░░███░░░░│ GPU 1
│██████████│ │░░░░░░████│ │░░░░░░████│ GPU 2
└──────────┘ └──────────┘ └──────────┘
┌──────────┐ ┌──────────┐ ┌──────────┐
ZeRO-3 │███░░░░░░░│ │███░░░░░░░│ │███░░░░░░░│ GPU 0
│░░░███░░░░│ │░░░███░░░░│ │░░░███░░░░│ GPU 1
│░░░░░░████│ │░░░░░░████│ │░░░░░░████│ GPU 2
└──────────┘ └──────────┘ └──────────┘
█ resident ░ held on another GPUZeRO-2 对梯度和优化器状态进行分片,其通信开销低于 ZeRO-3。仅当使用 ZeRO-2 时模型无法在多个 GPU 上容纳时,才使用 ZeRO-3。
安装
从 PyPI 安装 DeepSpeed,或者使用 deepspeed 附加组件安装 Transformers。
pip install deepspeed pip install transformers[deepspeed]
如果遇到与 CUDA 相关的安装错误,请查阅 DeepSpeed CUDA 文档。从源代码安装 是更可靠的选择,因为它与您的具体硬件相匹配,并且包含 PyPI 发布版本中尚未提供的功能。
配置
Trainer 通过 deepspeed 参数集成 DeepSpeed,该参数接受一个 JSON 配置文件。或者,使用 Accelerate 配置文件 来替代 TrainingArguments。
在配置中使用 "auto" 表示希望由 DeepSpeed 从 TrainingArguments 中自动填充的值。如果您想显式指定某个值,请确保 DeepSpeed 参数和 TrainingArguments 使用相同的值。
有关 DeepSpeed 配置选项的完整列表,请参阅 DeepSpeed Configuration JSON 参考文档。
{
"train_micro_batch_size_per_gpu": "auto",
"gradient_accumulation_steps": "auto",
"optimizer": {
"type": "AdamW",
"params": { "lr": "auto" }
},
"fp16": { "enabled": "auto" }
}| DeepSpeed 配置 | TrainingArguments |
|---|---|
train_micro_batch_size_per_gpu | per_device_train_batch_size |
gradient_accumulation_steps | gradient_accumulation_steps |
optimizer.params.lr | learning_rate |
fp16.enabled | fp16 |
将 config 传递给 deepspeed 参数。
from transformers import TrainingArguments
args = TrainingArguments(
deepspeed="path/to/deepspeed_config.json",
...
)# DeepSpeed launcher
deepspeed --num_gpus 4 train.py
# torchrun
torchrun --nproc_per_node 4 train.py
# Accelerate
accelerate launch --num_processes 4 train.pyAccelerate 会忽略 TrainingArguments 中的
deepspeed参数。
运行 accelerate config 命令,并根据你的硬件和训练配置回答相关问题,以在缓存中创建 default_config.yaml 文件。
distributed_type: DEEPSPEED
deepspeed_config:
deepspeed_config_file: path/to/ds_config.json
machine_rank: 0
num_machines: 1
num_processes: 4使用基于 Trainer 的脚本运行 accelerate launch。
accelerate launch --config_file deepspeed_config.yaml train.py
ZeRO 阶段
选择一个 ZeRO 阶段配置作为起点。
{
"bf16": { "enabled": "auto" },
"zero_optimization": { "stage": 1 },
"gradient_clipping": "auto",
"train_micro_batch_size_per_gpu": "auto",
"train_batch_size": "auto",
"gradient_accumulation_steps": "auto"
}{
"bf16": { "enabled": "auto" },
"zero_optimization": {
"stage": 2,
"overlap_comm": true,
"allgather_bucket_size": 2e8,
"reduce_bucket_size": 2e8,
"contiguous_gradients": true
},
"gradient_clipping": "auto",
"train_micro_batch_size_per_gpu": "auto",
"train_batch_size": "auto",
"gradient_accumulation_steps": "auto"
}ZeRO-3 在初始化阶段对参数进行分片。您必须在加载模型之前实例化 TrainingArguments——如果模型在配置 DeepSpeed 之前已经加载到每个 GPU 上,则不会节省任何内存。
{
"bf16": { "enabled": "auto" },
"zero_optimization": {
"stage": 3,
"overlap_comm": true,
"contiguous_gradients": true,
"reduce_bucket_size": "auto",
"stage3_prefetch_bucket_size": "auto",
"stage3_param_persistence_threshold": "auto",
"stage3_gather_16bit_weights_on_model_save": true,
"offload_optimizer": { "device": "cpu", "pin_memory": true },
"offload_param": { "device": "cpu", "pin_memory": true }
},
"gradient_clipping": "auto",
"train_micro_batch_size_per_gpu": "auto",
"train_batch_size": "auto",
"gradient_accumulation_steps": "auto"
}以下字段对于自定义训练非常重要。
zero_optimization用于设置 ZeRO 阶段。{ "zero_optimization": { "stage": 3 } }将批大小和梯度累积参数设置为
"auto"。如果手动将这些参数设置为与 TrainingArguments 不一致的值,训练将静默地以错误的值继续进行。{ "train_micro_batch_size_per_gpu": "auto", "train_batch_size": "auto", "gradient_accumulation_steps": "auto", "gradient_clipping": "auto" }bf16用于设置训练精度。将其设置为"auto",使其与 TrainingArguments 中的bf16标志保持一致。{ "bf16": { "enabled": "auto" } }stage3_gather_16bit_weights_on_model_save在保存之前会在所有 GPU 之间执行 all-gather,从分片中重建完整的张量。这是一个 ZeRO-3 参数。{ "zero_optimization": { "stage": 3, "stage3_gather_16bit_weights_on_model_save": true } }将
overlap_comm设置为true,可将 all-reduce 的延迟隐藏在反向传播过程中。allgather_bucket_size和reduce_bucket_size在通信速度与 GPU 显存之间进行权衡。较小的值会占用更少的显存,但会降低通信速度。{ "zero_optimization": { "stage": 2, "overlap_comm": true, "allgather_bucket_size": 2e8, "reduce_bucket_size": 2e8, "contiguous_gradients": true } }offload_optimizer将优化器卸载到 CPU 内存。为了进一步节省内存,还可以使用offload_param卸载模型参数(仅限 ZeRO-3)。将pin_memory设置为true可以加快 CPU 与 GPU 之间的数据传输速度,但这会锁定 RAM,使其无法被其他进程使用。{ "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true } } }optimizer和scheduler的默认值分别为 TrainingArguments 中配置的优化器和调度器。将其设置为"auto",以便 DeepSpeed 从 TrainingArguments 中读取这些值,除非您需要使用 LAMB 等 DeepSpeed 原生优化器。{ "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupDecayLR", "params": { "total_num_steps": "auto", "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } } }如果正在卸载优化器,请将
zero_force_ds_cpu_optimizer设置为false,以使用 DeepSpeed 的 CPU Adam 优化器。{ "zero_force_ds_cpu_optimizer": false }
检查点
DeepSpeed 以分片格式保存检查点,无法直接使用 from_pretrained() 加载。将 load_best_model_at_end() 设置为 True,以便 Trainer 在训练结束时跟踪并重新加载最佳检查点。
from transformers import TrainingArguments, Trainer
args = TrainingArguments(
deepspeed="ds_config_zero3.json",
load_best_model_at_end=True,
...
)
# after training, save a normal transformers checkpoint
trainer.save_model("./best-model")设置 save_only_model=True 会跳过保存完整的优化器状态,这意味着你无法在训练结束时重新加载最佳模型。同时,请设置 stage3_gather_16bit_weights_on_model_save: true,以便从分片中重建完整权重。在 ZeRO-3 中,保存合并后的 16 位模型工件或 16 位状态字典需要此设置。当 save_only_model=True 与 load_best_model_at_end=True 同时使用时,Transformers 会抛出错误。
有关在不同并行配置之间恢复训练,请参阅 DeepSpeed 的 Universal Checkpointing 指南。
后续步骤
- 阅读《The Ultra-Scale Playbook》中的 Zero Redundancy Optimizer 章节,以了解 ZeRO 的工作原理。
- 阅读 ZeRO 论文:Memory Optimizations Toward Training Trillion Parameter Models、Democratizing Billion-Scale Model Training 和 Breaking the GPU Memory Wall for Extreme Scale Deep Learning。