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 , 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.
- safetensors: a checkpoint format of an 8-byte header length, a JSON header, and raw little-endian row-major tensor bytes. Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement in AI Engineering - BF16: a 16-bit float with float32’s sign and exponent and 7 mantissa bits; the top half of a rounded float32. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream in AI Engineering
- ties to even: rounding a value exactly halfway between two representable numbers to the one with an even last bit. Read more: 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32 in AI Engineering
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Tolerance budget: a test allowance that sums every deliberate perturbation and the rounding bound, and nothing else. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Integer significand: the float32 magnitude written as with an integer . Read more: 15.7 Low-precision conversions in C
- master weights: the float32 copy of the parameters and optimizer state that receives every update. Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing in AI Engineering
- fp16: a 16-bit format with 5 exponent bits and 10 mantissa bits; finer precision but a maximum of 65504 and a smallest subnormal of . Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing in AI Engineering
- fp8 E4M3: an 8-bit float with 1 sign, 4 exponent (bias 7), and 3 mantissa bits; largest finite value 448, no infinity. Read more: 8.1 Interface migration: KV format v1 to v2 in Software Engineering
- E5M2: an 8-bit float with 5 exponent bits (bias 15) and 2 fraction bits, IEEE-style infinities and NaNs, largest finite value 57344. Read more: 15.4 FP8 and microscaling formats
- dynamic loss scaling: halving and skipping the step on overflow, and doubling after a run of good steps. Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing in AI Engineering
- Microscaling (MX): a block format in which a fixed number of low-precision elements share one power-of-two scale. Read more: 15.4 FP8 and microscaling formats
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 , 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
astypeis wrong.
The notation
Section titled “The notation”The section uses a handful of symbols throughout. The table collects them so you can refer back to it.
| Symbol | Meaning | Type |
|---|---|---|
| sign bit: 0 for positive, 1 for negative | int, 0 or 1 | |
| biased exponent field: 8 bits in float32 | int, 0 to 255 | |
| mantissa (fraction) field: 23 bits in float32 | int, 0 to | |
| the unbiased exponent of a normal float32 | int, -126 to 127 | |
| precision: significand bits including the implicit leading 1 | 24 (f32), 11 (f16), 8 (bf16) | |
| smallest normal exponent | -126 (f32, bf16), -14 (f16) | |
| the gap from to the next larger magnitude in the format | float64 | |
| unit roundoff: the largest relative error of one rounding | float | |
| rounded to the nearest representable value, ties to even | a value of the format | |
the 32 bits of a float32 read as an unsigned integer (a uint32 view) | int |
The binary32 encoding
Section titled “The binary32 encoding”A float32 occupies 32 bits: bit 31 is the sign , bits 30 to 23 the biased exponent , bits 22 to 0 the mantissa . Reading the same 32 bits as an unsigned integer gives , so the fields are b >> 31, (b >> 23) & 0xFF, and b & 0x7FFFFF. What those fields mean depends on , which sorts every pattern into one of three classes:
| class | value | |
|---|---|---|
| 1 to 254 | normal | |
| 0 | zero () or subnormal () | |
| 255 | infinity () or NaN () | , or not a number |
A normal number has 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 , , which is . The smallest normal is . Below it, drops the implicit 1 and keeps the exponent at , so the subnormals fill the gap down to in equal steps. There are two zeros, and , which compare equal. A NaN is any pattern with and ; there are about of them.
Spacing and the ulp
Section titled “Spacing and the ulp”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 and (one binade) a format with precision has equally spaced values, so their spacing is
The spacing doubles at every power of two and is constant across the subnormal range, which is why is clamped at . At it is in float32, in float16, and in bfloat16. At the gap to the next value is the smallest subnormal, . 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 , so one rounding has a relative error of at most :
for any 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 needs care. np.log2(x) returns a rounded float, and for a hair below the true value rounds up to exactly , giving the next binade’s ulp. The exponent is already stored exactly, though: np.frexp(x) returns with and , so 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 (). 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: and . The halfway point of the dropped half is , and the rule has three cases:
| dropped half | result |
|---|---|
below 0x8000 | (round down) |
above 0x8000 | (round up) |
exactly 0x8000 | if is even, if odd |
All three rows collapse into one integer expression:
When , adding at most keeps the low half below , so no carry reaches . When , adding already carries. When , the sum is plus the parity bit, so it carries exactly when is odd.
The carry needs no special case. If the 7 kept mantissa bits are all ones, adding 1 to 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 . That is exactly IEEE’s rule, since is nearer to than to the largest bf16 value. Infinity itself has 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:
0x7F800001has and , and so does every NaN whose payload is small. Truncated, it becomes0x7F80, infinity. Rounded,0x7F800001 + 0x7FFF = 0x7F808000, still infinity. A NaN loss that turns into infinity no longer tripsnp.isnan. So NaNs are mapped first, to the single quiet NaN code0x7FC0, matching the C conversions intinyllm/numerics.h.
binary16: a different exponent range
Section titled “binary16: a different exponent range”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 (, ). Its range is tiny: the largest finite value is , and the smallest subnormal is . 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 with an integer significand : and for a normal float32, and for a subnormal. binary16 spaces its values apart with . Dividing by that spacing gives with : shift right by and round the remainder to nearest even, exactly as for bf16 but with a variable cut. Then
For a normal result () this equals the field form ; for a subnormal (, ) it is just ; and a that rounded up to 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.
Bit views versus value casts
Section titled “Bit views versus value casts”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 is the float32 with bits , not the number .
Working it by hand
Section titled “Working it by hand”Before writing code, run each idea on concrete numbers. Start with the anatomy of . Since , you get , , and a mantissa equal to the fraction after the leading 1, , padded to 23 bits: . All 32 bits are 1 10000001 10010000000000000000000 = 0xC0C80000, so decompose_f32(-6.25) == (1, 129, 0x480000). To check: .
The ulp follows directly. lies in the binade , so and in float32, in float16, and in bfloat16. At 1.0 the three are , , .
Now round to bfloat16. has no finite binary expansion. float32(0.1) has bits 0x3DCCCCCD and the value . The kept half is , the dropped half , and the expression evaluates in four steps:
| step | value |
|---|---|
vs 0x8000 | 0xCCCD > 0x8000: round up |
0 (0x3DCC is even) | |
0x3DCCCCCD + 0x7FFF = 0x3DCD4CCC | |
0x3DCD |
Decode 0x3DCD = 0 01111011 1001101: , , mantissa , value . The error, about , is below half the bf16 ulp at , .
Ties are where the parity bit earns its place. has bits 0x3F808000: (that is 1.0), , exactly halfway to . is even, so the sum 0x3F808000 + 0x7FFF = 0x3F80FFFF does not carry, and the result is 0x3F80, . Next, 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 . One tie went down and one went up, both to the even code.
For float16, take again. , so the result is normal and the cut is at . The float32 mantissa 0x4CCCCD is ; the top 10 bits are and the 13 dropped bits are , below the halfway point 0x1000, so it rounds down. The code is , the value . float16 lands closer to than bf16 did, thanks to its 3 extra mantissa bits.
Finally, the edges of float16. is below the midpoint between and the would-be next value , so it rounds to . is the tie, and ties to even picks , which does not exist, so the result is . At the bottom, is half the smallest subnormal : a tie between and , and the even choice is .
Designing the API
Section titled “Designing the API”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: ... # float64def f32_to_bf16_bits(x: ArrayLike) -> NDArray: ... # uint16, RNE, NaN -> 0x7FC0def bf16_bits_to_f32(u16: ArrayLike) -> NDArray: ... # float32, exactdef round_to_bf16(x: ArrayLike) -> NDArray: ... # float32 in, float32 outdef round_to_fp16(x: ArrayLike) -> NDArray: ... # float32, same bits as numpy's castArray 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).
Building it step by step
Section titled “Building it step by step”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 with clamped at , where the exact exponent comes from frexp, not log2, and one table of 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 , compute the shift to the fp16 spacing at , round the remainder to nearest even, and form the code . 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 neighbourbf16 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 , 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 : 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.
Why this design
Section titled “Why this design”Every function is a fixed number of vectorized integer operations per element: 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.
What can go wrong
Section titled “What can go wrong”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 (, plus 1.0 and ), and every class is exercised: , the smallest subnormal and normal, the largest finite value, , 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 in each format, , NaN for 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 random patterns must equal numpy’s cast bit for bit, an independent IEEE implementation agreeing with yours. The edges (, , , subnormals, ) 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:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| keeping the top 16 bits (truncation) | every value rounds toward zero; 0.1 gives 0x3DCC | adds 0x7FFF + lsb before shifting |
adding 0x8000 (ties away from zero) | 1 + 2**-8 rounds to 0x3F81, a biased tie | adds 0x7FFF plus the parity bit lsb, so ties go to even |
| no special case for NaN | 0x7F800001 becomes 0x7F80, infinity | np.where(np.isnan(f), BF16_NAN, r) |
through np.log2 | the ulp just below a power of two is twice too large | np.frexp reads the exponent exactly |
| no clamp at | subnormal ulps keep shrinking past the real spacing | np.maximum(k - 1, emin) |
| flushing float16 subnormals to zero | values below vanish | Eh = max(E, -14) and a larger shift keep subnormal codes |
no clamp at 0x7C00 | values past 65504 wrap into NaN codes | code >= 0x7C00 becomes 0x7C00 |
| float16 ties rounded up | half of all ties off by one ulp | rounds up on a tie only when q & 1 is 1 |
astype instead of a bit view | code 0x3F80 reads as | (u << 16).view(np.float32) |
exponent not masked with 0xFF | the sign bit leaks into the exponent of negative numbers | (bits >> 23) & 0xFF |
Where this leads
Section titled “Where this leads”The next section, Stable numerics, uses where float32 overflows and underflows, and the unit roundoff 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.
Further reading
Section titled “Further reading”- 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.
Key terms
Section titled “Key terms”- Biased exponent: the stored exponent field , 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 , filling the gap between zero and the smallest normal.
- Binade: the interval , inside which a format’s values are equally spaced.
- ulp: unit in the last place, the gap from to the next larger representable magnitude.
- Unit roundoff: , 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.
Summary
Section titled “Summary”- A float32 is three integers: sign , biased exponent , and mantissa ; a normal value is , and and hold the zeros, subnormals, infinities, and NaNs.
- The gap between neighbouring floats, one ulp, is : it doubles at every power of two and stops shrinking in the subnormal range. One rounding has relative error at most .
- bfloat16 is the top half of a float32, so rounding to it is integer arithmetic on the bits: add 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:
astypeturns the code0x3F80into instead of .
Review questions
Section titled “Review questions”-
Why does
f32_to_bf16_bitswiden touint64before adding0x7FFF + lsb?Answer
Bit patterns at or above
0xFFFF8000(negative NaNs) plus0x8000exceed and would wrap inuint32to 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. -
What does the expression
(b + 0x7FFF + lsb) >> 16do with1 + 2**-8and1 + 3 * 2**-8, and why is that unbiased?Answer
Both are exact ties (
ℓ = 0x8000). For0x3F808000,lsb = 0, the sum is0x3F80FFFF, no carry:0x3F80. For0x3F818000,lsb = 1, the sum is0x3F820000:0x3F82. One tie rounds down and one up, each to the even code, so ties do not push values consistently in one direction. -
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. -
In
_f16_bits, why isshiftcapped at 25?Answer
sighas at most 24 bits, so at a shift of 25qis 0 andrem = sigis belowhalf: the value rounds to 0, which is right for every magnitude that reaches that shift (all of them are below , half the smallest fp16 subnormal). Larger shifts would give the same answer, but for the smallest float32 subnormals the uncapped shift reaches , andnp.int64(1) << 125overflows. The cap keeps the masks representable without changing any result. -
Why is
bf16_bits_to_f32(np.uint16(0x3F80))equal to 1.0 whilenp.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.astypeconverts the integer value into the float 16256.0. -
Why does
ulpusenp.frexpinstead ofnp.floor(np.log2(x))?Answer
np.log2returns a rounded float, so for a hair below the result rounds up to exactly and the ulp comes out twice too large.frexpreads the stored exponent with no rounding: with gives exactly.