Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsNumerical Computing

How computers store numbers

P1.G140 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Every number in a model is a pattern of a few bits, and the choice of pattern decides how much memory the model needs, how fast it runs, and how much rounding error creeps in. Knowing the layouts explains why deep learning runs on 16-bit and 8-bit numbers and when that is safe.

  • Mixed-precision training keeps most numbers in 16 bits (fp16 or bf16) to save memory and time, and a few in fp32 for accuracy. Choosing between fp16 and bf16 is a choice between precision and range. (P10.B5: Mixed-precision training, coming soon)
  • Quantization stores a trained model's weights as int8 or even 4-bit integers with a scale, so that a large model fits on smaller hardware. (P10.F1: Quantization, coming soon)
  • The memory a model needs is the number of parameters times the bytes per parameter, which is why a 7-billion-parameter model is about 14 GB in 16 bits and about 28 GB in fp32 (weights only). (P10.B4: Counting compute and memory, coming soon)
  • Computing exp of a large number overflows to infinity in fp32 (and much sooner in fp16), which is why softmax and log-sum-exp are written in a careful way. (P1.G2: Numerical stability)

Before this: Exponents and logarithms

After this lesson you can

  • Read an unsigned or two's-complement integer from its bits, and say what int8 can and cannot hold
  • Decode a floating-point bit pattern (sign, exponent, fraction) by hand, and name the special values
  • Compare fp32, fp16, bf16 and the two fp8 formats by range and by precision, and explain why the spacing between numbers grows with their size
  • Explain why 0.1 + 0.2 is not 0.3, how catastrophic cancellation and ordering of sums lose digits, and compare floats with a tolerance
  • Work out the memory of a model's weights from its parameter count and format, and describe int8 quantization with a scale

Type 0.1 + 0.2 into Python and it answers 0.30000000000000004. Ask whether that equals 0.3 and it says False. Python is not broken, and neither is your computer. Every number inside a computer has to fit into a fixed number of bits, and most real numbers do not fit exactly. This lesson shows what is stored, what is lost, and why deep learning chooses its number formats so carefully.

Bits, bytes and integers

A bit is one switch that is either 0 or 1. A byte is 8 bits. A pattern of nn bits can be arranged in 2n2^n ways, so 88 bits give 256256 patterns, 1616 bits give 65,53665{,}536, and 3232 bits give about 4.34.3 billion. A number format is a rule that says which number each pattern means. Whatever the rule, at most 2n2^n different numbers can be stored in nn bits.

For whole numbers that cannot be negative (unsigned integers), the rule is the one you know from the decimal system, with 22 in place of 1010. In decimal, each place is worth ten times the one to its right. In binary, each place is worth two times the one to its right: 1,2,4,8,16,…1, 2, 4, 8, 16, \dots from the right. So

10112=1⋅8+0⋅4+1⋅2+1⋅1=11.\begin{aligned} 1011_2 &= 1\cdot8 + 0\cdot4 + 1\cdot2 + 1\cdot1\\ &= 11 . \end{aligned}

Going the other way, 13=8+4+113 = 8+4+1, which is 110121101_2. With 8 bits the range is 00 to 255255.

Negative whole numbers: two’s complement

To store negative numbers, almost every computer uses two’s complement. It is the unsigned rule with one change: the leftmost bit counts as −2n−1-2^{n-1} instead of +2n−1+2^{n-1}. For 8 bits (int8) the place values are −128,64,32,16,8,4,2,1-128, 64, 32, 16, 8, 4, 2, 1. So

100100112=−128+16+2+1=−109.\begin{aligned} 10010011_2 &= -128 + 16 + 2 + 1\\ &= -109 . \end{aligned}

The leftmost bit is therefore a sign bit: it is 1 for exactly the negative numbers. The smallest int8 is 100000002=−12810000000_2 = -128, the largest is 011111112=12701111111_2 = 127, and all 256256 patterns are used, so there is one more negative number than positive ones. To negate a number, flip every bit and add 1: 5=0000010125 = 00000101_2 becomes 111110102+1=111110112=−511111010_2 + 1 = 11111011_2 = -5. The reason this rule is popular is that the same adding circuit works for negative and positive numbers.

Overflow. What happens when the true answer does not fit? Adding 1 to 01111111201111111_2 (which is 127) gives 10000000210000000_2, which is −128-128. The result wraps around, like a car odometer going from 999999 to 000000. In NumPy, fixed-width integers wrap: np.array([127], dtype=np.int8) + 1 gives -128. Python’s own int does not wrap, because it grows as large as needed, so 127 + 1 is 128. Other languages choose differently again (some wrap, some give an error), so check what your tool does before trusting integer arithmetic near the limits.

