Skip to content

15.1 IEEE 754 anatomy, ulps, and round to nearest even

Every number a language model stores is a floating-point number. The byte bigram of Byte bigram: counts, logits, safetensors v0 in AI Engineering writes its weights as F32 in safetensors, and Vectors, matrices, row-major layout, and matmul multiplies them. Up to this point you can treat float32 as “a real number, roughly”. From here on the book leans on what float32 actually is. The stable softmax of the next section exists because float32 overflows at e88.72e^{88.72}, and that number comes straight out of the exponent field.

Concepts from other sections (13)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

Later work goes below 32 bits, and that is where vague knowledge of floats gets expensive. The SmolLM2 checkpoint loaded in The Llama-family model: config, weight loading, and download is stored as BF16, two bytes per weight, and the obvious loader, np.frombuffer(raw, np.uint16).astype(np.float32), gives a model whose weight 1.0 reads as 16256.0. Its first forward pass returns NaN and nothing crashes. Mixed-precision training in Mixed precision, loss scaling, gradient accumulation, and activation checkpointing rounds every weight to bf16, and the obvious rounding (keep the top 16 bits) is biased: it always rounds toward zero, and over thousands of steps the weights drift.

This section takes float32 apart bit by bit and rebuilds the two 16-bit formats, bfloat16 and float16, from it, so that the loader and the rounding are right the first time. The only background you need is comfort with powers of two and log⁡2\log_2, from Exponents, logarithms, and units of information. The reference implementation is fp.py (decompose_f32, compose_f32, ulp, f32_to_bf16_bits, bf16_bits_to_f32, round_to_bf16, round_to_fp16), with its interface in fp.pyi.

Learning objectives

  • Decode any float32 bit pattern into sign, exponent, and mantissa, and classify it as normal, subnormal, zero, infinity, or NaN.
  • Compute the ulp of a value in float32, float16, and bfloat16, including at the subnormal boundary.
  • Round a float32 to bfloat16 with round to nearest, ties to even, as a single integer expression, and explain why NaN needs a special case.
  • Round a float32 to float16 with a variable cut that handles overflow, subnormals, and underflow.
  • Tell a bit view from a value cast, and explain why decoding bf16 with astype is wrong.

The section uses a handful of symbols throughout. The table collects them so you can refer back to it.

SymbolMeaningType
sssign bit: 0 for positive, 1 for negativeint, 0 or 1
EEbiased exponent field: 8 bits in float32int, 0 to 255
MMmantissa (fraction) field: 23 bits in float32int, 0 to 223−12^{23} - 1
e=E−127e = E - 127the unbiased exponent of a normal float32int, -126 to 127
ppprecision: significand bits including the implicit leading 124 (f32), 11 (f16), 8 (bf16)
emin⁡e_{\min}smallest normal exponent-126 (f32, bf16), -14 (f16)
ulp(x)\mathrm{ulp}(x)the gap from ∣x∣\lvert x \rvert to the next larger magnitude in the formatfloat64
u=2−pu = 2^{-p}unit roundoff: the largest relative error of one roundingfloat
rn(x)\mathrm{rn}(x)xx rounded to the nearest representable value, ties to evena value of the format
bbthe 32 bits of a float32 read as an unsigned integer (a uint32 view)int

A float32 occupies 32 bits: bit 31 is the sign ss, bits 30 to 23 the biased exponent EE, bits 22 to 0 the mantissa MM. Reading the same 32 bits as an unsigned integer gives b=s⋅231+E⋅223+Mb = s \cdot 2^{31} + E \cdot 2^{23} + M, so the fields are b >> 31, (b >> 23) & 0xFF, and b & 0x7FFFFF. What those fields mean depends on EE, which sorts every pattern into one of three classes:

EEclassvalue
1 to 254normal(−1)s(1+M223)2E−127(-1)^s \left(1 + \frac{M}{2^{23}}\right) 2^{E - 127}
0zero (M=0M = 0) or subnormal (M≠0M \ne 0)(−1)sM223 2−126(-1)^s \frac{M}{2^{23}}\, 2^{-126}
255infinity (M=0M = 0) or NaN (M≠0M \ne 0)±∞\pm\infty, or not a number

A normal number has p=24p = 24 significant bits: the 23 stored ones plus a leading 1 that is implied, not stored. The bias 127 lets the exponent field be an unsigned integer, which has a useful consequence: for non-negative floats, ordering the bit patterns as integers orders the values. The largest finite float32 is E=254E = 254, M=223−1M = 2^{23} - 1, which is (2−2−23) 2127≈3.40×1038=e88.72(2 - 2^{-23})\, 2^{127} \approx 3.40 \times 10^{38} = e^{88.72}. The smallest normal is 2−1262^{-126}. Below it, E=0E = 0 drops the implicit 1 and keeps the exponent at −126-126, so the subnormals fill the gap down to 2−1492^{-149} in equal steps. There are two zeros, +0+0 and −0-0, which compare equal. A NaN is any pattern with E=255E = 255 and M≠0M \ne 0; there are about 2242^{24} of them.

