Module contents
Lesson 1 of 26Core 80 min

Machine numbers: IEEE 754 floating point

How computers represent real numbers using a finite nonuniform set and what IEEE 754 guarantees for each operation, including binary64, binary32, binary16, bfloat16, FP8, ulps and special values.

After this lesson you can

  • Decode binary32, binary16 or bfloat16 bit patterns by hand and in code.
  • Calculate machine epsilon, unit roundoff and the ulp of a number in any format.
  • Explain why 0.1 + 0.2 != 0.3 and decide which floating-point comparisons are safe.
  • Choose FP32, FP16, BF16 or FP8 based on the range and precision a tensor needs.
  • Reason about subnormals, infinities and NaN propagation in NumPy and PyTorch.

Before you start

Motivation: real numbers do not fit in 64 bits

Two failures that arise sooner or later in numerical projects and have nothing to do with a programming mistake.

  • Training diverges in FP16. A normalization layer calculates the mean of the squares of 256 activations. If activations are 20, each square is 400 and the sum is 102,400. In float16 the largest finite number is 65,504: the sum becomes +∞+\infty, the variance ∞\infty, the normalized output 0 or NaN depending on operation order, and in the backward pass gradients through that layer become NaN and contaminate weights. Nobody wrote anything wrong: the format has no room for 102,400.
  • A balance does not add up. Ten deposits of €0.10 summed in float64 do not give 1.00. They give 0.9999999999999999, and comparison saldo == 1.0 is false.
[ ]Two failures with ordinary numbersBrowser
import numpy as np

# 1) Un entrenamiento en FP16: la suma de los cuadrados de 256 activaciones de valor 20
a = np.full(256, 20.0, dtype=np.float16)
with np.errstate(over="ignore"):
    sq16 = np.sum(a * a)                      # 256 · 400 = 102400
print("suma de cuadrados en float16:", sq16, "  en float32:", np.sum(a.astype(np.float32) ** 2))
print("mayor float16 finito:", np.finfo(np.float16).max)

# 2) Un saldo que no cuadra: diez ingresos de 0.10
saldo = 0.0
for _ in range(10):
    saldo += 0.1
print("\nsaldo tras diez ingresos de 0.1:", repr(saldo), "  ¿== 1.0?", saldo == 1.0)
print("0.1 + 0.2 =", repr(0.1 + 0.2), "  ¿== 0.3?", 0.1 + 0.2 == 0.3)

Both failures have the same root. The reals form an uncountable set and 64 bits hold only 2642^{64} distinct patterns, so a computer works with a finite subset F⊂R\mathbb{F} \subset \R and replaces each result with a nearby element of that subset. We must choose which numbers to include. A uniform grid (fixed point) wastes bits: one spacing cannot represent both an electron’s mass and a galaxy’s. Floating point chooses something else: keep relative precision constant, so every representable number has roughly the same number of significant digits whether large or small. The cost is that the grid is no longer uniform.

This lesson builds that set bit by bit and establishes vocabulary for the module: what IEEE 754 guarantees for each operation, machine epsilon, unit roundoff and ulp, the behavior of signed zeros, infinities, NaNs and subnormals, and why deep learning has added 16- and 8-bit formats with very different properties. You already know dtype as a tool (dtypes and promotion rules) and how they are stored (the ndarray memory model); here you look inside each one. The next lesson uses all this to analyze rounding error in algorithms.

Floating-point systems

Before IEEE 754, the general definition. It is the same scientific notation used on paper, with a fixed number of digits.

Three properties follow directly from the definition.

  1. F\mathbb{F} is finite. Each exponent has (β−1)βp−1(\beta - 1)\beta^{p-1} normalized significands, so the number of nonzero elements is 2(β−1)βp−1(emax⁡−emin⁡+1)2(\beta - 1)\beta^{p-1}(e_{\max} - e_{\min} + 1).
  2. Spacing is constant within each binade and grows between them. A binade (in base 2) is interval [βe,βe+1)[\beta^e, \beta^{e+1}). Within it the elements of F\mathbb{F} are Mβe−p+1M\beta^{e-p+1} with consecutive integer MM, spaced exactly βe−p+1\beta^{e-p+1} apart. In the next binade spacing is multiplied by β\beta: in base 2, it doubles.
  3. Relative spacing is bounded. Dividing spacing by the size of numbers in the binade, βe−p+1/x\beta^{e-p+1}/x lies between β−p\beta^{-p} and β1−p\beta^{1-p} for every xx in the binade. That is the precise meaning of “constant relative precision”: it varies by a factor of β\beta, but does not depend on the magnitude of xx.
InteractiveThe real line of a toy floating-point format
Δ = 2^−4Δ = 2^−3Δ = 2^−200.5124
Relative error ∣fl(x)−x∣/∣x∣|\mathrm{fl}(x) - x|/|x| across the range (log⁡2\log_2 axes)
12^−22^−42^−62^−82^−62^−52^−42^−32^−22^−12^02^12^22^3u = 2^−4
  • normal binades (alternating colors)
  • subnormals
  • relative rounding error
  • xx y fl(x)\mathrm{fl}(x)
Format
3 (bias 3)
3
z = 2
0.04737
Finite values (including ±0\pm 0)112
ε=2−m\varepsilon = 2^{-m} (spacing in [1,2)[1, 2))0.125 = 2^−3
u=2−pu = 2^{-p} (unit roundoff)0.0625 = 2^−4
Smallest normal and smallest subnormal0.25 and 0.03125
Largest finite15
xx, fl(x)\mathrm{fl}(x) and relative error0.04737 → 0.0625: 0.32
Relative error exceeds uu: xx is below 2−22^{-2}, where the bound ∣fl(x)−x∣≤u∣x∣|\mathrm{fl}(x) - x| \le u|x| no longer holds.
Above are all positive values of an IEEE-like binary format with ww exponent bits and mm fraction bits (precision p=m+1p = m + 1); the format is symmetric about 0. Brackets mark spacing Δ\Delta in each binade. Start with zoom and watch Δ\Delta double across each power of 2. Below is actual relative error ∣fl(x)−x∣/∣x∣|\mathrm{fl}(x) - x|/|x| when rounding each xx to nearest, with both axes on a log⁡2\log_2 scale: a sawtooth that never exceeds u=2−pu = 2^{-p} in the normal range. Disable subnormals and take xx below 2emin⁡2^{e_{\min}}: what happens to the error? Change mm and check that tooth height moves with uu.

The figure shows what the rest of the lesson formalizes: relative rounding error in the normal range is a sawtooth whose peak approaches u=2−pu = 2^{-p} (in the first gap of each binade) and halves by the end, because absolute spacing is fixed while xx doubles. Below 2emin⁡2^{e_{\min}} the picture changes completely. Without subnormals, numbers there round to 0 or 2emin⁡2^{e_{\min}} with relative errors up to 100%. With subnormals, spacing stops shrinking and relative error increases gradually. We return to that region in the special-values section.

IEEE 754 bit by bit

Until 1985 each manufacturer had its own arithmetic, with bases 2, 8 or 16, different rounding rules and overflow behavior, and the same program produced different results on different machines. IEEE 754, published in 1985 and promoted by William Kahan (1989 Turing Award winner largely for this work), specified binary formats, rounding of each operation and exception handling. The 2008 revision added, among other things, 16-bit format binary16, decimal formats and fused operation fma(a,b,c)=ab+c\mathrm{fma}(a, b, c) = ab + c with one rounding; the 2019 revision is minor.

FormatBits (s, w, t)ppBiasLargest finiteSmallest normalSmallest subnormalu=2−pu = 2^{-p}
binary64 (float64)1, 11, 525310231.80×103081.80 \times 10^{308}2.23×10−3082.23 \times 10^{-308}4.94×10−3244.94 \times 10^{-324}1.11×10−161.11 \times 10^{-16}
binary32 (float32)1, 8, 23241273.40×10383.40 \times 10^{38}1.18×10−381.18 \times 10^{-38}1.40×10−451.40 \times 10^{-45}5.96×10−85.96 \times 10^{-8}
binary16 (float16)1, 5, 10111565 50465\,5046.10×10−56.10 \times 10^{-5}5.96×10−85.96 \times 10^{-8}4.88×10−44.88 \times 10^{-4}
bfloat161, 8, 781273.39×10383.39 \times 10^{38}1.18×10−381.18 \times 10^{-38}9.18×10−419.18 \times 10^{-41}3.91×10−33.91 \times 10^{-3}

