Softmax turns a list of scores into a probability distribution. In attention the scores are the logits \(s_i = q^\top k_i/\sqrt{d}\) and the distribution is the weights \(\alpha_i\) of the paper's Eq. 1 ([refinekv], Section 2). Section 12.6 treats softmax as a distribution; this chapter is about computing it. As written it overflows (section 15.1); a shift fixes that (15.2) and gives log-sum-exp (15.3). Then the two ideas every fast attention kernel is built on: computing softmax in one pass over the keys (15.4), and merging the results of separate passes exactly (15.5). The second is how the paper's kernel combines its expanded blocks, its cluster representatives and its recent tokens into one attention ([refinekv], Appendix B.2; section 20.3).
For scores \(s_1, \dots, s_N\),
\[ \alpha_i = \operatorname{softmax}(s)_i = \frac{e^{s_i}}{\sum_{j=1}^{N} e^{s_j}}. \]Each \(\alpha_i\) is positive, and they sum to 1. The exponential keeps the order of the scores and exaggerates their differences: a score larger by 1 gets \(e \approx 2.7\) times the weight, larger by 10 gets 22026 times. So softmax is a soft version of “pick the largest”: when one score stands far above the others, nearly all the weight goes there. Only differences of scores matter (section 15.2).
Typed in as it stands:
#include <math.h>
#include <stdio.h>
static void softmax_naive(const float *s, float *w, int n)
{
float sum = 0;
for (int i = 0; i < n; i++) sum += expf(s[i]);
for (int i = 0; i < n; i++) w[i] = expf(s[i]) / sum;
}
int main(void)
{
float tests[3][3] = { { 1, 2, 3 }, { 100, 101, 102 }, { -200, -201, -202 } };
for (int t = 0; t < 3; t++) {
float w[3];
softmax_naive(tests[t], w, 3);
printf("s = (%g, %g, %g) -> w = (%g, %g, %g)\n", tests[t][0], tests[t][1],
tests[t][2], w[0], w[1], w[2]);
}
printf("expf(100) = %g, expf(-200) = %g\n", expf(100), expf(-200));
return 0;
}
s = (1, 2, 3) -> w = (0.0900306, 0.244728, 0.665241) s = (100, 101, 102) -> w = (nan, nan, nan) s = (-200, -201, -202) -> w = (nan, nan, nan) expf(100) = inf, expf(-200) = 0
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.
The two loops are the formula read literally: the first forms the denominator \(\sum_j e^{s_j}\), the second each numerator over it. Nothing in it bounds the size of \(e^{s_j}\), and that is the whole problem. Logits of 100 are not exotic, and the second test breaks: \(e^{100}\) overflows fp32, which stops at \(e^{88.72}\) (section 14.7), and \(\infty/\infty\) is NaN. The third breaks the other way: \(e^{-200}\) is far below the smallest fp32 subnormal, \(2^{-149} \approx e^{-103.3}\), so every term is 0 and the division is \(0/0\). In fp16 the overflow comes at \(e^{11.09}\). The answer in all three tests is the same distribution, \((0.090, 0.245, 0.665)\) or its reverse, because the logits differ by the same steps.
Adding the same constant \(c\) to every score does not change softmax:
\[ \frac{e^{s_i + c}}{\sum_j e^{s_j + c}} = \frac{e^{c}\, e^{s_i}}{e^{c} \sum_j e^{s_j}} = \frac{e^{s_i}}{\sum_j e^{s_j}}. \]This is shift invariance (section 12.6). Choose \(c = -m\) with \(m = \max_j s_j\). Then every exponent \(s_i - m\) is at most 0, so every term is in \((0, 1]\), the largest is exactly \(e^0 = 1\), and the denominator lies between 1 and \(N\). Nothing overflows, and the denominator cannot be 0.
#include <math.h>
#include <stdio.h>
static void softmax(const float *s, float *w, int n)
{
float m = s[0], sum = 0;
for (int i = 1; i < n; i++) if (s[i] > m) m = s[i];
for (int i = 0; i < n; i++) sum += w[i] = expf(s[i] - m); /* every term in (0, 1] */
for (int i = 0; i < n; i++) w[i] /= sum;
}
int main(void)
{
float tests[4][3] = { { 1, 2, 3 }, { 100, 101, 102 }, { -200, -201, -202 },
{ 1000, 0, -1000 } };
for (int t = 0; t < 4; t++) {
float w[3];
softmax(tests[t], w, 3);
printf("s = (%g, %g, %g) -> w = (%.7f, %.7f, %.7f)\n", tests[t][0], tests[t][1],
tests[t][2], w[0], w[1], w[2]);
}
return 0;
}
s = (1, 2, 3) -> w = (0.0900306, 0.2447285, 0.6652409) s = (100, 101, 102) -> w = (0.0900306, 0.2447285, 0.6652409) s = (-200, -201, -202) -> w = (0.6652409, 0.2447285, 0.0900306) s = (1000, 0, -1000) -> w = (1.0000000, 0.0000000, 0.0000000)
The first loop finds \(m\); the second computes \(e^{s_i - m}\), the shifted numerators with \(c = -m\), stores them in w and adds them up in the same pass; the third divides by the sum. Storing the numerators means expf runs once per score, not twice. The term of the max is exactly expf(0) = 1, which is what guarantees sum \(\ge 1\). The first three tests return the same weights as each other, which is shift invariance seen in the output. Terms far below the max still underflow, as \(e^{-1000}\) does in the last test, but now that is harmless: a term below \(2^{-149}\) added to a denominator of at least 1 would vanish in rounding anyway. The weight 0 it gets is within \(10^{-38}\) of the truth.
In the machine. The subtraction \(s_i - m\) is one rounding, an absolute error of at most \(u|s_i - m|\). The exponential turns an absolute error \(\eta\) in its argument into a relative error of about \(\eta\) in its result, since \(e^{x + \eta} = e^x e^\eta \approx e^x(1 + \eta)\). So a weight far below the max (large \(|s_i - m|\)) is computed with a relative error of about \(u|s_i - m|\): \(6 \times 10^{-6}\) in fp32 at \(|s_i - m| = 100\). It is a relative error on a weight smaller than \(e^{-100}\): nobody will notice.
The logarithm of the softmax denominator has a name:
\[ \operatorname{LSE}(s) = \log \sum_{j=1}^{N} e^{s_j}. \]It is a smooth maximum. With \(m = \max_j s_j\), the sum contains the term \(e^m\) and has \(N\) terms each at most \(e^m\), so \(e^m \le \sum_j e^{s_j} \le N e^m\), and taking logs,
\[ \max_j s_j \;\le\; \operatorname{LSE}(s) \;\le\; \max_j s_j + \ln N. \]The lower bound is near-equality when one score dominates; the upper bound is equality when all scores are equal. LSE is convex (section 11.5), and its gradient is softmax (section 7.6): \(\partial \operatorname{LSE}/\partial s_i = \alpha_i\). It turns up wherever softmax does. The log of a softmax weight is \(\log \alpha_i = s_i - \operatorname{LSE}(s)\) (the log-softmax, which a language model's loss uses), and the attention normalizer in Eq. 1 is \(e^{\operatorname{LSE}(s)}\).
The same shift computes it safely. Factor \(e^m\) out of the sum:
\[ \operatorname{LSE}(s) = m + \log \sum_{j=1}^{N} e^{s_j - m}. \]The sum is in \([1, N]\), so the log is between 0 and \(\ln N\) and nothing overflows. One refinement: when the other terms are tiny, the sum is \(1 + \text{tiny}\), and \(1 + \text{tiny}\) rounds to 1, losing the tiny part. Writing the sum as \(1 + r\), with \(r\) the sum of the terms other than the max, and calling log1p(r) keeps it (section 14.4, exercise 4).
#include <math.h>
#include <stdio.h>
static double lse_naive(const double *s, int n)
{
double sum = 0;
for (int i = 0; i < n; i++) sum += exp(s[i]);
return log(sum);
}
static double lse(const double *s, int n) /* m + log sum exp(s_i - m) */
{
double m = s[0], sum = 0;
for (int i = 1; i < n; i++) if (s[i] > m) m = s[i];
for (int i = 0; i < n; i++) sum += exp(s[i] - m);
return m + log(sum);
}
static double lse1p(const double *s, int n) /* m + log1p(sum over the others) */
{
int k = 0;
double rest = 0;
for (int i = 1; i < n; i++) if (s[i] > s[k]) k = i;
for (int i = 0; i < n; i++) if (i != k) rest += exp(s[i] - s[k]);
return s[k] + log1p(rest);
}
int main(void)
{
double a[3] = { 1, 2, 3 }, b[3] = { 1000, 999, 998 }, c[2] = { 0, -40 };
printf("(1, 2, 3): naive %.15g stable %.15g\n", lse_naive(a, 3), lse(a, 3));
printf("(1000, 999, 998): naive %g stable %.15g\n", lse_naive(b, 3), lse(b, 3));
printf("(0, -40): stable %g with log1p %g (e^-40 = %g)\n",
lse(c, 2), lse1p(c, 2), exp(-40.0));
printf("bounds for (1000, 999, 998): max %g <= lse <= max + ln 3 = %.15g\n",
1000.0, 1000 + log(3.0));
printf("log-softmax of 998: %.15g, log of its weight: %.15g\n",
998 - lse(b, 3), log(exp(-2.0) / (1 + exp(-1.0) + exp(-2.0))));
return 0;
}
(1, 2, 3): naive 3.40760596444438 stable 3.40760596444438 (1000, 999, 998): naive inf stable 1000.40760596444 (0, -40): stable 0 with log1p 4.24835e-18 (e^-40 = 4.24835e-18) bounds for (1000, 999, 998): max 1000 <= lse <= max + ln 3 = 1001.09861228867 log-softmax of 998: -2.40760596444443, log of its weight: -2.40760596444438
The three functions are the three formulas. lse_naive is the definition. lse is \(m + \log \sum_j e^{s_j - m}\): the sum it passes to log lies in \([1, N]\). lse1p splits that sum as \(1 + r\): the max's own term is exactly 1 and is left out of the loop, the others form \(r\), and log1p(r) computes \(\log(1 + r)\) from \(r\) itself, so the digits of \(r\) are never added to 1. For the scores \((0, -40)\), \(r = e^{-40} \approx 4 \times 10^{-18}\) is below double's \(u\), so \(1 + r\) rounds to 1 and lse returns 0; log1p returns \(r\), the right answer to all digits. The naive form overflows already at 710 in double. The last line shows the limit of any method: \(\operatorname{LSE} \approx 1000.4\) carries an absolute error of about \(u \times 1000 \approx 10^{-13}\), and \(s_i - \operatorname{LSE}\) inherits it. Computing the log weight from the shifted logits directly, as the second number does, avoids even that.
Fact. The pair \((m, l)\) with \(l = \sum_j e^{s_j - m}\) stores \(\operatorname{LSE}(s) = m + \ln l\) without ever forming \(e^{\operatorname{LSE}}\). It is a floating-point number of its own: \(m\) plays the exponent (base \(e\)), \(l \in [1, N]\) the significand. The next two sections compute with such pairs.
The safe softmax reads the scores twice: once for the max, once for the sum, and attention reads the values a third time for the weighted sum. In attention the scores are computed from keys streamed out of memory, and memory traffic is the cost (section 17.4). Milakov and Gimelshein [online-softmax] showed how to do it in one pass: keep a running max \(m\) and a running sum \(l\) relative to it, and when the max grows, rescale the old sum.
After the scores \(s_1, \dots, s_i\), keep
\[ m_i = \max_{j \le i} s_j, \qquad l_i = \sum_{j \le i} e^{s_j - m_i}. \]Start with \(m_0 = -\infty\), \(l_0 = 0\). When \(s_i\) arrives, \(m_i = \max(m_{i-1}, s_i)\), and every old term \(e^{s_j - m_{i-1}}\) must become \(e^{s_j - m_i} = e^{s_j - m_{i-1}}\, e^{m_{i-1} - m_i}\). One factor fixes them all:
\[ l_i = l_{i-1}\, e^{m_{i-1} - m_i} + e^{s_i - m_i}. \]That the invariant holds after the update is exactly the line above; by induction it holds after every step, so at the end \(l_N\) is the safe denominator of section 15.2. The rescale factor \(e^{m_{i-1} - m_i}\) is at most 1, so no term ever exceeds 1, and when the max does not change it is exactly 1.
The weighted sum of values goes along with the same factor [flash]. Keep \(a_i = \sum_{j \le i} e^{s_j - m_i} v_j\) (unnormalized) and update
\[ a_i = a_{i-1}\, e^{m_{i-1} - m_i} + e^{s_i - m_i}\, v_i, \qquad o = a_N / l_N. \]Each key and value is read once, and the division happens once at the end. With scalar values:
#include <math.h>
#include <stdio.h>
int main(void)
{
double s[6] = { 2, 1, 5, 3, 9, 0 }; /* logits, seen one at a time */
double v[6] = { 10, 20, 30, 40, 50, 60 }; /* one scalar value each */
double m = -INFINITY, l = 0, a = 0; /* running max, sum, weighted sum */
for (int i = 0; i < 6; i++) {
double mn = fmax(m, s[i]);
double r = exp(m - mn); /* rescale old terms: e^(m_old - m_new) */
l = l * r + exp(s[i] - mn);
a = a * r + exp(s[i] - mn) * v[i];
m = mn;
printf("after s = %g: m = %g l = %.6f o = a/l = %.6f\n", s[i], m, l, a / l);
}
double M = 9, L = 0, A = 0; /* two-pass reference */
for (int i = 0; i < 6; i++) { L += exp(s[i] - M); A += exp(s[i] - M) * v[i]; }
printf("two-pass: m = %g l = %.6f o = %.6f\n", M, L, A / L);
return 0;
}
after s = 2: m = 2 l = 1.000000 o = a/l = 10.000000 after s = 1: m = 2 l = 1.367879 o = a/l = 12.689414 after s = 5: m = 5 l = 1.068103 o = a/l = 28.896269 after s = 3: m = 5 l = 1.203438 o = a/l = 30.144964 after s = 9: m = 9 l = 1.022042 o = a/l = 49.571799 after s = 0: m = 9 l = 1.022165 o = a/l = 49.573058 two-pass: m = 9 l = 1.022165 o = 49.573058
The variables are the state: m, l, a are \(m_i\), \(l_i\), \(a_i\), and after the \(i\)-th trip through the loop they satisfy the invariants \(l = \sum_{j \le i} e^{s_j - m}\) and \(a = \sum_{j \le i} e^{s_j - m} v_j\). mn is \(m_i\). r \(= e^{m_{i-1} - m_i}\) is the change of reference: every term already in l and a was computed relative to the old max, and multiplying by r re-expresses all of them relative to the new one at once, which is why one multiplication per state variable suffices however many keys are behind it. The new key's term \(e^{s_i - m_i}\) is then added on the new reference. The start \(m = -\infty\) needs no special case: on the first key r \(= e^{-\infty} = 0\) multiplies an l and a that are 0 anyway. a stays unnormalized because the normalizer is not known until the last key; dividing once at the end costs one division instead of one per key, and the printed \(a/l\) is the output we would get if the keys stopped there.
Watch the third and fifth steps: a new max arrives, \(l\) is scaled down by \(e^{-3}\) and \(e^{-4}\), and the new key enters with weight 1. The partial outputs \(a/l\) are the attention over the keys seen so far, each a correct softmax average at its moment. The final state equals the two-pass one.
In the machine. The extra cost is the rescaling exponential, one per key. On random-order scores the max changes rarely (about \(\ln N\) times, exercise 4), so kernels often test s > m and skip it. On a GPU, threads that take different sides of a branch wait for each other, so kernels process keys in blocks instead: one max per block of 32 or 64 keys, one rescale per block. That is the block form of section 15.5.
Split the keys into chunks: blocks for a GPU's thread blocks, or the paper's clusters. Each chunk can be processed alone, in parallel, to a state. The question is how to combine the states into the attention over all keys, without going back to the keys.
Definition. The state of a set \(A\) of keys (with scores \(s_i\) and values \(v_i\)) is the triple
\[ m_A = \max_{i \in A} s_i, \qquad l_A = \sum_{i \in A} e^{s_i - m_A}, \qquad a_A = \sum_{i \in A} e^{s_i - m_A}\, v_i. \]The attention output over \(A\) is \(o_A = a_A / l_A\). The empty set has state \((-\infty, 0, 0)\).
For two disjoint sets \(A\) and \(B\), define the merge:
\[ m = \max(m_A, m_B), \qquad l = l_A e^{m_A - m} + l_B e^{m_B - m}, \qquad a = a_A e^{m_A - m} + a_B e^{m_B - m}. \]Theorem. The merge of the states of disjoint \(A\) and \(B\) is the state of \(A \cup B\). Hence merging is associative and commutative: any order and any grouping of merges over a partition of the keys gives the state of all the keys, and \(a/l\) is the exact attention output.
Proof. \(\max(m_A, m_B)\) is the largest score in \(A \cup B\), so \(m = m_{A \cup B}\). For the sums, push the factor inside:
\[ l_A e^{m_A - m} = \sum_{i \in A} e^{s_i - m_A} e^{m_A - m} = \sum_{i \in A} e^{s_i - m}, \]and the same for \(B\). Since \(A\) and \(B\) are disjoint, adding gives \(\sum_{i \in A \cup B} e^{s_i - m} = l_{A \cup B}\). The argument for \(a\) is identical with \(v_i\) carried along. For the second claim: a merge tree over chunks \(C_1, \dots, C_k\) produces, by the first claim applied at each node, the state of the union of the chunks below that node; at the root that is the state of all the keys, whatever the tree's shape. \(\square\)
The online update of section 15.4 is this merge with \(B\) a single key, whose state is \((s_i, 1, v_i)\). The proof never uses that \(m\) is the maximum: any reference value works in exact arithmetic. The max is the choice that keeps every exponent \(\le 0\) in floating point.
#include <math.h>
#include <stdio.h>
typedef struct { double m, l, a; } State; /* max, sum e^(s-m), sum e^(s-m) v */
static State merge(State x, State y)
{
if (x.l == 0) return y; /* empty state: m = -inf */
if (y.l == 0) return x;
double m = fmax(x.m, y.m), ex = exp(x.m - m), ey = exp(y.m - m);
return (State){ m, x.l * ex + y.l * ey, x.a * ex + y.a * ey };
}
static State one(double s, double v) { return (State){ s, 1, v }; }
int main(void)
{
enum { N = 1000, B = 32, NB = (N + B - 1) / B };
double s[N], v[N];
for (int i = 0; i < N; i++) { s[i] = 8 * sin(0.37 * i * i); v[i] = cos(0.11 * i); }
State chunk[NB]; /* one state per chunk of B keys */
for (int c = 0; c < NB; c++) {
chunk[c] = (State){ -INFINITY, 0, 0 };
for (int i = c * B; i < N && i < (c + 1) * B; i++) chunk[c] = merge(chunk[c], one(s[i], v[i]));
}
State fwd = chunk[0], bwd = chunk[NB - 1];
for (int c = 1; c < NB; c++) fwd = merge(fwd, chunk[c]);
for (int c = NB - 2; c >= 0; c--) bwd = merge(chunk[c], bwd);
for (int w = 1; w < NB; w *= 2) /* tree: as a parallel reduction would */
for (int c = 0; c + w < NB; c += 2 * w) chunk[c] = merge(chunk[c], chunk[c + w]);
double m = s[0], l = 0, a = 0; /* two-pass reference */
for (int i = 1; i < N; i++) m = fmax(m, s[i]);
for (int i = 0; i < N; i++) { l += exp(s[i] - m); a += exp(s[i] - m) * v[i]; }
printf("two-pass o = %.15f\n", a / l);
printf("left-right o = %.15f\n", fwd.a / fwd.l);
printf("right-left o = %.15f\n", bwd.a / bwd.l);
printf("tree o = %.15f\n", chunk[0].a / chunk[0].l);
printf("states agree on m: %g %g %g %g\n", m, fwd.m, bwd.m, chunk[0].m);
return 0;
}
two-pass o = -0.117686771844677 left-right o = -0.117686771844677 right-left o = -0.117686771844677 tree o = -0.117686771844677 states agree on m: 8 8 8 8
State is the triple of the definition (with scalar values) and merge is the merge formula; the test for an empty state is exercise 5. one is the state of a single key, \((s_i, 1, v_i)\), so building a chunk's state by merging single keys into it is the online update of section 15.4. The keys are cut into chunks of 32, as a kernel would cut them into blocks. The three combinations then exercise what the theorem allows: left to right, right to left (the order of the operands changes too), and a tree, where the loop over w = 1, 2, 4, ... is one level of a reduction per pass, merging neighbours w apart. The scores are chosen erratic (\(8 \sin(0.37 i^2)\)) so that the running max changes during the merges and the rescaling is really exercised. Three merge orders agree with the two-pass result to all 15 printed digits. The tree is how a parallel reduction combines the states of thread blocks; FlashAttention applies the same rescaling to blocks of keys inside one thread block [flash] [flash2], and decoding kernels that split a long cache across many thread blocks (“split-K”, or flash-decoding) finish with exactly this merge.
The paper approximates a cluster \(C\) by its mean key \(\bar k_C\) and mean value \(\bar v_C\), counted \(|C|\) times: in its Eq. 2 the cluster gets the mass \(|C|\, e^{q^\top \bar k_C/\sqrt d}\) (before normalizing) and contributes \(\bar v_C\). With \(\bar s_C = q^\top \bar k_C/\sqrt{d}\), that is the state
\[ (m, l, a) = \big(\bar s_C,\; |C|,\; |C|\, \bar v_C\big), \]since \(|C|\, e^{\bar s_C - m} = |C|\) when \(m = \bar s_C\). A cluster expanded to its keys is the state of its keys. A merge of all of them is the paper's mixed attention, and the kernel computes it the same way: expanded blocks, representatives and the exact recent tokens enter as three kinds of contribution, “merged using online softmax” ([refinekv], Appendix B.2). Because the dot product is linear, \(\bar s_C\) is also the mean of the cluster's logits \(s_i\) (section 8.6), which lets the program below work with scores alone. Every fourth cluster of 32 is expanded:
#include <math.h>
#include <stdio.h>
typedef struct { double m, l, a; } State;
static State merge(State x, State y)
{
if (x.l == 0) return y;
double m = fmax(x.m, y.m), ex = exp(x.m - m), ey = exp(y.m - m);
return (State){ m, x.l * ex + y.l * ey, x.a * ex + y.a * ey };
}
int main(void)
{
enum { N = 1024, B = 32, NB = N / B };
double s[N], v[N];
for (int i = 0; i < N; i++) { s[i] = 8 * sin(0.37 * i * i); v[i] = cos(0.11 * i); }
State st = { -INFINITY, 0, 0 };
double num = 0, den = 0; /* the same thing written directly */
for (int c = 0; c < NB; c++) {
double sbar = 0, vbar = 0;
for (int i = c * B; i < (c + 1) * B; i++) { sbar += s[i] / B; vbar += v[i] / B; }
if (c % 4 == 0) { /* expanded: every key */
for (int i = c * B; i < (c + 1) * B; i++) {
st = merge(st, (State){ s[i], 1, v[i] });
num += exp(s[i]) * v[i]; den += exp(s[i]);
}
} else { /* represented: (sbar, |C|, |C| vbar) */
st = merge(st, (State){ sbar, B, B * vbar });
num += B * exp(sbar) * vbar; den += B * exp(sbar);
}
}
double l = 0, a = 0;
for (int i = 0; i < N; i++) { l += exp(s[i]); a += exp(s[i]) * v[i]; }
printf("mixed, merged states %.15f\n", st.a / st.l);
printf("mixed, written out %.15f\n", num / den);
printf("exact attention %.15f\n", a / l);
return 0;
}
mixed, merged states -0.192264456652678 mixed, written out -0.192264456652679 exact attention -0.118410622853183
Each cluster is either merged key by key (expanded) or as the single state \((\bar s_C, |C|, |C|\bar v_C)\) (represented). Alongside, num and den write the same mixed attention out as a ratio of sums with the Eq. 2 masses \(|C|\, e^{\bar s_C}\) for represented clusters and \(e^{s_i}\) for expanded keys, without any shifting; that is safe here only because \(|s_i| \le 8\). The last loop is exact attention over all keys. Merging states and writing out the mixed formula agree (to the last digit's rounding). Neither agrees with exact attention: the scores in this test jump around within each cluster, and a representative cannot capture that. Measuring how far off it is, from the spread of the logits in a cluster, is section 18.6 and chapter 19. One direction is clear already: by Jensen's inequality (section 11.4), \(|C|\, e^{\bar s_C} \le \sum_{i \in C} e^{s_i}\), so a representative never receives more mass than its cluster had.
The whole thing in fp32, as a kernel would do it: the output \(o = \sum_i \alpha_i v_i\) for 32768 keys, values of dimension \(d_v = 64\), logits up to 40. What to expect, from sections 14.3 and 14.5: each output coordinate is a ratio of two sums of positive terms, with at most \(u\) of relative error per exponential, per product and per rescale, and summation error that grows with the number of additions into one accumulator. So all methods should land within a small multiple of \(u\) times the output's scale, and the one with the shortest accumulation chains should do best. Three ways are compared with a double-precision two-pass reference: two passes in float, one online pass, and chunks of 32 keys processed online and merged in order.
#include <math.h>
#include <stdio.h>
enum { N = 32768, DV = 64, B = 32 };
static float s[N], v[N][DV];
typedef struct { float m, l, a[DV]; } State; /* running max, sum, unnormalized output */
static void push(State *st, float si, const float *vi) /* online update with one key */
{
float mn = fmaxf(st->m, si), r = expf(st->m - mn), p = expf(si - mn);
st->l = st->l * r + p;
for (int j = 0; j < DV; j++) st->a[j] = st->a[j] * r + p * vi[j];
st->m = mn;
}
static void merge(State *x, const State *y) /* x = merge(x, y) */
{
float mn = fmaxf(x->m, y->m), rx = expf(x->m - mn), ry = expf(y->m - mn);
x->l = x->l * rx + y->l * ry;
for (int j = 0; j < DV; j++) x->a[j] = x->a[j] * rx + y->a[j] * ry;
x->m = mn;
}
static double maxerr(const State *st, const double *ref)
{
double e = 0;
for (int j = 0; j < DV; j++) e = fmax(e, fabs(st->a[j] / st->l - ref[j]));
return e;
}
int main(void)
{
for (int i = 0; i < N; i++) {
s[i] = (float)(40 * sin(0.37 * i) * sin(0.0011 * i * i)); /* logits in [-40, 40] */
for (int j = 0; j < DV; j++) v[i][j] = (float)cos(0.11 * i + j);
}
double m = s[0], l = 0, ref[DV] = { 0 }; /* reference: two passes, double */
for (int i = 1; i < N; i++) m = fmax(m, s[i]);
for (int i = 0; i < N; i++) {
double p = exp(s[i] - m);
l += p;
for (int j = 0; j < DV; j++) ref[j] += p * v[i][j];
}
for (int j = 0; j < DV; j++) ref[j] /= l;
State two = { (float)m, 0, { 0 } }; /* two passes, float */
for (int i = 0; i < N; i++) {
float p = expf(s[i] - two.m);
two.l += p;
for (int j = 0; j < DV; j++) two.a[j] += p * v[i][j];
}
State on = { -INFINITY, 0, { 0 } }, all = { -INFINITY, 0, { 0 } };
for (int i = 0; i < N; i++) push(&on, s[i], v[i]); /* one pass, float */
for (int c = 0; c < N / B; c++) { /* chunks of B, merged */
State ch = { -INFINITY, 0, { 0 } };
for (int i = c * B; i < (c + 1) * B; i++) push(&ch, s[i], v[i]);
merge(&all, &ch);
}
printf("N = %d, max logit %.3f, sum l = %.6f\n", N, m, l);
printf("max |o_j - ref_j|: two-pass %.1e one-pass %.1e merged chunks %.1e\n",
maxerr(&two, ref), maxerr(&on, ref), maxerr(&all, ref));
return 0;
}
N = 32768, max logit 39.998, sum l = 255.406147 max |o_j - ref_j|: two-pass 3.0e-07 one-pass 3.0e-07 merged chunks 6.1e-08
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.
The pieces are the chapter's formulas. State is \((m, l, a)\) with \(a \in \mathbb{R}^{d_v}\). push is the online update of section 15.4 (merge with a one-key state), merge the merge of section 15.5; both apply the same rescale factor to \(l\) and to every coordinate of \(a\), because they share the reference \(m\). The reference is the two-pass algorithm in double: first \(m\), then the sums. The float two-pass version is given \(m\) in advance, standing in for a first pass over the scores. The chunked version is what a GPU does with thread blocks: each chunk's state starts empty and is built from its 32 keys alone, as if on its own processor, and only states are combined. maxerr divides \(a/l\) only at the end, as the kernel would.
All three are within a few units of fp32's \(u = 6 \times 10^{-8}\) times the size of the outputs (at most 1 here). The online form is as accurate as two passes: the rescaling multiplies by numbers in \((0, 1]\), each one more rounding, which the error model of section 14.3 says costs at most \(u\) each. The merged chunks are the most accurate, for the reason of section 14.5: each chunk sums 32 terms into a fresh accumulator, and the long sum then has 1024 terms instead of 32768. Blocking for parallelism gives pairwise-like summation for free.
Section 16.8 puts the dot products in front of this loop and gets attention for one query.
The exponentials are 1, 2, 3, sum 6: weights \((1/6, 1/3, 1/2)\). \(\operatorname{LSE} = \ln 6 \approx 1.79\), between the max \(\ln 3 \approx 1.10\) and \(\ln 3 + \ln 3 \approx 2.20\).
As \(T \to 0\) the gaps \((s_i - m)/T\) of the non-maximal scores go to \(-\infty\): all weight goes to the max (split evenly among ties). As \(T \to \infty\) all scores go to 0 and the weights to \(1/N\). By the bounds of section 15.3, \(\max s \le T\operatorname{LSE}(s/T) \le \max s + T \ln N\), so the limit is \(\max s\): LSE is a max with the corners rounded off, and \(T\) sets the rounding.
\(\log \sum e^{s_j + c} = \log(e^c \sum e^{s_j}) = c + \log \sum e^{s_j}\). The rescale \(l_{i-1} e^{m_{i-1} - m_i}\) is this identity in the pair representation: \(m + \ln l\) stays the same number when \(m\) grows and \(l\) shrinks by the same factor.
Add the probabilities: \(\sum_{i=1}^N 1/i = H_N \approx \ln N + 0.577\). For \(N = 32768\) that is 10.97; records.c measures 11.00 on 2000 random sequences. On sorted increasing scores it changes every time, which is the worst case for a kernel that skips the rescale when the max holds.
merge.c has a test if (x.l == 0) return y;. What goes wrong without it when both states are empty?
Both \(m\) are \(-\infty\), so \(m = -\infty\) and \(e^{m_A - m} = e^{-\infty - (-\infty)} = e^{\text{NaN}}\): the state becomes NaN. One empty state is fine (\(e^{-\infty} = 0\)). A GPU kernel meets this when a whole block of keys is masked out (section 16.5).
Divide by \(|C|\): the claim is \(e^{\text{mean}(s)} \le \text{mean}(e^{s})\), which is Jensen's inequality for the convex function \(e^x\) (section 11.4). Equality holds exactly when all \(s_i\) in the cluster are equal: zero logit spread. The paper's mass correction (section 19.3) is a bound on how large the gap gets for a given spread \(\delta_C\).
attnsm.c that merges the 1024 chunk states as a tree instead of in order. Do you expect it to be more accurate still?
A little: each output now goes through about \(\log_2 1024 = 10\) merges instead of up to 1023, so the bound on the merge-stage rounding shrinks; the 32-term chunk sums are unchanged. The measured error was already near the last rounding of the result, so expect only a small gain. This is the form a GPU uses anyway, as a parallel reduction.