Real numbers: from scientific notation to floating point

How do we store 0.50.5, 3.143.14 or 6.02×10236.02\times10^{23}? One idea is fixed point: agree to keep, say, 2 digits after the decimal point and store the number times 100 as an integer. Prices in cents work this way. Every number is then a multiple of the same smallest step, so the range is small: with 32 bits and 2 decimal digits you could not store both 10−3010^{-30} and 103010^{30}.

Floating point works like scientific notation. Write 6.02×10236.02\times10^{23}: a sign, a significand 6.026.02 with a few digits, and an exponent 2323 that says where the decimal point floats to. A few digits of significand plus a small exponent cover an enormous range, and the relative precision stays the same for small and large numbers.

Computers do this in base 2: a number is ± 1.f×2e\pm\,1.f\times2^{e}, where ff is a string of binary digits (the fraction) and ee is a whole-number exponent. And here the analogy breaks. In base 10, 13=0.3333…\frac13=0.3333\dots never ends, but 110=0.1\frac1{10}=0.1 does. In base 2 the fractions that end are only those whose denominator is a power of 2 (0.50.5, 0.250.25, 0.3750.375). The number 0.10.1 is

0.1=1.1001 1001 1001…2×2−4,0.1 = 1.1001\,1001\,1001\dots_2\times2^{-4},

a pattern that repeats for ever, so no finite number of bits can hold it. The computer keeps the nearest number it can, and 0.1 really means a slightly different value. Python’s own 64-bit float stores 0.1000000000000000055511…0.1000000000000000055511\dots, and a 32-bit float stores exactly 0.1000000014901161193847656250.100000001490116119384765625. In 0.1 + 0.2 the two small errors do not cancel, and the sum lands one step away from the stored 0.30.3. (With 32-bit floats the same sum happens to land on the stored 0.30.3: the error is smaller than the gap, so luck decides. The first code cell below prints both results.)

The IEEE 754 layout

Almost all hardware stores fp32 and fp64 floats in the layout of the IEEE 754 standard. The 16-bit bf16 and the two fp8 formats are not part of that standard, but they follow the same recipe (E4M3 changes the special values, as shown below). A float has three fields, from left to right:

  • sign SS: 1 bit, 0 for positive and 1 for negative;
  • exponent EE: ee bits, read as an unsigned integer, with a bias subtracted;
  • fraction MM: mm bits, the digits after the point of the significand.

For a normal number the value is

(−1)S×2E−bias×(1+M2m).(-1)^S\times2^{E-\text{bias}}\times\Bigl(1+\frac{M}{2^{m}}\Bigr).

The bias is 2e−1−12^{e-1}-1.

The “1 +” is the implicit leading 1: every normal number is written 1.f1.f in binary, so the leading 1 is always there and need not be stored. It buys one extra bit of precision for free. The bias lets the exponent field (which has no sign of its own) stand for negative exponents too: for fp32, e=8e=8 and the bias is 127127, so E=127E=127 means 202^0, and E=1E=1 means 2−1262^{-126}.

Decoding an fp32 pattern by hand. Take 1 10000001 10100000000000000000000.

  1. The sign bit is 11, so the number is negative.
  2. The exponent field 10000001210000001_2 is 129129. Subtract the bias: 129−127=2129-127=2, so the scale is 22=42^2=4.
  3. The fraction starts 101101, which means 12+18=0.625\frac12+\frac18=0.625, so the significand is 1.6251.625.
  4. The value is −1×4×1.625=−6.5-1\times4\times1.625=-6.5.

Encoding goes the other way, and rounds. For 0.1=1.6×2−40.1=1.6\times2^{-4}: the exponent field is −4+127=123=011110112-4+127=123=01111011_2. The fraction is 0.6×223=5033164.80.6\times2^{23}=5033164.8, which must be rounded to a whole number, 50331655033165. That rounding is the error: the stored number is 2−4×(1+5033165/223)=0.10000000149…2^{-4}\times(1+5033165/2^{23})=0.10000000149\dots, which is 1.49×10−91.49\times10^{-9} too large. The code below prints these bits.

The special values