Each row follows from the definition: in binary16, for example, b=15b = 15, the largest normal exponent is E=30E = 30 and the largest significand (1.1111111111)2=2−2−10(1.1111111111)_2 = 2 - 2^{-10}, so the largest finite value is (2−2−10)×215=65 504(2 - 2^{-10}) \times 2^{15} = 65\,504. bfloat16 is not an IEEE 754 format, but follows its rules: it is binary32 with the fraction shortened to 7 bits. The library cell below prints these values with np.finfo and torch.finfo.

Decode by hand

Take binary32 pattern 0x40490FDB:

0⏟s  10000000⏟E=128  10010010000111111011011⏟f.\underbrace{0}_{s}\;\underbrace{10000000}_{E = 128}\;\underbrace{10010010000111111011011}_{f}.

The sign is positive. E=128E = 128 is a normal exponent, so e=128−127=1e = 128 - 127 = 1. The fraction is f=0x490FDB/223=4788187/8388608≈0.5707963705f = \texttt{0x490FDB}/2^{23} = 4788187/8388608 \approx 0.5707963705 and the value is (1+f)×21=3.14159274101257…(1 + f) \times 2^1 = 3.14159274101257\ldots: the float32 closest to π\pi, exceeding π\pi by about 8.7×10−88.7 \times 10^{-8}.

Two design choices explain field order and bias. With sign first, biased exponent (always nonnegative) next and fraction last, two nonnegative floating-point values (other than NaNs) sort in the same order as their bit patterns interpreted as unsigned integers. Thus comparisons or sorting can use integer instructions, and adding 1 to a positive float’s pattern gives the next float: if the fraction is all ones, carry advances the exponent and resets the fraction to zero, exactly the first number in the next binade. The implicit bit provides one extra bit of precision: binary64 stores 52 fraction bits and has p=53p = 53.

InteractiveA float's bits, one by one
  • sign ss (1 bit)
  • biased exponent EE (8 bits, bias 127)
  • fraction ff (23 bits)
(−1)0×2123−127×(1.10011001100110011001101)2=0.100000001(-1)^{0}\times 2^{123 - 127}\times (1.10011001100110011001101)_2 = 0.100000001
Exact stored value: 0.100000001490116119384765625
Format
Enter a decimal
Hexadecimal pattern0x3DCCCCCD
Classnormal
Stored exponent EE and actual e=E−127e = E - 127123 and −4
Previous float0.09999999404
Next float0.1000000089
ulp (spacing in this binade)7.4506·10^−9 = 2^−27
Relative error versus 0.11.490·10^−8
Each box is one bit: red sign, orange biased exponent, blue fraction. Click any to change it, or enter a decimal and it will be rounded to the chosen format (nearest, ties to even). Start with 0.1 in FP32: the stored value is not 0.1. Use “pattern + 1” from the largest subnormal and largest finite value: the first gives the smallest normal without a spacing jump, the second gives ∞\infty. Switch to FP16, BF16 and E4M3 with the same decimal and compare relative error; in E4M3 find the pattern that would be ∞\infty in IEEE.

Correct rounding

A floating-point system is useful only if it says what happens to an operation’s result, which generally is not in F\mathbb{F}. Let fl:R→F∪{±∞}\mathrm{fl}: \R \to \mathbb{F} \cup \{\pm\infty\} be a rounding function. IEEE 754 defines four required binary modes.

The requirement is strong: hardware must behave as if it computed the exact result with infinitely many digits and only then rounded. A few extra bits suffice (guard, round and the “sticky” bit, which records whether anything nonzero was lost on the right). In return, each isolated operation incurs the smallest possible error and the result is reproducible: the same calculation in the same format and operation order gives the same bit pattern on any conforming machine. Elementary functions (exp⁡\exp, sin⁡\sin, log⁡\log) are not on that list: the standard only recommends correct rounding, and common libraries do not guarantee it.

Why ties to even instead of ties upward, as in school? Always rounding ties in the same direction introduces accumulating bias. The classic example is by Reiser and Knuth (1975), given as theorem 5 in Goldberg’s 1991 article: in base 10 with 3 digits, iterate xn+1=(xn⊖y)⊕yx_{n+1} = (x_n \ominus y) \oplus y from x0=1.00x_0 = 1.00 with y=−0.555y = -0.555.

[ ]Ties upward versus ties to evenBrowser
import decimal

# Reiser y Knuth (1975): x_{n+1} = (x_n - y) + y con 3 cifras decimales, x_0 = 1.00 e y = -0.555
for modo in [decimal.ROUND_HALF_UP, decimal.ROUND_HALF_EVEN]:
    ctx = decimal.Context(prec=3, rounding=modo)
    x, y = decimal.Decimal("1.00"), decimal.Decimal("-0.555")
    serie = [x]
    for _ in range(6):
        x = ctx.add(ctx.subtract(x, y), y)
        serie.append(x)
    print(f"{modo:>16}:", " ".join(str(v) for v in serie))

With ties upward, 1.00+0.555=1.555→1.561.00 + 0.555 = 1.555 \to 1.56 and 1.56−0.555=1.005→1.011.56 - 0.555 = 1.005 \to 1.01: each iteration adds a nonexistent cent and the series drifts without bound. With ties to even, 1.555→1.561.555 \to 1.56 (6 is even) and 1.005→1.001.005 \to 1.00 (0 is even): the series stays still. The theorem says ties to even always make the sequence constant from x1x_1 onward. Directed modes have another use: calculating the same thing toward −∞-\infty and toward +∞+\infty gives an interval guaranteed to contain the exact result. This underlies interval arithmetic, as the lab will check.

Machine epsilon, unit roundoff and ulp

Three quantities measure the granularity of F\mathbb{F} and are often confused. Define them precisely.

The first two are format constants; ulp depends on xx. They relate as follows: ulp(1)=ε\mathrm{ulp}(1) = \eps, ulp(x)=ε⋅βe\mathrm{ulp}(x) = \eps \cdot \beta^{e} in the normal range, and therefore ε∣x∣/β<ulp(x)≤ε∣x∣\eps|x|/\beta < \mathrm{ulp}(x) \le \eps|x|. Epsilon is not the spacing between floats everywhere: near 101610^{16} the float64 are spaced by 22, and near 10−30010^{-300} by about 10−31610^{-316}.

The central theorem states that rounding incurs a uniform relative error.

Proof

Let e≥emin⁡e \ge e_{\min} with βe≤∣x∣<βe+1\beta^e \le |x| < \beta^{e+1} (if ∣x∣=max⁡F|x| = \max\mathbb{F}, x∈Fx \in \mathbb{F} and there is nothing to prove). By symmetry, assume x>0x > 0. Elements of F\mathbb{F} in [βe,βe+1][\beta^e, \beta^{e+1}] are Mβe−p+1M\beta^{e-p+1} with βp−1≤M≤βp\beta^{p-1} \le M \le \beta^p (the last, βe+1\beta^{e+1}, belongs to F\mathbb{F} if e<emax⁡e < e_{\max}; if e=emax⁡e = e_{\max}, x≤max⁡Fx \le \max\mathbb{F} and the previous values suffice). Thus xx lies between consecutive elements a≤x≤a+βe−p+1a \le x \le a + \beta^{e-p+1} with a≥βea \ge \beta^e, and the closest is at most half the gap away:

d:=∣fl(x)−x∣≤12βe−p+1.d := |\mathrm{fl}(x) - x| \le \tfrac{1}{2}\beta^{e-p+1}.

Also x≥βe+dx \ge \beta^e + d: if fl(x)=a\mathrm{fl}(x) = a, then x=a+d≥βe+dx = a + d \ge \beta^e + d; if fl(x)\mathrm{fl}(x) is the upper one, d≤x−ad \le x - a, hence x≥a+d≥βe+dx \ge a + d \ge \beta^e + d. Since t↦t/(βe+t)t \mapsto t/(\beta^e + t) is increasing,

dx≤dβe+d≤12βe−p+1βe+12βe−p+1=u1+u.\frac{d}{x} \le \frac{d}{\beta^e + d} \le \frac{\tfrac{1}{2}\beta^{e-p+1}}{\beta^e + \tfrac{1}{2}\beta^{e-p+1}} = \frac{u}{1 + u}.

It suffices to define δ=(fl(x)−x)/x\delta = (\mathrm{fl}(x) - x)/x. With a directed mode, d<βe−p+1d < \beta^{e-p+1} and the same calculation, dividing by x≥βex \ge \beta^e, gives ∣δ∣<β1−p=ε|\delta| < \beta^{1-p} = \eps.

∎

