15.7 Low-precision conversions in C
FP8 and microscaling formats described, in Python, how float32 values map to compact formats. The optional C kernels of AI Engineering, Paged attention for decode in C and Fused int4 and int8 dequantize-matmul in C, need the same conversions when they read half-precision cache values and quantization scales. They cannot call Python, and they must not drift from it: if the C decoder disagrees with the Python encoder on even one code, a cached value silently changes.
Concepts from other sections (9)
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.
- E4M3: an 8-bit float with 4 exponent bits (bias 7) and 3 fraction bits, no infinity, largest finite value 448. Read more: 15.4 FP8 and microscaling formats
- 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
- Round to nearest, ties to even: IEEE 754’s default rounding, which breaks exact ties toward the code whose last kept bit is 0. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent , filling the gap between zero and the smallest normal. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- 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
- 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
- Magic constant:
0x5F3759DF, the offset that turns the bit-pattern logarithm into a first guess for within 3.44%. Read more: 15.5 Fixed-point iteration and fast inverse square root in C - paged KV cache: a cache stored as fixed-size blocks anywhere in a pool, with a per-sequence table mapping logical blocks to physical ones. Read more: 22.6 Paged attention for decode in C in AI Engineering
- undefined behavior: an operation the C standard gives no meaning to, which the compiler assumes never happens. Read more: 1.3 C: memory, pointers, structs, headers, and the C11 toolchain in Programming and Algorithms
This optional section writes those conversions in standalone C: ordinary function calls inside one process, with bit patterns that agree with the Python version on every code. The heart of it is one integer rounding routine shared by four formats (E4M3, E5M2, bfloat16, and binary16), one decoder, and a thin per-format wrapper for the special values. Because the arithmetic is on integers, it is exact, sanitizer-clean, and identical on every platform.
You should read FP8 and microscaling formats first, since this section reuses its value and rounding rules and its code formula. The solution, lowp.c (tl_f32_to_e4m3, tl_e4m3_to_f32, tl_f32_to_e5m2, tl_e5m2_to_f32, tl_f32_to_bf16, tl_bf16_to_f32, tl_f32_to_f16, tl_f16_to_f32, and the shared helpers rne_code and decode_mag), is built under sanitizers and does not call Python. The interface is in numerics.h.
Learning objectives
- Express round to nearest, ties to even as a shift and compare on a float32’s integer significand.
- Compute the destination quantum for any of the four formats, including the subnormal range.
- Apply per-format special-value and overflow policies around a shared rounding core.
- Explain why every finite code decodes and re-encodes to the same bits.
The rounding rule in integers
Section titled “The rounding rule in integers”These symbols describe a destination format:
| Symbol | Meaning | Type / shape |
|---|---|---|
| Number of retained fraction bits | integer: 3 for E4M3, 2 for E5M2, 7 for bfloat16, 10 for binary16 | |
| Exponent bias | integer: 7 for E4M3, 15 for E5M2 and binary16, 127 for bfloat16 | |
| Smallest normal exponent, | integer | |
| Exponent of the spacing between adjacent representable values | integer: |
A positive normal float32 is with an integer significand of at most 24 bits. A destination format with fraction bits and bias has smallest normal exponent . In the binade containing , adjacent destination values are separated by , where
The conversion rounds to an integer using round to nearest, ties to even. If the discarded bits are greater than half a unit, increment the retained integer. If they equal half a unit, increment only when the retained integer is odd. A carry can increment the exponent. Values below the smallest normal use the fixed subnormal quantum .
Special values are format rules applied around that rounding core. Here E4M3 saturates finite magnitudes above 448. E5M2 uses the all-ones exponent for infinity and NaN. Signed zero preserves its sign bit. bfloat16 rounds the high half of float32 with the low half deciding ties. Binary16 uses 5 exponent bits and 10 fraction bits.
Working it by hand
Section titled “Working it by hand”For E4M3, , , and . The float32 value 0.3 lies between and , so its binade exponent is . Thus and one destination step is . Dividing gives , which rounds to 10. The retained significand is 10, or binary 1010. The low 3 bits are the fraction, 010; the carry into the exponent makes the final code 0x2A, whose decoded value is 0.3125.
The solution does the same computation in integers. 0.3f has bits 0x3E99999A, exponent field 125 and fraction 0x19999A, so $s = $ 0x99999A (with the implicit bit) and . has 24 bits, so and . The shift is : , and the 20 discarded bits are 0x9999A, more than half (0x80000), so . The code is $((q_e + M + B - 1) \ll M) + n = (4 \ll 3) + 10 = 42 = $ 0x2A.
Designing the API
Section titled “Designing the API”/* tinyllm/numerics.h, low-precision section */uint8_t tl_f32_to_e4m3(float x); float tl_e4m3_to_f32(uint8_t b);uint8_t tl_f32_to_e5m2(float x); float tl_e5m2_to_f32(uint8_t b);uint16_t tl_f32_to_bf16(float x); float tl_bf16_to_f32(uint16_t b);uint16_t tl_f32_to_f16(float x); float tl_f16_to_f32(uint16_t b);Encoders receive one float and return the exact stored bit pattern in an unsigned integer. Decoders receive that integer and return a float, exactly, for every code. No function allocates memory, retains a pointer, or touches the error slot. The header fixes the edge rules: E4M3 saturates and to and gives 0x7F for NaN; E5M2 saturates finite overflow to , keeps , and gives 0x7F for NaN; bfloat16 and binary16 overflow to and give the quiet NaNs 0x7FC0 and 0x7E00.
Building it step by step
Section titled “Building it step by step”The solution follows six steps. Work on the integer significand: a finite float32 magnitude is exactly with , where $s = $ frac | 0x800000 and for normals, and $s = $ frac and for float32 subnormals; everything after this is integer arithmetic, which is exact. Find the destination quantum: is plus the bit length of minus one; clamp it below at and subtract to get . Round by a shift with round half to even: is a right shift of by , and you compare the bits shifted out with half, rounding up if they are more and, if they are equal, only when the kept integer is odd. Let addition build the code: is the same formula as the Python version, where a subnormal has field 0 and code , and a carry from to moves into the exponent field.
The shared rounder implements those four steps:
/* Rounded magnitude code of the finite, non-negative float32 with bits * `abs` in a format with M fraction bits and bias B. Never overflows a * uint32 for M <= 10 and B <= 127. */static uint32_t rne_code(uint32_t abs, int M, int B) { uint32_t exp = abs >> 23, frac = abs & 0x7FFFFFu; uint32_t s; int e2; if (exp == 0) { if (frac == 0) return 0; /* +0 */ s = frac; /* subnormal float32: 0.frac * 2^-126 */ e2 = -149; } else { s = frac | 0x800000u; /* normal: 1.frac * 2^(exp - 127) */ e2 = (int)exp - 150; } int bits = 0; /* bit length of s */ for (uint32_t t = s; t != 0; t >>= 1) bits++; int floorlog2 = e2 + bits - 1; int emin = 1 - B; int qe = (floorlog2 > emin ? floorlog2 : emin) - M; int shift = qe - e2; /* > 0: the target has fewer fraction bits */ uint32_t n; if (shift > 24) { n = 0; /* v < 2^(qe - 1), half a quantum: rounds to 0 */ } else { uint32_t half = 1u << (shift - 1); uint32_t rem = s & ((half << 1) - 1u); /* the bits shifted out */ n = s >> shift; if (rem > half || (rem == half && (n & 1u))) n++; /* ties to even */ } if (n == 0) return 0; return ((uint32_t)(qe + M + B - 1) << M) + n; /* carries into the exponent */}The shift is always positive because every destination has fewer than 23 fraction bits (and bfloat16’s equals float32’s). The shift > 24 branch is both a correctness and a safety rule: , so a shift of 25 or more leaves less than half a quantum, which rounds to 0, and it also keeps 1u << (shift - 1) from reaching an undefined shift of 32 or more. For E4M3 the boundary case is , exactly half the smallest subnormal : there , rem == half, and is even, so the result is 0, which is the header’s ” gives ”.
The remaining two steps are per format. Apply each format’s specials around the core: NaN, infinity, sign, and overflow differ between formats, so each wrapper extracts the sign and absolute bits, answers NaN and infinity first, calls the shared rounder, then clamps or overflows by its own rule. And decode exactly: ldexpf of a small integer by a power of two is exact for every code of these formats, normal or subnormal.
static float decode_mag(uint32_t code, int M, int B) { uint32_t ef = code >> M, mant = code & ((1u << M) - 1u); if (ef == 0) return ldexpf((float)mant, 1 - B - M); /* subnormal */ return ldexpf((float)((1u << M) + mant), (int)ef - B - M); /* implicit 1 */}
uint8_t tl_f32_to_e4m3(float x) { uint32_t u = f32_bits(x), sign = (u >> 24) & 0x80u, abs = u & 0x7FFFFFFFu; if (abs > 0x7F800000u) return 0x7F; /* NaN */ if (abs == 0x7F800000u) return (uint8_t)(sign | 0x7Eu); /* inf saturates */ uint32_t c = rne_code(abs, 3, 7); if (c > 0x7Eu) c = 0x7Eu; /* above 448: saturate (0x7F is NaN) */ return (uint8_t)(sign | c);}
uint8_t tl_f32_to_e5m2(float x) { uint32_t u = f32_bits(x), sign = (u >> 24) & 0x80u, abs = u & 0x7FFFFFFFu; if (abs > 0x7F800000u) return 0x7F; /* NaN */ if (abs == 0x7F800000u) return (uint8_t)(sign | 0x7Cu); /* inf stays inf */ uint32_t c = rne_code(abs, 2, 15); if (c > 0x7Bu) c = 0x7Bu; /* finite overflow saturates to 57344 */ return (uint8_t)(sign | c);}The wrappers share a shape. The sign is taken from bit 31 and moved to the destination’s top bit, so -0.0f (bits 0x80000000) becomes 0x80 through rne_code’s path: the sign survives because it never went through the arithmetic. NaN and infinity are recognized by comparing the absolute bits with 0x7F800000 before rounding, since rne_code assumes a finite input. The clamp after rounding is the per-format overflow policy: both FP8 formats saturate, to 0x7E (448) and 0x7B (57344), which keeps a rounding carry from ever producing E4M3’s NaN 0x7F or E5M2’s infinity 0x7C.
bfloat16 uses the same rounder with a different policy:
uint16_t tl_f32_to_bf16(float x) { uint32_t u = f32_bits(x), sign = (u >> 16) & 0x8000u, abs = u & 0x7FFFFFFFu; if (abs > 0x7F800000u) return 0x7FC0; /* NaN: quiet, sign dropped */ if (abs == 0x7F800000u) return (uint16_t)(sign | 0x7F80u); uint32_t c = rne_code(abs, 7, 127); if (c > 0x7F80u) c = 0x7F80u; /* overflow to inf */ return (uint16_t)(sign | c);}
float tl_bf16_to_f32(uint16_t b) { uint32_t u = (uint32_t)b << 16; /* bf16 is the top half of a float32 */ float x; memcpy(&x, &u, sizeof x); return x;}bfloat16 has float32’s exponent, so with , the shared rounder is exactly “round the top 16 bits, the low 16 decide”: the shift is always 16. Overflow goes to infinity (0x7F80), the IEEE rule, rather than saturating. Decoding is a 16-bit shift because bf16 is the top half of a float32. tl_f32_to_f16 and tl_f16_to_f32 follow the same pattern with , , infinity 0x7C00, and NaN 0x7E00; the E4M3 and E5M2 decoders check their NaN and infinity codes, then call decode_mag on the low 7 bits and apply the sign. The full solution is in lowp.c.
Why this design
Section titled “Why this design”One rounder serves four formats. Writing each conversion separately would quadruple the places a tie or a subnormal can be wrong; parameterizing by makes the formats differ only where the contract says they differ, in the special values and the overflow policy.
Integer arithmetic beats float tricks here. Adding and subtracting a magic constant (x + 0x1.8p23f-style rounding) or converting through double would also round, but each depends on the floating-point environment and FMA contraction. The integer shift-and-compare is exact, sanitizer-clean, and identical on every platform.
The C version works on bits, unlike the Python twin, which works on float64 values with frexp, ldexp, and rint. C has no vectorized rint to the format, and bit manipulation avoids any intermediate rounding. Both compute the same , , and code formula, which is why they agree on every input.
Each encode costs a bit-length loop of at most 24 iterations, a shift, and a compare; a production version would use __builtin_clz for the bit length. The tradeoff accepted is a few cycles for portability, since these conversions are not on the hottest path of the optional kernels.
What can go wrong
Section titled “What can go wrong”The tests lock the hand-worked value to the interface: 0.3 must give E4M3 code 0x2A and decode to 0.3125. FP8 saturation and specials are checked separately for E4M3 and E5M2, because a shared overflow branch would give one format the wrong policy. Subnormal ties and signed zero are checked because small values otherwise disappear or lose their sign. Every finite E4M3 and E5M2 code must survive decode then encode, an exhaustive check that finds errors across exponent transitions. Midpoint values must choose the even code, which both truncation and ties away from zero fail. For bfloat16, representative hand values and tie behavior check that the high-half shortcut still rounds correctly, and all bfloat16 codes must preserve finite values and specials. For binary16, hand examples cover normal and subnormal values (subnormal scaling differs from normal scaling), and every finite binary16 code must be a fixed point, which exercises all exponent and fraction combinations.
The mistakes those checks catch:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| Always incrementing on a half-way remainder | Alternating midpoint values round away from even | rne_code increments on a tie only when n & 1 |
| Applying E5M2 infinity rules to E4M3 | Large finite values become infinity instead of 448 | each format has its own wrapper and clamp (0x7E vs 0x7B) |
| Using the normal quantum below | Smallest subnormal codes decode at the wrong scale | qe clamps at and decode_mag drops the implicit 1 when ef == 0 |
| Dropping the sign before handling zero | -0.0 returns as positive zero | the sign bit is extracted first and ORed back after rounding |
Where this leads
Section titled “Where this leads”In AI Engineering, Paged attention for decode in C decodes half-precision values stored in its paged KV cache, and Fused int4 and int8 dequantize-matmul in C decodes half-precision quantization scales, both through their C headers only.
Beyond these books, device conversion instructions provide hardware support that may round or flush subnormals differently, so the exhaustive format checks here are worth running on each new target; compiler and device conformance suites run the same vectors on additional architectures. A practical way to do that is to add a standalone C target and compare output files.
Further reading
Section titled “Further reading”- The OCP FP8 specification, compared with IEEE 754 binary16’s infinity and NaN encodings.
- IEEE Std 754-2019.
Key terms
Section titled “Key terms”- Quantum: the spacing between adjacent representable values of the destination format in the binade of the input.
- Integer significand: the float32 magnitude written as with an integer .
- Saturation: clamping finite overflow to the largest finite code, as both FP8 formats do.
- Fixed point (of a codec): a code that decodes and re-encodes to the same bits.
Summary
Section titled “Summary”- Encoding a value means rounding its significand in units of the destination format’s quantum; for E4M3, 0.3 encodes to
0x2A. - One integer rounder parameterized by serves E4M3, E5M2, bfloat16, and binary16, and the code formula lets a rounding carry move into the exponent field on its own.
- E4M3 finite overflow saturates, while E5M2 reserves infinity and NaN codes; one shared overflow branch would give one of them the wrong policy.
- Ties to even depend on the low bit of the retained significand, not the sign.
- Every finite encoding decodes and re-encodes to the same bits, in both FP8 formats, bfloat16, and binary16.
Review questions
Section titled “Review questions”-
Why does
rne_codecompare the discarded bits withhalfand then testn & 1?Answer
Round to nearest needs to know whether the discarded part is below, at, or above half a quantum. Above half rounds up, below rounds down. Exactly half is a tie, and ties to even rounds up only when the kept integer is odd, so the result’s last bit is 0. The sign plays no part: the magnitude is rounded and the sign reattached.
-
How does a rounding carry move into the exponent field without special code?
Answer
The code is , where a normal lies in and includes the implicit bit. If rounding takes to , the addition adds , which is one more in the exponent field and a zero fraction: exactly the next binade’s first value.
-
Why is the
shift > 24branch needed?Answer
, so with a shift of 25 or more the value is below half a quantum and must round to 0. Without the branch,
1u << (shift - 1)could shift by 32 or more for tiny inputs in formats with a small , which is undefined behavior in C and would trip UBSan. -
Why do E4M3 and E5M2 clamp to different codes, and why after rounding?
Answer
E4M3 has no infinity and uses
0x7Ffor NaN, so its largest finite code is0x7E(448). E5M2 keeps IEEE infinity at0x7C, so its largest finite code is0x7B(57344). Clamping after rounding catches both a large input and a value just below the limit that rounds up past it; clamping the input first would miss the second case.