Out of memory

Out of memory specifically at long context lengths

torch.cuda.OutOfMemoryError or 'cannot allocate KV cache' at >32K tokens
By Eruo Fredoline · Last verified Oct 7, 2026

Cause

KV cache memory grows linearly with context length. A model that comfortably runs at 4K context can OOM at 32K because the cache went from 1 GB to 8 GB.

The math: KV cache bytes = 2 × num_layers × num_kv_heads × head_dim × context × bytes_per_element. Llama 3.1 8B at 32K context = ~4 GB just for KV cache, on top of weights.

Solution

Quantize the KV cache — biggest single win:

# llama.cpp — INT8 KV cache halves memory
./main --cache-type-k q8_0 --cache-type-v q8_0

# Or INT4 KV (more aggressive, slight quality cost)
./main --cache-type-k q4_0 --cache-type-v q4_0

Enable Flash Attention if not already on (some runners default it off):

./main --flash-attn

Use a smaller working context. A model that "supports 128K" doesn't mean you have to use it.

Move to a model designed for long context efficiency — Mistral Small 3, Llama 4 Scout (10M context with native efficiency), or Qwen 3 with its sliding window mode.

More VRAM is the only real fix for very-long-context workloads. Calculate your specific scenario at /will-it-run — pick a context where the prediction shows reasonable headroom, not the model's maximum.

Cloud GPU rental

Not enough VRAM for this model? Rent a GPU by the hour

If you need the long context and it still runs out of VRAM after quantizing the KV cache, you can rent a GPU with more VRAM by the hour for those runs instead of buying a bigger card.

RunPod

billed per GPU-hour

Hourly GPU pods, in community-cloud and secure-cloud tiers.

The two tiers run on different hosts and terms. Check which tier a pod is on before a long job.

Rent on RunPod

Vast.ai

billed per GPU-hour

Marketplace of host-listed GPUs; price and reliability vary by host.

Host quality varies. Filter for verified hosts and check the host's reliability before a long run.

Rent on Vast.ai

Referral links: RunLocalAI may earn a commission or account credits if you sign up and rent, at no extra cost to you. Hourly rates and which GPUs are listed change all the time, so check the provider's page before you start. Editorial opinions are independent of the referral relationship; see how we make money.

Related errors

Did this fix it?

If your case was different, email Contact support with what you saw and we'll update the page. If it worked but took different commands on your platform, we want to know that too.