Notice the two assumptions. If ∣x∣>max⁡F|x| > \max\mathbb{F} (beyond half an ulp above the maximum), fl(x)=±∞\mathrm{fl}(x) = \pm\infty and relative error is infinite: this is the motivating overflow. If ∣x∣<βemin⁡|x| < \beta^{e_{\min}}, spacing no longer shrinks with xx, the proof step dividing by βe\beta^e fails and the bound no longer holds: in the toy figure you saw it rise above uu. You will quantify this in the proof exercise.

Form fl(x)=x(1+δ)\mathrm{fl}(x) = x(1 + \delta) is the building block of error analysis: combined with correct rounding, it says each basic operation incurs relative error at most uu, x⊕y=(x+y)(1+δ)x \oplus y = (x + y)(1 + \delta) with ∣δ∣≤u|\delta| \le u, provided the exact result lies in the normal range. The next lesson builds the standard model of floating-point arithmetic on this.

Why 0.1 + 0.2 != 0.3

Now you can explain the second motivating failure precisely. 0.1=1/100.1 = 1/10 and 10=2⋅510 = 2 \cdot 5; a rational has a finite binary expansion if and only if its reduced denominator is a power of 2, so 0.10.1 has a repeating binary expansion and is not in F\mathbb{F}. fl(0.1)\mathrm{fl}(0.1) is stored, slightly larger. The same happens with 0.20.2 and 0.30.3, and the three errors do not cancel.

InteractiveWhy 0.1 does not exist in binary
580.2 × 2 = 0.4→ 0
590.4 × 2 = 0.8→ 0
600.8 × 2 = 1.6→ 1
610.6 × 2 = 1.2→ 1
620.2 × 2 = 0.4→ 0
630.4 × 2 = 0.8→ 0
640.8 × 2 = 1.6→ 1
In binary: 0.0001100110011001100110011001100110011001100110011001100110011001…
The remainder after bit 53 exceeds half an ulp: round up (add 1 to the last bit).
You entered: 0.1
Exactly stored: 0.1000000000000000055511151231257827021181583404541015625
  • significant bits stored
  • repeating block
  • bits beyond significant bit 53 (rounded)
Mode
Format (precision p)
Positive decimal
rounding
Period0011 (from bit 2)
Fractional bits generated64
Absolute error fl(x)−x\mathrm{fl}(x) - x5.5511·10^−18
Relative error5.5511·10^−17 (u = 2^−53)
In “One decimal” mode, the multiply-by-2 algorithm is applied to the fractional part with exact rational arithmetic. Each step doubles the remainder and its integer part is the next bit. Press play with 0.1: after four steps the remainder returns to 0.2 and the repeating block 0011 appears. At pp significant bits, the remainder determines rounding, and below you see every digit of the stored number. Try 0.375 (which terminates), 0.2 and 3.14, and switch to bfloat16. In “Sum” mode see how fl(0.1)+fl(0.2)\mathrm{fl}(0.1) + \mathrm{fl}(0.2) lands exactly on a tie.

The complete binary64 calculation, reproduced by the figure with exact arithmetic. These are the three values involved, with all digits:

fl(0.1)                = 0.1000000000000000055511151231257827021181583404541015625
fl(fl(0.1) + fl(0.2))  = 0.3000000000000000444089209850062616169452667236328125
fl(0.3)                = 0.299999999999999988897769753748434595763683319091796875
  • fl(0.1)\mathrm{fl}(0.1) is M⋅2−56M \cdot 2^{-56} with M=7205759403792794M = 7205759403792794, and fl(0.2)=2 fl(0.1)=M⋅2−55\mathrm{fl}(0.2) = 2\,\mathrm{fl}(0.1) = M \cdot 2^{-55} (multiplication by 2 is exact).
  • Their exact sum is 3M⋅2−563M \cdot 2^{-56}, and 3M3M has 55 bits: 2 too many. Since M≡2(mod4)M \equiv 2 \pmod 4, the two excess bits of 3M3M are 10: exactly half an ulp. It is a tie and even wins, here upward: 0.1⊕0.20.1 \oplus 0.2 is the second value in the list.
  • But fl(0.3)\mathrm{fl}(0.3), the third, is the immediately preceding float. The results differ by one ulp, 2−54≈5.55×10−172^{-54} \approx 5.55 \times 10^{-17}, and 0.1 + 0.2 == 0.3 is false.

Each step is correct in the theorem’s sense: the three roundings incur relative errors below uu. The problem is exact comparison of two results carrying different errors. This yields comparison rules:

  • == is reliable when all intermediate values are exactly representable: integers with absolute value below 2532^{53} in float64, sums of small dyadic fractions such as 0.5+0.250.5 + 0.25, products by powers of 2 without overflow or subnormals.
  • Otherwise compare with tolerance: ∣a−b∣≤max⁡(r⋅max⁡(∣a∣,∣b∣), aabs)|a - b| \le \max(r \cdot \max(|a|, |b|),\ a_{\text{abs}}). Relative tolerance rr is chosen according to accumulated roundings (a few ulps for one operation, much more for a long algorithm); absolute tolerance aabsa_{\text{abs}} only makes sense when the expected value can be 0 and depends on problem scale.
  • Beware defaults. math.isclose(a, b) uses r=10−9r = 10^{-9} and aabs=0a_{\text{abs}} = 0, symmetric in aa and bb. np.isclose(a, b) checks ∣a−b∣≤aabs+r∣b∣|a - b| \le a_{\text{abs}} + r|b| with r=10−5r = 10^{-5} and aabs=10−8a_{\text{abs}} = 10^{-8}: it is not symmetric, and for quantities around 10−810^{-8} or smaller the absolute tolerance makes it almost always true.

Special values and subnormals

IEEE 754 closes F\mathbb{F} with a few more values so every operation has a defined result and computation can continue. Together with subnormals these form the special values and subnormals.

  • ±0\pm 0. There are two zeros. They compare equal (0.0 == -0.0 is true), but the sign is retained and has consequences: 1/(+0)=+∞1/(+0) = +\infty and 1/(−0)=−∞1/(-0) = -\infty. An underflowing result remembers which side it came from, relevant for functions with branch cuts such as log⁡\log or  \sqrt{\ } in the complex plane.
  • ±∞\pm\infty. Result of overflow (in default mode) and division of a nonzero number by zero. They behave as limits: ∞+x=∞\infty + x = \infty for finite xx, 1/∞=01/\infty = 0.
  • NaN (not a number). Result of operations without a reasonable value: ∞−∞\infty - \infty, 0×∞0 \times \infty, 0/00/0, −1\sqrt{-1}. Every operation with a NaN yields NaN, and every ordered comparison with a NaN is false: nan == nan, nan < 1 and nan > 1 give False, and nan != nan gives True. There are quiet NaNs (which propagate) and signaling NaNs (which raise an exception when used); numerical practice typically encounters the former. NaN fraction bits are a “payload” the standard allows for diagnostics.

Each case also sets an exception flag (overflow, division by zero, invalid operation, underflow, inexact). NumPy translates these into RuntimeWarning controlled with np.errstate.

[ ]Signed zeros, infinities, NaNs and subnormalsBrowser
import math
from fractions import Fraction
import numpy as np

inf, nan = math.inf, math.nan
with np.errstate(divide="ignore", invalid="ignore"):
    uno, cero, mcero = np.float64(1.0), np.float64(0.0), np.float64(-0.0)
    print("+0 == -0:", cero == mcero, "   1/+0 =", uno / cero, "   1/-0 =", uno / mcero, "   copysign(1, -0) =", math.copysign(1, -0.0))
    print("inf - inf =", np.float64(inf) - inf, "   0 * inf =", cero * inf, "   0/0 =", cero / cero, "   sqrt(-1) =", np.sqrt(np.float64(-1.0)))
print("1/inf =", 1 / inf, "   inf + 1e308 =", inf + 1e308, "   exp(1000) en NumPy:", end=" ")
with np.errstate(over="ignore"):
    print(np.exp(np.float64(1000.0)))

# NaN: no es igual a nada, ni a sí mismo, y todas las comparaciones ordenadas son falsas
print("\nnan == nan:", nan == nan, "  nan != nan:", nan != nan, "  nan < 1:", nan < 1, "  nan > 1:", nan > 1)
print("max(nan, 1) =", max(nan, 1), "  max(1, nan) =", max(1, nan), "   (el max de Python depende del orden)")
print("np.max([1, nan]) =", np.max([1, nan]), "  np.nanmax([1, nan]) =", np.nanmax([1, nan]),
      "  np.fmax(1, nan) =", np.fmax(1, nan))
print("sorted([3, nan, 1, 2]) =", sorted([3, nan, 1, 2]), "   np.sort:", np.sort([3, nan, 1, 2]))

