Suppose you load Llama-3.1–8B in BF16 onto a 24 GB GPU. The weights take about 16 GB, so there seems to be plenty of room. Then a user pastes a long document, or a reasoning model thinks for 30,000 tokens, and the server crashes with an out-of-memory error.
The culprit usually isn’t the model. It’s the KV cache.
To generate each new token, attention compares the new token’s query with the keys of every previous token, then mixes their values:
Generating token t new token ──► compute q_t, k_t, v_t │ ├──► append k_t, v_t to the cache ▼ attention = softmax( q_t · [k_1, k_2, …, k_t] / √d ) · [v_1, v_2, …, v_t] ▲ ▲ └──── every past key and value, at every step
Recomputing all past keys and values at every step would be wasteful, so models store them. That store is the KV cache. It trades compute for memory, and the memory grows with every token.
KV cache bytes = 2 × L × H_kv × d_head × T × B × bytes_per_element 2 keys and values L number of layers H_kv number of KV heads d_head dimension per head T sequence length (tokens) B batch size (sequences)
For Llama-3.1–8B (32 layers, 8 KV heads, head dimension 128, BF16 = 2 bytes):
2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB per tokenContext KV cache 4K tokens 0.5 GiB 32K tokens 4 GiB 128K tokens 16 GiB ← as large as the model weights 32K tokens × 8 seqs 32 GiB ← more than the GPU
Every factor in the size formula is a lever, and each family of techniques pulls a different one:
KV bytes = 2 × L × H_kv × d_head × T × B × bytes_per_element │ │ │ │ │ │ │ │ │ └─ Quantization: fewer bits per number │ │ │ └─ Eviction: fewer tokens kept │ │ └─ Low-rank: fewer dimensions per token │ └─ Architecture: fewer KV heads (MQA, GQA, MLA) └─ Cross-layer: fewer layers with their own cacheQuery-aware : same bytes stored, fewer bytes read per step
Three questions help classify any method:
The families also stack. A GQA model can evict unimportant tokens and quantize the ones it keeps. The savings multiply, and so can the errors.
These change the attention design itself, so they must be introduced during pretraining or with additional training.
Trade-off: large, permanent savings, but you can’t apply them to a model that’s already trained.
Keep a fixed budget of tokens and delete the rest. No retraining is needed. The hard part is predicting which cached tokens future queries will need, because eviction is usually permanent.
Trade-off: big savings on long sequences, but a token evicted by mistake can’t come back.
Keep every token, but store each number with fewer bits. Going from 16 bits to 4 bits is a nominal 4x reduction, minus metadata such as scales.
The enemy is outliers: a few huge values force the quantizer to stretch its levels, crushing the small values. Keys in LLMs tend to have outlier channels (the same dimensions are large across tokens).
Trade-off: no token is lost, but quality drops at very low bit widths, and the quantize/dequantize steps cost compute.
Keys and values often live close to a lower-dimensional subspace.
Trade-off: fewer stored dimensions, more compute during attention, and accuracy drops with aggressive rank reduction.
Neighboring layers often produce similar keys and values.
Trade-off: layer-specific details are lost where layers aren’t truly similar.
Keep the full cache, but avoid reading all of it at each step.
Trade-off: saves bandwidth and time, not capacity (unless combined with off).
Bucket What shrinks Training? Examples───────────── ─────────────── ──────────────── ────────────────────────────────Architectural KV heads / size Yes MQA, GQA, MLA, sliding windowEviction Tokens (T) No StreamingLLM, H2O, SnapKV, PyramidKV, R-KV, TriAttentionQuantization Bits per number No (some calib.) KIVI, KVQuant, QJL, PolarQuant, TurboQuantLow-rank Dims per token Post-training PaluCross-layer Layers (L) CLA yes, MC no CLA, MiniCacheQuery-aware Bytes read No Quest, off
Now for the two deep dives: TurboQuant (how to store each kept number in very few bits) and TriAttention (how to decide which tokens to keep).
TurboQuant (Zandieh, Daliri, Hadian, and Mirrokni, 2025) is a vector quantization method. Applied to LLMs, it quantizes the KV cache, not the model weights. Its standout property is that it’s data-oblivious: no calibration, no per-model tuning, and almost no setup time, so it can quantize each new token as it’s generated.
Quantizing with b bits means snapping each number to one of 2^b levels. Try 2 bits (4 levels) on a spiky vector:
x = [8.0, 0.1, -0.1]Uniform 2-bit levels covering [-8, 8]: -6 -2 +2 +6 8.0 → +6 0.1 → +2 (20x too large)-0.1 → -2 (20x too large)
The single outlier forces wide spacing, so the small values are destroyed. Real key vectors have exactly this kind of spike.
TurboQuant’s fix has three ideas:
OFFLINE (once per head dimension d and bit width b) ├─ 1. Draw a random rotation Π (d × d) QR decomposition of a Gaussian matrix ├─ 2. Build the codebook c_1 … c_(2^b) Lloyd-Max on the coordinate distribution └─ 3. Draw a Gaussian matrix S (d × d) inner-product variant onlyONLINE (every new key or value vector x) x │ 1. n = ‖x‖, u = x / n store the norm n ▼ u │ 2. y = Π · u spread the energy ▼ y │ 3. idx_j = index of nearest centroid to y_j ▼ idx ──► store (idx, n) ◄── TurboQuant-MSE stops here │ │ Inner-product variant (idx uses b − 1 bits): │ 4. û = Πᵀ · c[idx] reconstruct │ 5. r = u − û, γ = ‖r‖ residual and its length │ 6. z = sign(S · r) 1 bit per coordinate ▼ store (idx, z, γ, n) ◄── TurboQuant-prodATTENTION (a query q arrives) q′ = Π · q, q″ = S · q once per query, reused for every key q·x ≈ n · ( ⟨q′, c[idx]⟩ + γ · √(π/2) / d · ⟨q″, z⟩ )
The rest of this section explains each step with an example.
Take an illustrative key vector, say for the token “caleb” (a made-up example, not a real embedding):
x = [8.0, 0.1, -0.1]‖x‖ = √(8.0² + 0.1² + 0.1²) = 8.00125u = x / ‖x‖ = [0.99984, 0.01250, -0.01250] ← unit length, still spiky
The norm 8.00125 is stored separately (one 16-bit number per vector) so the vector can be rescaled later.
Multiply by an orthogonal (rotation) matrix. Here is a fixed 3×3 one for illustration; TurboQuant draws a random one:
┌ 0.577 0.577 0.577 ┐ rows are 1/√3, 1/√2, and 1/√6 multiplesΠ = │ 0.707 -0.707 0.000 │ └ 0.408 0.408 -0.816 ┘y = Π · u = [0.57726, 0.69816, 0.42349]
The energy that was piled into one coordinate is now spread across all three.
Doesn’t this just turn numbers we understand into numbers we don’t? No:
Each rotated coordinate is a weighted sum of all input coordinates, with random weights:
y_i = Π_i1·u_1 + Π_i2·u_2 + … + Π_id·u_d
A sum of many small random contributions tends toward a bell curve. That’s the intuition behind the central limit theorem, and here it’s made exact by geometry: a randomly rotated unit vector is a uniformly random point on the sphere, and each coordinate of such a point follows a known (scaled Beta) distribution:
mean of y_i = 0variance of y_i = 1/dtypical size |y_i| ≈ 1/√d (exact RMS, since Σ y_i² = 1)d = 3 y_i ~ Uniform[-1, 1] flatd = 16 bell-shaped Beta, std 0.25d = 128 ≈ Normal(0, 1/128), std ≈ 0.088 narrow, Gaussian-like
The 0.577 = 1/√3 in our example is the typical magnitude of a coordinate in 3 dimensions (its root-mean-square). The mean is 0, and the variance is 1/3. As d grows, the distribution gets narrower and closer to a Gaussian.
This holds for any input direction, whether the text was English, code, or HTML. It’s a property of the random rotation, not of the data. That’s what makes a single precomputed codebook possible.
A second, subtler benefit: in high dimensions, different rotated coordinates become nearly independent. So each coordinate can be quantized on its own with a 1-D quantizer, and that’s still close to optimal for the whole vector.
Since the coordinate distribution is known, the best possible levels (centroids) can be computed once. Lloyd-Max is 1-D k-means on a continuous distribution:
repeat until stable: 1. boundaries = midpoints between neighboring centroids 2. centroids = average of the distribution inside each cell
This runs once per (d, b) pair, and the result is stored in a lookup table. A few published high-dimensional codebooks:
1 bit: ±0.798/√d d = 128 → ±0.07052 bits: ±0.453/√d, ±1.51/√d d = 128 → ±0.0400, ±0.1335
For our 3-D toy, the coordinates are uniform on [-1, 1], so the optimal 2-bit codebook is evenly spaced:
codebook: c_0 = -0.75 c_1 = -0.25 c_2 = 0.25 c_3 = 0.75y = [0.57726, 0.69816, 0.42349]nearest = 0.75 0.75 0.25idx = 3 3 2 → stored as bits 11 11 10
To reconstruct: look up the centroids, rotate back, and rescale:
ŷ = [0.75, 0.75, 0.25]û = Πᵀ · ŷ = [1.0654, 0.0047, 0.2289]x̂ = 8.00125 · û = [8.525, 0.038, 1.831] original: [8.0, 0.1, -0.1]squared error (unit vector): ‖y − ŷ‖² = 0.0626
Three dimensions at 2 bits is very crude, but notice the error is spread evenly rather than wiping out the small coordinates. Mean squared error (MSE) measures this:
MSE(x, x̂) = (1/d) · Σ_i (x_i − x̂_i)²
The paper reports its distortion as the total squared error for a unit vector, ‖u − û‖² (d times the per-coordinate MSE). In high dimensions:
bits per coordinate 1 2 3 4expected ‖u − û‖² 0.36 0.117 0.03 0.009
The error drops about 4x for every extra bit. The paper proves this is within a factor of about 2.7 of the best that any quantizer can achieve at the same bit width.
For a head dimension of 128:
BF16: 128 × 16 bits = 2048 bitsTurboQuant 2-bit: 128 × 2 bits + 16-bit norm = 272 bits ≈ 7.5x smallerTurboQuant 3-bit: 128 × 3 bits + 16-bit norm = 400 bits ≈ 5.1x smaller
Attention doesn’t use keys directly. It uses dot products q·k. A quantizer can have a small MSE and still give systematically wrong dot products.
Rounding to the nearest centroid shrinks or stretches vectors in a consistent direction. At 1 bit, the TurboQuant paper shows that the MSE-optimal quantizer gives, on average:
E[ q · x̂ ] = (2/π) · (q · x) ≈ 0.64 · (q · x)
Every attention logit shrinks by about 36% on average. That makes the softmax flatter, so the model attends less sharply. The bias fades at higher bit widths but doesn’t vanish. It comes from the deterministic rounding, not simply from the codebook being precomputed.
For a target of b bits per coordinate:
┌──────── b − 1 bits ────────┐┌─ 1 bit ─┐MSE codebook index (Part A) QJL sign of the residuale.g. b = 3: 2 bits MSE + 1 bit QJL, for each of the d coordinates
The dimension stays d; only the bits are split. The steps are:
1. Quantize u with TurboQuant-MSE at b − 1 bits → û2. Residual r = u − û (small, since MSE is small)3. γ = ‖r‖, and z = sign(S · r) (S: random Gaussian d × d matrix)4. Store idx, z, γ (one extra 16-bit number), and n
Each row s of S defines a random hyperplane, and sign(s · r) records which side of it r falls on. Many random hyperplanes together reveal r’s direction. For a Gaussian row s and any query q:
E[ (s · q) · sign(s · r) ] = √(2/π) · (q · r) / ‖r‖
So averaging over all d rows and correcting the constant gives an unbiased estimate:
q · r ≈ γ · √(π/2) / d · ⟨S·q, z⟩
q · u = q · û + q · r ≈ q · û + γ · √(π/2)/d · ⟨S·q, z⟩ └ MSE part ┘ └──── QJL correction ────┘
The MSE stage makes the residual small, and QJL estimates its contribution without bias. So the combined estimate is unbiased: correct on average over the random rotation and projection. Individual estimates still have some variance, which shrinks as the bit width grows.
From the TurboQuant paper:
Component Why it's there──────────────────────── ─────────────────────────────────────────────────Normalize + store norm Quantize the direction; keep the scale exactlyRandom rotation Π Makes coordinates predictable for any inputLloyd-Max codebook Optimal levels for that known distribution, offlinePer-coordinate rounding Near-independence makes 1-D quantization near-optimal1-bit QJL on residual Removes dot-product bias at the cost of one bitRotate the query once Avoids de-rotating every cached key
Limitations: extra compute for the rotation and projection, per-vector metadata (norms), quality loss at very low bit widths, and results that are measured on specific models and benchmarks.
TriAttention (Mao, Lin, Huang, et al., 2026, Efficient Long Reasoning with Trigonometric KV Compression) is a training-free token eviction method built for long reasoning, where the cache grows throughout generation. Where TurboQuant asks how many bits each token needs, TriAttention asks which tokens are worth keeping at all.
This is a common point of confusion, so it’s worth stating up front. RoPE and attention are not modified. Every decoding step runs exactly as usual: compute q, k, and v, apply RoPE, append to the cache, and run standard attention (FlashAttention or similar) over whatever is in the cache.
TriAttention is a periodic side step that decides which cache entries to delete. Its “pre-RoPE” math is used only to rank keys; the scores are thrown away after each pruning round. NVIDIA’s TensorRT-LLM guide describes it the same way: a pure compression method, with decode running the model’s standard attention over the compacted cache.
Rotary Position Embedding (RoPE) splits each d-dimensional query and key into d/2 pairs of numbers. Think of each pair as a clock hand (a 2-D vector, or one complex number). At position p, RoPE spins hand f by an angle ω_f·p, and every hand spins at a different speed:
ω_f = θ^(−2f/d), θ = 10000 typicallyband f = 0 fastest hand (completes a turn every ~6 tokens)…band f = d/2−1 slowest hand (barely moves over thousands of tokens)
The vectors before spinning are pre-RoPE; after spinning, they are post-RoPE. When a query at position p_q meets a key at position p_k, only their distance Δ = p_q − p_k matters, and the attention logit becomes:
logit(q, k) = Σ_f ‖q_f‖ · ‖k_f‖ · cos(ω_f·Δ + φ_f)q_f, k_f pre-RoPE components in band f (complex numbers)φ_f arg(q_f) − arg(k_f), their angle difference
Most eviction methods (H2O, SnapKV, R-KV) score keys by the attention they get from recent post-RoPE queries. But post-RoPE queries keep rotating as positions advance, so only the very latest queries reflect where future queries will point. Older queries are effectively pointing in stale directions.
The usable observation window is tiny. The TriAttention paper cites prior work in which accuracy peaked with a window of about 25 queries and got worse with larger windows. With so few observers, a key that’s quiet during the window but crucial later (common for retrieval-style heads, and fatal in long reasoning) gets evicted forever.
Post-RoPE view (what other methods observe)position: 1 ──────────────────────────────── t−25 ── t queries: rotated far away (stale) │ usable │ └─ ~25 ──┘
Look before RoPE and something striking appears: in most heads, query vectors (and key vectors) cluster tightly around a fixed, non-zero center, and that center barely changes across positions or input content.
The paper measures this with the Mean Resultant Length:
R = ‖E[q]‖ / E[‖q‖] (length of the average ÷ average length)Tight cluster: q = [1, 0], [0.9, 0.1], [1, −0.1] ‖mean‖ = 0.9667, mean ‖q‖ = 0.9702 → R = 0.996Spread out: q = [1, 0], [−1, 0], [0, 1], [0, −1] ‖mean‖ = 0, mean ‖q‖ = 1 → R = 0
R near 1 means all vectors point roughly the same way. In Qwen3–8B, roughly 90% of heads have R above 0.95, with nearly identical values on math, code, and chat data. That suggests it’s a property of the model, not the input. The paper also finds it in other architectures it tested: Qwen2.5 and Llama3 variants (GQA), and an MLA model (GLM-4.7-Flash, where 96.6% of heads exceed R = 0.95). That’s evidence across tested models, not a guarantee for every model.
If queries and keys barely move, replace them with their centers q̄_f and k̄_f. Then everything in the logit is constant except the distance:
logit(Δ) ≈ Σ_f ‖q̄_f‖ · ‖k̄_f‖ · cos(ω_f·Δ + φ̄_f) = Σ_f [ a_f · cos(ω_f·Δ) + b_f · sin(ω_f·Δ) ]
That’s a trigonometric series in Δ (hence the name). The centers set the coefficients, and the coefficients draw an attention-versus-distance curve for each head. Some heads prefer nearby tokens, others prefer far ones (such as attention sinks at the start).
A one-band example: let ω = 0.1, ‖q̄‖·‖k̄‖ = 1, and φ̄ = −2.
logit(Δ) ≈ cos(0.1·Δ − 2) peaks when 0.1·Δ = 2 → Δ = 20attention ▲ ╭─╮ │ ╱ ╲ │ ╱ ╲ │ ───╯ ╰───── └───────────────────► distance Δ 20
This head “likes” keys about 20 tokens back. A single band repeats periodically, but real heads add up many bands with geometrically spaced speeds, giving rich, non-repeating preferences over practical context lengths.
Does this prediction match reality? On Qwen3–8B the predicted curve correlates with real attention logits (Pearson r = 0.72 for the paper’s example head), and mean correlations exceed 0.5 across the Qwen3, Qwen2.5, and Llama3 models tested.
Cached keys are known exactly, so TriAttention uses each key’s real pre-RoPE components. Future queries aren’t known, so it substitutes the query center, measured offline.
The cache stores post-RoPE keys. Undoing the rotation is cheap and exact:
stored: k̃_f = k_f · e^(i·ω_f·p_k)recovered: k_f = k̃_f · e^(−i·ω_f·p_k) (‖k_f‖ is unchanged)
S_trig(k, Δ) = Σ_f ‖E[q_f]‖ · ‖k_f‖ · cos(ω_f·Δ + φ_f)φ_f = arg(E[q_f]) − arg(k_f) angle between the query center and this key
A worked example with the one-band head above. Assume both keys share the angle that gives φ = −2:
Key A: distance 20, ‖k‖ = 1.0 → S_trig = 1.0 · cos(0.1·20 − 2) = 1.0 · cos(0) = +1.00Key B: distance 100, ‖k‖ = 1.5 → S_trig = 1.5 · cos(0.1·100 − 2) = 1.5 · cos(8) = −0.22→ keep A, evict B, even though B has the larger norm
The trigonometric score assumes queries sit exactly at their center. Where they wander more, a norm-based signal helps:
S_norm(k) = Σ_f (1 − R_f) · E[‖q_f‖] · ‖k_f‖Tight cluster (R_f ≈ 1): 1 − R_f ≈ 0 → S_trig dominates (distance decides)Loose cluster (R_f ≪ 1): 1 − R_f large → S_norm matters more (magnitude decides)
The weighting is per frequency band, so it adapts automatically. The norm term also catches keys with tiny norms, which get little attention whatever their distance.
A key will be queried from many future positions, not just the current one. So the combined score S = S_trig + S_norm is averaged over geometrically spaced future offsets:
S̃(k) = (1/|D|) · Σ_{δ ∈ D} S(k, Δ + δ)D = {1, 2, 4, 8, …, 2^16} (17 offsets)
Geometric spacing samples near distances densely and far ones sparsely. In the paper’s ablation, it beat linear spacing by a wide margin (45.8% versus 28.7% on AIME24).
In GQA, one KV head serves G query heads, each with its own calibration statistics and its own score scale. TriAttention scores each key once per query head, z-score normalizes each head’s scores, then takes the maximum:
Ŝ_g(k) = ( S̃_g(k) − μ_g ) / σ_g normalize within query head gS_final(k) = max over g of Ŝ_g(k) keep if ANY head wants it
Instead of asking recent queries which keys they liked, ask which keys a typical query is predicted to like at many future distances, using centers measured once offline.
calibration text (e.g. ~50K–1M tokens) │ ▼run the model, capture pre-RoPE queries, per layer and per head │ ▼for each band f: E[q_f] query center (complex number) E[‖q_f‖] expected query norm R_f concentration = ‖E[q_f]‖ / E[‖q_f‖] │ ▼save to a calibration .pt file ──► reused for every request
Calibration is robust. The paper found stable accuracy from 50K to 960K calibration tokens, and comparable accuracy whether it calibrated on reasoning text, code, or even raw HTML from a web homepage.
prompt ──► prefill ──► KV cache (post-RoPE keys, values) │ ┌────────────▼─────────────┐ │ decode loop, per token: │ │ q,k,v → RoPE(q,k) → │ │ append k,v → standard │ │ attention over the cache │ └────────────┬─────────────┘ │ every β = 128 generated tokens ▼ TriAttention pruning round
Triggered when a 128-token window completes and the cache exceeds the budget B (2,048 tokens by default). For each layer and KV head:
1. Undo RoPE on cached keys k_f = k̃_f · e^(−i·ω_f·p_k)2. Distance to the current position Δ = p_now − p_k3. Score against each query head g S_trig + S_norm, averaged over 17 offsets4. Combine across the G query heads z-normalize, then max5. Keep the top-B keys, evict the rest physically compact the cache
The model continues with the smaller cache. Kept keys still carry the RoPE rotation from their original positions, and new tokens keep counting from the true sequence position, so relative distances stay correct.
With B = 2,048 and β = 128:
generated: 128 256 … 2048 2176 2304 2432cache: 128 256 … 2048 2176 → 2048 2176 → 2048 2176 → 2048 ▲ prune ▲ prune ▲ prunepeak ≈ B + β = 2,176 tokens, no matter how long generation runs
For Qwen3–8B (36 layers, 8 KV heads, head dimension 128, BF16), that’s 144 KiB per token: 4.5 GiB for a 32K-token trace with full attention, versus about 288 MiB at a 2,048-token budget.
Component Role───────────────────────────── ──────────────────────────────────────────────Pre-RoPE space Removes position spin, so centers are stableCalibrated query centers Stand in for future queries; no window neededTrigonometric series Turns centers into an attention-vs-distance curveNorm term weighted by (1 − R) Covers heads and bands with looser clustersMulti-offset averaging Hedges over when a key will be neededZ-normalize then max (GQA) Keeps any key that any query head needsWindowed pruning (β = 128) Spreads the scoring cost over many tokens
From the paper (Qwen3–8B unless noted):
Limitations: eviction is permanent, and at the deepest recursion levels of the paper’s memory benchmark, accuracy fell behind full attention. The method relies on RoPE structure and per-model calibration. Evaluation centers on math reasoning (plus LongBench and RULER), and the authors list coding, agentic tasks, and dedicated kernels as future work.
TurboQuant TriAttention─────────────────── ────────────────────────────── ──────────────────────────────Bucket Quantization EvictionQuestion answered How many bits per number? Which tokens to keep?What is lost Precision (every token kept) Whole tokens (permanently)Setup None (data-oblivious) One-time calibration per modelCore trick Random rotation → known Pre-RoPE Q/K centers → distribution → fixed codebook predicted distance preferenceMath tools Beta/Gaussian, Lloyd-Max, QJL RoPE, trigonometric series, RWhen it runs Every new token Every 128 generated tokensTypical gain ~4.5x+ at 2.5–3.5 bits up to 10.7x memory, 2.5x speedBest for Keeping all context, cheaply Very long generation
TurboQuant and TriAttention
Architectural
Token eviction and selection
Quantization
Low-rank, cross-layer, and system-level
Shrinking the KV Cache: An End-to-End Guide to KV Compression, with Deep Dives into TurboQuant and… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.