所以采用混合精度:
不管什么框架,思路都类似:
torch.cuda.amp(推荐)from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
optimizer.zero_grad()
with autocast():
outputs = model(inputs)
loss = criterion(outputs, labels)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()✅ 自动:
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = Truefrom tensorflow.keras.mixed_precision import set_global_policy
set_global_policy('mixed_float16')dtype='float32'training_args = TrainingArguments(
fp16=True,
# bf16=True, # A100 / 新 GPU
)| 类型 | 特点 |
|---|---|
| FP16 | 快,但易溢出 |
| BF16 | 动态范围大,更稳定(推荐新卡) |
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
...❌ 不加 Loss Scaling → 梯度为 0
❌ Embedding / Softmax 用 FP16 → 不稳定
✅ 大模型
✅ 显存不够
✅ 多卡训练
如果你愿意,我可以:
你现在是用的 PyTorch 还是 TF?GPU 是什么?