# subnormales y underflow gradual
tiny = np.finfo(np.float64).smallest_normal
print(f"\nmenor normal 2^-1022 = {tiny:.6e}   menor subnormal 2^-1074 = {np.finfo(np.float64).smallest_subnormal:.6e}")
x, y = 1.5 * tiny, tiny
print("x = 1.5·2^-1022, y = 2^-1022:  x - y =", x - y, "(subnormal, no 0)   ¿x - y == 0?", x - y == 0)
r = Fraction(3, 2 ** 1075)          # 1.5 veces el menor subnormal: empate entre 2^-1074 y 2^-1073
fl = Fraction(float(r))             # float(Fraction) redondea correctamente: gana el par, 2^-1073
print("fl(3·2^-1075) == 2^-1073:", fl == Fraction(1, 2 ** 1073), "  error relativo:", float(abs(fl - r) / r))

Read the output carefully: each line is a common trap. Python’s max compares with < and, since every comparison with NaN is false, returns the first thing it sees: max(nan, 1) is NaN and max(1, nan) is 1. sorted with a NaN leaves the list unsorted because the relation is no longer a total order. NumPy instead propagates: np.max returns NaN if any is present, np.nanmax and np.fmax ignore them and np.sort sends them to the end.

Subnormals and gradual underflow

Without subnormals, the smallest positive value would be 2emin⁡2^{e_{\min}} and the gap seen in the toy figure would lie between it and 0. Subnormals, with fixed exponent emin⁡e_{\min} and no implicit bit, fill it at the first binade’s spacing, 2emin⁡−p+12^{e_{\min} - p + 1}. Precision is lost gradually: a subnormal with its first nonzero bit at fraction position kk has only p−kp - k significant bits. The reward is a property code assumes without realizing it.

Proof

Let η=2emin⁡−p+1\eta = 2^{e_{\min} - p + 1} be the smallest positive subnormal. Every finite element of F\mathbb{F} is an integer multiple of η\eta: subnormals are kηk\eta and a normal is M2e−p+1=M2e−emin⁡ηM 2^{e-p+1} = M 2^{e - e_{\min}}\eta with e≥emin⁡e \ge e_{\min}. Thus x−yx - y is a nonzero integer multiple of η\eta and ∣x−y∣≥η|x - y| \ge \eta. Since η∈F\eta \in \mathbb{F} and rounding is monotonic, ∣fl(x−y)∣≥fl(η)=η>0|\mathrm{fl}(x - y)| \ge \mathrm{fl}(\eta) = \eta > 0.

∎

Without subnormals the property fails: with x=1.5×2emin⁡x = 1.5 \times 2^{e_{\min}} and y=2emin⁡y = 2^{e_{\min}}, the exact difference is 2emin⁡−12^{e_{\min} - 1}, which falls in the gap and rounds to 0. Then an if x != y: z = 1 / (x - y) divides by zero. The previous cell shows the other side: in the subnormal region the relative-error theorem’s bound no longer holds, and rounding 3×2−10753 \times 2^{-1075} (a tie between one and two minimum subnormals) gives 2−10732^{-1073}, a relative error of 1/31/3.

Formats for deep learning

A neural network tolerates substantial relative error in each number (weights are perturbed by noise anyway) but needs range: tiny gradients and large activations coexist in the same training. Every bit removed also means cheaper memory, bandwidth and arithmetic units. This has produced a family of formats allocating bits differently.

  • binary16 (FP16). 5 exponent bits and 10 fraction bits: u=2−11≈4.9×10−4u = 2^{-11} \approx 4.9 \times 10^{-4}, but the normal range is only [6.1×10−5,65 504][6.1 \times 10^{-5}, 65\,504] and below 2−25≈3×10−82^{-25} \approx 3 \times 10^{-8} everything rounds to zero. This is the motivating format.
  • bfloat16 (BF16). FP32’s 8-bit exponent and only 7 fraction bits: u=2−8≈3.9×10−3u = 2^{-8} \approx 3.9 \times 10^{-3}, eight times worse than FP16, but the same range as FP32. Kalamkar et al. (2019) explain in their abstract that retaining FP32 range allows training to converge “without adjusting hyperparameters,” whereas FP16 requires adjustment, and in their image classification, speech recognition, language model, generative network and recommendation experiments BF16 matched FP32 results in the same iteration count. Converting FP32 to BF16 is also straightforward: retain the upper 16 bits and round.
  • TF32. Not a storage format but an internal mode of NVIDIA tensor cores since Ampere: FP32 matrix-multiplication operands convert to 1 + 8 + 10 bits (FP32 range with FP16 precision) and accumulate in FP32. In PyTorch torch.set_float32_matmul_precision controls it; you will see inside tensor cores later in this module.
  • FP8 E4M3 and E5M2. Micikevicius et al. (2022, NVIDIA, Arm and Intel) propose two 8-bit encodings. E5M2 follows IEEE rules: it is FP16 with 2 fraction bits, maximum 57,344 and 32 binades of range counting subnormals (smallest subnormal 2−162^{-16}). E4M3 breaks the rules to gain range: it has no infinities and only pattern S.1111.111 is NaN, making the maximum exponent useful again. It gains seven magnitudes (256, 288, …, 448), increasing its maximum from 240 to 448 and range from 17 to 18 binades (smallest normal 2−62^{-6}, smallest subnormal 2−92^{-9}). They recommend E4M3 for weights and activations and E5M2 for gradients, with a per-tensor scaling factor placing each tensor’s maximum near the format maximum; with this scheme they match 16-bit training results in CNNs, RNNs and transformers with up to 175 000 million parameters without changing hyperparameters.
InteractiveRange and precision ruler for FP32, BF16, FP16 and FP8
10^−4010^−3010^−2010^−10110^1010^2010^3010^40FP32BF16FP16E5M2E4M3
Solid bar: normal range. Light bar: subnormals, with fewer bits of precision.
  • x⋅2kx \cdot 2^k, stored value
format (p)storedstatusrel. error
FP32 (24)1.00000·10^−8normal6.08·10^−9
BF16 (8)1.00117·10^−8normal0.00117
FP16 (11)0rounds to zero1
E5M2 (3)0rounds to zero1
E4M3 (4)0rounds to zero1
1.0000·10^−8
2^0 = 1
Stored value x⋅2kx \cdot 2^k1.000000·10^−8
An example value for a small gradient.
The value rounds to zero in FP16 but not BF16: BF16 has FP32's exponent. Raise the scale factor until FP16 stores it; at 222^{2} it no longer rounds to zero, and at 2132^{13} it is normal.
Each bar shows a format's range on a logarithmic scale: filled for normal values, light for subnormals. The vertical line is the value being stored; the table gives, for each format, rounded value, whether it is normal, subnormal, zero or overflow, and relative error. Start with the 10−810^{-8} gradient: FP16 zeros it and BF16 does not. Raise scale factor 2k2^k until FP16 stores it: multiplying by a power of 2 changes only the exponent, adding no error. Then try the large activation, the motivating sum of squares and probability 0.9999.

The figure condenses the practical difference. A gradient of 10−810^{-8} vanishes in FP16 because it is below half the smallest subnormal, and survives in BF16 with relative error 1.2×10−31.2 \times 10^{-3}. Multiplying the loss by 2k2^{k} multiplies all gradients by the same amount (differentiation is linear), brings them into FP16 range and is undone at the end by dividing by 2k2^k: this is loss scaling, essential for FP16 and unnecessary for BF16, which already has FP32 range. But scaling shifts a fixed-width window: if one tensor’s gradients span more binades than fit, some are lost at the top or bottom regardless. No scaling fixes precision: 0.99990.9999 is stored as 11 in BF16 and FP16, so log⁡(1−p)\log(1 - p) gives −∞-\infty; the solution is to represent 1−p1 - p (or the logit) directly. Scaling, FP32 master weights and FP8 recipes are studied in mixed-precision training, loss scaling and FP8 training.

Implementation from scratch

The lab has two parts. First, convert between floats and bits with struct, decode any format, calculate ulp and the next float, and build a generic miniature floating-point system with four rounding modes, checked against NumPy. Then simulate BF16 and FP8 with NumPy and measure what happens to typical network tensors.

Bits, fields and value

struct.pack("<d", x) gives the 8 bytes of a float64 and struct.unpack("<Q", ...) reinterprets them as an unsigned integer: a portable way to see bits. Shifts and masks separate the fields, turning the definition table into four lines. math.ldexp(M, k) calculates M⋅2kM \cdot 2^k exactly.

[ ]Generic IEEE 754 decoderBrowser
import math
import struct
import numpy as np

