Ollama Context Window & VRAM Scaling: KV Cache Formulas
One of the most confusing surprises for Windows Ollama users is downloading an 8-billion parameter model (like Llama 3.1 8B), noticing that the file on disk is only 4.7 GB, loading it on an 8 GB or 12 GB GPU, and suddenly watching Windows crash with CUDA error: out of memory when pasting a large PDF or codebase. The culprit is the KV (Key-Value) Cache. Here is how context window memory scales and how to budget for it.
The Mathematical Formula for KV Cache Memory
In modern Transformer architectures (especially those utilizing Grouped-Query Attention / GQA like Llama 3, Mistral, and Qwen), the KV cache stores key and value vector tensors for every token processed in the active conversation.
The exact byte requirement for the KV Cache is calculated as:
KV_Cache_Bytes = 2 × n_layers × n_kv_heads × head_dim × context_length × precision_bytes
For Llama 3.1 8B, the architectural parameters are:
n_layers= 32n_kv_heads= 8 (due to 4:1 GQA grouping)head_dim= 128precision_bytes= 2 (FP16 half-precision cache default in llama.cpp)
Multiplying these constants:
2 × 32 × 8 × 128 × 2 = 131,072 bytes per token (~128 KB per token)
VRAM Impact at Different Context Lengths (Llama 3.1 8B)
| Context Tokens (num_ctx) | Raw Model Weights | KV Cache Footprint | CUDA Overhead | Total VRAM Needed | Minimum Safe GPU |
|---|---|---|---|---|---|
| 2,048 tokens (Default) | 4.52 GB | 0.26 GB | ~0.85 GB | 5.63 GB | 6 GB (RTX 2060, RTX 3060M) |
| 8,192 tokens (Medium Doc) | 4.52 GB | 1.05 GB | ~0.85 GB | 6.42 GB | 8 GB (RTX 4060, RTX 3070) |
| 16,384 tokens (Long Chat) | 4.52 GB | 2.10 GB | ~0.90 GB | 7.52 GB | 12 GB (RTX 3060 12GB, RTX 4070) |
| 32,768 tokens (Full Codebase) | 4.52 GB | 4.19 GB | ~0.95 GB | 9.66 GB | 12 GB / 16 GB (RTX 4070 / 4080) |
| 65,536 tokens (Deep Analysis) | 4.52 GB | 8.39 GB | ~1.00 GB | 13.91 GB | 16 GB / 24 GB (Arc A770, RTX 4090) |
| 131,072 tokens (Full Window) | 4.52 GB | 16.78 GB | ~1.10 GB | 22.40 GB | 24 GB (RTX 3090, RTX 4090, RX 7900 XTX) |
How to Set Context Length in Ollama on Windows
By default, Ollama initializes models with a modest context window (usually 2,048 or 4,096 tokens) to prevent accidental out-of-memory errors on average consumer hardware. You can configure the context length in three ways:
Method 1: Creating a Custom Modelfile (Permanent)
Create a text file named Modelfile in any folder:
FROM llama3.1:8b
# Set context window to 8k tokens:
PARAMETER num_ctx 8192
# Optional: enable Flash Attention
PARAMETER flash_attn true
Build your customized model in PowerShell:
ollama create llama3.1-8k -f Modelfile
ollama run llama3.1-8k
Method 2: Configuring Web UIs (Open WebUI / Continue)
If you are using Open WebUI, navigate to Workspace > Models > Edit Model > Advanced Parameters > Context Length (num_ctx) and input your budgeted token count (e.g., 8192 or 16384).
Method 3: Via REST API Payload
If you are developing applications that call Ollama's /api/generate or /api/chat endpoints, pass num_ctx inside the options dictionary:
{
"model": "llama3.1:8b",
"prompt": "Analyze this technical document...",
"options": {
"num_ctx": 8192
}
}
Techniques to Cut Context VRAM in Half
1. Enable 4-Bit KV Cache Quantization (K-quants)
By default, the KV cache is stored in 16-bit floating point (FP16). Ollama and llama.cpp now support quantizing the KV cache to Q4_0 or Q8_0, slashing KV cache memory consumption by up to 75% with virtually undetectable perplexity degradation.
In your Modelfile:
FROM llama3.1:8b
PARAMETER num_ctx 32768
PARAMETER kv_quant q4_0
2. Activate Flash Attention
Flash Attention eliminates the need to materialize the full N × N attention matrix in VRAM. On Windows, set:
[Environment]::SetEnvironmentVariable('OLLAMA_FLASH_ATTENTION', '1', 'User')
Frequently Asked Questions
What happens if my prompt exceeds the configured num_ctx?
Ollama will truncate the oldest messages from the beginning of the context history (sliding window attention) to maintain the active token count within num_ctx. The model will not crash, but it will lose awareness of earlier instructions.
Does a larger context window slow down generation speed?
It slightly increases prompt evaluation duration (since more tokens must be processed initially), but once the prompt is evaluated, the per-token decoding generation speed remains largely identical until VRAM is exhausted.