Transformers documentation
用于训练的 torch.compile
快速入门
基类
模型
预处理器
推理
Pipeline API
生成 API
优化
与模型对话
服务
训练
硬件
量化
生态系统集成
资源
API
You are viewing main version, which requires installation from source. If you'd like
regular pip install, checkout the latest stable version (v5.22.2).
用于训练的 torch.compile
torch.compile 将 PyTorch 代码编译为融合内核,以提升运行速度。在训练过程中,它会同时追踪前向和反向传播,并将其编译为优化后的内核,从而降低单个算子启动的开销,并通过融合操作来减少内存带宽的占用。
在 TrainingArguments 中设置 torch_compile=True 即可启用该功能。与推理仅编译前向传播不同,训练会同时编译前向和反向传播。编译发生在第一个训练步骤,因此该步骤的速度会明显慢于后续步骤。
from transformers import TrainingArguments
args = TrainingArguments(
...,
torch_compile=True,
torch_compile_backend="inductor",
torch_compile_mode="reduce-overhead",
)后端
在未指定后端时,TrainingArguments 会根据您的硬件自动选择一个。在大多数 CPU 和 GPU 上,默认值为 inductor,它通过 AOTAutograd 编译为 Triton 内核,适用于大多数训练任务。在 Intel Gaudi (HPU) 上,默认值为 hpu_backend。在 AWS Trainium 和 Inferentia (Neuron) 上,默认值为 neuron。
对于固定形状的输入,请使用 cudagraphs。
编译模式
使用下表来帮助您选择 torch.compile 模式。
| mode | 描述 |
|---|---|
| default | 平衡编译时间与运行时间 |
| reduce-overhead | 通过使用 CUDA 图来减少 Python/CPU 开销,但会额外占用一些内存 |
| max-autotune | 在编译时基准测试多个内核实现并选择最快的一个(编译时间更长) |
| max-autotune-no-cudagraphs | 与 max-autotune 相同,但不使用 CUDA graphs |
后续步骤
- 有关 fullgraph 编译和推理基准测试的详细信息,请参阅 torch.compile for inference 指南。