TechBuzzPro

How to Cut GPU Memory Use and Stop AI Out of Memory Errors

· 5 min read · Windows & PC

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You can cut GPU memory use and stop out-of-memory (OOM) errors by reducing the memory your model and data occupy, using more efficient precision, and controlling batch sizes and caching. The exact steps depend on your framework, but the core levers are the same: use smaller data types (fp16 or bf16 instead of fp32), shrink batch sizes, enable gradient checkpointing or memory-efficient attention, offload parts of the model to CPU or disk, and clear unused memory between runs. Before you start, confirm your GPU model and available VRAM (for example with nvidia-smi on NVIDIA or Activity Monitor on macOS), and note which framework you are using (PyTorch, TensorFlow, etc.) because the settings differ.

What You'll Need

  • Access to your training or inference script and the ability to edit it.
  • Knowledge of your GPU's total VRAM and current usage (use nvidia-smi for NVIDIA, rocm-smi for AMD, or the framework's own memory summary).
  • The framework's documentation for memory-saving features (PyTorch, TensorFlow, JAX, etc.).
  • Optional: a CPU with enough RAM if you plan to offload tensors, and disk space if you use memory-mapped files.

Step-by-Step

  1. Measure current memory use. Run a small version of your workload and log peak GPU memory. In PyTorch, torch.cuda.max_memory_allocated() gives the peak; torch.cuda.memory_summary() shows a breakdown. This baseline tells you how much you need to cut.
  2. Reduce batch size. Halve your batch size and see if the OOM disappears. If it does, you have found the simplest fix. You can later use gradient accumulation to keep the effective batch size for training.
  3. Switch to lower precision. Use fp16 or bf16 instead of fp32 where supported. In PyTorch, wrap training in torch.cuda.amp.autocast() and use a gradient scaler for fp16. For inference, load the model with .half() if the model supports it. bf16 is often more stable on newer GPUs.
  4. Enable memory-efficient attention or checkpointing. For transformer models, use built-in options such as torch.utils.checkpoint (gradient checkpointing) or framework-specific efficient attention (e.g., attn_implementation="flash_attention_2" in Hugging Face Transformers when available). These trade compute for memory.
  5. Free unused memory. Delete tensors you no longer need and call torch.cuda.empty_cache() (PyTorch) or the equivalent in your framework. Avoid holding references to large intermediate outputs. In notebooks, restart the kernel between experiments.
  6. Offload to CPU or disk. Use framework features like accelerate (Hugging Face) with device_map="auto" and offload_folder to move parts of a large model to CPU RAM or disk. This slows things down but can make a model fit.
  7. Use memory-mapped data loading. For large datasets, load batches lazily with DataLoader and avoid loading the entire dataset into GPU memory. Keep preprocessing on CPU and transfer only the current batch.
  8. Limit concurrent processes. Ensure no other process (another notebook, a game, a browser with GPU acceleration) is using the GPU. On shared servers, check with nvidia-smi and coordinate with other users.
  9. Consider smaller models or quantization. If you still OOM, use a smaller model variant or 8-bit/4-bit quantization (e.g., bitsandbytes in Hugging Face). Quantization reduces memory at some cost to quality.
  10. Re-measure and iterate. After each change, log peak memory again. Stop when you are comfortably under your VRAM limit (leave 10–20% headroom for fragmentation and overhead).

Common Mistakes

  • Only reducing batch size but leaving fp32 precision on; switching to fp16/bf16 often saves more memory with less impact on throughput.
  • Forgetting that empty_cache() does not free memory held by live tensors; you must delete references first.
  • Using gradient checkpointing without adjusting the model's use_cache setting (for transformers, set use_cache=False during training).
  • Ignoring memory fragmentation: repeated allocation of different sizes can waste VRAM. Restarting the process or using PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (where supported) can help.
  • Assuming offloading is free; it uses CPU RAM and PCIe bandwidth, so it can be very slow.

Tips

  • Start with the cheapest change (batch size) and work up to more invasive ones (quantization, offloading).
  • Use mixed precision training by default on modern GPUs; it is well supported and usually stable with a gradient scaler.
  • Profile memory by layer if you can; some frameworks offer memory profiling tools that show which operations peak.
  • Keep an eye on VRAM during long runs; memory can creep up due to leaks or caching. Log peak memory periodically.
  • If you are on a laptop with a shared GPU, close other GPU-using apps before running your job.

Troubleshooting

If you still get OOM errors after trying the steps above, work through these checks in order:

  • Confirm the error is really GPU OOM. Some frameworks report OOM when system RAM is exhausted. Check both GPU and CPU memory.
  • Restart the process. A fresh process clears fragmented memory. In notebooks, restart the kernel.
  • Check for hidden allocations. Some libraries allocate memory on import or during model loading. Load the model, then measure, before running data through it.
  • Reduce sequence length or image resolution. For transformers, shorter sequences use less memory; for vision models, smaller input sizes help.
  • Try a smaller model or a distilled variant. If nothing else works, the model may simply be too large for your GPU.
  • Use CPU offloading more aggressively. If your framework supports it, offload more layers or use disk offload, accepting the speed penalty.
  • Update your framework and GPU drivers. Memory management improves over time; ensure you are on a recent stable version.

Frequently Asked Questions

Why do I get out-of-memory errors even when my GPU has free memory?

Memory can be fragmented, or other processes may be using it. Check with nvidia-smi and restart your process. Also ensure you are measuring allocated memory, not just reserved memory.

Does reducing batch size always fix OOM?

Not always. If the model itself plus a single sample does not fit, you need other methods such as lower precision, offloading, or a smaller model.

Is fp16 always safe?

fp16 can cause numerical instability in some models. bf16 is often more stable if your GPU supports it. Use a gradient scaler with fp16 during training.

Can I use multiple GPUs to avoid OOM?

Yes, model parallelism or data parallelism can help, but it requires code changes and multiple GPUs. For a single GPU, the steps above are the main options.

What is gradient checkpointing?

It trades compute for memory by recomputing activations during the backward pass instead of storing them. It can significantly reduce memory at the cost of slower training.

Does clearing the cache with torch.cuda.empty_cache() always help?

It only frees memory that is no longer referenced. If tensors are still alive, it will not help. Delete references first.