Two exponent fields are reserved:

  • Exponent field all zeros. If the fraction is also zero, the number is zero. There are two zeros, +0+0 and −0-0, and they compare equal (although 1/(−0)1/(-0) is −∞-\infty). If the fraction is not zero, the number is subnormal: there is no implicit 1, and the exponent is fixed at 1−bias1-\text{bias}. Subnormal numbers fill the gap between zero and the smallest normal number with evenly spaced values, at the price of fewer significant digits (this is called gradual underflow). In fp32 the smallest normal number is about 1.18×10−381.18\times10^{-38} and the smallest subnormal about 1.4×10−451.4\times10^{-45}.
  • Exponent field all ones. If the fraction is zero, the value is ±∞\pm\infty (the result of an overflow or of 1/01/0). If the fraction is not zero, the value is NaN, “not a number” (the result of 0/00/0 or ∞−∞\infty-\infty). NaN is unequal to everything, itself included, and almost any arithmetic with a NaN gives a NaN.

One of the fp8 formats, E4M3, bends this rule to gain range: it has no infinity, and only the patterns with exponent and fraction all ones (of either sign) are NaN. Its largest number is 448448. (This follows the 2022 proposal FP8 Formats for Deep Learning by Micikevicius and co-authors, arXiv 2209.05433.)

The bit-flipper

Choose a format and tap bits. The cells are coloured by field and also carry a letter and a bit number: S for the sign, e for the exponent and m for the fraction. Below the cells the formula is filled in with the current numbers. Type a number to see the nearest value the format can hold, and press Pattern + 1 to step to the next pattern and watch the gap between neighbouring numbers.

Flip the bits, read the number

1 sign, 8 exponent, 23 fraction bits

S: signe: exponent (8 bits)m: fraction (23 bits)
The pattern counted as a whole number.
bits: 1 10000001 10100000000000000000000
hex: 0xC0D00000
sign: bit S = 1, so the sign factor is −1
exponent: field 129 − bias 127 = 2, so the scale is 2² = 4
significand: 1 + 5242880/2²³ = 1.625 (the leading 1 is not stored)
value = −1 × 4 × 1.625 = −6.5

−6.5 · normal number

gap to the next number away from zero: 4.768×10⁻⁷, to −6.5000004768 (7.34×10⁻⁸ of the value itself)

nearest fp32 value: 0.10000000149

rounding error (stored − typed): 1.49×10⁻⁹, relative 1.49×10⁻⁸

Typed numbers are read as 64-bit values first, then rounded to the chosen format (ties go to the even fraction). The colours are a second signal: every cell also carries its field letter and bit number.

Bit cells for the chosen format, coloured by field: sign in pink, exponent in blue, fraction in green (int8: the sign bit in pink, value bits in grey). Tap a cell to flip it. Under the cells: the bits in groups, the hex form, the formula with the fields filled in, the decoded value, and the gap to the next number away from zero. The typing box shows the nearest representable value and the rounding error. Buttons jump to 1, 0.1, the largest value, the smallest normal and subnormal values, negative zero, infinity and NaN (int8: 0, 1, −1, 127, −128).

Things to try, each checked against the widget:

  • fp32, 0.1. Press 0.1. The bits are 0 01111011 10011001100110011001101 and the value is 0.100000001490.10000000149. Type 0.3 and press Show its bits: the error is not zero either.
  • Pattern + 1 on a float. Start from 1 in fp32 and press Pattern + 1: the value goes from 11 to 1.00000011921.0000001192 (a gap of 1.19×10−71.19\times10^{-7}). In fp16 the next number after 11 is 1.0009771.000977, and in fp8 E4M3 it is 1.1251.125. A smaller format has far bigger gaps.
  • Overflow in int8. Press 127, then Pattern + 1: the value wraps to −128-128.
  • Largest values. Press Largest. fp16 gives 6550465504, E4M3 gives 448448, E5M2 gives 5734457344, and fp32 and bf16 are near 3.4×10383.4\times10^{38}.
  • Subnormals. Press Smallest normal, then Pattern − 1. The value drops into the subnormal range, where the formula has no leading 1. Press Smallest subnormal to see the smallest positive number the format can hold.
  • Same bits, different meaning. In fp16 type 70000: it is too big and rounds to ∞\infty. Switch to bf16 and it is stored, as 7014470144. Switch to E4M3 and the widget reports that there is no infinity.
  • Special patterns. Press NaN, ∞ and −0. (E4M3 has no ∞ button, and int8 has none of these.)

The formats side by side

