A query, a key and a value are each an array of numbers. This chapter is the arithmetic of such arrays: adding them, scaling them, taking weighted sums, and the dot product, which turns two arrays into one number that says how much they point the same way. Attention (chapter 16) is exactly these operations: a dot product of the query with every key, then a weighted sum of the values. RefineKV summarizes a group of keys by their mean and measures how far the keys stray from it along the query; section 8.6 sets up those quantities in the paper's notation. Chapter 9 stacks vectors into matrices, and chapter 10 measures them with norms and inequalities.
A vector \(x \in \mathbb{R}^d\) is a list of \(d\) real numbers, its coordinates (or components): \(x = (x_1, x_2, \dots, x_d)\). In C it is double x[d], indexed from 0 where the math indexes from 1. \(d\) is the dimension. A query \(q\) and the keys \(k_i\) of one attention head live in \(\mathbb{R}^d\) with \(d\) typically 64 or 128; the values \(v_i\) live in \(\mathbb{R}^{d_v}\), usually with \(d_v = d\).
For \(d = 2\) or 3 a vector is also an arrow from the origin to the point with those coordinates. The array and the arrow are the same object; the arrow is how to see it, the array is how to compute with it. Nothing in the arithmetic below depends on \(d\), so pictures in the plane are honest about what happens in \(\mathbb{R}^{128}\).
Two operations, both coordinate by coordinate:
\[ x + y = (x_1 + y_1, \dots, x_d + y_d), \qquad c\,x = (c x_1, \dots, c x_d) \quad (c \in \mathbb{R}). \]Adding puts the arrows head to tail. Scaling by \(c\) stretches the arrow by \(|c|\) and flips it when \(c < 0\). The difference \(x - y = x + (-1)y\) is the arrow from the tip of \(y\) to the tip of \(x\). The zero vector \(0 = (0, \dots, 0)\) changes nothing when added. All the rules of ordinary arithmetic hold: \(x + y = y + x\), \(c(x + y) = cx + cy\), and so on, because they hold in each coordinate.
In the machine. A vector of floats is a contiguous array, and vector addition is the loop a compiler turns into vaddps: eight floats per AVX instruction. Throughput, not latency, limits such a loop, since no coordinate depends on another.
Scaling and adding several vectors gives a linear combination:
\[ c_1 v_1 + c_2 v_2 + \dots + c_n v_n = \sum_{i=1}^{n} c_i v_i, \]with any real coefficients \(c_i\). In code: zero an accumulator, then o[j] += c[i] * v[i][j] for each \(i\) and \(j\). With all coefficients allowed, the combinations of two arrows that do not lie on one line reach every point of the plane.
Restrict the coefficients and the reach shrinks. A convex combination has weights that are nonnegative and sum to 1:
Definition. \(\sum_i \alpha_i v_i\) is a convex combination of \(v_1, \dots, v_n\) when \(\alpha_i \ge 0\) for every \(i\) and \(\sum_i \alpha_i = 1\). The set of all convex combinations of the \(v_i\) is their convex hull.
For two points, \(w a + (1 - w) b\) with \(0 \le w \le 1\) runs along the segment from \(b\) (at \(w = 0\)) to \(a\) (at \(w = 1\)). For three points the hull is the filled triangle; for many it is the smallest convex polygon (in higher dimension, polytope) around them, the shape a rubber band would take. A convex combination is a weighted average: the weights say how much each point pulls.
The attention output is a convex combination. Its weights are the softmax of the logits,
\[ \alpha_i = \frac{e^{s_i}}{\sum_{j=1}^{N} e^{s_j}}, \qquad o = \sum_{i=1}^{N} \alpha_i v_i , \]and each \(\alpha_i\) is positive (an exponential) and they sum to 1 (by the division). So \(o\) lies in the hull of the values. Whatever the query, attention cannot produce a vector outside the region its values span: it can only blend. Coordinate by coordinate this is easy to prove: \(o_j = \sum_i \alpha_i v_{i,j} \le \sum_i \alpha_i \max_i v_{i,j} = \max_i v_{i,j}\), and the same with min.
Take three values in the plane, \(v_1 = (0.5, 0.5)\), \(v_2 = (4, 1)\), \(v_3 = (2, 3.5)\), and logits \(s = (1, 0.2, -0.5)\). The softmax gives \(\alpha = (0.5979, 0.2687, 0.1334)\) and \(o = (1.6404, 1.0346)\), inside the triangle (figure 8.2; hull.c in this chapter's sources computes it). The weights pull \(o\) toward the value with the largest logit, but never past the edge. The linear combination \(2v_2 - v_3 = (6, -1.5)\), with weights 2 and \(-1\), is outside: negative weights are what lets a combination escape.
The cost of a combination of \(n\) vectors in \(\mathbb{R}^{d}\) is \(nd\) multiply-adds, and every value is read once. For attention that read of all \(N\) values is the expensive part (section 17.4).
Two consequences come back later. In section 10.2, the length of \(o\) is at most the largest length of a value, which is how the paper's \(V_C = \max_{i \in C} \|v_i\|_2\) enters its bound. And the paper splits \(o\) by clusters: \(v_C\), the attention-weighted average of the values in cluster \(C\), is a convex combination of those values, and \(o = \sum_C p_C v_C\) is a convex combination of the \(v_C\) with the cluster masses \(p_C\) as weights (section 18.5). A weighted average of weighted averages is still one.
Definition. The dot product (inner product) of \(a, b \in \mathbb{R}^d\) is the number \[ a^\top b = a \cdot b = \sum_{j=1}^{d} a_j b_j . \]
Multiply matching coordinates, add. The notation \(a^\top b\) comes from matrices (section 9.4: a row times a column); the paper writes \(q^\top k_i\). Attention's logits are dot products, scaled: \(s_i = q^\top k_i / \sqrt{d}\).
The rules, each a one-line check on the sum:
Cost: \(d\) multiplications and \(d - 1\) additions, each coordinate of both vectors read once. The logits of one query against \(N\) keys cost \(Nd\) multiply-adds.
Linearity is the property this book uses most. It says the dot product with a fixed \(q\) passes through sums and scalings, so the logit of an average is the average of the logits (section 8.6). The program laws.c in this chapter's sources checks every rule here on 100 000 random 16-dimensional vectors; the largest discrepancy is \(1.2 \times 10^{-14}\), rounding.
In the machine. The loop s += a[j]*b[j] is a reduction: each add waits for the previous one, so it runs at one element per add latency, not per cycle. The fix is several accumulators (say eight AVX registers of vfmadd231ps) summed at the end, which a compiler will do only under -ffast-math, because it changes the order of the additions and so the rounding (section 14.5). SSE4.1 has a dot-product instruction, dpps, but it decodes to several micro-ops with a long latency; tuned code uses multiply-adds and one horizontal sum at the end [fog], [intel-sdm].
The length (Euclidean norm) of a vector is Pythagoras in \(d\) dimensions:
\[ \|a\| = \sqrt{a \cdot a} = \sqrt{a_1^2 + \dots + a_d^2}. \]Scaling scales length, \(\|c a\| = |c|\,\|a\|\), and expanding the sum gives \(\|a + b\|^2 = \|a\|^2 + 2\,a \cdot b + \|b\|^2\). A unit vector has length 1; \(a / \|a\|\) is the unit vector pointing the way \(a\) does.
The dot product measures angle. Write the law of cosines for the triangle with sides \(a\), \(b\) and \(a - b\): \(\|a - b\|^2 = \|a\|^2 + \|b\|^2 - 2\|a\|\|b\|\cos\theta\). Expand the left side with the rule above: \(\|a\|^2 - 2\,a \cdot b + \|b\|^2\). Compare:
\[ a \cdot b = \|a\|\,\|b\|\cos\theta, \qquad \cos\theta = \frac{q^\top k}{\|q\|\,\|k\|}. \]So the dot product is the product of the lengths times the cosine of the angle between the arrows. In \(\mathbb{R}^{128}\) there is no picture, and this formula becomes the definition of the angle. That the right side is always in \([-1, 1]\), so that an angle exists, is the Cauchy–Schwarz inequality (section 10.3).
For attention this reads: a key gets a large logit \(q^\top k_i\) when it points the way the query does, or when it is long, or both. A long key that is only roughly aligned can beat a short one that is perfectly aligned. That is what “the query looks for keys” means in numbers.
An example by hand: \(q = (1, 2, 2)\) and \(k = (2, 0, 1)\) give \(q^\top k = 4\), \(\|q\| = 3\), \(\|k\| = \sqrt{5}\), \(\cos\theta = 4/(3\sqrt 5) \approx 0.5963\), \(\theta \approx 53.4^\circ\); and \(x = (1, 3, -2)\) is perpendicular to \(k\).
How large is a dot product of two vectors that have nothing to do with each other? Take \(a, b\) with independent coordinates of mean 0 and variance 1. Then \(a^\top b = \sum_j a_j b_j\) is a sum of \(d\) independent terms, each of mean 0 and variance \(E[a_j^2]E[b_j^2] = 1\), so its variance is \(d\) and its typical size is \(\sqrt{d}\) (section 12.7). Meanwhile \(\|a\|^2 = \sum_j a_j^2\) is close to its mean \(d\), so \(\|a\| \approx \|b\| \approx \sqrt{d}\) and
\[ \cos\theta = \frac{a^\top b}{\|a\|\,\|b\|} \approx \frac{\sqrt{d}\, z}{d} = \frac{z}{\sqrt{d}}, \qquad E|\cos\theta| \approx \sqrt{\frac{2}{\pi d}} , \]with \(z\) standard normal, whose mean absolute value is \(\sqrt{2/\pi} \approx 0.8\). Two consequences. Logits of unrelated query–key pairs grow like \(\sqrt{d}\), which is why attention divides by \(\sqrt{d}\) (section 16.4). And in high dimension random directions are nearly perpendicular, so a cosine of 0.3 in \(\mathbb{R}^{128}\) is a strong signal, not a weak one. Both are statements about large \(d\); a simulation shows how large is large:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
static double gauss(void) /* Box-Muller: one standard normal sample */
{
double u = (rand() + 1.0) / (RAND_MAX + 2.0), v = (rand() + 1.0) / (RAND_MAX + 2.0);
return sqrt(-2 * log(u)) * cos(6.283185307179586 * v);
}
int main(void)
{
static double a[1024], b[1024];
const int trials = 20000;
srand(1);
for (int d = 2; d <= 1024; d *= 8) {
double sd = 0, sc = 0;
for (int t = 0; t < trials; t++) {
double ab = 0, aa = 0, bb = 0;
for (int j = 0; j < d; j++) {
a[j] = gauss(); b[j] = gauss();
ab += a[j] * b[j]; aa += a[j] * a[j]; bb += b[j] * b[j];
}
sd += ab * ab; /* mean of (a.b)^2 estimates its variance */
sc += fabs(ab) / sqrt(aa * bb); /* |cos theta| */
}
printf("d = %4d: rms a.b = %6.3f sqrt(d) = %6.3f "
"mean |cos| = %.4f sqrt(2/(pi d)) = %.4f\n",
d, sqrt(sd / trials), sqrt(d), sc / trials, sqrt(2 / (3.141592653589793 * d)));
}
return 0;
}
d = 2: rms a.b = 1.402 sqrt(d) = 1.414 mean |cos| = 0.6363 sqrt(2/(pi d)) = 0.5642 d = 16: rms a.b = 4.017 sqrt(d) = 4.000 mean |cos| = 0.2027 sqrt(2/(pi d)) = 0.1995 d = 128: rms a.b = 11.326 sqrt(d) = 11.314 mean |cos| = 0.0709 sqrt(2/(pi d)) = 0.0705 d = 1024: rms a.b = 31.870 sqrt(d) = 32.000 mean |cos| = 0.0249 sqrt(2/(pi d)) = 0.0249
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.
How it maps to the math. gauss is the Box–Muller transform: from two independent uniform numbers \(u, v \in (0, 1)\) it makes \(\sqrt{-2\ln u}\,\cos(2\pi v)\), which is exactly standard normal. Normal coordinates are chosen because the argument needs mean 0 and variance 1; uniform coordinates on \([-1, 1]\) would have variance \(1/3\) and give \(\sqrt{d}/3\). The \(+1\) and \(+2\) keep \(u\) strictly inside \((0, 1)\), so \(\ln u\) is finite. One pass over \(j\) accumulates three sums, \(a^\top b\), \(\|a\|^2\) and \(\|b\|^2\), because the cosine needs all three. sd sums \((a^\top b)^2\) over trials: its mean estimates \(E[(a^\top b)^2]\), which is the variance since the mean is 0, so sqrt(sd / trials) estimates \(\sqrt{d}\). sc averages \(|\cos\theta|\) to compare with \(\sqrt{2/(\pi d)}\). The output confirms \(\sqrt{d}\) at every size, and the cosine formula from \(d = 16\) on; at \(d = 2\) the approximation \(\|a\| \approx \sqrt{d}\) is poor, and so is the formula.
How much of \(a\) points along \(b\)? Drop a perpendicular from the tip of \(a\) to the line through \(b\). The foot is the projection of \(a\) onto \(b\):
\[ p = \frac{a \cdot b}{b \cdot b}\, b, \qquad e = a - p, \qquad e \cdot b = 0. \]The coefficient is forced by the last condition: \((a - c\,b) \cdot b = a \cdot b - c\,(b \cdot b) = 0\) gives \(c = a \cdot b / b \cdot b\). Then \(a = p + e\) splits \(a\) into a part along \(b\) and a part perpendicular to it, and since \(p \cdot e = 0\), Pythagoras holds: \(\|a\|^2 = \|p\|^2 + \|e\|^2\). The length of the projection is \(\|p\| = \|a\|\,|\cos\theta|\).
In the figure, \(c = 15/17 \approx 0.8824\), \(p = (3.5294, 0.8824)\), \(e = (-0.5294, 2.1176)\); \(e \cdot b = 0\), and \(\|p\|^2 + \|e\|^2 = 18 = \|a\|^2\). The cost is two dot products and a scaling, \(O(d)\).
For a unit vector \(u\) the formula shortens to \(p = (a \cdot u)\,u\): the dot product with a unit vector is the coordinate along it. Read \(q^\top r\) the same way: it is \(\|q\|\) times the signed length of \(r\)'s shadow on the query's direction. Components of \(r\) perpendicular to \(q\) contribute nothing. This is the paper's remark that a cluster “may be dispersed in the original key space while remaining tightly concentrated along the direction relevant to the current query” [refinekv], section 3.3.
RefineKV partitions the \(N\) cached keys into clusters and represents each cluster \(C\) by its mean key
\[ \bar k_C = \frac{1}{|C|} \sum_{i \in C} k_i , \]coordinate by coordinate the average of the keys, and by its mean value \(\bar v_C\), defined the same way. It is a convex combination with equal weights \(1/|C|\), so it sits inside the keys' hull, at their center of mass.
Three facts make the mean the right summary for dot products.
Linearity. By the rules of section 8.3, the dot product with the mean is the mean of the dot products:
\[ q^\top \bar k_C = \frac{1}{|C|} \sum_{i \in C} q^\top k_i . \]One dot product with \(\bar k_C\) gives the average logit of the whole cluster, for any query, at the cost of one key. Computing \(\bar k_C\) costs \(|C|\,d\) additions, once, when the cluster is formed (at prefill, in RefineKV); after that every query pays \(d\) multiply-adds for the cluster instead of \(|C|\,d\).
Residuals sum to zero. Define each key's residual (its centered key) \(r_i = k_i - \bar k_C\). Then
\[ \sum_{i \in C} r_i = \sum_{i \in C} k_i - |C|\,\bar k_C = 0 . \]The residuals balance; by linearity again, the deviations \(q^\top r_i\) average to zero for every \(q\), so some are \(\ge 0\) and some \(\le 0\).
Logit = shared part + deviation. Since \(k_i = \bar k_C + r_i\),
\[ q^\top k_i = q^\top \bar k_C + q^\top r_i . \]The first term is the same for every key of the cluster; only the second varies. If every \(q^\top r_i\) is small, the cluster's keys all score about the same, and replacing them by \(\bar k_C\) loses little. The paper measures this by the maximum logit deviation
\[ \delta_C = \max_{i \in C} \frac{|q^\top (k_i - \bar k_C)|}{\sqrt{d}} = \max_{i \in C} \frac{|q^\top r_i|}{\sqrt{d}} , \]and its whole error bound (chapter 19) is a function of the \(\delta_C\), through \(\cosh \delta_C - 1\) and \(\tanh(\delta_C / 2)\).
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define D 4 /* d: key dimension */
#define C 6 /* |C|: keys in the cluster */
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;
}
int main(void)
{
double k[C][D], kbar[D] = { 0 }, r[C][D], rsum[D] = { 0 }, q[D];
srand(8);
for (int i = 0; i < C; i++)
for (int j = 0; j < D; j++)
k[i][j] = 2.0 * rand() / RAND_MAX - 1;
for (int j = 0; j < D; j++)
q[j] = 4.0 * rand() / RAND_MAX - 2;
for (int i = 0; i < C; i++) /* kbar_C = (1/|C|) sum k_i */
for (int j = 0; j < D; j++)
kbar[j] += k[i][j] / C;
for (int i = 0; i < C; i++) /* r_i = k_i - kbar_C */
for (int j = 0; j < D; j++)
rsum[j] += r[i][j] = k[i][j] - kbar[j];
double mean_logit = 0, delta = 0;
for (int i = 0; i < C; i++) {
double s = dot(q, k[i]), dev = dot(q, r[i]);
mean_logit += s / C;
printf("i=%d q.k_i = %8.5f q.kbar + q.r_i = %8.5f q.r_i = %8.5f\n",
i, s, dot(q, kbar) + dev, dev);
if (fabs(dev) / sqrt(D) > delta) delta = fabs(dev) / sqrt(D);
}
printf("q.kbar = %.17g\nmean of q.k_i = %.17g\n", dot(q, kbar), mean_logit);
printf("sum of r_i = (%.1e, %.1e, %.1e, %.1e)\n", rsum[0], rsum[1], rsum[2], rsum[3]);
printf("delta_C = max |q.r_i| / sqrt(d) = %.5f\n", delta);
double se = 0;
for (int i = 0; i < C; i++) se += exp(dot(q, k[i]) / sqrt(D));
printf("|C| exp(q.kbar/sqrt d) = %.5f <= sum exp(q.k_i/sqrt d) = %.5f\n",
C * exp(dot(q, kbar) / sqrt(D)), se);
printf("ratio %.5f <= cosh(delta_C) = %.5f\n",
se / (C * exp(dot(q, kbar) / sqrt(D))), cosh(delta));
return 0;
}
i=0 q.k_i = -0.22301 q.kbar + q.r_i = -0.22301 q.r_i = -0.53782 i=1 q.k_i = 0.63567 q.kbar + q.r_i = 0.63567 q.r_i = 0.32086 i=2 q.k_i = -1.82099 q.kbar + q.r_i = -1.82099 q.r_i = -2.13580 i=3 q.k_i = -1.10589 q.kbar + q.r_i = -1.10589 q.r_i = -1.42070 i=4 q.k_i = 1.94811 q.kbar + q.r_i = 1.94811 q.r_i = 1.63330 i=5 q.k_i = 2.45497 q.kbar + q.r_i = 2.45497 q.r_i = 2.14016 q.kbar = 0.3148103794466296 mean of q.k_i = 0.31481037944662954 sum of r_i = (-5.6e-16, 1.1e-16, 0.0e+00, -2.2e-16) delta_C = max |q.r_i| / sqrt(d) = 1.07008 |C| exp(q.kbar/sqrt d) = 7.02282 <= sum exp(q.k_i/sqrt d) = 9.30751 ratio 1.32532 <= cosh(delta_C) = 1.62930
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.
How it maps to the math. The keys and the query are random, just to have numbers; \(d = 4\) and \(|C| = 6\) keep the printout short. The first loop builds \(\bar k_C\) by adding \(k_i / |C|\) coordinate by coordinate, the definition read literally. The second forms each \(r_i = k_i - \bar k_C\) and adds them up, to see \(\sum_i r_i = 0\). The main loop prints, for each key, \(q^\top k_i\) next to \(q^\top \bar k_C + q^\top r_i\) (the decomposition), and keeps the largest \(|q^\top r_i| / \sqrt{d}\), which is \(\delta_C\); it also averages the logits, to compare with \(q^\top \bar k_C\) (linearity). The last two lines compare \(|C|\,e^{q^\top \bar k_C/\sqrt{d}}\) with \(\sum_i e^{q^\top k_i/\sqrt{d}}\), and their ratio with \(\cosh\delta_C\).
The two printings of the mean logit differ in the 17th digit: the same sum, added in a different order. The residuals sum to zero up to rounding. And the last line is a warning: the representative's logit is the mean logit, but its exponential is not the mean exponential. \(|C|\,e^{q^\top \bar k_C / \sqrt{d}}\), the cluster's weight in the approximate softmax (the numerator of the paper's \(\hat p_C\)), is always at most the true \(\sum_{i \in C} e^{q^\top k_i / \sqrt{d}}\). That is Jensen's inequality (section 11.4). The ratio of the two is at most \(\cosh \delta_C\), the paper's cosh lemma (section 19.4), so it is near 1 when \(\delta_C\) is small.
Computing \(\delta_C\) exactly needs every key of the cluster, which is what RefineKV wants to avoid reading. Section 10.6 bounds \(\delta_C\) from a few numbers stored per cluster.
\(a \cdot b = 3 + 0 + 8 = 11\), \(\|a\| = 3\), \(\|b\| = 5\), \(\cos\theta = 11/15 \approx 0.7333\), \(\theta \approx 42.83^\circ\).
No: the weights sum to 1 but one is negative. It can leave the hull, as \(2a - b\) does in section 8.2. Summing to 1 alone gives an affine combination, which reaches the whole plane through the three points.
\(o_j = \sum_i \alpha_i v_{i,j} \le \sum_i \alpha_i u = u\) because each \(\alpha_i \ge 0\) and they sum to 1; the same with \(l\) gives \(o_j \ge l\). With a negative \(\alpha_i\) the first inequality can fail.
\(c = 3/2\), \(p = (1.5, 1.5)\), \(e = (0.5, -0.5)\), and \(e \cdot b = 0.5 - 0.5 = 0\).
\(\delta_C\) is a maximum of absolute values, so \(\ge 0\). It is 0 iff \(q^\top r_i = 0\) for all \(i\), i.e. \(q^\top k_i = q^\top \bar k_C\) for all \(i\): equal logits. Since the \(q^\top r_i\) average to zero, if they are not all zero then one is positive and one negative.
float arrays of length 1000 with one accumulator and with four, and compare both to the sum done in double.
The program ex.c prints one accumulator -5.33409405, four -5.33409119, in double -5.33409133. Different orders round differently. Here four accumulators happened to be closer; split sums often are, since each partial sum stays smaller (section 14.5).
\(\bar k_C = (k_1 + k_2)/2\), \(r_1 = (k_1 - k_2)/2 = -r_2\), so \(\delta_C = |q^\top (k_1 - k_2)| / (2\sqrt{d})\). It is 0 when \(q\) is perpendicular to \(k_1 - k_2\): the keys differ only in directions the query does not look at.
dpps, FMA latency and multiple accumulators.