def f64_to_bits(x):
    return struct.unpack("<Q", struct.pack("<d", x))[0]

def bits_to_f64(b):
    return struct.unpack("<d", struct.pack("<Q", b))[0]

def f32_to_bits(x):
    return struct.unpack("<I", struct.pack("<f", x))[0]

def fields(b, ebits, mbits):
    """(signo, exponente almacenado E, fracción F) del patrón b."""
    return b >> (ebits + mbits), (b >> mbits) & ((1 << ebits) - 1), b & ((1 << mbits) - 1)

def decode(b, ebits, mbits):
    """Valor exacto del patrón b en un formato IEEE binario con ebits de exponente y mbits de fracción."""
    s, E, F = fields(b, ebits, mbits)
    bias = (1 << (ebits - 1)) - 1
    sign = -1.0 if s else 1.0
    if E == (1 << ebits) - 1:                          # exponente todo a unos: inf o NaN
        return sign * math.inf if F == 0 else math.nan
    if E == 0:                                         # subnormal (o cero): 0.F · 2^(1 - bias)
        return sign * math.ldexp(F, 1 - bias - mbits)
    return sign * math.ldexp((1 << mbits) | F, E - bias - mbits)   # normal: 1.F · 2^(E - bias)

def show(x):
    b = f64_to_bits(x)
    s, E, F = fields(b, 11, 52)
    print(f"{x!r:>24}  s={s}  E={E:4d} (e={E - 1023:5d})  F={F:013x}  hex={x.hex()}")

for x in [1.0, 0.1, -2.5, 5e-324, float("inf")]:
    show(x)

# pi en binary32, como en el ejemplo a mano
b = f32_to_bits(math.pi)
print(f"\npi en binary32: {b:032b} = 0x{b:08X} ->", decode(b, 8, 23))

# comprobación exhaustiva: los 65536 patrones de binary16 frente a NumPy
todos = np.arange(1 << 16, dtype=np.uint16)
ref = todos.view(np.float16).astype(np.float64)
mio = np.array([decode(int(k), 5, 10) for k in range(1 << 16)])
iguales = (mio == ref) | (np.isnan(mio) & np.isnan(ref))
print("binary16: patrones descodificados igual que NumPy:", int(iguales.sum()), "de", len(todos))

The 0.1 line shows fraction 999999999999a: repeated block 1001 (9 in hexadecimal), rounded upward in the last digit, a instead of 9. The 5e-324 line has E=0E = 0 and F=1F = 1: the smallest subnormal, 2−10742^{-1074}. The decoder matches NumPy on all 65,536 binary16 patterns, including NaNs.

Next float and ulp

Pattern ordering gives the next float without real arithmetic: add 1 to a positive pattern, subtract 1 from a negative one. The ulp comes from the exponent returned by math.frexp.

[ ]Next float and ulp, checked against NumPyBrowser
def next_up(x):
    """Menor float64 estrictamente mayor que x (x finito o -inf)."""
    if x != x or x == math.inf:
        return x
    if x == 0.0:
        return 5e-324                         # el menor subnormal positivo, venga de +0 o de -0
    b = f64_to_bits(x)
    return bits_to_f64(b + 1 if x > 0 else b - 1)   # los positivos crecen con el patrón; los negativos, al revés

def ulp(x):
    """Espaciado de la binada de x: 2^(max(e, emin) - 52)."""
    x = abs(x)
    if x == 0.0:
        return 5e-324
    e = math.frexp(x)[1] - 1                  # x = m · 2^e con 1 <= m < 2
    return math.ldexp(1.0, max(e, -1022) - 52)

rng = np.random.default_rng(0)
xs = np.concatenate([rng.standard_normal(3000) * 10.0 ** rng.integers(-300, 300, 3000),
                     [0.0, -0.0, 1.0, 2.0 ** -1022, 5e-324, -5e-324, 1.7976931348623157e308]])
with np.errstate(over="ignore"):
    ok_next = all(next_up(float(x)) == np.nextafter(x, np.inf) for x in xs)
    ok_ulp = all(ulp(float(x)) == np.spacing(abs(x)) for x in xs if np.isfinite(np.spacing(abs(x))))
print("next_up coincide con np.nextafter:", ok_next, "  ulp coincide con np.spacing:", ok_ulp)
print("ulp(1) =", ulp(1.0), " ulp(1e16) =", ulp(1e16), " ulp(5e-324) =", ulp(5e-324))
print("1 + 2**-52 es el siguiente a 1:", next_up(1.0) == 1 + 2 ** -52)

fi = np.finfo(np.float64)                     # y frente a las constantes de np.finfo
print("ulp(1) == finfo.eps:", ulp(1.0) == fi.eps,
      "  next_up(0) == finfo.smallest_subnormal:", next_up(0.0) == fi.smallest_subnormal,
      "  next_up(finfo.smallest_subnormal * (2**52 - 1)) == finfo.smallest_normal:",
      next_up(fi.smallest_subnormal * (2 ** 52 - 1)) == fi.smallest_normal,
      "  next_up(finfo.max) == inf:", next_up(float(fi.max)) == math.inf)

np.spacing(x) is the distance from ∣x∣|x| to the next float away from 0, matching the defined ulp even at powers of 2 (where spacing below is half). ulp(1e16) equals 2: a fact needed in one exercise.

A miniature floating-point system with four rounding modes

The following class implements the definition’s rounding for any IEEE-like format with ebits exponent bits and mbits fraction bits. It uses Fraction, so the “exact result” the standard asks to round really is exact. The algorithm is the theorem’s proof in code: find the binade of ∣x∣|x|, take its ulp as quantum (2max⁡(e,emin⁡)−m2^{\max(e, e_{\min}) - m}, also covering subnormals), divide, decide using the remainder and detect overflow.

[ ]MiniFloat(1, 4, 3) and verificationBrowser
from fractions import Fraction

class MiniFloat:
    """Coma flotante binaria tipo IEEE: 1 bit de signo, ebits de exponente y mbits de fracción."""

    MODES = ("RNE", "RZ", "RU", "RD")   # al más cercano par, hacia cero, hacia +inf, hacia -inf

    def __init__(self, ebits=4, mbits=3):
        self.ebits, self.mbits = ebits, mbits
        self.p = mbits + 1                               # precisión, con el bit implícito
        self.bias = (1 << (ebits - 1)) - 1
        self.emin, self.emax = 1 - self.bias, (1 << ebits) - 2 - self.bias
        self.max = Fraction((1 << self.p) - 1, 1 << mbits) * Fraction(2) ** self.emax

    def round(self, x, mode="RNE"):
        """Redondea el real x (float, int o Fraction) al formato. Devuelve un Fraction exacto o ±inf."""
        x = Fraction(x)
        if x == 0:
            return x
        s, a = (1, x) if x > 0 else (-1, -x)
        e = a.numerator.bit_length() - a.denominator.bit_length()   # 2^e <= a < 2^(e+1), corrigiendo abajo
        if Fraction(2) ** e > a:
            e -= 1
        q = Fraction(2) ** (max(e, self.emin) - self.mbits)   # cuanto: ulp de la binada (o de los subnormales)
        n, r = divmod(a, q)                                   # a = n·q + r con 0 <= r < q
        if r:
            if mode == "RNE":
                n += r > q / 2 or (r == q / 2 and n % 2 == 1)
            elif mode == "RU":
                n += s > 0
            elif mode == "RD":
                n += s < 0
        v = n * q
        if v > self.max:                                      # desbordamiento
            hacia_inf = mode == "RNE" or (mode == "RU" and s > 0) or (mode == "RD" and s < 0)
            return s * math.inf if hacia_inf else s * self.max
        return s * v

    def decode(self, b):
        v = decode(b, self.ebits, self.mbits)
        return v if not math.isfinite(v) else Fraction(v)

    def values(self):
        """Todos los valores finitos no negativos, en orden (el patrón crece con el valor)."""
        n = 1 << (self.ebits + self.mbits)
        return [v for v in (self.decode(b) for b in range(n)) if v == v and abs(v) != math.inf]

mf = MiniFloat(4, 3)
vals = mf.values()
print(f"MiniFloat(4, 3): p = {mf.p}, emin = {mf.emin}, emax = {mf.emax}, máximo = {mf.max}")
print("finitos no negativos:", len(vals), "  finitos en total (con -0):", 2 * len(vals))
binadas = {"subnormales": [v for v in vals if 0 < v < Fraction(2) ** mf.emin]}
for e in [mf.emin, 0, mf.emax]:
    binadas[f"[2^{e}, 2^{e + 1})"] = [v for v in vals if Fraction(2) ** e <= v < Fraction(2) ** (e + 1)]
