torch.cuda.is_available() + .to('cuda')tf.config.list_physical_devices('GPU')DataParallel 时主卡瓶颈(尽量用 DistributedDataParallel)torch.backends.cudnn.benchmark = Trueloss = loss / accumulation_steps
loss.backward()
if step % accumulation_steps == 0:
optimizer.step()
optimizer.zero_grad()使用 FP16 / AMP(自动混合精度)
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
with autocast():
output = model(x)
loss = criterion(output, y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()✅ 优点:
MobileNetV3、EfficientNet-B0/B1DeiT-Tiny、MobileViTfor p in backbone.parameters():
p.requires_grad = FalseDataLoader(
dataset,
batch_size=32,
num_workers=4, # 一般 2~8
pin_memory=True, # 加速 CPU→GPU
prefetch_factor=2
)num_workers=4~8@torch.no_grad()
def infer(model, x):
with torch.cuda.amp.autocast():
return model(x)DistributedDataParallel > DataParallelwatch -n 1 nvidia-smi✅ 立竿见影(推荐先做)
✅ 中期优化
✅ 高阶
| 任务 | 建议 |
|---|---|
| 图像分类 | CNN + AMP + 大 batch |
| 目标检测 | 减小输入尺寸 + AMP |
| NLP | FP16 + 梯度累积 |
| 微调大模型 | LoRA + 冻结 backbone |
如果你愿意,可以告诉我:
我可以直接给你 一份针对 RTX 1080 Ti 的优化配置模板。