Every number in an attention kernel is a float. The paper's kernel reads keys and values in bf16, multiplies them on tensor cores and adds the products in fp32 ([refinekv], Appendix B.2). Its softmax has to survive exponentials that overflow fp32 above 88.7. Its error bounds are about the exact real-number attention, and the difference between that and what the GPU computes is the subject of this chapter. Section 1.1 gave a first look; here are the formats, the one rule IEEE 754 arithmetic obeys, and what follows from it: cancellation, summation error, fused multiply-add, the x87, and the 16-bit formats. Chapter 15 uses all of it to compute softmax without overflow.
A binary floating-point number is scientific notation in base 2: a sign, a significand with a fixed number of bits, and an exponent. A normal number is
\[ x = (-1)^s \times 1.f_1 f_2 \dots f_p \times 2^{e - \text{bias}}, \]where \(s\) is one bit, \(e\) is the exponent field read as an unsigned integer, and \(f_1 \dots f_p\) are the \(p\) fraction bits. The leading 1 is not stored: every normal number starts with it, so the format gets one bit of precision for free. The significand has \(t = p + 1\) bits of precision. The bias, \(2^{\text{exponent bits} - 1} - 1\), makes the stored exponent unsigned, so that comparing two positive floats as integers gives the same order as comparing them as numbers.
Two exponent values are reserved. \(e = 0\) holds zero and the subnormals \(0.f \times 2^{1 - \text{bias}}\), which fill the gap between 0 and the smallest normal number with evenly spaced values. \(e\) all ones holds \(\pm\infty\) (fraction 0) and NaN (fraction not 0). IEEE 754 [ieee754] defines the formats; the four that matter here are in figure 14.1.
The program takes a float apart and builds the field table from the widths alone: largest value \((2 - 2^{-p}) \times 2^{\text{bias}}\), smallest normal \(2^{1 - \text{bias}}\), and the gap after 1, \(2^{-p}\).
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static void show(float x)
{
uint32_t b;
memcpy(&b, &x, sizeof b); /* the bits, without breaking aliasing rules */
unsigned s = b >> 31, e = (b >> 23) & 0xff, f = b & 0x7fffff;
double val = ldexp(1.0 + f / 8388608.0, (int)e - 127) * (s ? -1 : 1);
printf("%-10g bits %08x sign %u exp %3u (2^%-4d) frac 0x%06x -> %.10g\n",
x, (unsigned)b, s, e, (int)e - 127, f, val);
}
int main(void)
{
show(1.0f); show(-6.5f); show(0.1f); show(65504.0f);
/* fields: name, exponent bits, fraction bits */
struct { const char *name; int ebits, p; } fmt[] = {
{ "fp64", 11, 52 }, { "fp32", 8, 23 }, { "fp16", 5, 10 }, { "bf16", 8, 7 } };
printf("\nformat bits exp frac bias max min normal eps (2^-p)\n");
for (int i = 0; i < 4; i++) {
int bias = (1 << (fmt[i].ebits - 1)) - 1;
printf("%-6s %4d %4d %4d %5d %-12.5g %-12.5g %.5g\n", fmt[i].name,
1 + fmt[i].ebits + fmt[i].p, fmt[i].ebits, fmt[i].p, bias,
ldexp(2 - ldexp(1, -fmt[i].p), bias), ldexp(1, 1 - bias), ldexp(1, -fmt[i].p));
}
return 0;
}
1 bits 3f800000 sign 0 exp 127 (2^0 ) frac 0x000000 -> 1 -6.5 bits c0d00000 sign 1 exp 129 (2^2 ) frac 0x500000 -> -6.5 0.1 bits 3dcccccd sign 0 exp 123 (2^-4 ) frac 0x4ccccd -> 0.1000000015 65504 bits 477fe000 sign 0 exp 142 (2^15 ) frac 0x7fe000 -> 65504 format bits exp frac bias max min normal eps (2^-p) fp64 64 11 52 1023 1.7977e+308 2.2251e-308 2.2204e-16 fp32 32 8 23 127 3.4028e+38 1.1755e-38 1.1921e-07 fp16 16 5 10 15 65504 6.1035e-05 0.00097656 bf16 16 8 7 127 3.3895e+38 1.1755e-38 0.0078125
How it maps to the formula. show splits the 32 bits by position: b >> 31 is \(s\), the next 8 bits ((b >> 23) & 0xff) are \(e\), the low 23 bits are the fraction \(f\) read as an integer. The value line is the definition itself: \(1 + f/2^{23}\) is \(1.f_1 \dots f_{23}\) with the hidden 1 put back, and ldexp multiplies by \(2^{e - 127}\). The table needs nothing but the two widths, because everything else follows from them. The largest exponent field, all ones, is reserved for \(\infty\) and NaN, so the top normal exponent is one less, which after the bias is \(2^{\text{bias}}\); the largest significand is all fraction bits set, \(2 - 2^{-p}\). The smallest normal has \(e = 1\) and fraction 0, hence \(2^{1 - \text{bias}}\).
Read the table by columns. The exponent bits set the range: fp32 and bf16 both reach \(3.4 \times 10^{38}\), fp16 stops at 65504. The fraction bits set the precision: about \(p \log_{10} 2\) decimal digits, so 16 for fp64, 7 for fp32, 3 for fp16 and 2 for bf16. And 0.1 is not a float: its fraction is the repeating binary 0x4ccccc..., cut and rounded up to ...cd.
In the machine. memcpy into a uint32_t is the portable way to read the bits; compilers turn it into one register move (movd). Casting a float * to uint32_t * breaks C's aliasing rules, and -O2 is allowed to miscompile it.
Between \(2^E\) and \(2^{E+1}\) there are exactly \(2^p\) floats, evenly spaced. The spacing is the ulp (unit in the last place):
\[ \operatorname{ulp}(x) = 2^{E - p} \quad \text{for } 2^E \le |x| < 2^{E+1}. \]It doubles at each power of two. In fp32 the ulp of 1 is \(2^{-23} \approx 1.2 \times 10^{-7}\); at \(2^{24} = 16777216\) it is 2, so from there on odd integers are not floats. nextafter(x, y) returns the neighbour of \(x\) in the direction of \(y\); the difference is the ulp.
A real number that falls between two floats must be rounded to one of them. The default rule of IEEE 754, and the only one you meet unless you call fesetround, is round to nearest, ties to even: take the nearer float; on an exact tie, take the one whose last fraction bit is 0. Always rounding ties up would push sums of many ties upward on average; ties to even goes up half the time and down half the time.
#include <math.h>
#include <stdio.h>
int main(void)
{
float xs[] = { 1.0f, 1000.0f, 16777216.0f }; /* 16777216 = 2^24 */
for (int i = 0; i < 3; i++)
printf("ulp(%.0f) = %g\n", xs[i], nextafterf(xs[i], INFINITY) - xs[i]);
/* integers between 2^24 and 2^25 are 2 apart in float: odd ones are ties */
for (long n = 16777217; n <= 16777223; n += 2)
printf("%ld -> %.0f\n", n, (float)n);
printf("0.1f is exactly %.30f\n", 0.1f);
printf("0.1f - 0.1 = %.3g (half an ulp of 0.1f is %.3g)\n",
(double)0.1f - 0.1, (nextafterf(0.1f, 1) - 0.1f) / 2.0);
return 0;
}
ulp(1) = 1.19209e-07 ulp(1000) = 6.10352e-05 ulp(16777216) = 2 16777217 -> 16777216 16777219 -> 16777220 16777221 -> 16777220 16777223 -> 16777224 0.1f is exactly 0.100000001490116119384765625000 0.1f - 0.1 = 1.49e-09 (half an ulp of 0.1f is 3.73e-09)
The first loop is the definition: for positive \(x\), nextafterf(x, INFINITY) - x is \(\operatorname{ulp}(x)\), and the subtraction is exact because neighbouring floats differ by a float. The second loop picks inputs that test only the tie rule: every odd integer between \(2^{24}\) and \(2^{25}\) lies exactly midway between two floats, so the cast (float)n has no nearer neighbour to choose and must decide by evenness. 16777217 is exactly halfway between 16777216 and 16777218; the first has an even significand, so it wins. 16777219 is halfway between 16777218 and 16777220, and this time the upper one is even. The last two lines show the rounding error of 0.1: about \(1.5 \times 10^{-9}\), under half an ulp, as the rule promises.
The other modes, toward zero, toward \(+\infty\) and toward \(-\infty\), exist for interval arithmetic: compute a lower bound rounding down and an upper bound rounding up, and the true result lies between them. Nothing in this book needs them.
IEEE 754 requires that \(+\), \(-\), \(\times\), \(/\) and \(\sqrt{\ }\) be correctly rounded: the result is the exact real result, rounded by the rule of section 14.2 [ieee754]. That one requirement gives a model of every float computation.
Let \(u = 2^{-t} = 2^{-(p+1)}\), the unit roundoff: half the gap after 1. It is \(2^{-53} \approx 1.1 \times 10^{-16}\) for fp64, \(2^{-24} \approx 6.0 \times 10^{-8}\) for fp32, \(2^{-11} \approx 4.9 \times 10^{-4}\) for fp16 and \(2^{-8} \approx 3.9 \times 10^{-3}\) for bf16. (Machine epsilon, FLT_EPSILON, is \(2u\).) If \(2^E \le |x| < 2^{E+1}\), rounding moves \(x\) by at most half an ulp, \(2^{E-p-1} = 2^E u \le u|x|\). So the rounded value \(\operatorname{fl}(x)\) has relative error at most \(u\):
Theorem (the standard model). For floats \(a, b\) and \(\circ\) one of \(+, -, \times, /\), if the result neither overflows nor falls into the subnormal range,
\[ \operatorname{fl}(a \circ b) = (a \circ b)(1 + \varepsilon), \qquad |\varepsilon| \le u. \]The same holds for \(\operatorname{fl}(\sqrt{a})\) [higham].
Each operation is exact up to a relative wobble of at most \(u\), and \(\varepsilon\) is a different unknown number each time.
A check on ten million random pairs in \([-1000, 1000]\) (errmodel.c in this chapter's sources) compares each fp32 result with the same operation in long double (64-bit significand, section 14.6) and prints the largest \(|\varepsilon|\) in units of \(u\), so that the theorem reads “every number is at most 1”:
a + b max |eps| = 1.000000 u a * b max |eps| = 0.999261 u a / b max |eps| = 0.999706 u sqrt(|a|) max |eps| = 0.999998 u
The bound is reached and never exceeded. (The 1.000000 is a value just under 1 rounded for printing: measured against the exact result, the worst case is \(u/(1+u)\).) Why the reference can be trusted: the product of two 24-bit significands has at most 48 bits and the 64-bit significand holds it exactly; a sum of two floats is exact in it unless their exponents differ by more than 40, which random values in this range practically never do, and otherwise its own error, \(2^{-64}\), is far below what is being measured. Division and square root are rounded in long double too, at the same negligible \(2^{-64}\).
The model makes error analysis algebra. Two operations in a row give a factor \((1 + \varepsilon_1)(1 + \varepsilon_2)\), which lies between \((1-u)^2\) and \((1+u)^2\), so the relative error is at most \(2u + u^2\). After \(n\) operations the factors multiply to something within \(\gamma_n = nu/(1 - nu)\) of 1, which is \(nu\) to first order [higham]. Section 14.5 uses exactly this.
exp, log, sin and the rest are not covered: IEEE 754 recommends correct rounding for them but does not require it, and most libms do not promise it. FreeBSD's expf stays within an ulp: a scan of every float in \([-87, 88.7]\) against the double exp (expulp.c in this chapter's sources) finds at most 0.91 ulp. Section 5.6 shows how a libm gets there.
Watch out. The model is about relative error. Near underflow it fails: a subnormal result has an absolute error up to half the smallest subnormal (\(2^{-150}\) in fp32), which can be a 100% relative error. Softmax produces many tiny weights; they underflow to 0, harmlessly, because they are small next to the sum they are divided by.
Subtracting two nearly equal floats is itself exact. (If \(y/2 \le x \le 2y\), then \(x - y\) is a float, Sterbenz's lemma [higham].) The trouble is what the operands carry with them. Suppose \(\tilde x = x(1 + \varepsilon_1)\) and \(\tilde y = y(1 + \varepsilon_2)\) are earlier results, each off by at most \(u\). Then
\[ \frac{|(\tilde x - \tilde y) - (x - y)|}{|x - y|} = \frac{|x\varepsilon_1 - y\varepsilon_2|}{|x - y|} \le u \, \frac{|x| + |y|}{|x - y|}. \]The factor \((|x| + |y|)/|x - y|\) is the condition number of the subtraction. When \(x \approx y\) it is huge: the leading digits cancel, and what is left is mostly the earlier rounding errors, promoted to the leading digits. Floats are like a fixed-width register with an automatic shift: after the subtraction the result is shifted left to normalize it, and the low bits shifted in are zeros, not information.
The classic case is the small root of \(x^2 - 2bx + c = 0\), which is \(b - \sqrt{b^2 - c}\). For \(b \gg c\), \(\sqrt{b^2 - c} \approx b\). Multiplying top and bottom by \(b + \sqrt{b^2 - c}\) gives the same root as \(c / (b + \sqrt{b^2 - c})\), which adds instead of subtracting:
#include <math.h>
#include <stdio.h>
int main(void)
{
/* the small root of x^2 - 2bx + c = 0 is b - sqrt(b^2 - c) = c / (b + sqrt(b^2 - c)) */
float bs[] = { 10.0f, 100.0f, 1000.0f, 10000.0f };
float c = 1.0f;
for (int i = 0; i < 4; i++) {
float b = bs[i];
float r = sqrtf(b * b - c);
float naive = b - r;
float stable = c / (b + r);
double exact = 1.0 / ((double)b + sqrt((double)b * b - 1.0));
printf("b = %5.0f naive %.7e (rel err %.1e) stable %.7e (rel err %.1e)\n", b,
naive, fabs(naive - exact) / exact, stable, fabs(stable - exact) / exact);
}
return 0;
}
b = 10 naive 5.0126076e-02 (rel err 8.9e-06) stable 5.0125629e-02 (rel err 4.5e-09) b = 100 naive 4.9972534e-03 (rel err 5.7e-04) stable 5.0001252e-03 (rel err 2.9e-08) b = 1000 naive 4.8828125e-04 (rel err 2.3e-02) stable 5.0000014e-04 (rel err 3.0e-08) b = 10000 naive 0.0000000e+00 (rel err 1.0e+00) stable 4.9999999e-05 (rel err 2.8e-08)
r is \(\sqrt{b^2 - c}\), already off by a relative error of order \(u\) from the rounding of \(b^2\), the subtraction and the root. naive subtracts it from \(b\): condition number \((b + r)/(b - r) \approx 4b^2/c\), so the relative error of r is multiplied by about \(4 \times 10^{8}\) at \(b = 10^4\), which is more than \(1/u\). stable is the same real number, because \((b - r)(b + r) = b^2 - r^2 = c\), but it only adds two positive numbers and divides: each step has relative error at most \(u\), and none amplifies the error before it. The reference uses the stable form in double, so that its own error (around \(10^{-16}\)) is far below what it measures. Each tenfold increase of \(b\) loses two more decimal digits of the naive root (the condition number grows like \(b^2\)), until at \(b = 10^4\) nothing is left: \(b^2 - 1\) rounds to \(b^2\). The rewritten form keeps full fp32 accuracy throughout. As in section 1.3, the cure is algebra done before the code runs.
The paper has a case of its own. The logit deviation \(q^\top(k_i - \bar k_C)/\sqrt{d}\) behind \(\delta_C\) (chapter 19) is small exactly when the cluster is good, and keys share large common components. Computed as \(q^\top k_i - q^\top \bar k_C\), it is a difference of two large, nearly equal dot products. Subtracting the vectors first is better: each \(k_{ij} - \bar k_{Cj}\) is exact when the two are within a factor 2 of each other (Sterbenz, coordinate by coordinate), so the only errors left are those of a dot product with small terms. On a test with \(d = 128\), key coordinates of size about 10 and offsets of size \(10^{-3}\) (dev.c), in fp32:
q.k - q.kbar = -2.286911e-03 (rel err 4.0e-03) q.(k - kbar) = -2.277724e-03 (rel err 2.3e-07)
The difference of dot products keeps two correct digits; the dot product of the difference keeps nearly all seven.
A dot product, a softmax denominator and an attention output are all sums. The obvious loop computes \(\hat s_k = \operatorname{fl}(\hat s_{k-1} + x_k)\). By the model each addition multiplies everything summed so far by its own \((1 + \varepsilon_k)\), so \(x_1\) and \(x_2\) pass through \(n - 1\) roundings, \(x_3\) through \(n - 2\), and \(x_n\) through one. Bounding each product of factors by \(\gamma_{n-1}\):
Fact (recursive summation). \(\displaystyle \Big|\hat s_n - \sum_{i=1}^n x_i\Big| \le \gamma_{n-1} \sum_{i=1}^n |x_i| \approx (n-1)\,u \sum_{i=1}^n |x_i|\) [higham].
The error is relative to \(\sum |x_i|\), not to the sum itself: if the terms cancel (mixed signs), the relative error of the result can be any size. Softmax sums are of positive terms, where the two are the same. The bound grows with \(n\) because one accumulator collects every rounding. Two fixes:
Ten million uniform numbers in \([0, 1)\), summed in fp32, against a double reference:
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static float pairwise(const float *x, long n)
{
if (n <= 8) {
float s = 0;
for (long i = 0; i < n; i++) s += x[i];
return s;
}
return pairwise(x, n / 2) + pairwise(x + n / 2, n - n / 2);
}
static float kahan(const float *x, long n)
{
float s = 0, c = 0; /* c holds the low bits lost so far, negated */
for (long i = 0; i < n; i++) {
float y = x[i] - c;
float t = s + y;
c = (t - s) - y; /* what of y did not make it into t */
s = t;
}
return s;
}
int main(void)
{
const long n = 10000000;
float *x = malloc(n * sizeof *x);
uint64_t st = 1;
double ref = 0; /* double: exact enough to judge float */
for (long i = 0; i < n; i++) {
st = st * 6364136223846793005u + 1442695040888963407u;
x[i] = (float)(st >> 40) / 16777216.0f; /* uniform in [0, 1) */
ref += x[i];
}
float naive = 0;
for (long i = 0; i < n; i++) naive += x[i];
float p = pairwise(x, n), k = kahan(x, n);
printf("exact %.1f\n", ref);
printf("naive %.1f rel err %.1e\n", naive, fabs(naive - ref) / ref);
printf("pairwise %.1f rel err %.1e\n", p, fabs(p - ref) / ref);
printf("kahan %.1f rel err %.1e\n", k, fabs(k - ref) / ref);
printf("bounds: n*u = %.1e, log2(n)*u = %.1e, 2u = %.1e\n",
n * 0x1p-24, log2((double)n) * 0x1p-24, 2 * 0x1p-24);
float ones = 0;
for (long i = 0; i < 20000000; i++) ones += 1.0f;
printf("1.0f added 20000000 times = %.0f\n", ones);
free(x);
return 0;
}
exact 4999328.3 naive 4999149.0 rel err 3.6e-05 pairwise 4999328.5 rel err 3.3e-08 kahan 4999328.5 rel err 3.3e-08 bounds: n*u = 6.0e-01, log2(n)*u = 1.4e-06, 2u = 1.2e-07 1.0f added 20000000 times = 16777216
The three functions are the three bounds. pairwise splits the array in halves and adds the two sums, so a term passes through one addition per level of the recursion, \(\lceil \log_2(n/8) \rceil\) levels, plus at most 7 in its leaf; the leaves of 8 are there only to keep call overhead down and change the bound by a constant. In kahan, t = s + y loses the low part of y; t - s is the part of y that got in (exactly, as long as \(|s| \ge |y|\), which holds here after the first few terms), and subtracting y leaves minus the lost part, \(c\). The next term is corrected by \(-c\) before it is added, so the lost bits re-enter the sum one step late instead of never. The double reference has its own error, at most about \(n\,2^{-53} \approx 10^{-9}\) relative by the same bound, far below every float error it is used to measure.
Pairwise and Kahan are both off by the last rounding only: 4999328.5 is the float nearest the true sum (the ulp there is 0.5). The naive loop is a thousand times worse, though still far inside its bound \(nu\), because the individual errors have both signs and partly cancel; the bounds are guarantees, not predictions. The last line is the failure the bound allows: once the running sum reaches \(2^{24}\), adding 1 is a tie that rounds back down, and the loop stops moving.
In the machine. Algebraically \((t - s) - y = 0\), and -ffast-math allows the compiler to use algebra. Compiled with it (flags.sh in the sources), this program's Kahan sum prints the same 4999339.0 as its naive sum: the correction is gone. The naive sum itself gets better, since reassociation lets clang keep several accumulators in vector registers, and the loop of 20000000 ones now reaches 20000000, because the compiler may regroup it too. Reproducibility is gone too: the result now depends on the vector width.
An FMA computes \(ab + c\) with a single rounding: \(\operatorname{fl}(ab + c) = (ab + c)(1 + \varepsilon)\). The product is kept exact, all \(2t\) bits of it, until the addition. C99 has it as fma and fmaf; x86 has had it in hardware since Haswell (vfmadd), GPUs for longer. It does two things for this book. A dot product becomes \(d\) FMAs, with \(d\) roundings instead of \(2d\). And it gives the rounding error of a product exactly: if \(p = \operatorname{fl}(ab)\), then \(ab - p\) is a float, and fma(a, b, -p) computes it with no error at all.
#include <float.h>
#include <math.h>
#include <stdio.h>
int main(void)
{
volatile float a = 1.0f + 0x1p-12f; /* volatile: computed at run time */
float p = a * a; /* exact: 1 + 2^-11 + 2^-24; rounded */
float lost = a * a - p; /* rounded again: the low bit is gone */
float err = fmaf(a, a, -p); /* a*a - p with one rounding: exact */
printf("a*a = %.10f\n", p);
printf("a*a - p = %g without fma, %g with fma (2^-24 = %g)\n", lost, err, 0x1p-24);
return 0;
}
a*a = 1.0004882812 a*a - p = 0 without fma, 5.96046e-08 with fma (2^-24 = 5.96046e-08)
\(a = 1 + 2^{-12}\) is chosen so that \(a^2 = 1 + 2^{-11} + 2^{-24}\) needs 25 bits; the 24-bit float drops the last one (a tie, rounded to even), so \(p = \operatorname{fl}(a^2)\) is off by exactly \(2^{-24}\). a * a - p is \(\operatorname{fl}(\operatorname{fl}(a^2) - p) = \operatorname{fl}(p - p) = 0\): the product is rounded again before the subtraction sees it. fmaf(a, a, -p) is \(\operatorname{fl}(a^2 - p) = \operatorname{fl}(2^{-24})\), and \(2^{-24}\) is a float, so the one rounding changes nothing. That \(ab - \operatorname{fl}(ab)\) is always a float (barring underflow) is the theorem that makes this exact [muller]. a is volatile so the compiler cannot fold the arithmetic at compile time and the instructions really run. The same trick refines a reciprocal: rcpps gives \(1/a\) to about 12 bits [intel-sdm], and a Newton step \(x + x(1 - ax)\), with the residual \(1 - ax\) computed by an FMA, roughly doubles that (section 2.6).
In the machine. The C standard allows a compiler to contract a * b + c into an FMA, and clang does by default when the target has one. Compiled with -march=haswell, the program above prints 5.96046e-08 without fma: the subtraction was fused. Results then depend on the target flags. -ffp-contract=off forbids it.
The x87 floating-point unit of the 8087 through the Pentium Pro and its successors does not compute in float or double. Its eight stack registers hold 80-bit extended numbers: 1 sign bit, 15 exponent bits and a 64-bit significand whose leading 1 is stored explicitly [intel-sdm]. Loads convert float or double to extended exactly; arithmetic rounds to the precision control (PC) field, bits 8 and 9 of the FPU control word: 00 for 24 bits, 10 for 53, 11 for 64. Stores round to the memory format [intel-sdm].
So a double computed on the x87 can be rounded twice: once to 64 bits in the register, once to 53 bits when it is stored. Usually that is the same as rounding once. It is not when the first rounding lands exactly on a halfway point of the second [goldberg] [muller]. With \(a = 1\) and \(b = 2^{-53} + 2^{-78}\), the exact sum is a little above the midpoint between 1 and \(1 + 2^{-52}\): one rounding goes up. The 64-bit register cannot hold the \(2^{-78}\) and rounds to the midpoint exactly; the store then sees a tie and rounds to even, down to 1.
On FreeBSD/amd64 long double is the x87 extended format, so this runs without assembly. FreeBSD's <ieeefp.h> reads and sets the PC field:
#include <float.h>
#include <ieeefp.h> /* FreeBSD: fpgetprec, fpsetprec */
#include <stdio.h>
int main(void)
{
printf("LDBL_MANT_DIG = %d, x87 precision control = %d (FP_PS %d, FP_PD %d, FP_PE %d)\n",
LDBL_MANT_DIG, (int)fpgetprec(), FP_PS, FP_PD, FP_PE);
volatile double a = 1.0, b = 0x1p-53 + 0x1p-78; /* exact sum: 1 + 2^-53 + 2^-78 */
double once = a + b; /* SSE2: one rounding to 53 bits */
volatile long double wide = (long double)a + b; /* x87: rounded to 64 bits ... */
double twice = (double)wide; /* ... then to 53 bits */
printf("one rounding: 1 + %g ulp\n", (once - 1) / DBL_EPSILON);
printf("two roundings: 1 + %g ulp\n", (twice - 1) / DBL_EPSILON);
fpsetprec(FP_PD); /* x87 rounds significands to 53 bits */
volatile long double pd = (long double)a + b;
volatile long double big = DBL_MAX;
long double bigger = big * 2;
fpsetprec(FP_PE);
printf("PC = 53 bits: 1 + %g ulp\n", (double)((pd - 1) / DBL_EPSILON));
printf("PC = 53 bits: DBL_MAX * 2 = %Lg in a register, %g stored as double\n",
bigger, (double)bigger);
return 0;
}
LDBL_MANT_DIG = 64, x87 precision control = 3 (FP_PS 0, FP_PD 2, FP_PE 3) one rounding: 1 + 1 ulp two roundings: 1 + 0 ulp PC = 53 bits: 1 + 1 ulp PC = 53 bits: DBL_MAX * 2 = 3.59539e+308 in a register, inf stored as double
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 program is the two-rounding argument above, step by step. once is an SSE2 addsd: the exact sum rounded once to 53 bits. For wide, both conversions to long double are exact and the addition is an x87 fadd under PC = 64, which is the first rounding; the cast to double is the second. Then fpsetprec(FP_PD) writes 10 into the PC field, and the same fadd now rounds straight to 53 bits: one rounding again, the right answer. The last line multiplies DBL_MAX by 2 under PC = 53: the significand is rounded to 53 bits but the exponent field is still 15 bits, so the result is finite until it is stored as a double. The operands are volatile because the compiler folds constant expressions with the full 64-bit significand and knows nothing of the PC setting at run time.
The first line confirms the 64-bit significand, with PC set to 64 bits (FreeBSD/amd64's initial control word is 0x037F; FreeBSD/i386 starts with 0x127F, PC = 53 bits, per <x86/fpu.h>). Setting PC to 53 bits fixes the double rounding, but not everything: the exponent stays 15 bits wide, so a value past DBL_MAX lives on in the register and turns into infinity only when stored. Whether a 32-bit program printed a finite number then depended on whether the compiler happened to spill that register. This is why the same C code gave different answers on a Pentium Pro and on another machine, and why x87-era numerical results are hard to reproduce. Since SSE2, and by default on amd64, float and double arithmetic is done in XMM registers in the declared format: one rounding, the same everywhere.
The idea behind the x87 survives in a better form: keep a wider accumulator than the inputs, on purpose and visibly. That is the next section.
Model weights and the KV cache are stored in 16-bit formats, because decoding is limited by memory bandwidth (section 17.4): half the bytes, half the time. The two 16-bit formats split their bits differently (figure 14.1):
| format | exponent | fraction | largest | smallest normal | \(u\) |
|---|---|---|---|---|---|
| fp16 (IEEE binary16) | 5 | 10 | 65504 | \(6.1 \times 10^{-5}\) | \(4.9 \times 10^{-4}\) |
| bf16 (bfloat16) | 8 | 7 | \(3.39 \times 10^{38}\) | \(1.2 \times 10^{-38}\) | \(3.9 \times 10^{-3}\) |
| fp32 | 8 | 23 | \(3.40 \times 10^{38}\) | \(1.2 \times 10^{-38}\) | \(6.0 \times 10^{-8}\) |
fp16 has three decimal digits and a range that ends at \((2 - 2^{-10}) \times 2^{15} = 65504\). bf16 has fp32's range and barely two digits. For training and inference, range matters more: a value that overflows to infinity ruins a whole computation, while a value off in its third digit mostly averages out [bf16]. And bf16 is fp32 with the low 16 bits removed, so conversion is a shift. Truncation is the cheap way; adding 0x7fff plus the lowest kept bit before shifting rounds to nearest, ties to even (a NaN input needs a separate test, left out here). C has no bf16 type; clang's _Float16 (an extension) provides fp16 on amd64.
#include <float.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static uint32_t bits(float x) { uint32_t b; memcpy(&b, &x, 4); return b; }
static float from(uint32_t b) { float x; memcpy(&x, &b, 4); return x; }
/* bf16 is the top 16 bits of a float. (NaN inputs are not handled here.) */
static uint16_t bf16_trunc(float x) { return (uint16_t)(bits(x) >> 16); }
static uint16_t bf16_round(float x) /* round to nearest, ties to even */
{
uint32_t b = bits(x);
b += 0x7fff + ((b >> 16) & 1); /* add just under half, plus 1 if the kept part is odd */
return (uint16_t)(b >> 16);
}
static float bf16_to_float(uint16_t h) { return from((uint32_t)h << 16); }
int main(void)
{
float xs[] = { 1.0f / 3, 3.14159265f, 1.00390625f, 300.5f, 65504.0f };
for (int i = 0; i < 5; i++)
printf("%-11.9g bf16 truncated %-9.6g rounded %-9.6g fp16 %.9g\n", xs[i],
bf16_to_float(bf16_trunc(xs[i])), bf16_to_float(bf16_round(xs[i])),
(double)(_Float16)xs[i]);
printf("fp16: 65519 -> %g, 65520 -> %g, 1e-8 -> %g, 2^-24 -> %g\n",
(double)(_Float16)65519.0f, (double)(_Float16)65520.0f,
(double)(_Float16)1e-8f, (double)(_Float16)0x1p-24f);
printf("bf16: 1e38 -> %g, 1e-38 -> %g\n",
bf16_to_float(bf16_round(1e38f)), bf16_to_float(bf16_round(1e-38f)));
volatile float a = 88.72f, b = 88.73f;
printf("ln(FLT_MAX) = %.4f: expf(88.72) = %g, expf(88.73) = %g\n",
log(FLT_MAX), expf(a), expf(b));
printf("ln(65504) = %.4f: exp(11.09) = %.1f, exp(11.10) = %.1f\n",
log(65504.0), exp(11.09), exp(11.10));
return 0;
}
0.333333343 bf16 truncated 0.332031 rounded 0.333984 fp16 0.333251953 3.14159274 bf16 truncated 3.14062 rounded 3.14062 fp16 3.140625 1.00390625 bf16 truncated 1 rounded 1 fp16 1.00390625 300.5 bf16 truncated 300 rounded 300 fp16 300.5 65504 bf16 truncated 65280 rounded 65536 fp16 65504 fp16: 65519 -> 65504, 65520 -> inf, 1e-8 -> 0, 2^-24 -> 5.96046e-08 bf16: 1e38 -> 9.96921e+37, 1e-38 -> 1.00101e-38 ln(FLT_MAX) = 88.7228: expf(88.72) = 3.39318e+38, expf(88.73) = inf ln(65504) = 11.0899: exp(11.09) = 65512.7, exp(11.10) = 66171.2
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.
Why the rounding line works. The low 16 bits of the float are what bf16 drops. Adding 0x7fff carries into bit 16 exactly when they exceed 0x8000, half an ulp of the bf16 result: round up above the midpoint, down below. At exactly 0x8000, the tie, the extra (b >> 16) & 1 (the last kept bit) supplies the carry only when that bit is 1, which leaves the kept part even. A carry out of the 7 fraction bits increments the exponent, which is right: the value after the largest significand is the next power of 2; a carry into the all-ones exponent gives infinity, which is right too. A NaN's fraction could carry into a different pattern, which is why NaN needs its own test. Truncation keeps only the top half, rounding toward zero: cheaper, and up to a whole ulp off, as 1/3 shows.
65504 is the largest fp16; 65520 is the midpoint between it and \(2^{16}\), which would be the next value if the exponent had room, so it rounds to infinity. The smallest fp16 is the subnormal \(2^{-24}\); anything up to half of it rounds to zero, as \(10^{-8}\) does. bf16 rounds 65504 to 65536, a perfectly ordinary bf16, and holds \(10^{38}\) without trouble, but 1/3 has only two correct digits.
The last two lines matter for chapter 15: \(e^x\) overflows fp32 (and bf16) for \(x\) above ln(FLT_MAX) \(\approx 88.72\), and fp16 for \(x > \ln 65504 \approx 11.09\). Attention logits \(q^\top k_i/\sqrt d\) of 20 or 100 are normal. Softmax as written in a textbook is therefore broken in every one of these formats.
The paper's kernel does its matrix products with bf16 tensor-core operations and fp32 accumulation ([refinekv], Appendix B.2). The split is deliberate. The product of two bf16 numbers has at most \(8 + 8 = 16\) significant bits, so it is exact in fp32. The only roundings left are the additions, made at fp32's \(u = 6 \times 10^{-8}\). Accumulating in bf16 instead would round every partial sum to 8 bits. Measured on dot products of length 128, the head dimension of both models in the paper:
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static float bf16(float x) /* round a float to the nearest bf16, kept in a float */
{
uint32_t b;
memcpy(&b, &x, 4);
b += 0x7fff + ((b >> 16) & 1);
b &= 0xffff0000u;
memcpy(&x, &b, 4);
return x;
}
static uint64_t st = 12345;
static float gauss(void) /* sum of 4 uniforms, roughly normal */
{
double s = 0;
for (int i = 0; i < 4; i++) {
st = st * 6364136223846793005u + 1442695040888963407u;
s += (double)(st >> 11) / 9007199254740992.0 - 0.5;
}
return (float)s;
}
int main(void)
{
enum { D = 128, T = 10000 };
double e_in = 0, e32 = 0, e16 = 0;
for (int t = 0; t < T; t++) {
float q[D], k[D];
double exact = 0, exact_bf = 0, mag = 0;
float acc32 = 0, acc16 = 0;
for (int j = 0; j < D; j++) {
q[j] = gauss(); k[j] = gauss();
float qb = bf16(q[j]), kb = bf16(k[j]);
exact += (double)q[j] * k[j];
exact_bf += (double)qb * kb;
mag += fabs((double)q[j] * k[j]);
acc32 += qb * kb; /* product exact in float; fp32 add */
acc16 = bf16(acc16 + qb * kb); /* sum kept in bf16 */
}
e_in += fabs(exact_bf - exact) / mag;
e32 += fabs(acc32 - exact_bf) / mag;
e16 += fabs(acc16 - exact_bf) / mag;
}
printf("mean error / sum|q_j k_j|, d = %d:\n", D);
printf(" rounding inputs to bf16 %.1e\n", e_in / T);
printf(" fp32 accumulation %.1e\n", e32 / T);
printf(" bf16 accumulation %.1e\n", e16 / T);
return 0;
}
mean error / sum|q_j k_j|, d = 128: rounding inputs to bf16 2.5e-04 fp32 accumulation 6.4e-09 bf16 accumulation 1.3e-03
The program separates the two sources of error by computing three dot products of the same vectors. exact uses the original fp32 inputs, exact_bf the bf16-rounded ones, both in double, where the products are exact and 128 additions cost about \(10^{-14}\): these are the real numbers, and their difference is the price of storing in bf16. acc32 is the tensor-core arithmetic: qb * kb is exact in float, and only the fp32 additions round. acc16 rounds every partial sum to bf16, as a bf16 accumulator would. Errors are divided by \(\sum_j |q_j k_j|\), the scale in the summation bound of section 14.5, because a dot product itself can be near 0.
Rounding the inputs costs about \(2.5 \times 10^{-4}\) of the magnitude: that error is fixed once the cache is stored in bf16. The fp32 accumulator adds almost nothing on top. A bf16 accumulator would add five times the input error. A cheap format for the bytes that move, a wide one for the register that sums: the x87 idea, without its surprises.
0xc1480000 by hand.
Sign 1. Exponent field 0x82 = 130, so \(2^{130 - 127} = 2^3\). Fraction 0x480000 = binary 1001 followed by zeros, so the significand is \(1.1001_2 = 1.5625\). Value \(-1.5625 \times 8 = -12.5\).
\(2^{23}\) in both: every binade has the same number. 1000 lies in \([2^9, 2^{10})\): the fp16 ulp is \(2^{9-10} = 0.5\), the bf16 ulp is \(2^{9-7} = 4\).
\(\operatorname{fl}(\operatorname{fl}(ab)c) = abc(1 + \varepsilon_1)(1 + \varepsilon_2)\), so the relative error is \(|\varepsilon_1 + \varepsilon_2 + \varepsilon_1\varepsilon_2| \le 2u + u^2\). Products, unlike sums, never suffer cancellation: the relative error just adds up.
\(\sqrt{x+1} - \sqrt{x} = 1/(\sqrt{x+1} + \sqrt{x})\). For \(\ln(1+x)\), the problem is that \(1 + x\) already rounded away the low digits of \(x\): use log1p(x), which takes \(x\) itself.
sum.c to add the numbers sorted in increasing order, then in decreasing order. Which is better for the naive loop, and why?
The bound says increasing: each rounding error is at most \(u\) times the current partial sum, and adding the small terms first keeps the partial sums small longest. The measurement disagrees (sortsum.c): relative error \(3.6 \times 10^{-5}\) unsorted, \(1.2 \times 10^{-2}\) increasing, \(1.0 \times 10^{-4}\) decreasing. Sorted neighbours are nearly equal, so consecutive additions make nearly the same rounding error with the same sign, and nothing cancels; in random order the errors have both signs. Both are inside the bound, which is a guarantee about the worst case. The practical answer is pairwise or Kahan, not sorting.
Above \(2^{24}\) the ulp is 2, so only even integers are floats. In bf16 the significand has 8 bits, so every integer up to \(2^8 = 256\) is exact, and 257 is not.
In \([0.5, 1)\) the bf16 ulp is \(2^{-8} = 0.0039\): 0.5 stays, 0.5019 rounds to 0.5 (it is below the midpoint 0.50195). The relative error per weight is at most \(u = 0.39\%\), the same order as rounding the values: a bf16 weight costs as much as a bf16 value. The unnormalized running sums of section 15.5 are a different matter: they are accumulators, and stay in fp32.