Smart Systems for Home

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

Run AI Models on GPUs with Less VRAM

· 4 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 large AI models on a GPU with limited VRAM can feel like a dead end, but there are several practical techniques that let you fit bigger models into smaller memory footprints. This guide walks you through the most effective methods, from quantization to offloading, so you can run models like Llama or Stable Diffusion on consumer GPUs with 4GB, 6GB, or 8GB of VRAM.

What You'll Need

  • A GPU with at least 4GB of VRAM (NVIDIA recommended for CUDA support).
  • Python 3.8+ installed on your system.
  • PyTorch or TensorFlow installed with CUDA support (check your GPU compatibility).
  • Hugging Face Transformers library (pip install transformers).
  • Optional: accelerate library (pip install accelerate) for easy offloading.
  • Optional: bitsandbytes library (pip install bitsandbytes) for quantization.

Step-by-Step

  1. Choose a model that fits your VRAM budget. Check the model's memory requirements on its Hugging Face page or use the transformers model card. For example, a 7B parameter model in FP16 needs about 14GB, but in 4-bit only about 4GB.
  2. Load the model in half precision (FP16) if your GPU supports it. This halves memory usage compared to FP32. In PyTorch: model = model.half() or pass torch_dtype=torch.float16 when loading with from_pretrained.
  3. Apply quantization with bitsandbytes. Use 8-bit or 4-bit quantization to drastically reduce memory. Example for 4-bit: model = AutoModelForCausalLM.from_pretrained("model_name", load_in_4bit=True, device_map="auto"). This requires bitsandbytes and accelerate.
  4. Enable CPU offloading. When your model is too large even after quantization, offload some layers to CPU RAM. With accelerate, set device_map="auto" to automatically place layers on GPU and CPU. You can also manually specify device_map to control which layers go where.
  5. Use gradient checkpointing during training or fine-tuning. This trades compute for memory by recomputing activations during the backward pass. Add model.gradient_checkpointing_enable() in your training script.
  6. Reduce batch size and sequence length. For inference, use a batch size of 1 or 2. For training, start with a batch size of 1 and use gradient accumulation to simulate larger batches.
  7. Use memory-efficient attention. Libraries like xformers or PyTorch's torch.nn.functional.scaled_dot_product_attention reduce memory usage for attention layers.
  8. Free up GPU memory before loading. Use torch.cuda.empty_cache() and set PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 to reduce fragmentation.
  9. Consider using a model server like vLLM or llama.cpp. These are optimized for inference and can handle large models with less VRAM. For example, llama.cpp uses quantization and memory mapping to run models on CPU or low-VRAM GPUs.

Common Mistakes

  • Forgetting to install required libraries. Quantization and offloading need bitsandbytes and accelerate. Without them, you'll get errors.
  • Using FP16 on GPUs that don't support it well. Some older GPUs have poor FP16 performance. Check your GPU's compute capability.
  • Ignoring the sequence length. Longer sequences use more memory. If you hit OOM, try truncating inputs.
  • Not setting device_map="auto" when using offloading. This can cause the model to try to fit entirely on GPU, defeating the purpose.
  • Using too high a batch size. Start small and increase only if memory allows.

Tips

  • Monitor VRAM usage with nvidia-smi to see how much memory is actually used and adjust accordingly.
  • Use the smallest model that meets your needs. Distilled versions or smaller parameter counts often perform well.
  • For inference, use torch.inference_mode() instead of torch.no_grad() to save memory.
  • Combine quantization with offloading for the best results on very tight VRAM.
  • Keep your libraries up to date. New versions often have memory optimizations.

Troubleshooting

  • Out of Memory (OOM) errors: Reduce batch size, sequence length, or use more aggressive quantization (e.g., 4-bit instead of 8-bit). Also, try clearing cache with torch.cuda.empty_cache().
  • Model loads but runs very slowly: This often happens with CPU offloading. Ensure that most layers are on GPU. You can check with model.hf_device_map to see the placement.
  • Quantization fails with an error: Make sure your GPU supports the required operations (e.g., bitsandbytes needs a CUDA GPU with compute capability 7.0+). Also, verify that bitsandbytes is correctly installed.
  • FP16 gives wrong outputs: Some models are sensitive to precision. Try using torch_dtype=torch.bfloat16 if your GPU supports it, or fall back to FP32 with a smaller model.
  • CUDA out of memory even with a small model: Check if other processes are using GPU memory. Use nvidia-smi to see and kill unnecessary processes.

Frequently Asked Questions

Can I run a 7B model on a 6GB GPU?

Yes, with 4-bit quantization and offloading, a 7B model can run on a 6GB GPU, though it will be slower. Use load_in_4bit=True and device_map="auto".

What is quantization and why does it help?

Quantization reduces the precision of the model's weights (e.g., from 16-bit to 4-bit), which reduces memory usage significantly while often maintaining acceptable performance.

Does CPU offloading slow down inference a lot?

Yes, because data has to move between CPU and GPU. It's a trade-off: you can run larger models but with lower speed. For interactive use, try to keep as many layers on GPU as possible.

Is FP16 always better than FP32?

FP16 uses half the memory and is faster on GPUs with tensor cores, but it can cause numerical instability in some models. If you see issues, try bfloat16 or fall back to FP32.

Can I use these techniques for training, not just inference?

Yes, quantization and offloading work for training, but you also need gradient checkpointing and smaller batch sizes. Note that training with quantization can be slower and may require special handling.

What if my GPU doesn't support bitsandbytes?

If you have an older GPU, you can still use CPU offloading and FP16. Alternatively, use llama.cpp which supports quantization and runs on CPU, though slower.