for nombre, b in binadas.items():
    print(f"  {nombre:>14}: {len(b)} valores, espaciado {b[1] - b[0]}:", [str(v) for v in b[:4]], "...")

# con (5, 10) debe redondear igual que np.float16, y con (8, 23) igual que np.float32
xs16 = np.concatenate([rng.standard_normal(1500) * 10.0 ** rng.uniform(-9, 5, 1500), [2.0 ** -25, 3 * 2.0 ** -25, 65519.99, 65520.0]])
h = MiniFloat(5, 10)
with np.errstate(over="ignore"):
    ok16 = all(float(h.round(float(x))) == float(np.float16(x)) for x in xs16)
xs32 = rng.standard_normal(800) * 10.0 ** rng.uniform(-44, 38, 800)
f = MiniFloat(8, 23)
ok32 = all(float(f.round(float(x))) == float(np.float32(x)) for x in xs32)
print("\nMiniFloat(5, 10) == np.float16:", ok16, "   MiniFloat(8, 23) == np.float32:", ok32)
fh = np.finfo(np.float16)
print("máximo, menor normal y menor subnormal de MiniFloat(5, 10) == np.finfo(np.float16):",
      [float(h.max), 2.0 ** h.emin, 2.0 ** (h.emin - h.mbits)] == [float(fh.max), float(fh.smallest_normal), float(fh.smallest_subnormal)])

MiniFloat(4, 3) has 240 finite values (256 patterns minus 16 with exponent 1111), maximum 240 and seven subnormals with the same spacing, 1/5121/512, as the first normal binade. The important part is last: the same class with binary16 and binary32 parameters rounds exactly like NumPy on all tested values, including delicate subnormal ties (2−252^{-25}, halfway between 0 and smallest subnormal 2−242^{-24}, becomes zero; 3×2−253 \times 2^{-25}, halfway between one and two minimum subnormals, rounds up to 2−232^{-23}) and overflow threshold (65 519.9965\,519.99 rounds down to 65,504; 65 52065\,520 is a tie whose even neighbor is above the maximum, so it overflows to ∞\infty). This is what fully specified IEEE rounding means.

Directed modes deliver what the rounding section promised: adding 0.10.1 ten times in binary32 toward −∞-\infty and toward +∞+\infty gives an interval guaranteed to contain the exact sum, 1.

[ ]Directed rounding: a guaranteed intervalBrowser
f32 = MiniFloat(8, 23)
lo = hi = cerca = Fraction(0)
for _ in range(10):
    lo = f32.round(lo + f32.round(Fraction(1, 10), "RD"), "RD")
    hi = f32.round(hi + f32.round(Fraction(1, 10), "RU"), "RU")
    cerca = f32.round(cerca + f32.round(Fraction(1, 10)))
print("suma de diez 0.1 en binary32:")
print("  hacia -inf:", float(lo), "  al más cercano:", float(cerca), "  hacia +inf:", float(hi))
print("  ¿el intervalo contiene 1?", lo <= 1 <= hi, "  anchura:", float(hi - lo), "=", (hi - lo) / Fraction(2) ** -23, "ulp(1)")

The nearest-rounding result, 1.0000001192…1.0000001192\ldots, exceeds 1 by one ulp; interval [0.99999982,1.00000024][0.99999982, 1.00000024] contains it, with width 3.53.5 ulps. Interval arithmetic does this for each operation of an algorithm and returns guaranteed results, at the cost of intervals that can grow very quickly.

Simulate bfloat16 and FP8 with NumPy

NumPy has neither bfloat16 nor FP8, but they are easily simulated. BF16 uses the upper 16 bits of a float32: reinterpret the array as uint32 and round to nearest even by adding 0x7FFF plus the last retained bit before truncating (if discarded bits are exactly 0x8000, the tie rounds up only if the retained bit is 1). FP8 has so few values that a sorted table and np.searchsorted suffice; overflow is handled by adding a “virtual” value at the table’s end, the one that would follow the maximum, so ties-to-even also determines the overflow threshold.

[ ]BF16 by bits and FP8 by tablesBrowser
def to_bf16(x):
    """Redondea un array float32 a bfloat16 (al más cercano par) y lo devuelve como float32."""
    x = np.asarray(x, dtype=np.float32)
    u = x.view(np.uint32).astype(np.uint64)
    lsb = (u >> 16) & 1                        # último bit que se conserva: decide los empates
    r = ((u + 0x7FFF + lsb) >> 16) << 16       # sumar medio ulp (menos 1 si el conservado es par) y truncar
    out = r.astype(np.uint32).view(np.float32)
    return np.where(np.isnan(x), np.float32(np.nan), out)

def fp8_table(ebits, mbits, fn):
    """Valores no negativos de un FP8 en orden de patrón, más el valor «virtual» que seguiría al máximo."""
    bias = (1 << (ebits - 1)) - 1
    vals = []
    for b in range(1 << (ebits + mbits)):          # patrones con signo +, en orden creciente
        E, F = b >> mbits, b & ((1 << mbits) - 1)
        if E == (1 << ebits) - 1 and (not fn or F == (1 << mbits) - 1):
            break                                  # E5M2: inf y NaN; E4M3: solo S.1111.111 es NaN
        vals.append(math.ldexp(F, 1 - bias - mbits) if E == 0 else math.ldexp((1 << mbits) | F, E - bias - mbits))
    return np.array(vals + [vals[-1] + (vals[-1] - vals[-2])])   # redondear al virtual es desbordar

E4M3 = fp8_table(4, 3, fn=True)                     # sin infinitos: desbordar da NaN
E5M2 = fp8_table(5, 2, fn=False)                    # IEEE: desbordar da inf
print("E4M3: máximo", E4M3[-2], " menor normal", E4M3[8], " menor subnormal", E4M3[1], " valores >= 0:", len(E4M3) - 1)
print("E5M2: máximo", E5M2[-2], " menor normal", E5M2[4], " menor subnormal", E5M2[1], " valores >= 0:", len(E5M2) - 1)

def to_fp8(x, table, overflow):
    """Redondeo al más cercano par a la tabla (índice par = patrón par). overflow: np.inf o np.nan."""
    x = np.asarray(x, dtype=np.float64)
    a = np.abs(x)
    i = np.clip(np.searchsorted(table, a), 1, len(table) - 1)   # table[i-1] < a <= table[i]
    lo, hi = table[i - 1], table[i]
    up = (a - lo > hi - a) | ((a - lo == hi - a) & ((i - 1) % 2 == 1))
    idx = np.where(up, i, i - 1)
    v = np.where(a >= table[-1], len(table) - 1, idx)            # por encima del virtual: también desborda
    out = np.where(v == len(table) - 1, overflow, table[v])
    return np.where(np.isnan(x), np.nan, np.copysign(out, x))

print("\n464 en E4M3 ->", to_fp8(464.0, E4M3, np.nan), "  470 ->", to_fp8(470.0, E4M3, np.nan),
      "  61440 en E5M2 ->", to_fp8(61440.0, E5M2, np.inf))
print("0.1 en BF16 ->", to_bf16(np.float32(0.1)), "   0.9999 ->", to_bf16(np.float32(0.9999)), "   7e4 ->", to_bf16(np.float32(7e4)))

# comprobación cruzada con MiniFloat, una implementación independiente
xs = (rng.standard_normal(1500) * 10.0 ** rng.uniform(-30, 30, 1500)).astype(np.float32)
bf = MiniFloat(8, 7)
print("\nto_bf16 == MiniFloat(8, 7):", all(float(bf.round(float(x))) == float(y) for x, y in zip(xs, to_bf16(xs))))
x8 = rng.standard_normal(1500) * 10.0 ** rng.uniform(-3, 2, 1500)
m52 = MiniFloat(5, 2)
print("to_fp8(E5M2) == MiniFloat(5, 2):", all(float(m52.round(float(x))) == float(y) for x, y in zip(x8, to_fp8(x8, E5M2, np.inf))))

The tables reproduce Micikevicius et al.’s table 1: E4M3 has maximum 448, smallest normal 2−62^{-6} and smallest subnormal 2−92^{-9}; E5M2 has maximum 57,344, smallest normal 2−142^{-14} and smallest subnormal 2−162^{-16}. Boundary ties resolve differently under the same rule: 464 is halfway between 448 (fraction 110, even) and virtual 480, so remains 448, while 470 exceeds the midpoint and overflows to NaN; in E5M2, 61,440 is halfway between 57,344 (fraction 11, odd) and 2162^{16}, so the tie rounds up and overflows to ∞\infty. These are exactly PyTorch conversion results, as the next section’s local cell checks. Both simulations match MiniFloat on every tested value.

