from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
with autocast():
output = model(input)torch.quantizationloss = loss / accumulation_steps
loss.backward()
if step % accumulation_steps == 0:
optimizer.step()
optimizer.zero_grad()model.gradient_checkpointing_enable()for param in model.base_model.parameters():
param.requires_grad = Falsedel tensor
torch.cuda.empty_cache().cuda() 拷贝pin_memory=True + DataLoaderexport PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128with torch.no_grad():
output = model(input)model.eval()
traced = torch.jit.trace(model, example_input)| 方法 | 说明 |
|---|---|
| QLoRA | 4-bit 量化 + LoRA |
| Paged Optimizer | 减少优化器显存 |
| Flash Attention | 降低 attention 显存 |
| Offloading | CPU / NVMe 卸载参数 |
torch.cuda.memory_summary()
torch.cuda.max_memory_allocated()✅ 训练:FP16 + Gradient Checkpointing + Gradient Accumulation
✅ 微调大模型:QLoRA + DeepSpeed ZeRO-2
✅ 推理:
FP16 + TensorRT / ONNX + no_grad如果你愿意,可以告诉我:
我可以给你更具体、可落地的方案。