Skip to content

LLM Field Guide 04 — Memory Is the Bottleneck: KV Cache, Attention Variants, and Long Context

The KV cache makes generation fast by never recomputing the past, and it costs memory that grows with every token in flight. On a Llama-3.1-8B-class model, one 128K-token conversation needs about 16 GiB of cache, roughly as much as the weights. Almost every modern attention variant, serving trick, and context-length caveat exists to manage this one cache.

In this post:

LLM Field Guide — all 12 posts
  1. How an LLM reads text
  2. Inside the transformer
  3. Training and generation
  4. KV cache and long context ← you are here
  5. Prompting, context, and RAG
  6. Reasoning models and agents
  7. Choosing a base model
  8. Adapting a model
  9. Making it smaller and faster
  10. Serving at scale
  11. Safety and evaluation
  12. Putting it all together

Where this fits: Post 03 showed how one token gets picked from the logits. This post covers what happens when you repeat that thousands of times: the cache that makes the loop cheap, the attention designs built to shrink it, and the memory wall it creates at long context. Attention itself (Q, K, V, multi-head, the causal mask) is in post 02.

Without a cache, every token re-reads the past

Generation is a loop: read every token so far, predict one more, append it, run again (post 01). Inside each run, attention needs a key K and a value V vector for every previous token at every layer.

Run 1: input "The"              → compute K,V for The               → predict "cat"
Run 2: input "The cat"          → compute K,V for The, cat          → predict "sat"
Run 3: input "The cat sat"      → compute K,V for The, cat, sat     → predict "on"
...
Run n: input n tokens           → compute K,V for all n tokens      → predict token n+1

The K and V for "The" never change. The causal mask means a token's representation depends only on the tokens before it, so "The" produces the same K and V at run 1, run 2, and run 1,000. Recomputing them is pure waste.

Count the work: producing n tokens this way pushes 1 + 2 + … + n ≈ n²/2 token positions through all 32 layers. At 1,000 output tokens that's ~500,000 token-passes when you only needed 1,000.

The KV cache: store K and V once, reuse them forever

KV cache: K and V vectors from earlier tokens are stored and reused at each new step

The KV cache stores each token's K and V the first time they're computed. Each later step computes Q, K, and V for the one new token only, appends the new K and V to the cache, and attends over everything stored:

Step 1: compute K₁,V₁ for "The"   → cache [K₁]       [V₁]
Step 2: compute K₂,V₂ for "cat"   → cache [K₁,K₂]    [V₁,V₂]     attention reads both
Step 3: compute K₃,V₃ for "sat"   → cache [K₁,K₂,K₃] [V₁,V₂,V₃]  attention reads all three
Step n: compute Kₙ,Vₙ only        → attention reuses all n-1 cached pairs

Why cache K and V but not Q? A query is only used by its own token. The new token's Q asks "what should I look at?" and the cached K and V answer it. Old queries are never needed again.

See the difference on your own machine with a small model:

# pip install "transformers==5.22.1" torch accelerate
import time, torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "Qwen/Qwen3-0.6B"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, dtype=torch.bfloat16, device_map="auto"
)
inputs = tok("The cat sat", return_tensors="pt").to(model.device)

for use_cache in (True, False):
    t0 = time.perf_counter()
    model.generate(**inputs, max_new_tokens=512, min_new_tokens=512,
                   do_sample=False, use_cache=use_cache)
    print(f"use_cache={use_cache}: {time.perf_counter() - t0:.1f}s")

The uncached run slows down as output grows, because every step reprocesses the whole sequence. Double max_new_tokens and watch the gap widen.

A broken cache doesn't crash. It just produces garbage.

An off-by-one in cache position or a stale entry still produces fluent-looking text, just wrong text. The test that catches it: cached decoding must match a full forward pass to about 1e-6. The build-from-scratch post has a working KVCache class and that 4-line equivalence test.

Prefill vs decode: two workloads, two bottlenecks

With a cache, every request runs in two phases with opposite bottlenecks.

