Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

GPU Out of Memory Errors: AI Workload Troubleshooting

· 5 min read · Home Tech

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

GPU out-of-memory (OOM) errors in AI workloads happen when a model, batch, or tensor exceeds the available VRAM on your graphics card. This guide walks you through systematic steps to diagnose the cause, reduce memory usage, and prevent recurrences. You’ll need access to your training or inference script, the ability to modify code, and basic familiarity with your deep learning framework (PyTorch, TensorFlow, or similar).

What You'll Need

  • Access to the AI workload code (training or inference script)
  • Command-line terminal with GPU monitoring tools (e.g., nvidia-smi)
  • Knowledge of your framework's memory management APIs (e.g., torch.cuda, tf.config)
  • Optional: a debugger or profiler like PyTorch's torch.profiler or TensorBoard

Step-by-Step

  1. Confirm the error and identify the GPU. Run your workload and note the exact error message. It often includes the GPU index (e.g., 'CUDA out of memory. Tried to allocate 2.00 GiB (GPU 0; 8.00 GiB total capacity)'). Use nvidia-smi to check which GPU is being used and its current memory usage.
  2. Check for other processes using the GPU. Run nvidia-smi again and look at the 'Processes' section. If another process (like a previous training run or a GUI) is using memory, kill it or set CUDA_VISIBLE_DEVICES to a free GPU. For example: CUDA_VISIBLE_DEVICES=1 python train.py.
  3. Reduce the batch size. The most common fix is to lower the batch size. Halve it (e.g., from 32 to 16) and rerun. If it still OOMs, halve again. This directly reduces the memory needed for activations and gradients.
  4. Lower input resolution or sequence length. For vision models, resize images to a smaller dimension (e.g., 224x224 instead of 512x512). For NLP models, truncate sequences to a shorter maximum length (e.g., 128 tokens instead of 512). This reduces memory for input tensors and intermediate computations.
  5. Use gradient accumulation. If a smaller batch size hurts convergence, keep the effective batch size by accumulating gradients over several steps. In PyTorch, set optimizer.zero_grad() every N steps and call loss.backward() each step, but only step the optimizer after N steps. This trades memory for time.
  6. Enable mixed precision training. Use automatic mixed precision (AMP) to store tensors in float16 where safe. In PyTorch, use torch.cuda.amp.autocast() and GradScaler. In TensorFlow, use tf.keras.mixed_precision.set_global_policy('mixed_float16'). This can cut memory usage by nearly half.
  7. Free memory in code. Delete large tensors when no longer needed using del tensor and call torch.cuda.empty_cache() (or tf.keras.backend.clear_session()) to release cached memory. Be careful: empty_cache() only clears unused cached blocks; it doesn't free memory that's still referenced.
  8. Offload to CPU. Move some tensors to CPU when not needed on GPU. For example, in PyTorch, you can move validation data to CPU and only transfer batches to GPU during evaluation. Use .to('cpu') and .to('cuda') as needed.
  9. Use memory-efficient layers. Replace standard layers with memory-saving alternatives. For transformers, use torch.utils.checkpoint (gradient checkpointing) to trade compute for memory. In TensorFlow, use tf.recompute_grad for similar effect.
  10. Profile memory usage. Use a profiler to identify which part of the model consumes the most memory. In PyTorch, wrap your code with torch.profiler and look at the memory table. In TensorFlow, use tf.profiler or TensorBoard's memory profiler.
  11. Switch to a smaller model or use model parallelism. If all else fails, consider a smaller architecture (e.g., fewer layers or hidden units) or split the model across multiple GPUs using model parallelism (e.g., torch.nn.DataParallel or model_parallelism in TF).
  12. Set memory growth (TensorFlow). For TensorFlow, set GPU memory growth to avoid allocating all memory at once: physical_devices = tf.config.list_physical_devices('GPU'); tf.config.experimental.set_memory_growth(physical_devices[0], True). This prevents OOM from pre-allocation.

Common Mistakes

  • Reducing batch size too aggressively, causing poor model convergence.
  • Forgetting to clear cache after deleting tensors, leading to fragmented memory.
  • Using mixed precision without a scaler, causing underflow or overflow.
  • Setting CUDA_VISIBLE_DEVICES incorrectly, so the workload still uses the wrong GPU.
  • Assuming OOM is always due to model size; often it's due to activations or batch size.

Tips

  • Start with a tiny batch size (e.g., 1) to establish a baseline memory footprint, then scale up.
  • Use nvidia-smi -l 1 to monitor memory usage in real time while training.
  • For inference, consider using torch.no_grad() or tf.stop_gradient to disable gradient computation.
  • Keep the GPU driver and CUDA toolkit updated; older versions may have memory leaks.
  • If you have multiple GPUs, use data parallelism to distribute the batch across them.

Troubleshooting

If the error persists after following the steps, try these additional checks:

  • Check for memory leaks. Run your workload for a few iterations and monitor memory with nvidia-smi. If memory grows continuously, you may have a leak—ensure you're not storing tensors in lists or retaining references.
  • Verify the error is not from CPU RAM. Sometimes the error message says 'CUDA out of memory' but actually refers to host memory. Check system RAM usage with free -h.
  • Test with a minimal script. Create a simple script that loads the model and runs a forward pass on a dummy input. If that works, the issue is likely in your data pipeline or training loop.
  • Try a different framework version. Occasionally, a bug in a specific version causes excessive memory usage. Updating or downgrading PyTorch/TensorFlow may help.
  • If using Docker, ensure the container has access to the correct GPU. Use --gpus all and verify with nvidia-smi inside the container.

Frequently Asked Questions

Why does my model use more memory than the model size?

During training, memory is used for activations (intermediate outputs), gradients, optimizer states, and workspace for operations like convolutions. These can exceed the model's parameter size by several times.

Can I use CPU memory to supplement GPU memory?

Yes, you can offload tensors to CPU, but it's slow due to PCIe transfer. Frameworks like PyTorch have 'pin_memory' for faster transfers, but it's not a substitute for VRAM.

What is the difference between 'CUDA out of memory' and 'RuntimeError: CUDA error: out of memory'?

They are the same; the first is a friendly message, the second is the raw CUDA error. Both indicate insufficient VRAM.

Will reducing batch size always fix OOM?

Not always. If the model itself is too large for the GPU, even batch size 1 will OOM. In that case, you need a smaller model, model parallelism, or a GPU with more memory.

How do I know which GPU has enough memory?

Check nvidia-smi to see total memory and current usage. You can also query with torch.cuda.get_device_properties(0) to get total memory.

Is it safe to use mixed precision on any GPU?

Mixed precision works best on GPUs with tensor cores (e.g., NVIDIA Volta, Turing, Ampere, and newer). On older GPUs, it may still work but with less speedup; in rare cases, it may cause numerical issues.