Now the experiment. Three tensors are quantized using an explicit model for each: weights N(0,0.022)\Normal(0, 0.02^2), a typical transformer initialization scale; gradients with log-uniform magnitude between 10−1210^{-12} and 10−210^{-2} (ten orders of magnitude, like different layers of a deep network), and activations N(0,302)\Normal(0, 30^2) with 20 outliers multiplied by 3000. For each format measure how many values overflow, what fraction becomes zero or subnormal and median relative error of the rest, unscaled and with per-tensor scaling: the power of 2 placing the tensor maximum just below the format maximum.

[ ]Quantize weights, gradients and activationsBrowser
FORMATOS = {   # nombre: (cuantizar, menor normal, mayor finito)
    "FP16": (lambda x: x.astype(np.float16).astype(np.float64), 2.0 ** -14, 65504.0),
    "BF16": (lambda x: to_bf16(x.astype(np.float32)).astype(np.float64), 2.0 ** -126, float(to_bf16(np.float32(3.38e38)))),
    "E5M2": (lambda x: to_fp8(x, E5M2, np.inf), 2.0 ** -14, 57344.0),
    "E4M3": (lambda x: to_fp8(x, E4M3, np.nan), 2.0 ** -6, 448.0),
}

def informe(nombre, x):
    print(f"\n{nombre}: {x.size} valores, |x| entre {np.abs(x).min():.1e} y {np.abs(x).max():.1e}")
    print(f"  {'formato':7} {'escala':>7} {'desbordan':>10} {'se anulan':>10} {'subnormales':>12} {'err. rel. mediano':>18}")
    for f, (q, tiny, big) in FORMATOS.items():
        escalas = [1.0] if f == "BF16" else [1.0, 2.0 ** np.floor(np.log2(big / np.abs(x).max()))]
        for s in escalas:                                  # potencia de 2: escalar y desescalar es exacto
            with np.errstate(over="ignore", invalid="ignore"):
                y = q(x * s) / s
            over = ~np.isfinite(y)
            zero = (y == 0) & (x != 0)
            sub = np.isfinite(y) & (y != 0) & (np.abs(y * s) < tiny)
            ok = np.isfinite(y) & (y != 0)
            rel = np.median(np.abs(y[ok] - x[ok]) / np.abs(x[ok]))
            print(f"  {f if s == escalas[0] else '':7} {'2^%d' % np.log2(s):>7} {int(over.sum()):10d} {zero.mean():10.1%} {sub.mean():12.1%} {rel:18.2e}")

rng = np.random.default_rng(1)
W = rng.normal(0.0, 0.02, size=65536)                                    # pesos de una capa
g = rng.choice([-1.0, 1.0], 65536) * 10.0 ** rng.uniform(-12, -2, 65536)  # modelo de gradientes: |g| log-uniforme
a = rng.standard_normal(65536) * 30.0                                    # activaciones...
a[rng.choice(65536, 20, replace=False)] *= 3000.0                        # ...con 20 valores atípicos

informe("pesos N(0, 0.02²)", W)
informe("gradientes, |g| log-uniforme en [1e-12, 1e-2]", g)
informe("activaciones N(0, 30²) con 20 atípicos x3000", a)

What the table says, row by row:

  • Each format’s precision appears in median error, which without subnormals is around 0.35 u0.35\,u for all: 1.7×10−41.7 \times 10^{-4} in FP16 (u=4.9×10−4u = 4.9 \times 10^{-4}), 1.35×10−31.35 \times 10^{-3} in BF16 (u=3.9×10−3u = 3.9 \times 10^{-3}), 2.2×10−22.2 \times 10^{-2} in E4M3 (u=6.25×10−2u = 6.25 \times 10^{-2}) and 4.3×10−24.3 \times 10^{-2} in E5M2 (u=0.125u = 0.125). Bound uu is approached only in the first gap of each binade (the toy figure’s tallest tooth); typical error is much smaller.
  • Unscaled E4M3 weights are a silent disaster: with deviation 0.02 and smallest normal 2−6≈0.01562^{-6} \approx 0.0156, half the weights (50.1%) become subnormal and 3.9% become zero. Multiplying by 2122^{12} brings them into normal range and median error drops to 2.2×10−22.2 \times 10^{-2}, better than E5M2: once scaling handles range, E4M3’s extra fraction bit is worth more than the exponent bit. This motivates the Micikevicius et al. recommendation.
  • Gradients show the range problem. Without scaling, FP16 zeros 44.5% (all magnitudes below 2−252^{-25}: on a log scale, fraction (log⁡102−25+12)/10(\log_{10} 2^{-25} + 12)/10) and E5M2 zeros 69%; BF16 loses none. With scale 2222^{22}, FP16 zeros none, though 11.5% are subnormal; E5M2 still loses 2.6% and E4M3 44.5%: ten orders of magnitude are about 33 binades, more than E5M2’s 32 and far more than E4M3’s 18. No per-tensor scale can fit what does not fit.
  • Outliers break the scale. Unscaled, 13 of 20 outliers overflow in FP16 and E5M2, all 20 in E4M3 and none in BF16. In E4M3, scaling to fit them (by 2−92^{-9}) pushes everything else down: 1.3% becomes zero and 18.7% subnormal. A handful of large values spoils quantization of the entire tensor; solutions (block scaling, smoothing outliers) are part of block scaling and quantization.

In libraries

All of the above is available in standard libraries; it helps to know how to read it.

ToolWhat it returns
np.finfo(t)eps (ε\eps), epsneg (ε/2\eps/2, distancia de 1 al anterior), smallest_normal, smallest_subnormal, max, nmant (tt), bits
np.nextafter(x, y), math.nextafterthe float after x toward y
np.spacing(x), math.ulp(x)the ulp of x
float.hex, float.fromhexexact value in hexadecimal notation: significand and exponent without decimal rounding
x.as_integer_ratio(), Fraction(x), Decimal(x)exact value as a rational or with all decimal digits
struct.pack, arr.view(np.uint32)the bits
torch.finfo(t)the same for float16, bfloat16, float8_e4m3fn, float8_e5m2
[ ]np.finfo, nextafter, spacing, float.hex y structBrowser
import math
import struct
import numpy as np

for t in (np.float16, np.float32, np.float64):
    fi = np.finfo(t)
    print(f"{t.__name__:8} bits={fi.bits:2d}  nmant={fi.nmant:2d}  eps={fi.eps:.3e}  epsneg={fi.epsneg:.3e}  "
          f"smallest_normal={fi.smallest_normal:.3e}  smallest_subnormal={fi.smallest_subnormal:.3e}  max={fi.max:.4e}")

print("\nnp.nextafter(1, 2) - 1 =", np.nextafter(1.0, 2.0) - 1, "  1 - np.nextafter(1, 0) =", 1 - np.nextafter(1.0, 0.0))
print("np.spacing:", np.spacing(np.float64(1.0)), np.spacing(np.float32(1.0)), np.spacing(np.float16(1000)), np.spacing(1e16))
print("math.ulp(1e16) =", math.ulp(1e16), "  math.nextafter(1, 0) =", math.nextafter(1.0, 0.0))

print("\n(0.1).hex() =", (0.1).hex(), "   float.fromhex('0x1.8p-1') =", float.fromhex("0x1.8p-1"))
print("(0.1).as_integer_ratio() =", (0.1).as_integer_ratio())
print("struct, 0.1 como float32:", struct.pack(">f", 0.1).hex(), "  como float64:", struct.pack(">d", 0.1).hex())
print("vista de bits en NumPy:", hex(np.float32(0.1).view(np.uint32)), "   y al revés:", np.uint32(0x3F800000).view(np.float32))
print("repr(0.1) =", repr(0.1), "  pero f'{0.1:.20f}' =", f"{0.1:.20f}")

The last line explains why 0.1 “looks” exact: repr prints the shortest decimal string which, read back, gives the same float, which for fl(0.1)\mathrm{fl}(0.1) is 0.1. With 20 decimal places the truth appears. epsneg is ε/2\eps/2 because below 1 another binade starts with half the spacing. And 0x3F800000 is the pattern of 1.01.0 in binary32: biased exponent 127 and zero fraction.

The next cell needs PyTorch and runs on your machine. It prints torch.finfo for the lesson’s five formats, converts ruler values, triggers a NaN in a backward and locates it with torch.autograd.detect_anomaly, shows torch.set_flush_denormal and measures how much slower your CPU is with subnormals.

[ ]PyTorch: formats, NaN in backward and subnormalsLocal GPU
import time
import warnings
import numpy as np
import torch

