Fix CUDA Out of Memory: Cut AI Model VRAM Use
In this article
The fastest way to fix a CUDA out-of-memory (OOM) error is to reduce the batch size, lower the input resolution, or switch to a smaller model variant—these three changes cut VRAM usage immediately. Beyond that, you can enable gradient checkpointing, use mixed precision, offload tensors to CPU, or apply quantization to shrink the model's memory footprint.
Why CUDA Out of Memory Happens
CUDA OOM occurs when your GPU's VRAM cannot hold all the data needed for a single forward and backward pass. During training, the GPU stores model weights, optimizer states, activations, and gradients. Inference is lighter but still requires space for weights and intermediate tensors. When the sum exceeds available VRAM, PyTorch or TensorFlow raises an error, often after the first batch or mid-training.
Common triggers include a batch size that is too large, high-resolution inputs, long sequences in transformers, or running multiple models simultaneously. Even a model that fits during a quick test can OOM when you increase the data size or add evaluation steps.
Immediate Fixes to Try First
- Reduce batch size to 1 or 2. This is the simplest change and often resolves OOM instantly.
- Lower input resolution for images (e.g., from 512×512 to 256×256) or truncate text sequences.
- Use a smaller model variant—for example, switch from a 7B to a 1B parameter model.
- Clear GPU cache with
torch.cuda.empty_cache()before retrying, though this only frees unused memory. - Set
torch.cuda.set_per_process_memory_fraction(0.9)to reserve headroom, but this does not reduce actual usage.
These steps work for both training and inference. If OOM persists, move to the deeper techniques below.
Gradient Checkpointing and Mixed Precision
Gradient checkpointing (also called activation checkpointing) trades compute for memory. Instead of storing all activations for the backward pass, it recomputes them on the fly. This can cut activation memory by up to 60–70% for transformer models. In PyTorch, wrap your model with torch.utils.checkpoint.checkpoint or use the use_checkpointing=True flag in Hugging Face transformers.
Mixed precision training uses FP16 (half precision) instead of FP32 for most operations, halving memory usage for tensors. With PyTorch, use torch.cuda.amp.autocast() and GradScaler. On newer GPUs, BF16 is even more stable. This method also speeds up training. Note that some operations, like softmax, still run in FP32 for stability.
Quantization: Shrink the Model Weights
Quantization reduces the precision of model weights, e.g., from FP32 (4 bytes) to INT8 (1 byte) or even INT4. This cuts memory by 4× or 8×. For inference, you can load a pre-quantized model (like those on Hugging Face) or quantize a model yourself using tools like bitsandbytes or PyTorch's quantization module.
For example, loading a 7B parameter model in FP16 takes about 14 GB; in INT8, it takes about 7 GB; in INT4, about 3.5 GB. The trade-off is a slight accuracy drop, usually under 1–2% for most tasks. During training, quantization is harder to apply, but you can use quantization-aware training (QAT) if needed.
Offloading to CPU or Using Unified Memory
When VRAM is still insufficient, you can offload some tensors to system RAM. PyTorch's device_map="auto" (from Hugging Face accelerate) automatically splits the model across GPU and CPU. This slows down training or inference because CPU-GPU transfer is slow, but it allows running models that would otherwise not fit.
Alternatively, enable unified memory on systems with shared memory (e.g., Apple M-series or NVIDIA with CUDA's unified addressing). In PyTorch, use model.to('cuda') with torch.cuda.memory.set_per_process_memory_fraction(1.0) and let the system swap. This is not recommended for training because of performance hits, but it works for inference.
Choosing the Right Technique for Your Case
Your choice depends on whether you are training or doing inference. For inference, quantization is the most effective because it directly reduces model size. For training, gradient checkpointing and mixed precision are the first-line options because they preserve accuracy. If you need to train a large model on a single GPU, consider using offloading with accelerate, but expect slower iterations.
Also, check if your GPU supports the latest features. For example, NVIDIA GPUs with compute capability 7.0+ support mixed precision well. Older GPUs may not benefit from BF16. Always verify your CUDA version and PyTorch compatibility.
Common Problems and Misconceptions
Misconception: torch.cuda.empty_cache() fixes OOM. It only releases unused cached memory; it does not reduce the memory your model actually needs. It can help if you have fragmented memory, but it is not a real solution.
Problem: OOM occurs during evaluation. Even without gradients, the model still stores activations. Use torch.no_grad() and reduce batch size for evaluation.
Problem: OOM after a few batches. This often indicates a memory leak or that your batch size is just over the limit. Monitor memory with nvidia-smi to see the actual usage.
Frequently Asked Questions
What is the difference between CUDA OOM and system RAM OOM?
CUDA OOM means the GPU's VRAM is full, while system RAM OOM means your computer's main memory is full. They are separate resources. Offloading to CPU can help with VRAM but may cause system RAM OOM if you have little RAM.
Can I use multiple GPUs to fix OOM?
Yes, you can use model parallelism or data parallelism to split the model or batch across GPUs. Tools like Hugging Face accelerate make this easier. However, this requires multiple GPUs and may not be an option for everyone.
Will reducing batch size affect model accuracy?
Batch size affects training dynamics. Smaller batches can lead to noisier gradients, but often still converge well. For inference, batch size does not affect accuracy, only throughput.
Does quantization always reduce accuracy?
Not always. INT8 quantization typically has negligible accuracy loss for many tasks. INT4 may cause a noticeable drop, but you can fine-tune after quantization to recover accuracy.
How do I know how much VRAM my model needs?
You can estimate by multiplying the number of parameters by the bytes per parameter (e.g., 4 bytes for FP32, 2 for FP16, 1 for INT8). Add about 20% for activations and overhead. For a 1B model in FP16, that's roughly 2 GB plus activations.
Is there a way to avoid OOM without changing the model?
You can use memory-efficient attention (like FlashAttention) or reduce the sequence length. Also, try to free memory by deleting unused variables and calling gc.collect().