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 bits can be arranged in ways, so bits give patterns, bits give , and bits give about billion. A number format is a rule that says which number each pattern means. Whatever the rule, at most different numbers can be stored in bits.
For whole numbers that cannot be negative (unsigned integers), the rule is the one you know from the decimal system, with in place of . 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: from the right. So
Going the other way, , which is . With 8 bits the range is to .
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 instead of . For 8 bits (int8) the place values are . So
The leftmost bit is therefore a sign bit: it is 1 for exactly the negative numbers. The smallest int8 is , the largest is , and all patterns are used, so there is one more negative number than positive ones. To negate a number, flip every bit and add 1: becomes . 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 (which is 127) gives , which is . 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 , or ? 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 and .
Floating point works like scientific notation. Write : a sign, a significand with a few digits, and an exponent 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 , where is a string of binary digits (the fraction) and is a whole-number exponent. And here the analogy breaks. In base 10, never ends, but does. In base 2 the fractions that end are only those whose denominator is a power of 2 (, , ). The number is
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 , and a 32-bit float stores exactly . In 0.1 + 0.2 the two small errors do not cancel, and the sum lands one step away from the stored . (With 32-bit floats the same sum happens to land on the stored : 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 : 1 bit, 0 for positive and 1 for negative;
- exponent : bits, read as an unsigned integer, with a bias subtracted;
- fraction : bits, the digits after the point of the significand.
For a normal number the value is
The bias is .
The “1 +” is the implicit leading 1: every normal number is written 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, and the bias is , so means , and means .
Decoding an fp32 pattern by hand. Take 1 10000001 10100000000000000000000.
- The sign bit is , so the number is negative.
- The exponent field is . Subtract the bias: , so the scale is .
- The fraction starts , which means , so the significand is .
- The value is .
Encoding goes the other way, and rounds. For : the exponent field is . The fraction is , which must be rounded to a whole number, . That rounding is the error: the stored number is , which is 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, and , and they compare equal (although is ). If the fraction is not zero, the number is subnormal: there is no implicit 1, and the exponent is fixed at . 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 and the smallest subnormal about .
- Exponent field all ones. If the fraction is zero, the value is (the result of an overflow or of ). If the fraction is not zero, the value is NaN, “not a number” (the result of or ). 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 . (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.
Things to try, each checked against the widget:
- fp32, 0.1. Press 0.1. The bits are
0 01111011 10011001100110011001101and the value is . Type0.3and 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 to (a gap of ). In fp16 the next number after is , and in fp8 E4M3 it is . A smaller format has far bigger gaps.
- Overflow in int8. Press 127, then Pattern + 1: the value wraps to .
- Largest values. Press Largest. fp16 gives , E4M3 gives , E5M2 gives , and fp32 and bf16 are near .
- 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 . Switch to bf16 and it is stored, as . 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 and the next number up, which is ), 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 : the significand has bits counting the hidden 1, and each bit is worth about decimal digits. Every whole number up to is exact in a float (fp32: ; fp16: ); 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 and the smallest normal one is .
- bf16 (short for “brain floating point”) has 8 exponent bits, the same as fp32, and 7 fraction bits. It has fp32’s range, about to , 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 becomes , because it is below half of the smallest subnormal (). bf16 holds it, with stored as . 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: is stored as in fp16 but as in bf16. P10.B5 returns to this with full training runs.
The gap grows with the number
Between and a format has exactly numbers, evenly spaced. The spacing inside that block is , 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 at , at and at .
- fp16: the gap is at , at and at .
So the relative spacing stays about the same (between and ), while the absolute spacing grows. This has a famous consequence. At the fp16 gap is , so lies exactly halfway between and and is rounded to the neighbour with the even fraction, . In fp16, . In fp32 the same happens at : .
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 the number, so for a normal number
where is the unit roundoff: for fp32, for fp16 and 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, , or use the shortcut . 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 , whose true variance is for any (the deviations are and , and ).
- In fp32 with : is about , and fp32 numbers near are apart. The nearly equal numbers and are both rounded to the same value, and the shortcut gives 0.0. Subtracting the mean first gives the correct .
- In fp64 with the shortcut also gives 0.0, because fp64 numbers near are 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 at each step reaches and then stays there for ever. Likewise in fp32 a total at ignores every .
Addition is not associative. Because each addition rounds, and can differ. In 64-bit floats but , and but . In fp32, a total that starts at and adds a thousand s one at a time stays at , while adding the thousand s first and the big number last gives the exact . 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 , absolute ) or math.isclose (relative ). 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 . In fp32, is above the largest value , so np.exp(np.float32(89)) is inf. In fp16, is above , so it overflows already at . 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 together with one shared real number, the scale , and recovers the weight as . For int8 with a symmetric range, choose so that the largest weight maps to .
Take the weights . The largest size is , so . The integers are , and the recovered weights are . The errors are and : each is at most , 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 to the list: the scale becomes and the other four weights become . Real quantization methods therefore use separate scales for small groups of weights. A variant with a zero point, , shifts the 256 levels (for example to ) 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 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 bytes):
- fp32: GB.
- fp16 or bf16: GB.
- int8 or fp8: GB.
- 4-bit integers: GB.
This is the same arithmetic as in P1.C8 and P1.F6, where the Hessian of a model with parameters has entries, which is TB in fp32 (and 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 is an ordinary unsigned integer, and the real exponent is . 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 plus one ulp becomes with the exponent increased.
Go deeper Where the rounding bound comes from
Inside a block the spacing is , so rounding to the nearest number moves a value by at most half of that, . The value itself is at least , so the relative error is at most . That is the unit roundoff 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 , the gap at . Some textbooks and libraries call , and not , 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 carries one bit of surprise. Here a bit is one binary digit of storage. They meet in a simple fact: storage bits can tell apart cases, which is 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: . Two’s complement with bits: , range to .
Normal float: , bias (fp32: 127, fp16: 15, E5M2: 15, E4M3: 7). Subnormal (, ): . all ones: or NaN (E4M3: only and all ones is NaN).
Largest normal: for the IEEE-style formats (fp32: ). Gap at : . Unit roundoff .
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 # 127PyTorch 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.
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.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Check your understanding
What does the 8-bit two's-complement pattern
10000000stand for?The leftmost bit counts as and every other bit is zero, so the value is . The value does not fit in int8, whose largest value is . Two's complement has only one zero (all bits zero), so there is no negative zero among the integers, and the sign bit is part of the value and not a separate flag.
In fp16, gives . Why?
Between 2048 and 4096 fp16 has 1024 evenly spaced numbers, a gap of . The number 2049 is exactly halfway between two stored numbers, and ties go to the one with an even fraction. fp16 does store 2048 and 2050 (it stores all even integers there), the largest fp16 value is 65504 (so there is no overflow), and the size of the other number matters only through the gap.
Which statement about fp16 and bf16 is correct?
bf16 has 8 exponent bits and 7 fraction bits, fp16 has 5 and 10. More exponent bits mean more range (bf16), and more fraction bits mean finer spacing (fp16, gap about at 1 against for bf16). They are different layouts of the same 16 bits, and the larger fraction field belongs to fp16.
Why is
0.1 + 0.2 == 0.3false in Python?In base 2, 0.1 is a repeating fraction like in base 10, so each is stored as the nearest binary number, and the sum of the two stored values is one step away from the stored 0.3. Python does not store decimal digits, adding small numbers is no problem for a CPU, and NumPy float64 arithmetic follows the same IEEE 754 rules.
About how much memory do the weights of a model with 70 billion parameters take when each weight is stored in 8 bits?
Eight bits is one byte per weight, so bytes is 70 GB. Two bytes per weight (fp16 or bf16) would give 140 GB, half a byte per weight (4-bit) would give 35 GB, and 560 GB comes from counting 8 bytes per weight, which mixes up bits and bytes. These are the weights alone; training needs more.
The shortcut 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?
For these four values the exact difference is 1.25, but each term is rounded to a multiple of 8, and here both round to the same value, so the subtraction gives 0 (for other data the result is noise in multiples of 8, not always 0). The number 10000 is stored exactly, the true variance is 1.25, and subtracting the mean first, as
np.vardoes, gives the right result.
Exercises
- Write as an 8-bit unsigned binary number.
Show answer
, so . - What number is the int8 pattern ?
Show answer
. - Decode the fp16 pattern
0 10001 0100000000(fp16 bias is 15).Show answer
The exponent field , so the exponent is and the scale is . The fraction is , so the significand is . The sign is , so the value is . - How much memory do the weights of a 13-billion-parameter model need in fp16, and in int8?
Show answer
fp16 uses 2 bytes: GB. int8 uses 1 byte: GB. (Weights only.) - In fp16 the numbers between and are spaced apart. To which fp16 number is rounded?
Show answer
The neighbours are and ; is from the first and from the second, so it becomes (the rounding error is ). - Quantize the weight to int8 with the scale (a range of to ). What integer is stored, what value comes back, and what is the error?
Show answer
, which rounds to . The recovered value is , an error of , which is below half a step, . - Why is
x == 0.3a bad test for a computed float, and what should you use?Show answer
The computed value usually differs from the decimal by a rounding error, so equality fails even when the answer is right for practical purposes. Usenp.isclose(x, 0.3)orabs(x - 0.3) < tolwith a tolerance suited to the scale of the problem. - Code: in the second cell, find the smallest centre (from , , , ) for which the float32 shortcut is wrong by at least 20 percent.
Show answer
At centre the shortcut already gives instead of (an error of 20 percent), at and it is still , and at it gives . So 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.