Each line gives the layout (sign + exponent + fraction bits), the largest value, the machine epsilon ε (the gap between 11 and the next number up, which is 2−m2^{-m}), the smallest normal and subnormal values, and the significant decimal digits.

  • fp64: 1 + 11 + 52. Largest 1.8×10³⁰⁸. ε = 2.2×10⁻¹⁶. Smallest normal 2.2×10⁻³⁰⁸, subnormal 4.9×10⁻³²⁴. About 16 digits.
  • fp32: 1 + 8 + 23. Largest 3.4×10³⁸. ε = 1.2×10⁻⁷. Smallest normal 1.2×10⁻³⁸, subnormal 1.4×10⁻⁴⁵. About 7 digits.
  • fp16: 1 + 5 + 10. Largest 65504. ε = 9.8×10⁻⁴. Smallest normal 6.1×10⁻⁵, subnormal 6.0×10⁻⁸. About 3 digits.
  • bf16: 1 + 8 + 7. Largest 3.4×10³⁸. ε = 7.8×10⁻³. Smallest normal 1.2×10⁻³⁸, subnormal 9.2×10⁻⁴¹. About 2 to 3 digits.
  • fp8 E4M3: 1 + 4 + 3. Largest 448. ε = 0.125. Smallest normal 0.0156, subnormal 0.00195. About 1 digit.
  • fp8 E5M2: 1 + 5 + 2. Largest 57344. ε = 0.25. Smallest normal 6.1×10⁻⁵, subnormal 1.5×10⁻⁵. Under 1 digit.
  • int8: 8-bit integer. Largest 127, smallest −128, spacing 1.

The digits figure is (m+1)log⁡102(m+1)\log_{10}2: the significand has m+1m+1 bits counting the hidden 1, and each bit is worth about 0.30.3 decimal digits. Every whole number up to 2m+12^{m+1} is exact in a float (fp32: 16,777,21616{,}777{,}216; fp16: 20482048); above that, some whole numbers are skipped.

Precision against range: fp16 and bf16

fp16 and bf16 both use 16 bits, and they spend them in opposite ways.

  • fp16 has 5 exponent bits and 10 fraction bits. It is fairly precise (about 3 digits) but its range is small: the largest number is 6550465504 and the smallest normal one is 6.1×10−56.1\times10^{-5}.
  • bf16 (short for “brain floating point”) has 8 exponent bits, the same as fp32, and 7 fraction bits. It has fp32’s range, about 10−3810^{-38} to 3.4×10383.4\times10^{38}, but fewer than 3 digits. A bf16 number is an fp32 number with its lowest 16 bits rounded away, which also makes converting between the two cheap.

Which is better depends on what breaks first. During training, numbers such as gradients can be very small. In fp16 a gradient of 10−810^{-8} becomes 00, because it is below half of the smallest subnormal (6×10−86\times10^{-8}). bf16 holds it, with 10−810^{-8} stored as 1.0012×10−81.0012\times10^{-8}. In fp16, training therefore usually needs loss scaling (multiply the loss by a large constant before the backward pass so that gradients are larger, then divide it out), while with bf16 it is often not needed. That is why bf16 is popular for training: fp32’s range at half the memory. The price is precision: 1000.71000.7 is stored as 1000.51000.5 in fp16 but as 10001000 in bf16. P10.B5 returns to this with full training runs.

The gap grows with the number

Between 2e2^e and 2e+12^{e+1} a format has exactly 2m2^m numbers, evenly spaced. The spacing inside that block is 2e−m2^{e-m}, and it doubles at every power of two. The gap between neighbours is called the unit in the last place (ulp). Some values, checked by running NumPy:

  • fp32: the gap is 1.19×10−71.19\times10^{-7} at 11, 22 at 16,777,21616{,}777{,}216 and 10241024 at 101010^{10}.
  • fp16: the gap is 0.0009770.000977 at 11, 22 at 20482048 and 3232 at 6000060000.

So the relative spacing stays about the same (between 2−m−12^{-m-1} and 2−m2^{-m}), while the absolute spacing grows. This has a famous consequence. At 20482048 the fp16 gap is 22, so 2048+1=20492048+1=2049 lies exactly halfway between 20482048 and 20502050 and is rounded to the neighbour with the even fraction, 20482048. In fp16, 2048+1=20482048+1=2048. In fp32 the same happens at 224=16,777,2162^{24}=16{,}777{,}216: 16777216+1=1677721616777216+1=16777216.

