Transformers documentation

Accelerate

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Accelerate

Accelerate 为 FSDP 或 DeepSpeed 等分布式训练后端提供了统一接口。它会检测你的环境(GPU 数量、分布式后端、混合精度等),并自动配置训练,无论你是在 1 个 GPU 上使用 DDP,还是在 8 个 GPU 上使用 FSDP。

Accelerate 会将模型包装在合适的分布式包装器中,将其移动到正确的设备上,并创建一个兼容的优化器。在训练过程中,Accelerate 使用其自身的 backward 方法来处理混合精度下的梯度缩放。Trainer 会调用相应的 Accelerate API,并将所有分布式机制委托给 Accelerate。

使用 Accelerate 配置文件或 TrainingArguments 为 Trainer 配置 Accelerate。

Accelerate 配置文件

运行 accelerate config 命令,并回答有关您的硬件和训练配置的问题。这会在您的缓存中创建一个 default_config.yaml 文件。以下示例针对 FSDP。

compute_environment: LOCAL_MACHINE
distributed_type: FSDP
fsdp_config:
  fsdp_version: 2
  fsdp_reshard_after_forward: true
  fsdp_cpu_offload: false
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_cpu_ram_efficient_loading: true
  fsdp_activation_checkpointing: false
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_transformer_layer_cls_to_wrap: LlamaDecoderLayer
mixed_precision: bf16
num_machines: 1
num_processes: 4

运行 accelerate launch 并配合基于 Trainer 的脚本,Accelerate 会读取配置文件来设置训练。由于 Accelerate 配置文件已涵盖相同的设置,因此 fsdp_config 和 deepspeed 参数是多余的。

accelerate launch train.py

accelerator_config 接受那些没有专用顶级参数的设置。例如,将 non_blocking=True 与 dataloader_pin_memory() 一起使用,以重叠数据传输和计算,从而提高 GPU 吞吐量。

from transformers import TrainingArguments

TrainingArguments(
    ...,
    dataloader_pin_memory=True,
    accelerator_config={
        "non_blocking": True,
    },
)

TrainingArguments

将特定于后端的配置传递给 TrainingArguments。create_accelerator_and_postprocess() 方法会读取这些设置并配置训练。

FSDP
DeepSpeed
DDP

将 JSON 配置文件或字典传递给 ~TrainingArguments.fsdp_config。有关完整指南和配置参考,请参阅 FSDP。

from transformers import TrainingArguments

TrainingArguments(
    ...,
    fsdp=True,
    fsdp_config="path/to/fsdp.json",
)

后续步骤

  • 如果模型可以放入单个 GPU,请参阅 DDP 以进行数据并行训练。
  • 有关在 GPU 之间分片参数、梯度和优化器状态,请参阅 FSDP。
  • 有关 ZeRO 优化和卸载,请参阅 DeepSpeed。
Update on GitHub