Black Friday: Save 10% for life on all of our VPS plans, now through Cyber Monday

10% off on selected plans for as long as you keep the service · new orders · up to 10 uses per customer · ends Dec 1, 2026, 12:00 AM EST.

See plans
Guideschevron_rightServers

Servers · 7 min read · Updated

How to Fix CUDA Out of Memory Errors

"CUDA out of memory" means the GPU had no free memory for the next allocation. Fix it in this order: run nvidia-smi to see what else holds GPU memory and stop it; then ask for less, with a smaller batch, a shorter context, fewer requests at once or a quantized model; in PyTorch, set PYTORCH_ALLOC_CONF=expandable_segments:True to cut fragmentation. If the model itself does not fit, split it across GPUs or move to a GPU with more memory.

1. See What Is Using the GPU

nvidia-smi                       # memory per GPU, and the processes using it
ps -elf | grep python            # leftover Python processes still holding memory

The Processes table lists each program's PID and GPU memory. A crashed notebook, an old training run or a second inference server is often the culprit: stop it (kill PID) and try again. Remember that PyTorch's cache shows as used in nvidia-smi even when no tensor occupies it.

2. Fix It in PyTorch

  • Halve the batch size until it fits; use gradient accumulation to keep the effective batch.
  • Do not keep the graph alive: add up losses as numbers, total_loss += float(loss), not total_loss += loss, which keeps every step's history in memory.
  • Drop tensors you no longer need with del x.
  • Run inference without gradients: wrap it in with torch.no_grad():.
  • Do not recover inside except: the exception keeps the failed step's tensors alive. Set a flag in the handler and retry after it.

To reduce fragmentation and see where memory goes:

export PYTORCH_ALLOC_CONF=expandable_segments:True   # older PyTorch: PYTORCH_CUDA_ALLOC_CONF

python - <<'EOF'
import torch
print(torch.cuda.memory_allocated() / 2**30, "GiB in tensors")
print(torch.cuda.memory_reserved() / 2**30, "GiB reserved by the cache")
print(torch.cuda.memory_summary())
EOF

Details in PyTorch's CUDA memory notes and FAQ.

3. Fix It in vLLM

vLLM options that reduce GPU memory
OptionWhat it does
--max-model-len 8192Caps the context length; the default comes from the model and can be huge
--max-num-seqsFewer sequences processed at once, so a smaller conversation cache
--gpu-memory-utilization 0.85Leaves room for other programs sharing the GPU
--enforce-eagerTurns off CUDA graphs, which take extra GPU memory
--tensor-parallel-size 2Splits the model across two GPUs
A quantized modelAWQ, GPTQ, FP8 and other formats take less memory at some cost in precision

From vLLM's conserving memory guide. Start with --max-model-len: it is the most common cause when the weights alone fit.

4. Fix It in Ollama and llama.cpp

  • Ollama: a large OLLAMA_CONTEXT_LENGTH or a high OLLAMA_NUM_PARALLEL grows the conversation cache, and by default Ollama keeps up to three models loaded per GPU. Set OLLAMA_MAX_LOADED_MODELS=1 and a smaller context with sudo systemctl edit ollama.service, or pick a smaller quantization of the model.
  • llama.cpp: lower -ngl to keep some layers in system memory, use a smaller -c context or fewer --parallel slots, and for mixture-of-experts models move experts to the processor with --n-cpu-moe, as in the gpt-oss guide.

When the Model Simply Does Not Fit

Work out what the model needs with how much VRAM an LLM needs: at 4-bit, about 0.7 GB per billion parameters with context. If that is more than your card has, the fixes above only trade speed for memory. A GPU with more memory, or several, is the lasting fix: see the best GPU for running LLMs for what fits on each of ours.

Common Questions

  • Does torch.cuda.empty_cache() fix CUDA out of memory?

    Rarely. It returns memory PyTorch has cached but is not using, so other programs on the GPU can have it. Memory held by live tensors is not freed, so it gives your own PyTorch code no more room. Free the tensors themselves with del, or use less memory.

  • Why does nvidia-smi show memory used when my code is idle?

    PyTorch keeps freed memory in its cache for reuse, and nvidia-smi counts that cache as used. Check torch.cuda.memory_allocated() for what tensors actually occupy, and memory_reserved() for the cache as a whole.

  • What is PYTORCH_CUDA_ALLOC_CONF?

    The old name of PYTORCH_ALLOC_CONF, the setting for PyTorch's memory allocator; the old name still works for backward compatibility. Setting it to expandable_segments:True lets the allocator grow memory segments instead of making new ones, which reduces fragmentation when batch sizes vary.

  • How do I run a model bigger than my GPU's memory?

    Quantize it to 8-bit or 4-bit, split it across several GPUs, or let llama.cpp or Ollama keep part of it in system memory, which is slower. For a model that is simply too big, a GPU with more memory is the real fix.

Plans and prices

GPU Servers

GPU servers from small cards to 96 GB and multi-GPU, with full root access.

See all plans
  • Intel Core Ultra 9 285K w/ NVIDIA Tesla P4

    NVIDIA Tesla P4 · 8 GB GPU

    24 Cores · 192 GB RAM · 2x 3.84TB NVMe Gen4

    Los Angeles, CA (LA1) · 50 TB transfer · 25 Gbps

    $589.00/mo

  • NVIDIA DGX Spark

    NVIDIA DGX Spark · 128 GB GPU

    20 Cores · 128 GB RAM · 4TB NVMe Gen4

    Ogden, UT (UT1) · 50 TB transfer · 10 Gbps

    $609.00/mo

    Sold out
  • AMD EPYC 7443P w/ NVIDIA RTX 3090

    NVIDIA RTX 3090 · 24 GB GPU

    24 Cores · 256 GB RAM · 3.84TB NVMe

    Ogden, UT (UT1) · 100 TB transfer · 10 Gbps

    $659.00/mo

  • AMD Ryzen 9 9950X w/ NVIDIA RTX 3050

    NVIDIA RTX 3050 · 6 GB GPU

    16 Cores · 192 GB RAM · 2x 2 TB NVMe

    Ashburn, VA (ASH1) · Dallas, TX (TX3) · New York, NY (NY2) · Charlotte, NC (NC1) · Bend, OR (OR1) · Unmetered transfer · 1 Gbps

    $699.00/mo

Keep Reading

All guides