for t in (torch.float32, torch.bfloat16, torch.float16, torch.float8_e5m2, torch.float8_e4m3fn):
    fi = torch.finfo(t)
    print(f"{str(t):22} bits={fi.bits:2d}  eps={fi.eps:.3e}  tiny={fi.tiny:.3e}  max={fi.max:.4e}")

x = torch.tensor([1e-8, 7e4, 0.9999, 464.0, 470.0, 61440.0], dtype=torch.float32)
for t in (torch.bfloat16, torch.float16, torch.float8_e5m2, torch.float8_e4m3fn):
    print(f"{str(t):22}", x.to(t).float().tolist())

# un NaN que nace en el backward: d sqrt(w)/dw en w = 0 es inf, e inf · 0 = NaN
w = torch.tensor([0.0, 4.0], requires_grad=True)
(torch.sqrt(w) * torch.tensor([0.0, 1.0])).sum().backward()
print("\ngradiente:", w.grad.tolist(), "  ¿finito?", torch.isfinite(w.grad).tolist())
w.grad = None
warnings.filterwarnings("ignore")                # detect_anomaly avisa de que es lento; aquí lo sabemos
with torch.autograd.detect_anomaly():
    try:
        (torch.sqrt(w) * torch.tensor([0.0, 1.0])).sum().backward()
    except RuntimeError as e:
        print("detect_anomaly:", str(e).splitlines()[0])

# flush-to-zero en la CPU
print("\nset_flush_denormal disponible:", torch.set_flush_denormal(True))
print("1e-310 con flush:", torch.tensor([1e-310], dtype=torch.float64).item())
torch.set_flush_denormal(False)
print("1e-310 sin flush:", torch.tensor([1e-310], dtype=torch.float64).item())

# ¿son lentos los subnormales en esta CPU?
n = 2_000_000
def mejor(a, b, k=7):
    ts = []
    for _ in range(k):
        t0 = time.perf_counter()
        a * b
        ts.append(time.perf_counter() - t0)
    return min(ts)
t_norm = mejor(np.full(n, 1e-300), np.full(n, 0.5))
t_sub = mejor(np.full(n, 1e-310), np.full(n, 0.5))
print(f"multiplicar {n} subnormales frente a {n} normales: {t_sub / t_norm:.1f} veces más tiempo")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

PyTorch matches the lab simulations: 10−810^{-8} becomes zero in FP16 and both FP8 formats, 7×1047 \times 10^4 overflows to ∞\infty in FP16 and E5M2 and NaN in E4M3, 0.99990.9999 becomes 1 in all 16- and 8-bit formats, and boundary ties fall as in to_fp8: in E4M3, 464 stays 448 and 470 is NaN; in E5M2, 61,440 overflows to ∞\infty. The backward NaN is instructive: forward has no problem (0⋅0=0\sqrt{0} \cdot 0 = 0), but the derivative of w\sqrt{w} at 0 is ∞\infty and the chain rule multiplies it by 0. detect_anomaly points to the culprit operation, SqrtBackward0. The last line’s timing ratio depends on your CPU: on the recent Intel CPU used to prepare this lesson, subnormal multiplication was several times slower; others may show no difference.

Common mistakes

Exercises

NumericHow many floats lie between 1 and 2?
How many binary64 numbers are in [1,2)[1, 2)?
Numericbfloat16 unit roundoff
bfloat16 has 7 fraction bits. What is its unit roundoff uu with rounding to nearest?
NumericDecode a pattern
What number does binary32 pattern 0xC1480000 represent?
NumericThe FP16 maximum
Calculate the largest finite binary16 number (5 exponent bits, 10 fraction bits) from the definition.
QuizAdd 1 to 10¹⁶
With x = 1e16 in float64 and round to nearest even, what is (x + 1) - x?
QuizSmallest x changing 1
In float64 with round to nearest even, what is the smallest positive float x such that 1.0 + x != 1.0?
QuizComparisons that behave as expected
Which Python expressions return the same as with exact real numbers?

More than one answer may be correct.

QuizNaN in NumPy
What do np.nan == np.nan, np.max([1, np.nan]) and np.nanmax([1, np.nan]) return, in that order?
QuizWhich format for these gradients?
A network's gradient magnitudes range from 10−910^{-9} to 10−310^{-3}. You want to store them in 16 bits without loss scaling and lose as little information as possible. Which format do you choose?
QuizAnd for these weights?
You will store weights of an already-trained network for inference. All satisfy 10−3≤∣w∣≤410^{-3} \le |w| \le 4 and you want the smallest possible rounding error with 16 bits per weight. Which format?
ProofThe relative-error bound and where it fails
Prove: With rounding to nearest, every xx in the normal range satisfies ∣fl(x)−x∣/∣x∣≤u=12β1−p|\mathrm{fl}(x) - x|/|x| \le u = \tfrac{1}{2}\beta^{1-p}. In the subnormal region, relative error can reach 1.
0
Let x>0x > 0 (the negative case is symmetric) and let ee be the integer with βe≤x<βe+1\beta^e \le x < \beta^{e+1}.

Step 1 of 4. Suppose e≥emin⁡e \ge e_{\min} (normal range). How are elements of F\mathbb{F} distributed around xx?

CodeRound to binary16 using integer arithmetic
Implement to_float16(x), which receives a Python float (binary64) and returns, as an integer from 0 to 65535, the bit pattern of the nearest binary16: round to nearest ties to even, subnormals, signed zeros, overflow to ±∞\pm\infty and NaN for NaN (exponent 11111 and nonzero fraction). Work only with integers on the bits of x (use struct to obtain them); do not use np.float16 or floating-point conversions. Tests compare against NumPy for all 63,488 finite binary16 values, all ties between consecutive binary16 values and their float64 neighbors, and 100,000 random values.
import struct

def to_float16(x):
  """Patrón de 16 bits (int) del binary16 más cercano a x."""
  b = struct.unpack("<Q", struct.pack("<d", x))[0]
  s = (b >> 63) << 15             # signo, ya en su posición de binary16
  E = (b >> 52) & 0x7FF           # exponente almacenado de float64
  F = b & ((1 << 52) - 1)         # fracción de float64
  # tu código: casos inf/NaN y cero; significando entero M de 53 bits;
  # cuántos bits sobran según la binada (o la zona subnormal) de binary16;
  # redondeo al más cercano par; acarreo a la binada siguiente; desbordamiento
  return 0
Shift+Enter to run

Summary

Key idea
A computer calculates with a finite set of numbers whose spacing grows with magnitude, so relative error is nearly uniform: IEEE 754 guarantees each basic operation returns the rounded exact result, with relative error at most u=2−pu = 2^{-p} while remaining in the normal range.
  • A floating-point system F(β,p,emin⁡,emax⁡)\mathbb{F}(\beta, p, e_{\min}, e_{\max}) is finite; in each binade [βe,βe+1)[\beta^e, \beta^{e+1}) spacing is constant, βe−p+1\beta^{e-p+1}, and in base 2 doubles in the next binade.
  • An IEEE binary format stores sign, biased exponent and fraction with implicit bit. All-zero exponent encodes zeros and subnormals; all-ones, infinities and NaNs. Nonnegative patterns are ordered like integers, and adding 1 gives the next float.
  • Rounding is correct for +,−,×,÷, +, -, \times, \div, \sqrt{\ } and fma, by default to nearest ties to even (avoiding systematic drift). Directed modes bound the exact result.
  • ε=21−p\eps = 2^{1-p} is the distance from 1 to its successor, u=ε/2u = \eps/2 bounds relative error, and ulp is local spacing, increasing with ∣x∣|x|. 0.1+0.2≠0.30.1 + 0.2 \neq 0.3 because three legitimate roundings need not coincide: compare with tolerances.
  • Signed zeros, infinities and NaNs give every operation a result; NaNs propagate and make all comparisons false. Subnormals provide gradual underflow (x≠y⇒x⊖y≠0x \neq y \Rightarrow x \ominus y \neq 0) at the cost of precision and sometimes speed.
  • FP16 has precision (u=2−11u = 2^{-11}) but little range (maximum 65,504); BF16 has FP32 range with u=2−8u = 2^{-8} and needs no loss scaling; FP8 E4M3 (maximum 448) and E5M2 (maximum 57,344) generally need per-tensor scaling.

You will see this recur in vanishing and exploding gradients, numerically underflow and overflow; in catastrophic cancellation and the log-sum-exp trick in the next lesson; and in finance, where monetary amounts are stored as integer cents or in decimal arithmetic (decimal.Decimal), never binary64, so rounding follows accounting rules and ten deposits of 0.10 add exactly to 1.00.