Rounding error. A computation rounds to the nearest representable number (ties to the one with an even fraction). The error is at most half a gap, and a gap is at most ε×\varepsilon\times the number, so for a normal number

rounded=x (1+δ),∣δ∣≤u=2−(m+1),\begin{aligned} \text{rounded}&=x\,(1+\delta),\\ |\delta|&\le u=2^{-(m+1)} , \end{aligned}

where uu is the unit roundoff: 6×10−86\times10^{-8} for fp32, 4.9×10−44.9\times10^{-4} for fp16 and 3.9×10−33.9\times10^{-3} for bf16. Every single operation can add a relative error of this size, and the next sections are about how they combine.

How rounding errors hurt

Catastrophic cancellation. P1.D4 gave two formulas for the variance: subtract the mean first, Var(X)=E[(X−μ)2]\mathrm{Var}(X)=\mathbb{E}\bigl[(X-\mu)^2\bigr], or use the shortcut E[X2]−E[X]2\mathbb{E}[X^2]-\mathbb{E}[X]^2. On paper they agree. In floating point the shortcut can fail badly when the mean is large and the spread is small. Take four values μ−1.5, μ−0.5, μ+0.5, μ+1.5\mu-1.5,\ \mu-0.5,\ \mu+0.5,\ \mu+1.5, whose true variance is 1.251.25 for any μ\mu (the deviations are ±1.5\pm1.5 and ±0.5\pm0.5, and 2.25+0.25+0.25+2.254=1.25\frac{2.25+0.25+0.25+2.25}{4}=1.25).

  • In fp32 with μ=10000\mu=10000: E[X2]\mathbb{E}[X^2] is about 10810^8, and fp32 numbers near 10810^8 are 88 apart. The nearly equal numbers E[X2]\mathbb{E}[X^2] and E[X]2\mathbb{E}[X]^2 are both rounded to the same value, and the shortcut gives 0.0. Subtracting the mean first gives the correct 1.251.25.
  • In fp64 with μ=109\mu=10^9 the shortcut also gives 0.0, because fp64 numbers near 101810^{18} are 128128 apart.

A bigger format does not remove the problem; it only moves it to larger means. The fix is a better formula (subtract the mean first, or use a one-pass update such as Welford’s method), and np.var subtracts the mean. Subtracting two nearly equal numbers cancels their leading digits and leaves only the rounding noise, which is why it is called catastrophic cancellation. The same trap appears wherever a small difference of two big numbers is computed.

Adding small numbers to a big one. If a running total is large, adding a number smaller than half a gap does nothing. A float16 counter that adds 11 at each step reaches 20482048 and then stays there for ever. Likewise in fp32 a total at 16,777,21616{,}777{,}216 ignores every +1+1.

Addition is not associative. Because each addition rounds, (a+b)+c(a+b)+c and a+(b+c)a+(b+c) can differ. In 64-bit floats (0.1+0.2)+0.3=0.6000000000000001(0.1+0.2)+0.3=0.6000000000000001 but 0.1+(0.2+0.3)=0.60.1+(0.2+0.3)=0.6, and (1016+1)−1016=0(10^{16}+1)-10^{16}=0 but (1016−1016)+1=1(10^{16}-10^{16})+1=1. In fp32, a total that starts at 16,777,21616{,}777{,}216 and adds a thousand 11s one at a time stays at 1677721616777216, while adding the thousand 11s first and the big number last gives the exact 1677821616778216. The order of a sum matters, so a program that adds in a different order (as happens when a GPU splits a sum among many threads) can give slightly different answers. P1.G3 returns to this.

Comparing floats. Because results carry tiny errors, do not test floats for equality. Test whether they are close: np.isclose(a, b) (defaults: relative tolerance 10−510^{-5}, absolute 10−810^{-8}) or math.isclose (relative 10−910^{-9}). A tolerance has a scale: with the default absolute tolerance, np.isclose(1e-10, 2e-10) is True even though one number is twice the other, so for very small numbers choose the tolerances to fit your data.

A glimpse of overflow. Going past the largest number gives ∞\infty. In fp32, e89≈4.5×1038e^{89}\approx4.5\times10^{38} is above the largest value 3.4×10383.4\times10^{38}, so np.exp(np.float32(89)) is inf. In fp16, e11.1≈66171e^{11.1}\approx66171 is above 6550465504, so it overflows already at 11.111.1. P1.G2 shows how softmax and the log-sum-exp avoid this.

