Cut GPU Memory Use and Prevent AI Out of Memory Errors
In this article
To cut GPU memory use and prevent out-of-memory errors, start by reducing the batch size and sequence length, then enable mixed precision and gradient checkpointing, and finally offload or quantize parts of the model. These four changes alone resolve most OOM crashes without buying new hardware. The exact menu names below come from common tools like PyTorch, Hugging Face Transformers and CUDA; labels can differ slightly by version, framework or operating system, so treat them as signposts rather than exact strings.
What You'll Need
- Access to the training or inference script and its configuration file.
- A way to monitor GPU memory (nvidia-smi on Linux/Windows, Task Manager on Windows, or your framework's built-in memory profiler).
- Permission to change hyperparameters and, if needed, install official libraries such as bitsandbytes or DeepSpeed from their official sources.
- A baseline run that currently fails, so you can confirm each change actually helps.
Step-by-Step
- Measure before you change anything. Run the job and watch memory with
nvidia-smi -l 1in a separate terminal, or usetorch.cuda.memory_summary()after a forward pass. Note the peak allocation and where it occurs (model load, forward pass, backward pass, optimizer step). Without a baseline you cannot tell which fix worked. - Reduce batch size first. Halve it and rerun. Batch size scales activation memory almost linearly, so this is the fastest lever. If the job now runs, keep the smaller batch and compensate with gradient accumulation (for example, batch 4 with accumulation 4 mimics batch 16) so training quality stays similar.
- Shorten sequence length. For language models, memory grows with sequence length squared in attention layers. Cutting max length from 2048 to 1024 can roughly quarter attention memory. If your task needs long context, consider sliding-window attention or chunking the input instead of a single long sequence.
- Enable mixed precision. In PyTorch, wrap the forward pass in
torch.autocastand use a gradient scaler for FP16, or use BF16 if your GPU supports it. In Hugging Face Trainer, setfp16=Trueorbf16=True. This typically cuts activation memory by 30–50% with minimal accuracy loss. - Turn on gradient checkpointing. In Transformers, call
model.gradient_checkpointing_enable(). This trades roughly 20–30% more compute time for a large drop in stored activations. It is the single biggest win for fine-tuning large models on small GPUs. - Free memory you are not using. Delete intermediate tensors, avoid keeping references to past outputs, call
torch.cuda.empty_cache()between phases, and set unused models toNone. In notebooks, restart the kernel between runs; stale variables are a common hidden cause of OOM. - Use 8-bit or 4-bit optimizers and quantized loading. Libraries such as bitsandbytes provide 8-bit optimizers and quantized model loading (for example,
load_in_8bit=Truein Transformers). This reduces weight memory substantially, at some cost in speed and precision. Install only from the official package index. - Offload to CPU or disk. DeepSpeed ZeRO stages and Hugging Face's
device_map="auto"can move optimizer states or entire layers to CPU RAM. This is slower but lets a model that does not fit on the GPU still run. Check that your system RAM is large enough before enabling it. - Cap the memory PyTorch reserves. Set the environment variable
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True(ormax_split_size_mbfor older versions) before launching. This reduces fragmentation, which often causes OOM even when total free memory looks sufficient. - Re-measure and iterate. After each change, rerun the baseline and record peak memory. Stop when you have headroom of about 10–15%; running at the exact limit will still crash intermittently due to fragmentation and background processes.
Common Mistakes
- Changing five settings at once, then not knowing which one fixed or broke the run.
- Forgetting that the optimizer state (especially Adam) can use two to three times the model's weight memory; reducing batch size alone may not help if optimizer memory dominates.
- Leaving old tensors referenced in a notebook or debugger, so memory never actually frees.
- Assuming
torch.cuda.empty_cache()frees memory held by live tensors; it only returns unused cached blocks. - Running other GPU apps (browser hardware acceleration, games, other notebooks) on the same card.
- Using FP16 on hardware that handles it poorly; BF16 is often more stable where supported.
Tips
- Profile first with the framework's memory profiler; it shows exactly which operation allocates the most.
- Prefer gradient accumulation over large batches when memory is tight.
- Keep a small "smoke test" configuration that runs in under a minute, so you can validate changes quickly.
- Log peak memory alongside loss so regressions are visible immediately.
- If you regularly hit limits, consider a cloud GPU with more VRAM for the final run while developing on your local card.
Troubleshooting
If the error persists after the steps above, work through this order. First, confirm no other process is using the GPU: run nvidia-smi and check the process list. Second, restart the Python kernel or the whole machine to clear leaked memory. Third, lower batch size again, even to 1, to see whether the job runs at all; if it does, the problem is scale, not a bug. Fourth, check whether the model itself fits: compare parameter count times bytes per parameter against available VRAM. Fifth, try the smallest possible model or a distilled variant to isolate whether the issue is model size or your code. If you see "CUDA out of memory" during evaluation rather than training, disable gradient computation with torch.no_grad(); evaluation without it stores activations unnecessarily. If errors mention fragmentation, set the allocator configuration described above. Finally, update your GPU driver and framework to the latest official stable release; older versions sometimes handle memory less efficiently.
Frequently Asked Questions
Does reducing batch size hurt model quality?
Not if you compensate with gradient accumulation. A smaller batch with more accumulation steps approximates a larger batch, though very small batches can make batch normalization unstable.
Is gradient checkpointing always worth it?
It saves memory at the cost of extra compute. Use it when memory is the bottleneck; skip it when speed matters more and memory is sufficient.
Can I run a model larger than my GPU's VRAM?
Yes, with CPU offloading or quantized loading, but expect much slower performance. The model must still fit in combined GPU and system RAM.
Why does memory usage grow during training?
Usually because tensors are kept alive by references, caches are not cleared, or the optimizer state grows. Check for stored losses or outputs in lists.
Does mixed precision always reduce memory?
It reduces activation memory, but some layers still run in FP32. The savings vary by model and framework, so measure rather than assume.
What is the quickest single fix for an OOM error?
Halving the batch size. It is the fastest change to apply and usually gives immediate relief.