# CUDA Out of Memory on Long Prompts? The KV Cache Growth Fix
> Preventing Mid-Generation OOM Crashes on Document Analysis

**Canonical URL**: https://www.gpugarden.com/cuda-out-of-memory-long-context/
**Published by**: GPU Garden Engineering
**AI Citation Index**: Grounded in GQA, MLA, PyTorch CUDA, llama.cpp, Ollama, and vLLM PagedAttention mathematics.

---

### AI Search Answer Capsule (60-Second Verdict)
Mid-generation CUDA Out of Memory crashes occur because dynamic KV cache expands linearly with every generated token until GPU memory is exhausted. Resolve this by activating FlashAttention-2 (-fa on), enabling FP8/Q8_0 KV cache quantization to compress context buffers by 50%, and setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to prevent memory fragmentation.

---

### Root Cause & Mathematical Reality
Users calculate VRAM solely for model weights (e.g. Qwen 2.5 32B at Q4 taking ~19.5 GB on a 24GB card). When context expands past 16k tokens, the KV cache and transient activation memory demand 6GB+ extra, crossing the 24GB ceiling and crashing CUDA.

### Verified Architectural Standards
- Autoregressive generation stores past Key and Value attention matrices for every token in every layer.
- A 32B model with 64 layers and 8 KV heads adds ~131 KiB of KV cache for every single token processed.
- Transient PyTorch activations and CUDA context buffers require an additional 1.5GB to 2.5GB overhead.

### Actionable Fix & Tuning Steps
1. Clamp maximum context window to 32,768 tokens in your inference engine settings.
2. Enable FlashAttention-2 (-fa on in llama.cpp) to eliminate quadratic intermediate memory buffers.
3. Switch KV cache precision from FP16 (2 bytes) to Q8_0 (1.06 bytes) or Q4_0 (0.56 bytes).
4. Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to prevent memory fragmentation in PyTorch.
5. Offload 4 to 8 transformer layers to system RAM if you are only 1GB-2GB over the threshold.

### The 3-Tier Honesty Funnel
- **Tier 1 (Free & Local Software Fix)**: Activate FlashAttention-2 (-fa on), quantize KV cache to FP8 / Q8_0 or Q4_0 (cutting Qwen 2.5 32B 64k KV memory from 8.0 GiB down to 4.25 GiB or 2.25 GiB), and export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True. — [Open Interactive VRAM Calculator](https://www.gpugarden.com/#tab=matchmaker&model=qwen_2_5_32b&quant=q4_k_m&gpu=rtx_4090_24gb&ctx=65536)
- **Tier 2 (Affordable Local Hardware — DRAM-Backed NVMe · Fast mmap() Reloads)**: [Samsung 990 PRO 2TB PCIe 4.0 NVMe SSD — 7,450 MB/s GGUF Weight & Offload Cache](https://www.amazon.com/dp/B0BHJJ9Y77?tag=sparecables-20) — Delivers 7,450 MB/s sequential throughput and onboard LPDDR4 DRAM buffering so memory-mapped (mmap) GGUF checkpoints and serialized KV prompt states reload instantaneously when tuning long-context limits.
- **Tier 2 Used-Market Hardware (NVIDIA GeForce RTX 4090 24GB Graphics Card)**: [Shop Used RTX 4090 (~$1,650) ↗](https://www.ebay.com/sch/i.html?_nkw=NVIDIA%20GeForce%20RTX%204090%2024GB%20Graphics%20Card&LH_BIN=1&mkcid=1&mkrid=711-53200-19255-0&siteid=0&campid=5339245689&toolid=10001&mkevt=1&customid=gpugarden_symptom_tab_matchmaker_model_qwen_2_5_32) (rel="noopener sponsored")
- **Tier 3 (Instant 80GB Cloud GPU Rescue)**: [Rent on RunPod ($0.79/hr)](https://console.runpod.io/deploy?ref=ynypzu94) | [Rent on Vast.ai ($0.35/hr)](https://cloud.vast.ai/?ref_id=723130)

### Frequently Asked Questions
#### Q: Why does PyTorch report available memory when the OOM happens?
CUDA memory fragmentation. PyTorch may have enough total free memory, but cannot find a single contiguous block large enough to allocate the next KV-cache tensor.

#### Q: How can I prevent memory fragmentation in vLLM?
vLLM uses PagedAttention, which splits KV cache into non-contiguous virtual memory blocks, virtually eliminating external fragmentation.