The encoding tells you which values exist. The next question is how far apart they are, because that gap is the size of every rounding error. Between 2e2^e and 2e+12^{e+1} (one binade) a format with precision pp has 2p−12^{p-1} equally spaced values, so their spacing is

ulp(x)=2 e−p+1,e=max⁡(⌊log⁡2∣x∣⌋, emin⁡).\mathrm{ulp}(x) = 2^{\,e - p + 1}, \qquad e = \max(\lfloor \log_2 \lvert x \rvert \rfloor,\ e_{\min}).

The spacing doubles at every power of two and is constant across the subnormal range, which is why ee is clamped at emin⁡e_{\min}. At x=1x = 1 it is 2−232^{-23} in float32, 2−102^{-10} in float16, and 2−72^{-7} in bfloat16. At x=0x = 0 the gap to the next value is the smallest subnormal, 2emin⁡−p+12^{e_{\min} - p + 1}. Infinity and NaN have no next value, so their ulp is NaN.

Rounding to nearest moves a value by at most half an ulp, and within a binade the ulp is at most 2−(p−1)∣x∣2^{-(p-1)} \lvert x \rvert, so one rounding has a relative error of at most u=2−pu = 2^{-p}:

rn(x)=x(1+δ),∣δ∣≤u,\mathrm{rn}(x) = x(1 + \delta), \qquad \lvert \delta \rvert \le u,

for any xx in the normal range. That one fact is the model behind every error bound in this chapter, from the summation bounds of Stable numerics to the tolerance budgets of Error analysis, condition numbers, and tolerance budgets.

Computing ⌊log⁡2∣x∣⌋\lfloor \log_2 \lvert x \rvert \rfloor needs care. np.log2(x) returns a rounded float, and for xx a hair below 2k2^k the true value k−εk - \varepsilon rounds up to exactly kk, giving the next binade’s ulp. The exponent is already stored exactly, though: np.frexp(x) returns (m,k)(m, k) with x=m 2kx = m\, 2^k and m∈[0.5,1)m \in [0.5, 1), so ⌊log⁡2∣x∣⌋=k−1\lfloor \log_2 \lvert x \rvert \rfloor = k - 1 with no rounding at all.

Round to nearest even, on the bits, for bfloat16

Section titled “Round to nearest even, on the bits, for bfloat16”

With spacing understood, you can build the first 16-bit format. bfloat16 is the float32 layout cut in half: 1 sign bit, the same 8 exponent bits with the same bias, and 7 mantissa bits (p=8p = 8). Every bf16 code is the top 16 bits of a float32, and decoding is a shift: bf16_bits_to_f32(c) is the float32 whose bits are c << 16. Because the range is float32’s, nothing a float32 model produces overflows on the way down; only precision is lost.

Encoding has to round. IEEE 754’s default is round to nearest, ties to even: take the nearest representable value, and when the value is exactly halfway between two, take the one whose last kept bit is 0. Ties to even is unbiased: half of all ties round up and half round down, where “ties away from zero” pushes every tie the same way.

Split the float32 bits into the half that is kept and the half that is dropped: h=b≫16h = b \gg 16 and ℓ=b&0xFFFF\ell = b \mathbin{\&} \mathtt{0xFFFF}. The halfway point of the dropped half is ℓ=0x8000\ell = \mathtt{0x8000}, and the rule has three cases:

dropped half ℓ\ellresult
below 0x8000hh (round down)
above 0x8000h+1h + 1 (round up)
exactly 0x8000hh if hh is even, h+1h + 1 if odd

All three rows collapse into one integer expression:

bf16(b)=(b+0x7FFF+(h&1))≫16.\mathrm{bf16}(b) = (b + \mathtt{0x7FFF} + (h \mathbin{\&} 1)) \gg 16.

When ℓ<0x8000\ell < \mathtt{0x8000}, adding at most 0x8000\mathtt{0x8000} keeps the low half below 0x10000\mathtt{0x10000}, so no carry reaches hh. When ℓ>0x8000\ell > \mathtt{0x8000}, adding 0x7FFF\mathtt{0x7FFF} already carries. When ℓ=0x8000\ell = \mathtt{0x8000}, the sum is 0xFFFF\mathtt{0xFFFF} plus the parity bit, so it carries exactly when hh is odd.

