The memory toolbox
Mixed precision (bf16/fp16)
Training in 16-bit instead of 32-bit halves memory and speeds up training on modern GPUs.
bf16 vs fp16: bf16 has the same range as fp32 (just less precision), making it more numerically stable. Always prefer bf16 if your hardware supports it (Ampere+ : A100, RTX 3090+).
Gradient checkpointing
Trades compute for memory — recomputes activations during backward pass instead of storing them. Reduces VRAM by 30–50% at the cost of ~20% slower training.
Flash Attention 2
A faster, more memory-efficient attention implementation. Reduces attention memory from O(n²) to O(n) and significantly speeds up training.
Memory checklist (in order of impact)
- Use QLoRA (4-bit) — biggest single win for large models.
- Enable gradient checkpointing.
- Use bf16 (not fp32 or fp16 if avoidable).
- Enable Flash Attention 2.
- Reduce per_device batch and increase gradient accumulation.
- Reduce max_seq_length.