混合精度训练(Mixed Precision Training)是一种通过同时使用 FP16(半精度)和 FP32(单精度)来加速训练、降低显存占用的技术,核心是利用 TensorCore(如 NVIDIA GPU)或专用硬件加速低精度计算。
优化器更新时使用 FP32 权重,前向/反向传播使用 FP16
torch.cuda.amp(自动混合精度)from torch.cuda.amp import autocast, GradScaler
import torch
scaler = GradScaler()for data, target in dataloader:
data, target = data.cuda(), target.cuda()
optimizer.zero_grad()
# 前向传播使用 autocast
with autocast():
output = model(data)
loss = criterion(output, target)
# 缩放 loss 并反向传播
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()| 参数 | 说明 |
|---|---|
autocast() | 自动选择 FP16 / FP32 |
GradScaler() | 防止梯度下溢 |
scaler.scale() | 放大 loss |
scaler.step() | 优化器更新 |
scaler.update() | 动态调整 scale |
model = torch.nn.parallel.DistributedDataParallel(model)torch.cuda.amp 与 DDP 完全兼容from tensorflow.keras.mixed_precision import set_global_policy
set_global_policy("mixed_float16")model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dense(10, dtype="float32") # 输出层建议 FP32
]){
"fp16": {
"enabled": true
}
}或 BF16:
{
"bf16": {
"enabled": true
}
}args = TrainingArguments(
fp16=True
)或:
args = TrainingArguments(
bf16=True
)| 类型 | 优点 | 缺点 | 适用 |
|---|---|---|---|
| FP16 | 快、省显存 | 易溢出 | NVIDIA GPU(TensorCore) |
| BF16 | 稳定、范围大 | 稍慢 | A100 / TPU / 大模型 |
autocast 已自动处理GradScalerautocast(enabled=False)print(torch.cuda.get_device_properties(0))
# 看是否使用了 TensorCore(FP16)或:
nvidia-smi
# 显存占用是否明显下降✅ 推荐:
❌ 不推荐:
如果你愿意,可以告诉我:
我可以直接给你完整可用的训练脚本配置。