Chapter 19 derived the bound \(\|o - \hat o\|_2 \le 2\sum_C R_C\). This chapter follows the rest of [refinekv]: how the risk score becomes a decoding algorithm (Section 4), how it is shared by grouped query heads, what the GPU kernel saves and why that is a speedup (Appendix B.2), and how to read the experiments (Section 5, Appendices B.3 and C) without believing more than they show. It ends with the limits of the method (Section 7 and what the bound itself leaves out) and a toy RefineKV in C that reproduces the main trade-off on synthetic keys.
The chapter leans on the KV cache and why decoding is memory-bound (sections 17.3 and 17.4), on online softmax and merging partial results (sections 15.4 and 15.5), and on Spearman and partial correlation (sections 13.4 and 13.5).
The motivation (Section 2, and section 17.6): each query needs only a small part of the cache, but different queries need different parts, so the cache must be kept whole and the part read must depend on the query. RefineKV decides at the level of blocks, from summaries, and never inspects a token it does not read.
After the prompt's KV cache is computed, it is cut into contiguous blocks of \(|C| = 32\) tokens (Section 5.1; Appendix B.2). The paper calls them clusters in Section 3 and blocks in B.2; they are the same thing. For each block it stores (B.2):
The original keys and values stay where they are: nothing is evicted.
Each of the three sums can be computed on its own as a partial result \((m, \ell, a)\): running maximum, sum of weights, weighted sum of values. The partials are merged exactly by rescaling to a common maximum (section 15.5). That is what B.2 means by “the three types of contributions are merged using online softmax”. With \(E\) empty and no suffix, \(\hat o_E\) is the \(\hat o\) of chapter 19; with \(E\) all blocks it is the exact \(o\).
The paper's Figure 3 is internally consistent. It shows four blocks with \(\hat p_C\), \(\delta_C^{\text{bound}}\) and \(R_C\). Eq. 4 has two unknowns per figure, the shared \(V_{\max}/S\) and the blocks' \(V_C\). Assuming one \(V_C\) for all four blocks and solving from blocks 1 and 4 gives \(V_{\max}/S = 1.25 \times 10^{-6}\) and \(V_C = 9.99\). These two numbers reproduce the other two scores, 0.0268 and 0.0025, to the digits shown (our arithmetic). The large-\(\delta\) behaviour of chapter 19 is visible: block 1, with importance \(4.8 \times 10^{-4}\) but \(\delta = 23.44\), scores 4.56 and is expanded, while block 2, nearly five times more important but with \(\delta = 14.90\), scores 0.0268.
Optional: query anchors (B.1). The queries of the last \(Q\) prompt positions select blocks once at prefill, and those stay expanded throughout decoding, in addition to the per-query choice. The main results use \(Q = 0\).
With grouped-query attention (section 16.6; [gqa]) several query heads share one KV head: four per KV head in Llama-3.1-8B and seven in Qwen2.5-7B (C.2.1). Each query head has its own \(q\), so its own scores \(R_C^{(h)}\). But expansion is a decision about which keys and values to read, and those belong to the KV head, so all query heads in a group must use one expansion set (Section 4). Two rules:
The mean of numbers is never above their maximum, so every block that GQA-mean expands, GQA-any expands too. GQA-any reads more and errs less. It is also the rule that keeps the per-head reasoning of chapter 19: a block is approximated only if every head that reads it scored it at most \(\tau\). Table 3 measures the trade on Llama-3.1-8B and RULER-128K: GQA-mean reaches 68.82 accuracy at 1.62\(\times\) against 70.19 at 1.56\(\times\) for GQA-any. The toy of section 20.6 shows the same direction.
A larger group expands more under GQA-any, because one head out of seven above \(\tau\) suffices. Qwen2.5-7B has the larger group and also smaller speedups (Table 14: 1.19\(\times\) against 1.56\(\times\) for Llama on RULER at \(\tau = 0.01\)). The paper does not give the reason. A second plausible cause is in the next section: Qwen's cache is smaller, so attention is a smaller share of its decode step.
A sparse algorithm only saves time if it saves memory traffic. Batch-one decoding is memory-bound (section 17.4): each step reads every weight once for the GEMVs and every cached key and value once for attention, and does a few flops per byte. Time is bytes divided by bandwidth.
The bytes. A token's cache entry is \(2 \times \text{layers} \times \text{KV heads} \times \text{head dim} \times 2\) bytes in BF16 (section 17.3). For Llama-3.1-8B (32 layers, 8 KV heads, dim 128) that is 131,072 bytes; at the paper's 130,944-token prompts, 17.16 GB per step. For Qwen2.5-7B (28 layers, 4 KV heads) it is 57,344 bytes per token, 7.51 GB. The weights of an 8-billion-parameter model are about 16 GB in BF16.
The time. Figure 5 splits a Llama-3.1-8B decode step at 128K in BF16: attention 11.72 ms, GEMV 10.76 ms, other 2.30 ms, total 24.78 ms. Dividing bytes by time, attention moves the cache at 1.46 TB/s and the GEMVs move the weights at about 1.49 TB/s (our arithmetic). Both run at the same rate, as two memory-bound kernels on the same GPU should; and with about as many cache bytes as weight bytes, attention takes about half the step.
What RefineKV reads. An unexpanded block costs four \(d\)-vectors (\(\bar k_C\), \(\bar v_C\), \(k^{\min}_C\), \(k^{\max}_C\)) instead of 64 (32 keys and 32 values), so \(1/16\) of a block. If a share \(f\) of blocks is expanded, the attention reads about
\[ f + (1 - f)\cdot\tfrac{4}{64} \]of the full cache. Table 15 gives the measured \(f\) at 128K: 11.2% at \(\tau = 0.01\) and 4.0% at \(\tau = 0.1\). That is 0.168 and 0.100 of the bytes: 6.0\(\times\) and 10.0\(\times\) fewer (our estimate, ignoring the scalars). Figure 5 reports a 7.61\(\times\) attention speedup, between the two; the figure does not say which \(\tau\) it used.
Amdahl. Only the attention term shrinks. Even at zero attention cost the step would take \(10.76 + 2.30 = 13.06\) ms, a ceiling of \(24.78/13.06 = 1.90\times\). The measured 14.89 ms (1.66\(\times\)) is close to that ceiling: the GEMVs, not attention, now dominate. Figure 5's FP8 run halves the GEMV time (5.77 ms) and the speedup rises to 2.00\(\times\). The same reasoning gives the short-context limit of C.7: at 16K attention is about 2 ms of a 14.46 ms step, so no attention method can exceed \(14.46/12.46 = 1.16\times\) (the paper says “roughly 1.2\(\times\)”).
The implementation (B.2). Custom Triton kernels [triton]. A block-selection kernel processes all the query heads of a KV head together, computes \(s_C\), \(\delta_C^{\text{bound}}\) and \(R_C\) for every block, applies GQA-any, and writes a mask that stays on the GPU: no round trip to the CPU to decide what to read. The sparse-attention kernel reads that mask, loads token-level K/V from the original cache only for selected blocks, uses the cached representatives for the others, processes the suffix exactly, and merges the three by online softmax, with BF16 tensor-core products and FP32 accumulation. The cache is preallocated and every workspace reused, so the whole decode step can be captured once in a CUDA Graph and replayed per token, which removes per-kernel launch overhead. Full attention and the baselines are timed under the same CUDA Graph protocol. Without it (C.6, Table 14) RefineKV's speedups are 3–6% lower, because it launches more small kernels than full attention.
Watch out. B.2 says the kernel caches “diagonal-ellipsoid bound statistics”, while Section 5.3 and Table 3 name the box summary as the default and report that the box beats the ellipsoid. The paper does not say which statistics the default runs store; both are cheap.
The abstract claims “up to 7.6\(\times\) speedup in the attention phase and 1.66\(\times\) faster decoding”. Both come from Figure 5: one model (Llama-3.1-8B), one input length (128K), BF16, with the bars labelled “Attention: 7.61\(\times\)” and “TPOT: 1.66\(\times\)”. The figure's bars are consistent: \(11.72 + 10.76 + 2.30 = 24.78\), \(24.78/14.89 = 1.664\), and \(11.72\) over RefineKV's attention-plus-selection time (\(14.89 - 11.04 - 2.32 = 1.53\) ms) is 7.66, which matches 7.61 up to the rounding of the bars. Figure 5 does not state \(\tau\). Its 1.66\(\times\) matches the \(\tau = 0.1\) rows of Table 3 (1.67\(\times\)) and Table 14 (1.67\(\times\) on RULER and LongBench), not the \(\tau = 0.01\) default (1.56\(\times\)).
At the conservative \(\tau = 0.01\), Section 5.2 says “up to a 1.55\(\times\) decode speedup”, while the caption of Figure 4 says “up to 1.56\(\times\)” and Table 14 lists 1.56\(\times\). Treat it as 1.56\(\times\), on Llama, RULER. On Qwen2.5-7B the same setting gives 1.13–1.19\(\times\) (Table 14).
Figure 4 plots, for each model and benchmark, quality against TPOT on a log scale. A point is on the Pareto frontier if no other point is both faster and better. What is controlled: hardware, prompts, the CUDA Graph timing protocol (C.2.3), and the quality metric. What is not:
All ablations use one model and one benchmark (Llama-3.1-8B, RULER-128K): they say which design is better there, not in general. Table 3 changes one setting at a time: \(\tau\) is the main knob (\(\tau = 0.001\): 73.63 accuracy at 1.28\(\times\); \(\tau = 1\): 34.67 at 1.69\(\times\)); block sizes 16 and 64 change accuracy by under 0.2. Table 2 is the more careful design: it fixes the per-head token budget to the one RefineKV chose and changes only the score that ranks blocks. That isolates the ranking. Against RefineKV's 70.27 (\(\tau = 0.01\) budget): importance alone (\(\hat p_C\)) 59.35, spread alone (\(\delta_C\)) 47.23, a Quest-style bound 66.38, and the oracle with exact \(\delta_C\) 72.00. Neither factor alone is enough; their product is the point of Eq. 4. The deltas printed in Table 2 agree with the accuracies to within 0.01 (rounding).
The question: does \(R_C\) track the error a block actually causes? The target is \(\|o_C - \hat o_C\|\), with \(o_C = p_C v_C\) and \(\hat o_C = \hat p_C \bar v_C\), the block's share of \(o - \hat o\). For each (step, layer, head) the paper takes the Spearman correlation across blocks (section 13.4) and reports the median over instances.
The default configuration on Llama RULER-128K scores 70.27 in Tables 2, 12 and 15 and 70.19 in Tables 3, 4, 14 and 16; full attention scores 73.37 everywhere but Table 15 (73.35). Table 4 gives 1.42\(\times\) for \(Q = 32\) where Table 3 gives 1.43\(\times\) for the same TPOT (\(24.43/17.14 = 1.425\)). C.7 says RefineKV's TPOT stays within 14.4–15.7 ms; Table 15's full TPOT divided by its speedups gives 14.32–15.66. None changes a conclusion; they show that tables were produced by different runs.
The toy follows section 20.1 on synthetic data and measures three things as \(\tau\) varies: the share of blocks expanded, the bytes read, and the relative output error \(\|\hat o_E - o\|/\|o\|\). Two comparisons ride along: GQA-mean against GQA-any (section 20.2), and, at the same number of expanded blocks, expanding the blocks of largest \(\hat p_C\) instead of largest \(R_C\), the toy version of the “\(\hat p_C\)” row of Table 2.
The cache has \(N = 8192\) tokens, \(d = d_v = 64\), blocks of 32, so 256 blocks. Keys come in segments of 40 to 439 tokens that share a random “topic” vector plus small noise; values likewise. This is the local structure that makes contiguous blocks work: most blocks lie inside one segment and have a small spread under any query, a few straddle a boundary. Four query heads share each KV head, and there are 64 decode steps.
/* toy.c: a toy RefineKV. Blocks of 32 keys, box bound, risk scores, expand above tau,
one attention over the mixed set merged by online softmax. */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define N 8192 /* cached tokens */
#define D 64 /* head dimension (keys and values) */
#define B 32 /* block size |C| */
#define NB (N / B)
#define H 4 /* query heads sharing one KV head (GQA) */
#define STEPS 64 /* decode queries */
static double k[N][D], v[N][D], kb[NB][D], vb[NB][D], lo[NB][D], hi[NB][D], VC[NB], Vmax;
static double U(void) { return (rand() + 0.5) / (RAND_MAX + 1.0); }
static double G(void) { return sqrt(-2 * log(U())) * cos(6.283185307179586 * U()); }
static double dot(const double *a, const double *b) { double s = 0; for (int j = 0; j < D; j++) s += a[j] * b[j]; return s; }
typedef struct { double m, l, acc[D]; } Run; /* online softmax state */
static void push(Run *r, double s, const double *val)
{
if (s > r->m) { double c = exp(r->m - s); r->l *= c; for (int j = 0; j < D; j++) r->acc[j] *= c; r->m = s; }
double e = exp(s - r->m);
r->l += e;
for (int j = 0; j < D; j++) r->acc[j] += e * val[j];
}
static void merge(Run *a, const Run *b) /* fold partial b into a */
{
double m = fmax(a->m, b->m), ca = exp(a->m - m), cb = exp(b->m - m);
a->l = a->l * ca + b->l * cb;
for (int j = 0; j < D; j++) a->acc[j] = a->acc[j] * ca + b->acc[j] * cb;
a->m = m;
}
static Run empty(void) { Run r = { -INFINITY, 0, {0} }; return r; }
/* output with blocks where ex[c] != 0 exact, the rest by (kbar + log B, vbar); relative error */
static double attend(const double *q, const char *ex)
{
Run full = empty(), exact = empty(), rep = empty();
double sq = sqrt(D), e2 = 0, o2 = 0;
for (int c = 0; c < NB; c++) {
for (int i = c * B; i < (c + 1) * B; i++) {
double s = dot(q, k[i]) / sq;
push(&full, s, v[i]);
if (ex[c]) push(&exact, s, v[i]);
}
if (!ex[c]) push(&rep, dot(q, kb[c]) / sq + log(B), vb[c]);
}
merge(&exact, &rep);
for (int j = 0; j < D; j++) {
double o = full.acc[j] / full.l, oh = exact.acc[j] / exact.l;
e2 += (o - oh) * (o - oh); o2 += o * o;
}
return sqrt(e2 / o2);
}
/* risk scores R_C of Eq. 4 with the box bound of A.7.1 */
static void risk(const double *q, double *R, double *ph)
{
double sq = sqrt(D), s[NB], dl[NB], mx = -1e300, z = 0, den = 0;
for (int c = 0; c < NB; c++) {
double up = 0, dn = 0;
s[c] = dot(q, kb[c]) / sq;
for (int j = 0; j < D; j++) { up += fmax(q[j] * lo[c][j], q[j] * hi[c][j]); dn += fmin(q[j] * lo[c][j], q[j] * hi[c][j]); }
dl[c] = fmax(up / sq - s[c], s[c] - dn / sq);
if (s[c] > mx) mx = s[c];
}
for (int c = 0; c < NB; c++) z += exp(s[c] - mx);
for (int c = 0; c < NB; c++) { ph[c] = exp(s[c] - mx) / z; den += ph[c] * cosh(dl[c]); }
for (int c = 0; c < NB; c++) R[c] = ph[c] * (Vmax * (cosh(dl[c]) - 1) / den + VC[c] * tanh(dl[c] / 2));
}
int main(void)
{
static double R[STEPS][H][NB], P[STEPS][H][NB], q[STEPS][H][D];
double taus[] = { 1e-4, 1e-3, 1e-2, 0.03, 0.1, 0.3, 1, INFINITY }, full = (double)N * 2 * D;
srand(20);
for (int i = 0; i < N;) { /* segments: keys near a topic, values near another */
double t[D], w[D];
int len = 40 + rand() % 400;
for (int j = 0; j < D; j++) { t[j] = G(); w[j] = G(); }
for (; len-- > 0 && i < N; i++)
for (int j = 0; j < D; j++) { k[i][j] = t[j] + 0.4 * G(); v[i][j] = w[j] + 0.5 * G(); }
}
for (int c = 0; c < NB; c++) { /* prefill: representatives and box metadata */
VC[c] = 0;
for (int j = 0; j < D; j++) { kb[c][j] = vb[c][j] = 0; lo[c][j] = 1e300; hi[c][j] = -1e300; }
for (int i = c * B; i < (c + 1) * B; i++) {
for (int j = 0; j < D; j++) {
kb[c][j] += k[i][j] / B; vb[c][j] += v[i][j] / B;
lo[c][j] = fmin(lo[c][j], k[i][j]); hi[c][j] = fmax(hi[c][j], k[i][j]);
}
VC[c] = fmax(VC[c], sqrt(dot(v[i], v[i])));
}
Vmax = fmax(Vmax, VC[c]);
}
for (int t = 0; t < STEPS; t++) { /* queries: near some earlier key, varied sharpness */
int at = rand() % N;
for (int h = 0; h < H; h++) {
double a = 0.2 + U();
for (int j = 0; j < D; j++) q[t][h][j] = a * (k[at][j] + 0.8 * G());
risk(q[t][h], R[t][h], P[t][h]);
}
}
printf(" tau policy expanded bytes read mean err max err | p-hat top-k, same budget\n");
for (int x = 0; x < 8; x++)
for (int pol = 0; pol < 2; pol++) { /* 0: GQA-any, 1: GQA-mean */
double nexp = 0, err = 0, emax = 0, perr = 0;
if (pol == 1 && taus[x] != 1e-2 && taus[x] != 0.1) continue;
for (int t = 0; t < STEPS; t++) {
char ex[NB], top[NB];
int cnt = 0;
double key[NB];
for (int c = 0; c < NB; c++) {
double mx = 0, mean = 0, pm = 0;
for (int h = 0; h < H; h++) { mx = fmax(mx, R[t][h][c]); mean += R[t][h][c] / H; pm = fmax(pm, P[t][h][c]); }
ex[c] = (pol ? mean : mx) > taus[x];
cnt += ex[c]; key[c] = pm; top[c] = 0;
}
for (int e = 0; e < cnt; e++) { /* the cnt blocks of largest p-hat */
int best = -1;
for (int c = 0; c < NB; c++) if (!top[c] && (best < 0 || key[c] > key[best])) best = c;
top[best] = 1;
}
nexp += (double)cnt / NB;
for (int h = 0; h < H; h++) {
double e = attend(q[t][h], ex);
err += e / (STEPS * H); emax = fmax(emax, e); perr += attend(q[t][h], top) / (STEPS * H);
}
}
nexp /= STEPS;
/* per block: scoring reads kbar, lo, hi, V_C; then vbar or the 32 exact (k, v) */
double bytes = NB * (3.0 * D + 1) + NB * ((1 - nexp) * D + nexp * B * 2.0 * D);
printf("%7.0e %-6s %7.1f%% %9.1f%% %8.2e %8.2e | %8.2e\n", taus[x], pol ? "mean" : "any",
100 * nexp, 100 * bytes / full, err, emax, perr);
}
return 0;
}
tau policy expanded bytes read mean err max err | p-hat top-k, same budget
1e-04 any 99.8% 104.5% 1.73e-07 1.47e-05 | 1.68e-07
1e-03 any 97.1% 101.9% 1.08e-05 4.91e-04 | 1.75e-04
1e-02 any 85.0% 89.9% 2.96e-04 4.03e-03 | 5.45e-04
1e-02 mean 68.0% 73.2% 1.24e-03 1.10e-02 | 1.95e-03
3e-02 any 62.6% 67.9% 1.86e-03 1.05e-02 | 2.74e-03
1e-01 any 12.8% 18.9% 8.60e-03 3.35e-02 | 1.21e-02
1e-01 mean 6.8% 13.0% 1.13e-02 4.28e-02 | 1.39e-02
3e-01 any 4.7% 10.9% 1.33e-02 5.21e-02 | 1.41e-02
1e+00 any 3.2% 9.4% 1.47e-02 7.71e-02 | 1.79e-02
inf any 0.0% 6.3% 3.84e-02 2.65e-01 | 3.84e-02
Printed on FreeBSD 15.1 on amd64 (Core i5-9400), clang 19. It depends on the machine: elsewhere the timings, the random numbers or the last digits differ.
kb), \(\bar v_C\) (vb), \(k^{\min}_C, k^{\max}_C\) (lo, hi) and \(V_C\) (VC), and the global \(V_{\max}\). After it, decoding never needs a key it has not chosen to read, except in the reference output.risk is Eq. 4. s[c] is \(s_C\); up and dn are \(\sqrt d\,s_C^{\text{upper}}\) and \(\sqrt d\,s_C^{\text{lower}}\) of (81)–(82), so dl[c] is \(\delta_C^{\text{box}}\) of (83); ph is \(\hat p_C\); den is \(S = \sum \hat p_C\cosh\delta_C^{\text{box}}\). \(\hat p_C\) is a softmax of \(s_C\) without the \(\log n_C\) because every block has 32 tokens: the common \(\log 32\) cancels. The maximum is subtracted before the exponential, as in section 15.2.ex[c] per block, shared by the heads: the expansion set belongs to the KV head.attend keeps three online-softmax states. full sees every token: it is the reference \(o\), which a real decoder would not compute. exact sees the tokens of expanded blocks, rep one entry per other block, with logit \(s_C + \log 32\) and value \(\bar v_C\). The two parts of \(\hat o_E\) are accumulated apart because in the kernel they come from different memory (the original cache and the summary arrays) and different loops; merge then rescales both to the larger maximum and adds, which is exact (section 15.5). Only after the merge is \(a/\ell\) the output.cnt, and expands instead the cnt blocks with the largest \(\hat p_C\) (maximum over heads). Same budget, different ranking: the control of Table 2.If the mean of \(R_C^{(h)}\) exceeds \(\tau\), some term does, so the maximum does. They are equal when, for every block, either all heads are at most \(\tau\) or the mean is above \(\tau\): for example a group of identical query heads.
\(10.76 + 2.30 + 1.53 = 14.59\) ms, 1.70\(\times\). The figure shows 11.04 and 2.32 ms for RefineKV's GEMV and other parts, adding 0.30 ms; the paper does not explain the difference.
Attention is a smaller share of Qwen's step, so removing most of it saves a smaller fraction of the total. The ceiling \(T/(T - T_{\text{attn}})\) is lower. Table 14 agrees in direction (1.19\(\times\) against 1.56\(\times\) on RULER), but the paper gives no per-part breakdown for Qwen.
Per block the toy reads \(3d + 1 + (1 - f)d + f \cdot 64d\) against \(64d\). Ignoring the 1: \(4d - fd + 64fd = 64d\) gives \(f = 60/63 \approx 95\%\). Above that share, the summaries cost more than they save.
Because \(R_C\) and \(\hat p_C\) rank blocks almost identically (\(\hat p_C\) is a factor of \(R_C\)). Once \(\hat p_C\)'s ranking is removed from both, what is left of \(R_C\) is the spread factor, and that residual correlates .49 with what is left of the error.
Mixed-state re-scoring. In the mixed state an expanded block becomes 32 one-token clusters with \(R = 0\). The other scores move both ways: their \(\hat p_C\) shrink, because the exact tokens carry more mass than their representatives did (\(m_C \ge 1\)), but \(S\) may shrink too, as the expanded blocks' large \(\cosh\delta\) terms are replaced by ones, which raises every mass part. Whether more or fewer blocks cross \(\tau\), and whether the error at equal budget falls, depends on the data; the cost is a second pass over the summaries.
Every \(R_C\) scales with \(V_C\) and \(V_{\max}\), so ten times larger values make every score ten times larger and many more blocks cross the same \(\tau\): the method becomes slower, not less accurate. Section 7 raises the same point for modalities with different value scales.