The carry needs no special case. If the 7 kept mantissa bits are all ones, adding 1 to hh clears them and increments the exponent field: the next code is the first value of the next binade, which is the correct rounded result. At the top, the largest finite float32 0x7F7FFFFF rounds to 0x7F80, which is +∞+\infty. That is exactly IEEE’s rule, since (2−2−23) 2127(2 - 2^{-23})\, 2^{127} is nearer to 21282^{128} than to the largest bf16 value. Infinity itself has ℓ=0\ell = 0 and stays infinity. Work in uint64 (or check for it) so that the addition cannot wrap at 0xFFFFFFFF.

Warning: NaN breaks the trick. A NaN may have its only set mantissa bits in the dropped half: 0x7F800001 has h=0x7F80h = \mathtt{0x7F80} and ℓ=1\ell = 1, and so does every NaN whose payload is small. Truncated, it becomes 0x7F80, infinity. Rounded, 0x7F800001 + 0x7FFF = 0x7F808000, still infinity. A NaN loss that turns into infinity no longer trips np.isnan. So NaNs are mapped first, to the single quiet NaN code 0x7FC0, matching the C conversions in tinyllm/numerics.h.

bfloat16 was easy because it shares float32’s exponent. float16 (IEEE binary16) does not: it has 1 sign bit, 5 exponent bits with bias 15, and 10 mantissa bits (p=11p = 11, emin⁡=−14e_{\min} = -14). Its range is tiny: the largest finite value is (2−2−10) 215=65504(2 - 2^{-10})\, 2^{15} = 65504, and the smallest subnormal is 2−242^{-24}. So a float32 can overflow it, land in its subnormal range, or underflow it entirely, and the exponent field has to be re-biased. The top-half trick does not apply.

