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
float16the largest finite number is 65,504: the sum becomes , the variance , 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
float64do not give 1.00. They give0.9999999999999999, and comparisonsaldo == 1.0is false.
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 distinct patterns, so a computer works with a finite subset 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.
- is finite. Each exponent has normalized significands, so the number of nonzero elements is .
- Spacing is constant within each binade and grows between them. A binade (in base 2) is interval . Within it the elements of are with consecutive integer , spaced exactly apart. In the next binade spacing is multiplied by : in base 2, it doubles.
- Relative spacing is bounded. Dividing spacing by the size of numbers in the binade, lies between and for every in the binade. That is the precise meaning of “constant relative precision”: it varies by a factor of , but does not depend on the magnitude of .
The figure shows what the rest of the lesson formalizes: relative rounding error in the normal range is a sawtooth whose peak approaches (in the first gap of each binade) and halves by the end, because absolute spacing is fixed while doubles. Below the picture changes completely. Without subnormals, numbers there round to 0 or 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 with one rounding; the 2019 revision is minor.
| Format | Bits (s, w, t) | Bias | Largest finite | Smallest normal | Smallest subnormal | ||
|---|---|---|---|---|---|---|---|
binary64 (float64) | 1, 11, 52 | 53 | 1023 | ||||
binary32 (float32) | 1, 8, 23 | 24 | 127 | ||||
binary16 (float16) | 1, 5, 10 | 11 | 15 | ||||
| bfloat16 | 1, 8, 7 | 8 | 127 |
Each row follows from the definition: in binary16, for example, , the largest normal exponent is and the largest significand , so the largest finite value is . 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:
The sign is positive. is a normal exponent, so . The fraction is and the value is : the float32 closest to , exceeding by about .
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 .
Correct rounding
A floating-point system is useful only if it says what happens to an operation’s result, which generally is not in . Let 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 (, , ) 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 from with .
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, and : each iteration adds a nonexistent cent and the series drifts without bound. With ties to even, (6 is even) and (0 is even): the series stays still. The theorem says ties to even always make the sequence constant from onward. Directed modes have another use: calculating the same thing toward and toward 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 and are often confused. Define them precisely.
The first two are format constants; ulp depends on . They relate as follows: , in the normal range, and therefore . Epsilon is not the spacing between floats everywhere: near the float64 are spaced by , and near by about .
The central theorem states that rounding incurs a uniform relative error.
Proof
Let with (if , and there is nothing to prove). By symmetry, assume . Elements of in are with (the last, , belongs to if ; if , and the previous values suffice). Thus lies between consecutive elements with , and the closest is at most half the gap away:
Also : if , then ; if is the upper one, , hence . Since is increasing,
It suffices to define . With a directed mode, and the same calculation, dividing by , gives .
∎Notice the two assumptions. If (beyond half an ulp above the maximum), and relative error is infinite: this is the motivating overflow. If , spacing no longer shrinks with , the proof step dividing by fails and the bound no longer holds: in the toy figure you saw it rise above . You will quantify this in the proof exercise.
Form is the building block of error analysis: combined with correct rounding, it says each basic operation incurs relative error at most , with , 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. and ; a rational has a finite binary expansion if and only if its reduced denominator is a power of 2, so has a repeating binary expansion and is not in . is stored, slightly larger. The same happens with and , and the three errors do not cancel.
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
- is with , and (multiplication by 2 is exact).
- Their exact sum is , and has 55 bits: 2 too many. Since , the two excess bits of are
10: exactly half an ulp. It is a tie and even wins, here upward: is the second value in the list. - But , the third, is the immediately preceding float. The results differ by one ulp, , and
0.1 + 0.2 == 0.3is false.
Each step is correct in the theorem’s sense: the three roundings incur relative errors below . 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 infloat64, sums of small dyadic fractions such as , products by powers of 2 without overflow or subnormals.- Otherwise compare with tolerance: . Relative tolerance is chosen according to accumulated roundings (a few ulps for one operation, much more for a long algorithm); absolute tolerance only makes sense when the expected value can be 0 and depends on problem scale.
- Beware defaults.
math.isclose(a, b)uses and , symmetric in and .np.isclose(a, b)checks with and : it is not symmetric, and for quantities around or smaller the absolute tolerance makes it almost always true.
Special values and subnormals
IEEE 754 closes 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.
- . There are two zeros. They compare equal (
0.0 == -0.0is true), but the sign is retained and has consequences: and . An underflowing result remembers which side it came from, relevant for functions with branch cuts such as or in the complex plane. - . Result of overflow (in default mode) and division of a nonzero number by zero. They behave as limits: for finite , .
- NaN (not a number). Result of operations without a reasonable value: , , , . Every operation with a NaN yields NaN, and every ordered comparison with a NaN is false:
nan == nan,nan < 1andnan > 1giveFalse, andnan != nangivesTrue. 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.
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 and the gap seen in the toy figure would lie between it and 0. Subnormals, with fixed exponent and no implicit bit, fill it at the first binade’s spacing, . Precision is lost gradually: a subnormal with its first nonzero bit at fraction position has only significant bits. The reward is a property code assumes without realizing it.
Proof
Let be the smallest positive subnormal. Every finite element of is an integer multiple of : subnormals are and a normal is with . Thus is a nonzero integer multiple of and . Since and rounding is monotonic, .
∎Without subnormals the property fails: with and , the exact difference is , 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 (a tie between one and two minimum subnormals) gives , a relative error of .
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: , but the normal range is only and below everything rounds to zero. This is the motivating format.
- bfloat16 (BF16). FP32’s 8-bit exponent and only 7 fraction bits: , 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_precisioncontrols 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 ). E4M3 breaks the rules to gain range: it has no infinities and only pattern
S.1111.111is 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 , smallest subnormal ). 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.
The figure condenses the practical difference. A gradient of vanishes in FP16 because it is below half the smallest subnormal, and survives in BF16 with relative error . Multiplying the loss by multiplies all gradients by the same amount (differentiation is linear), brings them into FP16 range and is undone at the end by dividing by : 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: is stored as in BF16 and FP16, so gives ; the solution is to represent (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 exactly.
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 and : the smallest subnormal, . 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.
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 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 , take its ulp as quantum (, also covering subnormals), divide, decide using the remainder and detect overflow.
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, , 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 (, halfway between 0 and smallest subnormal , becomes zero; , halfway between one and two minimum subnormals, rounds up to ) and overflow threshold ( rounds down to 65,504; is a tie whose even neighbor is above the maximum, so it overflows to ). This is what fully specified IEEE rounding means.
Directed modes deliver what the rounding section promised: adding ten times in binary32 toward and toward gives an interval guaranteed to contain the exact sum, 1.
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, , exceeds 1 by one ulp; interval contains it, with width 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.
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 and smallest subnormal ; E5M2 has maximum 57,344, smallest normal and smallest subnormal . 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 , so the tie rounds up and overflows to . 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 , a typical transformer initialization scale; gradients with log-uniform magnitude between and (ten orders of magnitude, like different layers of a deep network), and activations 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.
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 for all: in FP16 (), in BF16 (), in E4M3 () and in E5M2 (). Bound 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 , half the weights (50.1%) become subnormal and 3.9% become zero. Multiplying by brings them into normal range and median error drops to , 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 : on a log scale, fraction ) and E5M2 zeros 69%; BF16 loses none. With scale , 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 ) 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.
| Tool | What it returns |
|---|---|
np.finfo(t) | eps (), epsneg (, distancia de 1 al anterior), smallest_normal, smallest_subnormal, max, nmant (), bits |
np.nextafter(x, y), math.nextafter | the float after x toward y |
np.spacing(x), math.ulp(x) | the ulp of x |
float.hex, float.fromhex | exact 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 |
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 is 0.1. With 20 decimal places the truth appears. epsneg is because below 1 another binade starts with half the spacing. And 0x3F800000 is the pattern of 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.
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")npm run lab and open the connection link.PyTorch matches the lab simulations: becomes zero in FP16 and both FP8 formats, overflows to in FP16 and E5M2 and NaN in E4M3, 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 . The backward NaN is instructive: forward has no problem (), but the derivative of at 0 is 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
0xC1480000 represent?x = 1e16 in float64 and round to nearest even, what is (x + 1) - x?float64 with round to nearest even, what is the smallest positive float x such that 1.0 + x != 1.0?More than one answer may be correct.
np.nan == np.nan, np.max([1, np.nan]) and np.nanmax([1, np.nan]) return, in that order?Step 1 of 4. Suppose (normal range). How are elements of distributed around ?
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 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 0Summary
- A floating-point system is finite; in each binade spacing is constant, , 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 and fma, by default to nearest ties to even (avoiding systematic drift). Directed modes bound the exact result.
- is the distance from 1 to its successor, bounds relative error, and ulp is local spacing, increasing with . 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 () at the cost of precision and sometimes speed.
- FP16 has precision () but little range (maximum 65,504); BF16 has FP32 range with 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.