Why does machine learning put up with low precision? Training already works with noisy gradient estimates (P1.F4), and many models seem to lose little accuracy when numbers are rounded to 16 or even 8 bits. That tolerance is an observation, and not a law: it depends on the model, and the sensitive steps (long sums, softmax, normalization, the weight update itself) are often kept in higher precision. P10.B5 and P10.F1 look at how.

Integers as a compressed number format: quantization

An integer format can stand in for a float format. Quantization stores each weight as a small integer qq together with one shared real number, the scale ss, and recovers the weight as w≈s qw\approx s\,q. For int8 with a symmetric range, choose s=max⁡∣w∣/127s=\max|w|/127 so that the largest weight maps to 127127.

Take the weights −0.62, 0.05, 0.31, 0.9-0.62,\ 0.05,\ 0.31,\ 0.9. The largest size is 0.90.9, so s=0.9/127=0.007087s=0.9/127=0.007087. The integers are q=round(w/s)=−87, 7, 44, 127q=\mathrm{round}(w/s)=-87,\ 7,\ 44,\ 127, and the recovered weights are −0.6165, 0.0496, 0.3118, 0.9-0.6165,\ 0.0496,\ 0.3118,\ 0.9. The errors are 0.0035, −0.0004, 0.00180.0035,\ -0.0004,\ 0.0018 and 00: each is at most s/2=0.0035s/2=0.0035, half a step.

Each weight now takes 1 byte instead of 4, but the 256 levels are spread evenly over the range, so one outlier hurts everybody. Add a single weight of 100100 to the list: the scale becomes 0.7870.787 and the other four weights become −1, 0, 0, 1-1,\ 0,\ 0,\ 1. Real quantization methods therefore use separate scales for small groups of weights. A variant with a zero point, w≈s (q−z)w\approx s\,(q-z), shifts the 256 levels (for example to 0…2550\dots255) when the values are not centred on zero. P10.F1 covers these methods and their quality trade-offs.

Memory: bytes per number

A byte is 8 bits, so a number takes n/8n/8 bytes: fp32 is 4 bytes, fp16 and bf16 are 2, fp8 and int8 are 1, and a 4-bit integer is half a byte. The memory for a model’s weights is the number of parameters times the bytes per parameter. For 7 billion parameters (using 1 GB=1091\text{ GB}=10^9 bytes):

  • fp32: 7×109×4=287\times10^9\times4=28 GB.
  • fp16 or bf16: 1414 GB.
  • int8 or fp8: 77 GB.
  • 4-bit integers: 3.53.5 GB.

This is the same arithmetic as in P1.C8 and P1.F6, where the Hessian of a model with 10610^6 parameters has 101210^{12} entries, which is 44 TB in fp32 (and 22 TB in bf16). These figures are the weights alone. Training needs much more, because it also keeps gradients, optimizer state (the Adam optimizer of P4.13 keeps two extra numbers per weight, and often a higher-precision copy of the weights too) and the activations of the forward pass. The total is commonly several times the size of the weights, depending on the setup; P10.B4 counts it properly.

Go deeper Why the exponent is stored with a bias

The exponent field has no sign bit. With a bias, the stored field EE is an ordinary unsigned integer, and the real exponent is E−biasE-\text{bias}. The pay-off: for positive floats, comparing two bit patterns as integers gives the same order as comparing the numbers, because larger exponents come first in the pattern and larger fractions come next. A computer can therefore compare floats with an integer comparator, and for positive floats the Pattern + 1 button of the widget moves to the next larger number (for negative floats it moves away from zero, and from the all-ones pattern it wraps around). The same fact is why a rounding that carries out of the fraction field correctly bumps the exponent by one: the fraction 111…1111\dots1 plus one ulp becomes 000…0000\dots0 with the exponent increased.

Go deeper Where the rounding bound comes from

Inside a block [2k,2k+1)[2^k,2^{k+1}) the spacing is 2k−m2^{k-m}, so rounding to the nearest number moves a value by at most half of that, 2k−m−12^{k-m-1}. The value itself is at least 2k2^k, so the relative error is at most 2k−m−1/2k=2−(m+1)2^{k-m-1}/2^k=2^{-(m+1)}. That is the unit roundoff uu used above. It holds only for normal numbers: for subnormals the spacing is fixed, so the relative error can be larger, and above the largest number there is overflow. The machine epsilon is 2u=2−m2u=2^{-m}, the gap at 11. Some textbooks and libraries call uu, and not 2u2u, the machine epsilon, so check which one a source means.

