Learn this hands-on: covered in Week 6: Deep learning with PyTorch of our 12-week AI and Machine Learning course, with live labs and a trainer to help. See the full syllabus →

What uses GPU memory
| Item | Grows with |
|---|---|
| Model weights | Number of parameters x bytes per parameter |
| Gradients | Same size as trainable weights |
| Optimizer state (Adam) | About 2x the trainable weights |
| Activations | Batch size x sequence length / image size x layers |
| Fragmentation and cache | Many differently sized allocations |
Fix it step by step
- Halve the batch size until it fits; keep the effective batch with gradient accumulation (e.g. batch 8 x 4 steps = 32).
- Turn on mixed precision:
torch.autocast("cuda", dtype=torch.bfloat16)(or fp16 with a GradScaler on older GPUs). - For inference, wrap code in
torch.no_grad()(ortorch.inference_mode()) so no activations are stored for backprop. - Do not accumulate tensors with graphs: log
loss.item(), notloss. - Enable gradient checkpointing for big models (
model.gradient_checkpointing_enable()in Hugging Face). - Fine-tune with LoRA or QLoRA (4-bit quantised base model) instead of full fine-tuning.
- Shorten sequence length or image resolution if the task allows.
- Still not enough: use a bigger GPU, or shard the model across GPUs (FSDP, DeepSpeed ZeRO).
Check memory while you work
import torch
print(torch.cuda.memory_allocated() / 1e9, "GB allocated")
print(torch.cuda.max_memory_allocated() / 1e9, "GB peak")
print(torch.cuda.memory_summary(abbreviated=True))
# in a terminal: nvidia-smi If memory keeps rising across steps, something is being kept alive. If the error mentions fragmentation, setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True can help.
In notebooks
Jupyter keeps variables alive between cells. After an OOM, delete large objects (del model, optimizer), run gc.collect() and torch.cuda.empty_cache(), or simply restart the kernel. empty_cache() does not free memory still referenced by Python variables.
Questions
Does torch.cuda.empty_cache() fix out of memory?
Rarely. It only returns cached, unused memory to the driver. You must first delete references to the tensors themselves.
How much GPU memory do I need to fine-tune a 7B model?
Full fine-tuning needs well over 80 GB. QLoRA can fine-tune a 7B model on a single GPU with roughly 16-24 GB, depending on sequence length and settings.