Prefill Decode
What happens Process the whole prompt in one forward pass; fill the cache Generate one token per forward pass; append to cache
Tokens per pass Thousands (all prompt tokens in parallel) 1 per sequence
Bottleneck Compute (big matrix multiplies) Memory bandwidth (read all weights + cache for 1 token)
User-facing metric Time to first token (TTFT) Time per output token (TPOT), tokens/sec
Gets worse with Longer prompts Longer context and bigger batches (more cache to read)

Decode is memory-bandwidth-bound. To produce one token, the GPU streams every weight from HBM (high-bandwidth memory, the GPU's main memory) through the compute units, then does very little math with it. Llama-3.1-8B in BF16 is ~16 GB of weights; an H100 SXM moves 3.35 TB/s1:

16 GB ÷ 3.35 TB/s ≈ 4.8 ms per decode step  →  at most ~210 tokens/s for one sequence

That's the theoretical ceiling at batch size 1, before reading any cache. Real single-stream speed lands below it: at 100 tokens/s, a 750-token answer takes 7.5 seconds. No sampling setting changes this number; only moving fewer bytes per token does.

Batching is the way out. Sixteen sequences decoding together share one read of the weights, but each still reads its own KV cache. At long context those cache reads start to dominate, which is why cache size drives both capacity and speed. Quantized weights (post 09) cut the weight bytes, speculative decoding (same post) gets more than one token per weight read, and continuous batching (post 10) keeps the batch full.

Prefill is the opposite: thousands of tokens per pass make it compute-heavy and quadratic in prompt length. Every modern engine runs it with a FlashAttention-style kernel (post 02) so the n × n score matrix never lands in HBM.

Sizing the cache: one formula, real numbers

The cache holds one K and one V vector, per KV head, per layer, per token:

KV bytes per token = 2 × layers × kv_heads × head_dim × bytes_per_element
KV cache total     = per_token × tokens_in_flight (context × concurrent sequences)

Plug in two reference models from their config.json:

Model Layers KV heads head_dim Per token (BF16)
Llama-3.1-8B2 32 8 128 2×32×8×128×2 = 131,072 B (128 KiB)
Qwen3-8B3 36 8 128 2×36×8×128×2 = 147,456 B (144 KiB)

Now turn the context dial on Llama-3.1-8B, one sequence:

Context KV cache vs ~16 GB of weights
8,192 tokens 1 GiB 6%
32,768 tokens 4 GiB 25%
131,072 tokens 16 GiB ~100%

At its full 128K window, one conversation's cache is as large as the model itself. Sixteen such conversations need 256 GiB, more than three H100s just for cache. That's the whole capacity-planning problem in one table.

Compute it from any model's config instead of trusting a blog table:

# pip install "transformers==5.22.1"
from transformers import AutoConfig

def kv_per_token(model_id: str, bytes_per_elem: int = 2) -> int:
    c = AutoConfig.from_pretrained(model_id)
    head_dim = getattr(c, "head_dim", None) or c.hidden_size // c.num_attention_heads
    return 2 * c.num_hidden_layers * c.num_key_value_heads * head_dim * bytes_per_elem

per_tok = kv_per_token("Qwen/Qwen3-8B")          # 147456
for ctx in (8_192, 32_768, 131_072):
    print(f"{ctx:>7} tokens: {per_tok * ctx / 2**30:5.1f} GiB")
# 8192: 1.1 GiB · 32768: 4.5 GiB · 131072: 18.0 GiB

This formula assumes every layer is full attention with standard K/V heads. Sliding-window, hybrid, and MLA models break it, so check the architecture before you trust the number (levers 1 and 2 below show how). The VRAM sizing field guide extends this to batch size, weights, and overhead.

Every term in the formula is a lever. Modern models pull three of them:

Lever Formula term it shrinks Section
Share K/V across heads kv_heads Lever 1
Keep fewer tokens per layer tokens_in_flight (per layer) Lever 2
Fewer bits per number bytes_per_element Lever 3

Lever 1: share keys and values across heads (MHA → MQA → GQA → MLA)

In the original multi-head attention (MHA), every query head has its own K and V head. Since the cache scales with the number of K/V heads, the biggest attention change of the 2020s has been sharing keys and values across query heads.

MHA (32 Q heads, 32 KV heads)    Q Q Q Q Q Q Q Q ...   each Q has its own K,V
                                 | | | | | | | |
                                 K K K K K K K K ...

GQA (32 Q heads, 8 KV heads)     Q Q Q Q   Q Q Q Q ...  4 Q heads share one K,V
                                  \ | | /   \ | | /
                                    K         K     ...

MQA (32 Q heads, 1 KV head)      Q Q Q Q Q Q Q Q ...    all Q heads share one K,V
                                  \ \ \ \ / / / /
                                         K
  • Multi-Query Attention (MQA) shares one K/V head across all query heads. Smallest cache, with what Shazeer called "minor quality degradation"5.
  • Grouped-Query Attention (GQA) shares one K/V head per group of query heads. It reaches quality close to MHA at speed comparable to MQA, and existing MHA checkpoints can be converted with about 5% of the original pretraining compute6.
  • Multi-head Latent Attention (MLA), from DeepSeek-V2, caches one small compressed latent vector per token and rebuilds K and V from it on the fly7.

What each scheme does to the cache, on a Llama-3.1-8B-shaped model (32 layers, head_dim 128, BF16):

Scheme KV heads Cache per token At 128K tokens Who uses it
MHA 32 512 KiB 64 GiB GPT-2, original Transformer
MQA5 1 16 KiB 2 GiB PaLM, early Falcon
GQA6 8 128 KiB 16 GiB Llama 3, Qwen3, Mistral, most open models
MLA7 n/a (latent) see below see below DeepSeek-V2/V3 family

GQA-8 is a 4× cut over MHA for little quality loss, which is why it became the default. It's also the difference between one 128K request fitting on an 80 GB card or not.

MLA goes further. DeepSeek-V2 reported a 93.3% smaller KV cache than its dense 67B predecessor and 5.76× higher peak generation throughput7. From DeepSeek-V3's config (61 layers, kv_lora_rank 512, qk_rope_head_dim 64)8:

61 layers × (512 + 64) × 2 bytes = 70,272 B ≈ 69 KiB per token

A 671B-parameter model with a smaller per-token cache than Llama-3.1-8B. That's the payoff of designing attention around the cache. Note the generic formula above doesn't apply to MLA; use the latent width instead.

GQA in PyTorch

PyTorch's fused attention accepts fewer K/V heads than query heads with enable_gqa=True9. Here's an 8B-shaped layer:

# pip install "torch>=2.6"
import torch
import torch.nn.functional as F

batch, seq, n_q, n_kv, head_dim = 1, 1024, 32, 8, 128   # Llama-3.1-8B / Qwen3-8B shape
q = torch.randn(batch, n_q,  seq, head_dim)
k = torch.randn(batch, n_kv, seq, head_dim)
v = torch.randn(batch, n_kv, seq, head_dim)

out = F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True)
print(out.shape)        # torch.Size([1, 32, 1024, 128]) — one output per query head