Go deeper Summing accurately: pairwise, Kahan and Welford

Naive summation can lose digits in proportion to the number of terms. Summing in a tree (pairwise summation, which NumPy’s np.sum does for contiguous arrays) keeps the partial sums of similar size and the error growing more slowly. Kahan summation keeps a second variable that holds the rounding error of each addition and feeds it back into the next one. Welford’s method updates a running mean and a running sum of squared deviations one value at a time, which gives the variance without the cancellation of the shortcut formula. Deep learning libraries often accumulate sums of 16-bit products in a 32-bit accumulator for the same reason.

Go deeper Bits of storage and bits of information

The word bit has two related meanings. In P1.E1 a bit is a unit of information: an event of probability 12\tfrac12 carries one bit of surprise. Here a bit is one binary digit of storage. They meet in a simple fact: nn storage bits can tell apart 2n2^n cases, which is log⁡2(2n)=n\log_2(2^n)=n bits of information if all patterns are equally likely. A number format can be wasteful in this sense: fp32 spends 32 bits of storage on each weight, and quantization is an attempt to keep most of the useful information in far fewer.

The recipe in one place

Intuition

A float is scientific notation in base 2: a sign, a few significant bits and an exponent, packed into a fixed number of bits. The exponent bits decide how far the numbers reach and the fraction bits decide how finely they are spaced. Spacing doubles at every power of two, so large numbers are coarse and small numbers fine, and every result is rounded to the nearest number the format owns. Integers have no exponent: evenly spaced, small range, exact until they wrap.

Math

Unsigned integer: ∑ibi2i\sum_i b_i2^i. Two’s complement with nn bits: −bn−12n−1+∑i<n−1bi2i-b_{n-1}2^{n-1}+\sum_{i<n-1}b_i2^i, range −2n−1-2^{n-1} to 2n−1−12^{n-1}-1.

Normal float: (−1)S 2E−bias (1+M/2m)(-1)^S\,2^{E-\text{bias}}\,(1+M/2^m), bias 2e−1−12^{e-1}-1 (fp32: 127, fp16: 15, E5M2: 15, E4M3: 7). Subnormal (E=0E=0, M≠0M\ne0): (−1)S 21−bias (M/2m)(-1)^S\,2^{1-\text{bias}}\,(M/2^m). EE all ones: ±∞\pm\infty or NaN (E4M3: only EE and MM all ones is NaN).

Largest normal: (2−2−m) 2bias(2-2^{-m})\,2^{\text{bias}} for the IEEE-style formats (fp32: 3.4028×10383.4028\times10^{38}). Gap at x∈[2k,2k+1)x\in[2^k,2^{k+1}): 2k−m2^{k-m}. Unit roundoff u=2−(m+1)u=2^{-(m+1)}.

Memory of weights: parameters × bits ÷ 8 bytes.

Code

import numpy as np
np.finfo(np.float16).max         # 65504.0
np.finfo(np.float32).eps         # 1.1920929e-07
np.spacing(np.float32(16777216)) # 2.0, the gap to the next float32
np.float16(2048) + np.float16(1) # 2048.0
np.isclose(0.1 + 0.2, 0.3)       # True
np.iinfo(np.int8).max            # 127

PyTorch has torch.bfloat16, torch.float16, torch.float32 and, in recent versions, torch.float8_e4m3fn and torch.float8_e5m2 (the fn means finite values and NaN only: no infinities). torch.finfo(dtype) reports max, eps and tiny for each. A tensor made from Python floats is float32 by default in PyTorch, and a NumPy array of Python floats is float64.

Try it: the bits of floats, wrap-around and the limits of each format

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The second cell shows the ways rounding errors add up, then a small int8 quantization and the memory arithmetic.

Try it: cancellation, order of sums, tolerances, quantization and memory

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Check your understanding

  1. What does the 8-bit two's-complement pattern 10000000 stand for?

  2. In fp16, 2048+12048+1 gives 20482048. Why?

  3. Which statement about fp16 and bf16 is correct?

  4. Why is 0.1 + 0.2 == 0.3 false in Python?

  5. About how much memory do the weights of a model with 70 billion parameters take when each weight is stored in 8 bits?

  6. The shortcut E[X2]−E[X]2\mathbb{E}[X^2]-\mathbb{E}[X]^2 returns 0 for the four fp32 values 9998.5, 9999.5, 10000.5 and 10001.5, whose true variance is 1.25. What causes this?

