Fix CUDA Out of Memory Errors When Fine-Tuning LLMs
In this article
Fine-tuning a large language model (LLM) on a GPU is a memory-hungry process. The dreaded CUDA out of memory error halts training mid-epoch, wasting time and often forcing you to restart. This guide walks you through practical, step-by-step fixes—from simple code tweaks to hardware-aware strategies—so you can train within your GPU's limits and keep your fine-tuning runs stable.
What You'll Need
- A working PyTorch (or TensorFlow) environment with CUDA installed.
- Access to the training script you're using (Hugging Face Transformers, custom PyTorch, etc.).
- Basic familiarity with command-line tools and Python.
- Optional:
nvidia-smito monitor GPU memory usage.
Step-by-Step
- Confirm the error is truly OOM, not a driver issue. Run
nvidia-smito see GPU memory usage. If the GPU is already full from other processes, kill them or choose another GPU. If memory is free but you still get OOM, proceed. - Reduce the batch size. The most direct fix: lower
per_device_train_batch_size(in Hugging Face) orbatch_size(in PyTorch). Halve it and retry. If it still fails, halve again. This reduces the memory footprint of activations and gradients. - Enable gradient accumulation. To keep an effective batch size while using a small physical batch, set
gradient_accumulation_stepsto 2, 4, or 8. For example, with physical batch size 4 and accumulation steps 8, the effective batch size is 32. This trades memory for training time but stabilizes runs. - Use mixed precision (fp16/bf16). Enable
fp16=Truein Hugging FaceTrainingArguments, or in PyTorch usetorch.cuda.ampwith GradScaler. This halves memory usage for activations and gradients. On Ampere+ GPUs,bf16is even more stable. - Enable gradient checkpointing. Set
gradient_checkpointing=Truein TrainingArguments, or callmodel.gradient_checkpointing_enable(). This recomputes activations during backward pass instead of storing them, drastically reducing memory at the cost of ~20% slower training. - Use LoRA or QLoRA for parameter-efficient fine-tuning. Instead of updating all model weights, use
peftlibrary to add low-rank adapters. This reduces optimizer states and gradients to a tiny fraction. QLoRA (4-bit quantization) can fine-tune a 7B model on a single 24GB GPU. - Free memory before training. Clear PyTorch cache with
torch.cuda.empty_cache()and delete unused variables (e.g.,del model,gc.collect()). Also, avoid keeping validation dataloaders in memory. - Reduce sequence length. If your task allows, truncate input sequences to a shorter maximum length (e.g., 512 instead of 1024). Memory scales quadratically with sequence length for attention, so this has a huge impact.
- Use a smaller model or a more memory-efficient architecture. If all else fails, switch to a smaller variant (e.g., from 7B to 3B) or a model with FlashAttention (if supported) to reduce memory.
- Consider offloading to CPU. In PyTorch, use
device_map="auto"withaccelerateto offload some layers to CPU. This is slow but allows training on a single GPU with limited memory.
Common Mistakes
- Ignoring evaluation memory. The OOM can happen during evaluation, not training. Reduce eval batch size or set
eval_accumulation_steps. - Forgetting to set
torch.cuda.empty_cache()between runs. Memory fragmentation can persist; clearing cache before each run helps. - Using too large a gradient accumulation step. While it reduces memory, it increases training time. Balance it with batch size.
- Not updating
learning_ratewhen changing batch size. If you reduce batch size, you may need to adjust the learning rate (e.g., linear scaling) to maintain convergence. - Assuming fp16 is always safe. Some models have numerical instability; use bf16 on Ampere+ GPUs or add loss scaling.
Tips
- Monitor memory with
nvidia-smi -l 1during training to see spikes and peaks. - Use
torch.cuda.max_memory_allocated()to log peak memory usage and compare after each change. - Set
optimizer="adamw_torch"or use 8-bit optimizers frombitsandbytesto save memory. - For Hugging Face, set
gradient_checkpointing_kwargs={"use_reentrant": False}to avoid warnings. - If using QLoRA, ensure you have
bitsandbytesinstalled and setload_in_4bit=Truein the model config.
Troubleshooting
- Error persists after reducing batch size to 1. Then the issue is likely model size or sequence length. Try gradient checkpointing and mixed precision. If still OOM, you may need to offload to CPU or use a smaller model.
- Training is very slow after enabling checkpointing. That's expected; it's a trade-off. Consider using a larger batch size with checkpointing to compensate.
- Mixed precision causes NaN loss. Switch from fp16 to bf16 (if supported) or disable mixed precision. Also check for inf in inputs.
- OOM occurs only at certain steps (e.g., during validation). Reduce eval batch size or set
eval_accumulation_stepsto a higher value. - Multiple GPUs? Use
accelerateorDistributedDataParallelto split memory across GPUs. But note that each GPU still needs enough memory for the model copy.
Frequently Asked Questions
What is the difference between OOM and CUDA OOM?
OOM (Out of Memory) can be system RAM; CUDA OOM specifically means GPU memory is exhausted. The fixes here target GPU memory.
Can I fine-tune a 7B model on a 8GB GPU?
Yes, with QLoRA and gradient checkpointing, it's possible, but slow. You'll need to use 4-bit quantization and a small batch size (1-2).
Why does my memory usage increase over time?
This could be due to caching or memory fragmentation. Clear cache periodically and avoid storing unnecessary tensors. Also, check for data leaks in your dataset.
Does reducing sequence length always help?
Yes, because attention memory scales quadratically with sequence length. Even a small reduction (e.g., from 1024 to 512) can free significant memory.
Is it better to use a smaller batch size or gradient accumulation?
Gradient accumulation is better for stability, but it increases training time. Use a small batch size with accumulation steps to keep effective batch size reasonable.
Can I use CPU offloading to avoid OOM completely?
Yes, but training will be very slow. It's a last resort. Use it only if you have no other options.