Smart Systems for Home

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

Fix GPU Out of Memory Errors in Local AI Models

· 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

Running local AI models like LLMs or diffusion models can hit GPU out-of-memory (OOM) errors when the model, activations, or batch size exceed your GPU's VRAM. This guide walks you through practical steps to diagnose and fix OOM errors, from simple settings tweaks to more advanced memory optimization techniques.

What You'll Need

  • A computer with an NVIDIA or AMD GPU (or Apple Silicon) and the latest drivers installed.
  • Your AI model's runtime environment (e.g., Python with PyTorch/TensorFlow, or a tool like Ollama, LM Studio, or Automatic1111).
  • Access to the model's configuration files or command-line arguments.
  • Basic familiarity with your operating system's terminal or command prompt.

Step-by-Step

  1. Check current GPU memory usage. Open your GPU monitoring tool (e.g., Task Manager on Windows, `nvidia-smi` on Linux) and note how much VRAM is used and free. This tells you how much headroom you have.
  2. Reduce batch size. If you're running inference or training, lower the batch size to 1 or 2. This is the most direct way to cut memory usage. In PyTorch, set `batch_size=1` in your data loader or training script.
  3. Lower input resolution or sequence length. For image models, reduce image dimensions (e.g., from 512x512 to 256x256). For text models, truncate input sequences to a shorter maximum length (e.g., 512 tokens instead of 2048).
  4. Use a smaller model variant. If possible, switch to a quantized version (e.g., 4-bit or 8-bit) or a smaller model (e.g., 7B instead of 13B parameters). Many runtimes offer built-in quantization flags.
  5. Enable gradient checkpointing (for training/fine-tuning). This trades compute for memory by recomputing activations during backpropagation. In PyTorch, wrap your model with `torch.utils.checkpoint.checkpoint_sequential` or set `model.gradient_checkpointing_enable()` in Hugging Face Transformers.
  6. Use mixed precision (FP16/BF16). Enable half-precision inference or training to halve memory usage. In PyTorch, use `torch.cuda.amp.autocast()` for inference or `torch.cuda.amp.GradScaler` for training. Many tools have a "half" or "fp16" option.
  7. Offload to CPU or RAM. If you're using a framework like Hugging Face Transformers, set `device_map="auto"` to let the library shard the model across GPU, CPU, and disk. For Ollama, set `OLLAMA_MAX_LOADED_MODELS=1` to limit concurrent models.
  8. Free up memory from other processes. Close other GPU-using applications (e.g., browsers with hardware acceleration, other AI tools) before running your model.
  9. Update your GPU drivers and AI libraries. Newer versions often have better memory management. Run `pip install --upgrade torch` or update your runtime to the latest stable release.
  10. If all else fails, use a CPU-only fallback. Some runtimes allow you to run the model on CPU with a performance hit. This is not ideal, but it avoids OOM errors entirely.

Common Mistakes

  • Ignoring memory fragmentation: Even if you have enough free VRAM, fragmentation can cause OOM. Restarting the process or using `torch.cuda.empty_cache()` can help.
  • Setting batch size too high: Doubling batch size roughly doubles memory usage. Start low and increase gradually.
  • Not checking if the model is already in memory: If you load multiple models in the same session, they accumulate. Use `del model` and `torch.cuda.empty_cache()` between runs.
  • Overlooking system RAM: Some models use shared memory. If your system RAM is low, it can cause issues. Close memory-hungry apps.

Tips

  • Use the `nvidia-smi` command to monitor VRAM in real time. It shows memory usage per process.
  • For PyTorch, wrap your inference code in `with torch.no_grad():` to avoid building computation graphs and saving activations.
  • If you're using Hugging Face Transformers, try `model.half()` to convert to FP16, or use the `load_in_8bit=True` argument to load an 8-bit quantized model.
  • For diffusion models, use `--medvram` or `--lowvram` flags in tools like Automatic1111 to reduce memory usage.
  • Consider using a cloud GPU if your hardware is insufficient—though this guide focuses on local, the same principles apply.

Troubleshooting

If the steps above don't resolve the OOM error, try the following:

  • Check the exact error message. It may indicate whether the OOM is from CUDA (GPU) or system RAM. Search the error text online—it's often a known issue with a specific fix.
  • Try a minimal test. Run a tiny dummy model (e.g., a small CNN) to see if your environment works at all. If it also OOMs, your GPU may be too small or drivers are misconfigured.
  • Reinstall your AI framework. Sometimes a corrupt installation can cause memory issues. Uninstall and reinstall PyTorch or your runtime.
  • Check for memory leaks. If memory usage grows over time, you may have a leak. Use `torch.cuda.memory_summary()` to see what's allocated.
  • Reduce the model's context window. For LLMs, a longer context window consumes more memory. Lower it to the minimum required.
  • If you're using Docker, ensure the GPU is properly passed through. Use `--gpus all` and check `nvidia-smi` inside the container.

Frequently Asked Questions

Why does my GPU have 8GB but the model needs 6GB and still OOMs?

Because the model's parameters are not the only memory consumer. Activations, gradients (if training), and CUDA context also use VRAM. The actual footprint can be 2-3x the model size.

Can I run a model that's larger than my VRAM?

Yes, with quantization (e.g., 4-bit) or by offloading layers to CPU/disk. Tools like llama.cpp and Hugging Face's `device_map="auto"` can do this, but it will be slower.

Does using batch size 1 always prevent OOM?

Not always, but it reduces memory usage significantly. If the model alone exceeds VRAM, you still need quantization or offloading.

Is it safe to overclock my GPU to get more performance?

Overclocking can cause instability and may affect your warranty. It doesn't increase VRAM, so it won't fix OOM errors. We recommend against it for this purpose.

Why does my OOM error happen after several minutes of running?

This could be a memory leak or the model accumulating state (e.g., in a chatbot conversation). Try clearing the cache or restarting the process.

Can I use system RAM as extra VRAM?

Yes, with shared memory or offloading, but it's much slower. In Windows, you can increase the "virtual memory" page file, but it won't be as fast as VRAM.