Exercises

  1. Write 4545 as an 8-bit unsigned binary number.
    Show answer45=32+8+4+145=32+8+4+1, so 00101101200101101_2.
  2. What number is the int8 pattern 11110000211110000_2?
    Show answer−128+64+32+16=−16-128+64+32+16=-16.
  3. Decode the fp16 pattern 0 10001 0100000000 (fp16 bias is 15).
    Show answerThe exponent field 100012=1710001_2=17, so the exponent is 17−15=217-15=2 and the scale is 44. The fraction 01…01\ldots is 0.250.25, so the significand is 1.251.25. The sign is ++, so the value is 4×1.25=54\times1.25=5.
  4. How much memory do the weights of a 13-billion-parameter model need in fp16, and in int8?
    Show answerfp16 uses 2 bytes: 13×109×2=2613\times10^9\times2=26 GB. int8 uses 1 byte: 1313 GB. (Weights only.)
  5. In fp16 the numbers between 512512 and 10241024 are spaced 29−10=0.52^{9-10}=0.5 apart. To which fp16 number is 1000.31000.3 rounded?
    Show answerThe neighbours are 10001000 and 1000.51000.5; 1000.31000.3 is 0.30.3 from the first and 0.20.2 from the second, so it becomes 1000.51000.5 (the rounding error is 0.20.2).
  6. Quantize the weight 0.50.5 to int8 with the scale s=2/127s=2/127 (a range of −2-2 to 22). What integer is stored, what value comes back, and what is the error?
    Show answer0.5/s=31.750.5/s=31.75, which rounds to q=32q=32. The recovered value is 32×2/127=0.5039432\times2/127=0.50394, an error of 0.00390.0039, which is below half a step, s/2=0.0079s/2=0.0079.
  7. Why is x == 0.3 a bad test for a computed float, and what should you use?
    Show answerThe computed value usually differs from the decimal 0.30.3 by a rounding error, so equality fails even when the answer is right for practical purposes. Use np.isclose(x, 0.3) or abs(x - 0.3) < tol with a tolerance suited to the scale of the problem.
  8. Code: in the second cell, find the smallest centre (from 100100, 10001000, 30003000, 1000010000) for which the float32 shortcut is wrong by at least 20 percent.
    Show answerAt centre 30003000 the shortcut already gives 1.01.0 instead of 1.251.25 (an error of 20 percent), at 10001000 and 100100 it is still 1.251.25, and at 1000010000 it gives 00. So 30003000 is the smallest of these.

Next: P1.G2 shows what happens when a number is too big or too small for its format, through overflow and underflow in exp and softmax, and how log-sum-exp avoids both. P10.B5 and P10.F1 return to fp16, bf16, fp8 and int8 in real training and inference.

Key takeaways

  • A format is a rule that maps 2ⁿ bit patterns to numbers. n bits give exactly 2ⁿ patterns, so only some numbers can be stored; the rest are rounded.
  • Signed integers use two's complement: the top bit counts as −2ⁿ⁻¹. int8 holds −128 to 127, and in NumPy 127 + 1 wraps to −128 (Python's own integers never wrap).
  • A float is sign × 2^(exponent − bias) × 1.fraction. fp32 uses 1+8+23 bits, fp16 1+5+10, bf16 1+8+7, fp8 E4M3 1+4+3 and E5M2 1+5+2. Exponent bits set the range, fraction bits set the precision.
  • Special values: ±0 and subnormals have exponent field 0 (subnormals fill the gap near zero with less precision); ±∞ and NaN have exponent field all ones. fp16 tops out at 65504, bf16 and fp32 near 3.4×10³⁸.
  • Floats are evenly spaced inside each power of two, so the gap grows with the size of the number: in fp16 2048 + 1 = 2048, in fp32 16777216 + 1 = 16777216. The relative error of one rounding is at most 2⁻⁽ᵐ⁺¹⁾ for m fraction bits.
  • Rounding errors add up in typical ways: subtracting nearly equal numbers (the variance shortcut gives 0 instead of 1.25), adding small numbers to a big total, and changing the order of a sum. Compare floats with a tolerance, never with ==.
  • Memory of the weights is parameters × bytes per parameter: 7 billion weights take 28 GB in fp32, 14 GB in fp16 or bf16, 7 GB in int8 or fp8 and 3.5 GB in 4 bits. Training needs more than the weights.
Found a mistake? Tell us