# Same result by hand: repeat each KV head for its group of 4 query heads
k_rep = k.repeat_interleave(n_q // n_kv, dim=1)
v_rep = v.repeat_interleave(n_q // n_kv, dim=1)
ref = F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=True)
print(torch.allclose(out, ref, atol=1e-5))   # True

The repeat_interleave version shows what GQA means: K and V tensors are 4× smaller, and the cache only ever stores the small ones. The enable_gqa version is what you want in production, because it never builds the repeated tensors.

Lever 2: attend to fewer tokens: windows, sinks, sparse, and linear layers

GQA shrinks what you store per token. The other lever is to stop every token from attending to every other token in every layer.

Technique Idea Shipped in (verified)
Sliding-window (local) attention Each token sees only the last W tokens; interleave with some full-attention layers Gemma 3: 5 local layers per global layer, 1,024-token window10
Banded + dense alternation Alternate 128-token banded layers with fully dense layers gpt-oss-120b / 20b11
Learned attention sinks Let a head put weight on "nothing" via a learned term in the softmax denominator gpt-oss11
Sparse attention A cheap indexer picks which past tokens each query attends to DeepSeek-V3.2 (DeepSeek Sparse Attention)12
Hybrid linear attention Most layers use a linear-time recurrent mixer with a fixed-size state; a few keep full attention Qwen3-Next-80B-A3B: 3 Gated DeltaNet layers per 1 gated-attention layer13

A sliding-window layer's cache stops growing at W tokens. Only the global layers store the full context. Worked example at 128K context with Gemma 3's 5:1 pattern10, assuming equal per-layer cache cost:

All-global:      6 layers × 131,072 tokens               = 786,432 token-slots
Gemma-3 style:   5 × 1,024  +  1 × 131,072              = 136,192 token-slots
Saving:          ~83% less KV cache at 128K

The Gemma 3 report measured the effect directly: global-only attention had 60% KV memory overhead for a 2B model at a 32K prefill, cut to under 15% with local layers and 1,024-token windows (at a 1:3 local:global ratio in that ablation)10.

Hybrid linear layers go one step further. A Gated DeltaNet layer keeps a fixed-size recurrent state instead of a per-token cache, so in Qwen3-Next only one layer in four grows with context13.

Windows can also be bolted on at serving time, without retraining. StreamingLLM keeps the first few "attention sink" tokens plus a sliding window, which lets a model run stably on 4 million+ tokens at a fixed cache size15. (Different mechanism from gpt-oss's learned sinks, same purpose: give attention somewhere harmless to park weight.) The model doesn't remember those 4M tokens; it just doesn't break.

Local layers don't mean a short memory, but they do mean weaker recall

Information still travels the whole context through the global layers and through stacking: each local layer extends what a token can indirectly "see" by another window. But exact long-range retrieval ("quote line 3 of the contract at token 90,000") leans on the few full-attention layers. Test long-context recall on your own documents before trusting a context number on a model card.

How 2026 models configure attention

Read these from config.json before you size anything:

Model Q heads KV heads Head dim Layout Native context
Original Transformer (2017)14 8 8 (MHA) 64 full attention (encoder-decoder) n/a
Llama 3.1 8B2 32 8 (GQA) 128 full attention, every layer 128K (RoPE-scaled)
Qwen3-8B3 32 8 (GQA) 128 full attention, every layer 32K (131K with YaRN)4
gpt-oss-120b11 64 8 (GQA) 64 banded (128) ↔ dense, with sinks 131K
Qwen3-Next-80B-A3B13 16 2 (GQA) 256 3 linear : 1 full 262K
DeepSeek-V38 128 MLA latent (512 + 64) — full attention, every layer 128K (YaRN over 4K)

The trend: keep a few full-attention layers for precise lookup, and make everything else cheaper. Plain "full MHA in every layer" is gone from new frontier designs.

Lever 3: store each number in fewer bits (FP8 KV)

The cache defaults to the model's dtype (BF16, 2 bytes). FP8 KV cache halves it to 1 byte per element, so Llama-3.1-8B drops from 128 KiB to 64 KiB per token and you fit twice the tokens in the same memory.

In vLLM it's one flag. --kv-cache-dtype fp8 (also fp8_e4m3 / fp8_e5m2) enables it; without calibration all scales default to 1.0, and calibrated scales via llm-compressor give the best accuracy16. Sliding-window layers are more sensitive to KV quantization, and vLLM lets you skip them with --kv-cache-dtype-skip-layers16.

Validate FP8 KV on your own eval

FP8 KV usually costs little quality, but "usually" isn't a test. Run your task eval (post 11) with auto and fp8 before flipping it in production, especially for long-context retrieval. Weight quantization formats are in post 09.

PagedAttention: stop wasting the memory you allocate

Shrinking the cache is half the job. The other half is not wasting the memory you allocate.

Early servers reserved a contiguous slab per request sized for the maximum possible length. A request that might generate 4K tokens but stops at 200 still held all 4K. The vLLM team measured that existing systems wasted 60–80% of KV memory to fragmentation and over-reservation17.

PagedAttention borrows the OS idea of paging. The cache is split into fixed-size blocks (e.g. 16 tokens), allocated on demand, and tracked by a block table, so a sequence's blocks needn't be contiguous:

Logical sequence:  [The cat sat on][the mat and  ][purred      ]
Block table:        →  block 7        →  block 2      →  block 19 (partially filled)
Physical GPU pool: [ 0 ][ 1 ][ 2 ][ 3 ]...[ 7 ]...[ 19 ]...

Waste drops to the unfilled tail of the last block: under 4% in vLLM's measurements17. The paper reports 2–4× throughput over prior systems at the same latency18. Every serious engine (vLLM, SGLang, TensorRT-LLM) now uses paged KV memory.

When GPU memory runs out, engines can spill cold blocks to CPU RAM instead of discarding them; vLLM exposes this as --kv-offloading-size (GiB, off by default)20.

Prefix caching: don't prefill the same prompt twice

Paging enables a second trick. If two requests start with the same tokens, they can share the same physical KV blocks. Your 3,000-token system prompt gets prefilled once, and every later request that starts with it skips straight to its new tokens. That cuts TTFT and frees prefill compute for everyone else.

vLLM identifies reusable blocks by hashing. Each full block's hash combines its parent block's hash with its own tokens, so a hash identifies the entire prefix up to that point. Only full blocks are cached, and eviction is least-recently-used19. Requests can pass a cache_salt so tenants never share cached blocks19.

Prefix caching only works if the prefix is byte-for-byte identical. Put a timestamp at the top of your system prompt and every request misses. Hosted APIs' "prompt caching" is the same mechanism billed as a discount; how to structure prompts to hit it is in post 05.

Sharing prefix caches across replicas is a routing problem; see the llm-d disaggregated inference post.

Advertised context: what the number on the model card means

The context window is the maximum number of tokens the model can attend to in one request: system prompt, history, documents, tool results, and the output it's generating. Anything outside it doesn't exist for the model.

Context window (e.g. 131,072 tokens)
├── System prompt        ← always present
├── Conversation history ← grows each turn until something must be dropped or summarized
├── Retrieved docs / tool results
├── Current user message
└── Model's output       ← counts too

Windows grew from 2,048 tokens (GPT-3)21 to 128K-class for open models and 1M+ for frontier APIs. Llama 4 Scout advertises 10M tokens, though it was pre- and post-trained at 256K22. Current Claude models default to a 1M-token window23.

Most long windows are stretched, not trained. Llama 3.1's config shows its 128K window is RoPE scaling with factor: 8.0 over an original_max_position_embeddings of 8,1922. Qwen3-8B is natively 32,768 tokens and reaches 131,072 with YaRN, and Qwen's card warns that static YaRN can hurt short-text quality, so enable it only when you need the length4. How RoPE scaling and YaRN work is in post 02.

Effective context is shorter than advertised

The window tells you what the model accepts. It doesn't tell you what the model uses well. Three lines of evidence:

Study What they found
Lost in the Middle (2023)24 Accuracy is highest when the relevant fact is at the start or end of the context; it "significantly degrades" in the middle
RULER (2024)25 17 long-context models, all claiming ≥32K; only about half stayed satisfactory at 32K once tasks went beyond simple needle retrieval (multi-hop tracing, aggregation)
Context Rot, Chroma (2025)26 18 models including GPT-4.1, Claude 4, Gemini 2.5, Qwen3: performance gets less reliable as input grows, even on simple tasks, and distractors hurt more at length

Anthropic's own docs say it plainly: "As token count grows, accuracy and recall degrade, a phenomenon known as context rot"23.

Treat the context window as a budget, not a bucket. Every token costs KV memory in every layer and dilutes the model's attention:

  • Put long documents near the top and the question and critical instructions at the end (post 05)
  • Retrieve the 5–20 relevant chunks instead of pasting the whole corpus (post 05)
  • Summarize or clear old tool results in long agent runs (post 06)
  • Test at your real lengths: a needle-in-a-haystack pass at 128K says little about multi-document reasoning at 128K

One GPU, real numbers: capacity for Qwen3-8B on an H100

Serve Qwen3-8B on one H100 80 GB. Here's the budget, with illustrative overhead:

GPU memory × 0.90 utilization          = 72 GB
– weights (8.2B params × 2 bytes BF16) ≈ 16.4 GB
– activations, CUDA graphs (rough)     ≈ 4 GB
= left for KV cache                    ≈ 51 GB

BF16 KV (144 KiB/token):  51e9 / 147,456 ≈ 346K tokens
FP8  KV ( 72 KiB/token):  51e9 /  73,728 ≈ 692K tokens
Per-request context Concurrent sequences (BF16 KV) (FP8 KV)
8K ~42 ~84
32K ~10 ~21
128K (YaRN) ~2 ~5

Capping max context at what your users actually send is the cheapest capacity win there is. A 32K cap instead of 128K doesn't shrink the cache per token, but it stops one runaway request from claiming the pool and lets the scheduler plan for realistic lengths.

# vllm==0.33.0
vllm serve Qwen/Qwen3-8B \
  --max-model-len 32768 \
  --gpu-memory-utilization 0.90 \
  --kv-cache-dtype fp8 \
  --enable-prefix-caching   # already the default in vLLM 0.33; shown for clarity

On startup vLLM logs the KV cache capacity in tokens and the maximum concurrency at your --max-model-len. Trust that line over any spreadsheet, including the one above. All flags are in the engine arguments reference20; the vLLM production guide covers the rest of the deployment.

Watch these once live:

  • KV cache utilization near 100% with requests queuing → FP8 KV, more GPUs, or a lower max length
  • Prefix cache hit rate low on a chat or agent workload → something dynamic sits at the top of your prompt
  • TTFT spiking with long prompts → prefill contention; look at chunked prefill or prefill/decode disaggregation (post 10)

Summary

Lever What it does Typical gain Where you control it
KV cache itself Stops recomputing past K,V Decode work O(n²) → O(n) Always on in every engine
GQA / MQA Fewer KV heads 4× (GQA-8 vs MHA-32) to 32× (MQA) Choice of model
MLA Cache a compressed latent ~93% smaller (DeepSeek-V2); 69 KiB/token for a 671B model Choice of model
Sliding window / hybrid layers Most layers keep only W tokens or a fixed state ~83% at 128K (Gemma 3 pattern) Choice of model
FP8 KV cache 2 bytes → 1 byte per element 2× tokens in same memory --kv-cache-dtype fp8
PagedAttention Blocks allocated on demand Waste 60–80% → <4% Built into vLLM/SGLang/TRT-LLM
Prefix caching Reuse KV of shared prompt prefixes Skip prefill on repeated prefix On by default in vLLM (enable_prefix_caching=True); your job is a stable prompt prefix
Max-length cap Size the pool for real requests More concurrent sequences --max-model-len
Context discipline Send fewer, better tokens Better accuracy and lower cost Your prompt and retrieval design

Rules to keep:

  1. KV per token = 2 × layers × KV heads × head_dim × bytes. Read the terms from config.json, check for sliding-window/hybrid/MLA layers, then multiply by tokens in flight.
  2. Decode is bandwidth-bound: ~210 tok/s is the ceiling for an 8B BF16 model on one H100 stream. Batch to amortize weights; shrink the cache to fit more batch.
  3. The advertised window is a ceiling, not a promise. Measure accuracy at your lengths.
  4. Stable prefix first, dynamic content last. It's what makes prefix caching hit.

Next: Post 05 — Prompting, Context Engineering, and RAG: how to decide what goes into that window, and in what order.

Go deeper:


  1. NVIDIA, H100 Tensor Core GPU: H100 SXM 80 GB, 3.35 TB/s memory bandwidth. ↩

  2. Meta Llama 3.1 8B config.json (as mirrored at unsloth/Meta-Llama-3.1-8B): 32 layers, 32 attention / 8 KV heads, hidden 4096, head_dim 128, max_position_embeddings 131072, rope_scaling factor 8.0 over original 8192. ↩↩↩

  3. Qwen, Qwen3-8B config.json: 36 layers, 32 attention / 8 KV heads, head_dim 128. ↩↩

  4. Qwen, Qwen3-8B model card: 8.2B parameters; 32,768 tokens native, 131,072 validated with YaRN; static YaRN "may impact performance on shorter texts." ↩↩

  5. Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019): keys and values shared across all heads; "minor quality degradation." ↩↩

  6. Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023): GQA "achieves quality close to multi-head attention with comparable speed to MQA"; uptraining with 5% of pretraining compute. ↩↩

  7. DeepSeek-AI, DeepSeek-V2 (2024): MLA "reduces the KV cache by 93.3%" and "boosts the maximum generation throughput to 5.76 times" vs DeepSeek 67B. ↩↩↩

  8. DeepSeek-AI, DeepSeek-V3 config.json: 61 layers, 128 attention heads, kv_lora_rank 512, qk_rope_head_dim 64; rope_scaling YaRN factor 40 over original_max_position_embeddings 4096 (128K context per the model card). ↩↩

  9. PyTorch, torch.nn.functional.scaled_dot_product_attention — fused attention backends; enable_gqa parameter. ↩

  10. Gemma Team, Gemma 3 Technical Report (2025): 5:1 local/global interleaving, 1,024-token local span; KV memory overhead 60% (global only) vs <15% (1:3, window 1024) for a 2B model at 32K in the §5.2 ablation. ↩↩↩

  11. OpenAI, gpt-oss-120b & gpt-oss-20b Model Card (2025) — alternating banded-window (bandwidth 128) and dense attention, 64 query heads of dim 64, 8 KV heads, learned softmax-denominator bias per head, 131,072 context via YaRN. ↩↩↩

  12. DeepSeek-AI, DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models (2025) — DeepSeek Sparse Attention reduces attention compute for long contexts. ↩

  13. Qwen, Qwen3-Next-80B-A3B-Instruct model card — 48 layers in a 3× Gated DeltaNet : 1× Gated Attention layout; gated attention 16 Q / 2 KV heads, head dim 256; 262,144 native context. ↩↩↩

  14. Vaswani et al., Attention Is All You Need (2017) — h = 8, d_k = d_v = 64, d_model = 512. ↩

  15. Xiao et al., Efficient Streaming Language Models with Attention Sinks (ICLR 2024): stable inference on "up to 4 million tokens and more." ↩

  16. vLLM docs, Quantized KV Cache: fp8, fp8_e4m3, fp8_e5m2; default scales 1.0; calibration via llm-compressor; --kv-cache-dtype-skip-layers. ↩↩

  17. vLLM team, vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention (2023): "existing systems waste 60% – 80% of memory"; vLLM "a mere waste of under 4%." ↩↩

  18. Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (SOSP 2023): 2–4× throughput at the same latency. ↩

  19. vLLM docs, Automatic Prefix Caching design: block hash of parent hash + tokens + extras, only full blocks cached, LRU eviction, cache_salt isolation. ↩↩

  20. vLLM docs, Engine Arguments: --max-model-len, --gpu-memory-utilization, --kv-cache-dtype, --enable-prefix-caching, --kv-offloading-size. ↩↩

  21. Brown et al., Language Models are Few-Shot Learners (2020): Table 2.1, 2,048-token context. ↩

  22. Meta, The Llama 4 herd (2025): Scout "industry leading 10M" context; pre- and post-trained at 256K. ↩

  23. Anthropic, Context windows: 1M-token window on current models; definition of context rot. ↩↩

  24. Liu et al., Lost in the Middle: How Language Models Use Long Contexts (2023). ↩

  25. Hsieh et al., RULER: What's the Real Context Size of Your Long-Context Language Models? (2024): 17 models, 13 tasks; "only half of them can maintain satisfactory performance at the length of 32K." ↩

  26. Hong, Troynikov, Huber, Context Rot: How Increasing Input Tokens Impacts LLM Performance (Chroma, July 2025): 18 LLMs. ↩

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.