Instead, write a finite ∣x∣=σ⋅2E′−23\lvert x \rvert = \sigma \cdot 2^{E' - 23} with an integer significand σ<224\sigma < 2^{24}: σ=223+M\sigma = 2^{23} + M and E′=E−127E' = E - 127 for a normal float32, σ=M\sigma = M and E′=−126E' = -126 for a subnormal. binary16 spaces its values 2Eh−102^{E_h - 10} apart with Eh=max⁡(E′,−14)E_h = \max(E', -14). Dividing ∣x∣\lvert x \rvert by that spacing gives q=σ/2tq = \sigma / 2^{t} with t=13+(Eh−E′)≥13t = 13 + (E_h - E') \ge 13: shift right by tt and round the remainder to nearest even, exactly as for bf16 but with a variable cut. Then

code=((Eh+14)≪10)+q.\text{code} = ((E_h + 14) \ll 10) + q.

For a normal result (210≤q<2112^{10} \le q < 2^{11}) this equals the field form ((Eh+15)≪10)∣(q−210)((E_h + 15) \ll 10) \mid (q - 2^{10}); for a subnormal (Eh=−14E_h = -14, q<210q < 2^{10}) it is just qq; and a qq that rounded up to 2112^{11} carries into the exponent on its own, as in bf16. Any code at or above 0x7C00 is infinity (overflow), and NaN gets 0x7E00. numpy’s float32.astype(float16) implements the same IEEE rounding, which gives you an independent oracle to compare against.

One distinction runs through every function in this section. np.asarray(x, np.float32).view(np.uint32) reinterprets the same bytes as integers and changes no bit; .astype(np.uint32) converts the value (1.0 becomes 1). Every function here moves between the two worlds with views. Decoding bf16 is the case people get wrong: the codes arrive as uint16, and the value of code cc is the float32 with bits c≪16c \ll 16, not the number cc.

Before writing code, run each idea on concrete numbers. Start with the anatomy of −6.25-6.25. Since 6.25=110.012=1.10012×226.25 = 110.01_2 = 1.1001_2 \times 2^2, you get s=1s = 1, E=2+127=129=1000 00012E = 2 + 127 = 129 = 1000\,0001_2, and a mantissa equal to the fraction after the leading 1, .10012.1001_2, padded to 23 bits: 100 1000 0000 0000 0000 00002=0x480000100\,1000\,0000\,0000\,0000\,0000_2 = \mathtt{0x480000}. All 32 bits are 1 10000001 10010000000000000000000 = 0xC0C80000, so decompose_f32(-6.25) == (1, 129, 0x480000). To check: (1+0x480000/223)⋅22=(1+0.5625)⋅4=6.25(1 + \mathtt{0x480000}/2^{23}) \cdot 2^{2} = (1 + 0.5625) \cdot 4 = 6.25.

The ulp follows directly. 6.256.25 lies in the binade [4,8)[4, 8), so e=2e = 2 and ulp(6.25)=22−23=2−21\mathrm{ulp}(6.25) = 2^{2 - 23} = 2^{-21} in float32, 22−10=2−82^{2 - 10} = 2^{-8} in float16, and 22−7=2−52^{2 - 7} = 2^{-5} in bfloat16. At 1.0 the three are 2−232^{-23}, 2−102^{-10}, 2−72^{-7}.

Now round 0.10.1 to bfloat16. 0.10.1 has no finite binary expansion. float32(0.1) has bits 0x3DCCCCCD and the value 0.1000000014901161193847656250.100000001490116119384765625. The kept half is h=0x3DCCh = \mathtt{0x3DCC}, the dropped half ℓ=0xCCCD\ell = \mathtt{0xCCCD}, and the expression evaluates in four steps:

stepvalue
ℓ\ell vs 0x80000xCCCD > 0x8000: round up
h&1h \mathbin{\&} 10 (0x3DCC is even)
b+0x7FFF+0b + \mathtt{0x7FFF} + 00x3DCCCCCD + 0x7FFF = 0x3DCD4CCC
≫16\gg 160x3DCD

Decode 0x3DCD = 0 01111011 1001101: E=123E = 123, e=−4e = -4, mantissa 10011012=771001101_2 = 77, value (1+77/128) 2−4=205/2048=0.10009765625(1 + 77/128)\, 2^{-4} = 205/2048 = 0.10009765625. The error, about 9.8×10−59.8 \times 10^{-5}, is below half the bf16 ulp at 0.10.1, 2−12≈2.4×10−42^{-12} \approx 2.4 \times 10^{-4}.

Ties are where the parity bit earns its place. 1+2−81 + 2^{-8} has bits 0x3F808000: h=0x3F80h = \mathtt{0x3F80} (that is 1.0), ℓ=0x8000\ell = \mathtt{0x8000}, exactly halfway to 1+2−71 + 2^{-7}. hh is even, so the sum 0x3F808000 + 0x7FFF = 0x3F80FFFF does not carry, and the result is 0x3F80, 1.01.0. Next, 1+3⋅2−81 + 3 \cdot 2^{-8} has bits 0x3F818000: halfway between 0x3F81 (odd) and 0x3F82 (even). Now the parity bit is 1, 0x3F818000 + 0x7FFF + 1 = 0x3F820000, and the result is 0x3F82 =1+2−6= 1 + 2^{-6}. One tie went down and one went up, both to the even code.

For float16, take 0.10.1 again. e=−4≥−14e = -4 \ge -14, so the result is normal and the cut is at t=13t = 13. The float32 mantissa 0x4CCCCD is 100 1100 1100 1100 1100 11012100\,1100\,1100\,1100\,1100\,1101_2; the top 10 bits are 10 0110 01102=0x26610\,0110\,0110_2 = \mathtt{0x266} and the 13 dropped bits are 0 1100 1100 11012=0x0CCD0\,1100\,1100\,1101_2 = \mathtt{0x0CCD}, below the halfway point 0x1000, so it rounds down. The code is ((−4+15)≪10)∣0x266=0x2C00∣0x266=0x2E66((-4 + 15) \ll 10) \mid \mathtt{0x266} = \mathtt{0x2C00} \mid \mathtt{0x266} = \mathtt{0x2E66}, the value (1+614/1024) 2−4=0.0999755859375(1 + 614/1024)\, 2^{-4} = 0.0999755859375. float16 lands closer to 0.10.1 than bf16 did, thanks to its 3 extra mantissa bits.

Finally, the edges of float16. 6551965519 is below the midpoint 6552065520 between 6550465504 and the would-be next value 6553665536, so it rounds to 6550465504. 6552065520 is the tie, and ties to even picks 6553665536, which does not exist, so the result is +∞+\infty. At the bottom, 2−252^{-25} is half the smallest subnormal 2−242^{-24}: a tie between 00 and 2−242^{-24}, and the even choice is 00.

The hand examples suggest the shape of the interface: a pair of scalar functions for the fields, a vectorized ulp, and encoders and decoders for the two 16-bit formats.

def decompose_f32(x: float) -> tuple[int, int, int]: ... # (sign, biased exponent, mantissa)
def compose_f32(sign: int, exponent: int, mantissa: int) -> float: ...
def ulp(x: ArrayLike, dtype: Literal["f32", "f16", "bf16"]) -> NDArray: ... # float64
def f32_to_bf16_bits(x: ArrayLike) -> NDArray: ... # uint16, RNE, NaN -> 0x7FC0
def bf16_bits_to_f32(u16: ArrayLike) -> NDArray: ... # float32, exact
def round_to_bf16(x: ArrayLike) -> NDArray: ... # float32 in, float32 out
def round_to_fp16(x: ArrayLike) -> NDArray: ... # float32, same bits as numpy's cast

Array functions accept anything numpy converts, convert it to float32 first, and keep the input’s shape (a scalar gives a 0-d array). Downstream, the Llama loader reads a BF16 tensor as bf16_bits_to_f32(np.frombuffer(raw, "<u2").reshape(shape)), and mixed-precision training keeps float32 master weights and computes with round_to_bf16(w).

The reasoning chain is short, and each link follows from a principle above. Every question here (fields, spacing, rounding) is about the bits, so the solution works on a uint32 view of float32 data and never on value casts; a shared helper converts any input to a fresh float32 array once. The fields are shifts and masks, and composing is the reverse, with the ranges checked so that a field cannot spill into its neighbour. The ulp is 2e−p+12^{e - p + 1} with ee clamped at emin⁡e_{\min}, where the exact exponent comes from frexp, not log2, and one table of (p,emin⁡)(p, e_{\min}) per format covers all three formats. bf16 rounding is one integer expression on the bits, done in a wider integer so the carry cannot wrap, with NaN overridden afterwards; bf16 decoding is a shift into the top half and a bit view. fp16 needs the variable cut: write ∣x∣=σ 2E′−23|x| = \sigma\,2^{E'-23}, compute the shift tt to the fp16 spacing at Eh=max⁡(E′,−14)E_h = \max(E', -14), round the remainder to nearest even, and form the code ((Eh+14)≪10)+q((E_h + 14) \ll 10) + q. Overflow clamps to 0x7C00; NaN becomes 0x7E00.

Start with the format table, the input conversion, and the fields:

# dtype -> (precision p in bits including the implicit 1, minimum normal exponent)
_FORMATS = {"f32": (24, -126), "f16": (11, -14), "bf16": (8, -126)}
BF16_NAN = 0x7FC0 # the quiet NaN every bf16 conversion produces
def _f32(x):
"""x as a fresh C-contiguous float32 array of the same shape (float64
inputs are rounded to nearest even by the cast; overflow to inf is the
IEEE result, not an error)."""
with np.errstate(over="ignore"):
return np.array(x, dtype=np.float32, order="C") # contiguous, so .view works
def decompose_f32(x):
bits = int(_f32(x).reshape(()).view(np.uint32)) # a view: no bit changes
# mask the exponent: without & 0xFF the sign bit would leak into it
return bits >> 31, (bits >> 23) & 0xFF, bits & 0x7FFFFF
def compose_f32(sign, exponent, mantissa):
if sign not in (0, 1) or not 0 <= exponent <= 255 or not 0 <= mantissa < 1 << 23:
raise ValueError(...) # an oversized field would corrupt its neighbour
bits = np.array((sign << 31) | (exponent << 23) | mantissa, dtype=np.uint32)
return float(bits.view(np.float32))

The ulp, vectorized, follows the formula directly:

def ulp(x, dtype):
if dtype not in _FORMATS:
raise ValueError(...)
p, emin = _FORMATS[dtype]
a = np.abs(np.asarray(x, dtype=np.float64))
# frexp writes a = m * 2^k with m in [0.5, 1), so floor(log2 a) = k - 1
# exactly (log2 itself rounds near powers of two).
_, k = np.frexp(a)
e = np.maximum(k.astype(np.int64) - 1, emin) # subnormals share emin's spacing
out = np.ldexp(1.0, e - (p - 1)) # 2^(e - p + 1), exact
# at 0 the next value up is the smallest subnormal
out = np.where(a == 0.0, np.ldexp(1.0, emin - (p - 1)), out)
return np.where(np.isfinite(a), out, np.nan) # inf and NaN have no neighbour

bf16 in both directions is where the rounding expression lives:

def f32_to_bf16_bits(x):
f = _f32(x)
b = f.view(np.uint32).astype(np.uint64) # room for the carry
# Round to nearest, ties to even, on the 16 bits being dropped: add just
# under half (0x7FFF), plus 1 when the kept part is odd, then truncate.
# A carry out of the mantissa bumps the exponent, which is exactly the
# next binade; a carry out of the largest finite value lands on inf.
lsb = (b >> 16) & 1
r = ((b + 0x7FFF + lsb) >> 16).astype(np.uint16)
# a NaN with a small payload would have rounded to inf: override it
return np.where(np.isnan(f), np.uint16(BF16_NAN), r)
def bf16_bits_to_f32(u16):
u = np.array(u16, dtype=np.uint16, order="C").astype(np.uint32) # widen the CODE
return (u << 16).view(np.float32) # reinterpret the bits; never astype(float32)
def round_to_bf16(x):
return bf16_bits_to_f32(f32_to_bf16_bits(x))

The one astype in the decoder converts uint16 codes to uint32 integers, which is a value-preserving widening of the code; the conversion to a float is the .view. Trace the hand example through it: for 0.10.1, b = 0x3DCCCCCD, lsb = 0, b + 0x7FFF = 0x3DCD4CCC, shifted to 0x3DCD.

fp16 is the one place where the cut moves:

def _f16_bits(f):
"""binary16 codes (as int64) of a float32 array, NaN mapped to 0x7E00."""
b = f.view(np.uint32).astype(np.int64)
sign = (b >> 31) << 15
exp = (b >> 23) & 0xFF
man = b & 0x7FFFFF
# Write |f| = sig * 2^(E - 23) with an integer significand sig < 2^24.
sig = np.where(exp > 0, man | 0x800000, man) # restore the implicit 1 for normals
E = np.where(exp > 0, exp - 127, -126)
# binary16 spaces its values 2^(Eh - 10) apart, Eh = max(E, -14): below
# -14 the spacing stops shrinking (subnormals). So the binary16 value is
# q * 2^(Eh - 10) with q = sig / 2^shift, shift = 13 + (Eh - E) >= 13.
Eh = np.maximum(E, -14)
shift = np.minimum(13 + (Eh - E), 25) # 25 already rounds everything to 0
q = sig >> shift
rem = sig & ((np.int64(1) << shift) - 1)
half = np.int64(1) << (shift - 1)
up = (rem > half) | ((rem == half) & ((q & 1) == 1)) # ties to even
q = q + up
# Normal codes are ((Eh + 15) << 10) | (q - 1024) = ((Eh + 14) << 10) + q,
# and the same formula gives the subnormals (Eh = -14, q < 1024). A q that
# rounded up to 2048 or 1024 carries into the exponent on its own.
code = ((Eh + 14) << 10) + q
code = np.where(code >= 0x7C00, 0x7C00, code) # overflow (and inf) -> inf
code = np.where(exp == 0xFF, np.where(man != 0, 0x7E00, 0x7C00), code)
return np.where((exp == 0xFF) & (man != 0), 0x7E00, sign | code)

round_to_fp16 then decodes these codes back to float32 values: ldexp(m16, -24) for subnormals, ldexp(m16 + 1024, e16 - 25) for normals, infinity or NaN for exponent 31, and the sign applied last. On the hand example 0.10.1: exp = 123, E = -4 = Eh, shift = 13, q = 0xCCCCCD >> 13 = 0x666, rem = 0x0CCD below half = 0x1000, so code = (10 << 10) + 0x666 = 0x2E66. The full solution is in fp.py.

Every function is a fixed number of vectorized integer operations per element: O(n)O(n) time and a few temporaries of the input’s size, so converting a 135M-parameter checkpoint is a handful of passes over its bytes.

The solution does integer arithmetic on bits rather than float arithmetic on values for a reason. Rounding with floats (for example, scaling and calling np.round) would itself be subject to float rounding and to numpy’s half-to-even rules on a different grid. Integer operations on the bit pattern are exact, so the result is correct by construction, and they match the C conversions of tinyllm/numerics.h bit for bit.

It does not use astype(np.float16) for fp16, even though that cast is correct and the solution is checked against it. Writing the rounding out makes the cut, the subnormal clamp, and the overflow rule visible, and it is the template that FP8 and microscaling formats reuses for fp8, which numpy does not provide. It uses frexp for the exponent because frexp reads the stored exponent exactly, while floor(log2(x)) can be off by one just below a power of two, which would double the ulp there.

One tradeoff is accepted deliberately: every NaN payload collapses to one quiet NaN code. Payloads carry no meaning in model weights, and a single code is what PyTorch and the C side produce.

A correct implementation has to survive a specific list of cases, and the reference tests check each of them. The hand example pins the fields (−6.25→(1,129,0x480000)-6.25 \to (1, 129, \mathtt{0x480000}), plus 1.0 and −2.5-2.5), and every class is exercised: ±0\pm 0, the smallest subnormal and normal, the largest finite value, ∞\infty, and NaN, since a checkpoint can hold any of them. Composing must invert decomposing on 3000 floats, and out-of-range fields must raise. The hand ulps cover ulp(1)\mathrm{ulp}(1) in each format, ulp(0)\mathrm{ulp}(0), NaN for ±∞\pm\infty and NaN, and an unknown dtype; float32 and float16 ulps must equal np.spacing, subnormals included, because that spacing is what later tolerances are built from. Values just below a power of two, nextafter(1024, 0) and nextafter(2**100, 0), must stay in the lower binade, which is exactly where np.log2 rounds up.

For bf16, the hand examples (0.1 -> 0x3DCD and the two ties) test the rounding rule itself, and a golden set of 10 156 float32 patterns, rounded with exact fractions.Fraction arithmetic, covers every binade, tie, and overflow. Four NaNs, including 0x7F800001, must give 0x7FC0, so that a NaN loss stays visible during mixed-precision training. All 65536 bf16 codes must decode exactly and encode back, which is what lets the loader read every weight exactly. Rounding must be idempotent and monotone: rounding twice changes nothing, and sorted inputs stay sorted.

For fp16, the golden inputs and 10510^5 random patterns must equal numpy’s cast bit for bit, an independent IEEE implementation agreeing with yours. The edges (6550465504, 65519→6550465519 \to 65504, 65520→∞65520 \to \infty, subnormals, 2−25→02^{-25} \to 0) show why fp16 training needs loss scaling and bf16 does not. Finally, matrices keep their shape, a scalar gives a 0-d array, and the sign survives. The golden cases were produced by rounding each float32 value as an exact fraction, with the float16 column also checked against numpy, so the comparison does not depend on any implementation of the bit tricks.

The mistakes people actually make are worth listing side by side with their symptoms:

PitfallSymptomHow the solution avoids it
keeping the top 16 bits (truncation)every value rounds toward zero; 0.1 gives 0x3DCCadds 0x7FFF + lsb before shifting
adding 0x8000 (ties away from zero)1 + 2**-8 rounds to 0x3F81, a biased tieadds 0x7FFF plus the parity bit lsb, so ties go to even
no special case for NaN0x7F800001 becomes 0x7F80, infinitynp.where(np.isnan(f), BF16_NAN, r)
⌊log⁡2x⌋\lfloor \log_2 x \rfloor through np.log2the ulp just below a power of two is twice too largenp.frexp reads the exponent exactly
no clamp at emin⁡e_{\min}subnormal ulps keep shrinking past the real spacingnp.maximum(k - 1, emin)
flushing float16 subnormals to zerovalues below 2−142^{-14} vanishEh = max(E, -14) and a larger shift keep subnormal codes
no clamp at 0x7C00values past 65504 wrap into NaN codescode >= 0x7C00 becomes 0x7C00
float16 ties rounded uphalf of all ties off by one ulprounds up on a tie only when q & 1 is 1
astype instead of a bit viewcode 0x3F80 reads as 16256.016256.0(u << 16).view(np.float32)
exponent not masked with 0xFFthe sign bit leaks into the exponent of negative numbers(bits >> 23) & 0xFF

The next section, Stable numerics, uses where float32 overflows and underflows, and the unit roundoff uu behind its summation bounds. FP8 and microscaling formats applies the same bit-level rounding with fewer bits, in Python and C, to fp8 E4M3 and E5M2 and the MX block formats. In AI Engineering, Safetensors for every dtype, atomic checkpoints, and the token stream encodes and decodes BF16 tensors with these bit converters, The Llama-family model: config, weight loading, and download loads the SmolLM2 BF16 safetensors through bf16_bits_to_f32, and Mixed precision, loss scaling, gradient accumulation, and activation checkpointing keeps float32 master weights and uses round_to_bf16 for the compute copy.

Each piece here has a production counterpart. PyTorch’s c10::BFloat16 uses the same add-0x7FFF-plus-parity rounding, in C++ and in CUDA for every kernel (c10/util/BFloat16.h, round_to_nearest_even). The F16C instruction vcvtps2ph and CUDA’s __float2half_rn do the fp16 conversion in one hardware instruction, with the rounding mode as an operand. Mixed-precision training with loss scaling combines float32 master weights, low-precision compute, and dynamic loss scaling for fp16’s narrow range. And the OCP FP8 and MX formats build 8-bit and block-scaled formats on the same encoding rules.

  • Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic” (ACM Computing Surveys, 1991), sections 1 and 2.
  • Muller et al., Handbook of Floating-Point Arithmetic (2nd ed.), chapters 2 and 3.
  • IEEE Std 754-2019, section 3.
  • Intel SDM, VCVTPS2PH; CUDA Math API, half precision intrinsics.
  • Micikevicius et al., “Mixed Precision Training” (ICLR 2018).
  • OCP Microscaling Formats (MX) v1.0 spec.
  • Biased exponent: the stored exponent field EE, equal to the true exponent plus a bias (127 in float32, 15 in float16) so it can be stored unsigned.
  • Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent emin⁡e_{\min}, filling the gap between zero and the smallest normal.
  • Binade: the interval [2e,2e+1)[2^e, 2^{e+1}), inside which a format’s values are equally spaced.
  • ulp: unit in the last place, the gap from ∣x∣\lvert x \rvert to the next larger representable magnitude.
  • Unit roundoff: u=2−pu = 2^{-p}, the largest relative error of a single round-to-nearest.
  • Round to nearest, ties to even: IEEE 754’s default rounding, which breaks exact ties toward the code whose last kept bit is 0.
  • Bit view: reinterpreting the bytes of an array as another dtype without changing any bit, as opposed to a value cast.
  • A float32 is three integers: sign ss, biased exponent EE, and mantissa MM; a normal value is (−1)s(1+M/223) 2E−127(-1)^s (1 + M/2^{23})\, 2^{E - 127}, and E=0E = 0 and E=255E = 255 hold the zeros, subnormals, infinities, and NaNs.
  • The gap between neighbouring floats, one ulp, is 2e−p+12^{e - p + 1}: it doubles at every power of two and stops shrinking in the subnormal range. One rounding has relative error at most u=2−pu = 2^{-p}.
  • bfloat16 is the top half of a float32, so rounding to it is integer arithmetic on the bits: add 0x7FFF\mathtt{0x7FFF} plus the lowest kept bit, then shift. Ties go to the even neighbour, and a carry walks into the exponent exactly as it should.
  • The trick is wrong for NaN, which can turn into infinity; every NaN must map to the quiet code 0x7FC0.
  • float16 has its own exponent range, so its rounding cut moves with the exponent, with clamps for overflow and subnormals.
  • Codes are decoded with a bit view, never a value cast: astype turns the code 0x3F80 into 16256.016256.0 instead of 1.01.0.
  1. Why does f32_to_bf16_bits widen to uint64 before adding 0x7FFF + lsb?

    Answer

    Bit patterns at or above 0xFFFF8000 (negative NaNs) plus 0x8000 exceed 232−12^{32} - 1 and would wrap in uint32 to a tiny code. The NaN override replaces those results anyway, but in 64 bits the sum is exact for every pattern, so the rounding expression is correct on its own and needs no reasoning about which inputs could wrap.

  2. What does the expression (b + 0x7FFF + lsb) >> 16 do with 1 + 2**-8 and 1 + 3 * 2**-8, and why is that unbiased?

    Answer

    Both are exact ties (ℓ = 0x8000). For 0x3F808000, lsb = 0, the sum is 0x3F80FFFF, no carry: 0x3F80. For 0x3F818000, lsb = 1, the sum is 0x3F820000: 0x3F82. One tie rounds down and one up, each to the even code, so ties do not push values consistently in one direction.

  3. Why is the NaN override applied after the rounding, and not by masking NaN inputs first?

    Answer

    The rounding is a pure vectorized expression over all elements; it computes a wrong value for NaNs (possibly infinity) but never fails. np.where(np.isnan(f), ...) then replaces exactly those elements. Masking first would need a separate path; overriding afterwards keeps one expression for every finite and infinite value.

  4. In _f16_bits, why is shift capped at 25?

    Answer

    sig has at most 24 bits, so at a shift of 25 q is 0 and rem = sig is below half =224= 2^{24}: the value rounds to 0, which is right for every magnitude that reaches that shift (all of them are below 2−252^{-25}, half the smallest fp16 subnormal). Larger shifts would give the same answer, but for the smallest float32 subnormals the uncapped shift reaches 13+112=12513 + 112 = 125, and np.int64(1) << 125 overflows. The cap keeps the masks representable without changing any result.

  5. Why is bf16_bits_to_f32(np.uint16(0x3F80)) equal to 1.0 while np.uint16(0x3F80).astype(np.float32) is 16256.0?

    Answer

    The decoder shifts the code into the top half of a 32-bit pattern, 0x3F800000, and reinterprets those bits as a float32: sign 0, exponent 127, mantissa 0, which is 1.0. astype converts the integer value 0x3F80=16256\mathtt{0x3F80} = 16256 into the float 16256.0.

  6. Why does ulp use np.frexp instead of np.floor(np.log2(x))?

    Answer

    np.log2 returns a rounded float, so for xx a hair below 2k2^k the result rounds up to exactly kk and the ulp comes out twice too large. frexp reads the stored exponent with no rounding: x=m 2kx = m\,2^k with m∈[0.5,1)m \in [0.5, 1) gives ⌊log⁡2x⌋=k−1\lfloor \log_2 x \rfloor = k - 1 exactly.