Phase 04/Numbers and precision/FP32, FP16 and BF16
PHASE 04 · Numbers and precision

FP32, FP16 and BF16

0%
5 h5 subtopics2 lessons · 1 required
In plain English

A computer stores every number in a fixed number of bits, like writing numbers on index cards of a fixed size. FP32 uses a big card with room for about seven decimal digits and a huge range. FP16 and BF16 use a card half the size. They store half as many digits, so they hold less detail, but they take half the memory and move through the machine twice as fast. The two half-size formats make a different trade: FP16 keeps more digits but can only count up to about 65,000 before it overflows, while BF16 keeps fewer digits but can represent numbers as large as FP32. Choosing the card size is the first and cheapest speedup in inference.

Why it matters

Almost every LLM is served in FP16 or BF16, and inference is dominated by moving weights from memory, so halving the bits nearly halves decode latency. Knowing the exact bit layout tells you when a model will overflow, lose precision in softmax or layer norm, or produce NaNs after conversion.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Decode an FP32, FP16 and BF16 value from its raw bits by hand.
  • Compute the largest representable value and the spacing between adjacent values for each format.
  • Predict which operations in a transformer are unsafe in FP16 and why BF16 avoids them.
  • Measure the memory and speed effect of casting a model from FP32 to FP16 on CPU and GPU.

Key concepts

Sign, exponent, mantissa
The three bit fields of a floating-point number; exponent sets the range, mantissa sets the precision.
FP32
1 sign, 8 exponent, 23 mantissa bits; about 7 decimal digits, max around 3.4e38.
FP16 (half)
1 sign, 5 exponent, 10 mantissa bits; about 3 decimal digits, max 65504.
BF16 (bfloat16)
1 sign, 8 exponent, 7 mantissa bits; same range as FP32 with about 2 decimal digits of precision.
Machine epsilon
The gap between 1.0 and the next representable number; 2^-23 for FP32, 2^-10 for FP16, 2^-7 for BF16.
Subnormal numbers
Values smaller than the smallest normal exponent, stored with reduced precision; often flushed to zero on GPUs.
Mixed precision
Doing matmuls in 16-bit while keeping accumulations, norms or softmax in FP32.
Memory-bound
An operation whose time is set by bytes moved, not arithmetic; the case for LLM decode.

Subtopics

  1. 1. Bit layout of IEEE floats

    Value is (-1)^sign * 2^(exponent - bias) * (1 + mantissa/2^m). Special cases for zero, inf, NaN and subnormals.

  2. 2. Range versus precision

    Exponent bits buy range, mantissa bits buy precision; FP16 and BF16 split the same 16 bits differently.

  3. 3. Where transformers break in FP16

    Attention logits, softmax sums, layer norm variance and large residual activations can exceed 65504; BF16 does not overflow but loses digits.

  4. 4. Tensor core support and autocast

    Which formats run on tensor cores per GPU generation, and how torch.autocast picks per-op precision.

  5. 5. Bandwidth consequences

    Halving bytes per weight halves the memory traffic that dominates decode; estimate the speedup from GPU bandwidth.

Resources

Hands-on lessons

L1

Decode floats bit by bit in numpy

CPU · your Macnotebook90 minrequired

Goal · Write your own FP32, FP16 and BF16 decoder and verify it against numpy and torch on thousands of random values.

  1. 1Use np.frombuffer / view to get the raw uint bits of a float32 and float16 array.
  2. 2Write decode(bits, exp_bits, man_bits) that returns the value, handling zero, inf, NaN and subnormals.
  3. 3Check your decoder against np.float32 and np.float16 on 10,000 random values with np.allclose.
  4. 4Implement BF16 by truncating or rounding the top 16 bits of an FP32 and decode with 8 exponent / 7 mantissa bits; compare with torch.bfloat16.
  5. 5Tabulate for each format the max finite value, min positive normal, min subnormal and machine epsilon.
  6. 6Plot the spacing between adjacent representable values versus magnitude for all three formats on a log-log chart.
Deliverable
A notebook with the decoder, the comparison table and the spacing plot.
Check
Your decoder agrees with numpy on every random value; your table shows FP16 max 65504 and BF16 epsilon 0.0078125.
L2

Find where GPT-2 overflows in FP16

CPU · your Macexperiment60 minoptional

Goal · Locate the first tensor in a GPT-2 forward pass whose FP32 value would overflow or lose meaningful precision in FP16.

  1. 1Load gpt2 in FP32 and register forward hooks that record max(abs(output)) per module.
  2. 2Run a long prompt and list modules whose max exceeds 65504 or exceeds 1024 (above which FP16 spacing is 1.0).
  3. 3Cast the model to torch.float16 and torch.bfloat16 and run the same prompt, catching NaN or inf.
  4. 4Compare the top-5 next-token logits across FP32, FP16 and BF16 and compute the max absolute logit difference.
  5. 5Write three sentences on which format you would serve this model in and why.
Deliverable
A table of per-module max magnitudes plus the logit-difference numbers.
Check
You can name at least one module where the FP16 spacing is coarser than 0.1 and explain its effect on the logits.
Fallback
If torch has no CPU bf16 matmul for your version, run only the FP32 versus FP16 comparison.

Build your own

Build your own float formats

PythonCPU · your Mac~5 h

A bit-level encoder and decoder for fp32, fp16, bf16, fp8 e4m3fn and fp8 e5m2 with selectable rounding modes, verified exhaustively against numpy and torch.

The real thing: github.com/jax-ml/ml_dtypes ↗

How you know a stage passes

Write tests/test_formats.py first. Every stage adds a test that runs your pure-numpy `encode(x, fmt, rounding)` and `decode(bits, fmt)` over every bit pattern of the format (65,536 for 16-bit, 256 for 8-bit) or over one million seeded random fp32 values, and compares bit-for-bit with numpy float16, torch.bfloat16 and torch.float8_e4m3fn / float8_e5m2 used as oracles. NaNs are compared with isnan, everything else with integer equality on the bits. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01take an fp32 apart and put it back
    `decompose(x)` returns sign, biased exponent and mantissa integers from the raw bits, and `compose(s, e, m)` rebuilds the float, with subnormals, zero, inf and NaN handled.
    test · compose(*decompose(x)) is bit-identical to x for one million random fp32 values plus the specials -0.0, inf, -inf, NaN, the smallest subnormal 1.4e-45 and the largest finite 3.4028235e38.
  2. 02a generic decoder for any (exponent bits, mantissa bits, bias)
    A `Format(e_bits, m_bits, bias)` class decodes any bit pattern to a Python float, so fp16 and bf16 are two instances of the same code.
    test · decode of all 65,536 fp16 patterns equals np.frombuffer(bits, np.float16) and all 65,536 bf16 patterns equal torch.tensor(bits).view(torch.bfloat16); the fp16 min normal decodes to 6.103515625e-05 and the min subnormal to 5.960464477539063e-08.
  3. 03encode with round-to-nearest-even
    `encode(x, fmt)` converts an fp32 to the target bits using RNE, including rounding into subnormals, rounding up into the next exponent and overflow to inf.
    test · encode to fp16 of one million random fp32 values matches np.float32(x).astype(np.float16) bit-for-bit; 1 + 2**-11 encodes to 1.0 and 1 + 3 * 2**-11 encodes to 1 + 2**-9 (ties go to even); 65520.0 encodes to inf and 65519.0 to 65504.0.
  4. 04the two fp8 formats and their quirks
    e4m3fn (no inf, max 448, one NaN pattern per sign) and e5m2 (IEEE-like, max 57344, has inf) are supported with saturating and non-saturating overflow.
    test · decode of all 256 patterns of each format equals torch's float8 views; encode(500.0, e4m3fn, saturate=False) is the NaN pattern 0x7F and with saturate=True is 0x7E (448.0); encode(70000.0, e5m2) is inf.
  5. 05truncation and stochastic rounding
    Rounding mode is a parameter with values rne, truncate and stochastic (seeded), and a report shows the bias of each.
    test · Over one million uniform values in [1, 2) encoded to fp16, truncation has a mean signed error of about -0.5 ulp (between -0.45 and -0.55), RNE and stochastic have a mean within 0.01 ulp of zero; the stochastic average of 10,000 encodings of 1 + 2**-12 is within 2 percent of the true value while RNE gives exactly 1.0 every time.
  6. 06a format explorer CLI and the overflow sweep
    `python floatlab.py table fp16 bf16 e4m3 e5m2` prints max finite, min normal, min subnormal and ulp at 1.0 for each format, and `floatlab.py accumulate` shows the error of summing 4,096 copies of 0.1 in each format's precision versus an fp32 accumulator.
    test · The table contains 65504, 448, 57344 and 3.3895e38 in the max column and 0.0009765625 for fp16 ulp at 1.0; the accumulate command reports an fp16-accumulator relative error above 1 percent and an fp32-accumulator error below 0.01 percent, and pytest asserts both.

Knowledge check

QWhy does BF16 have the same range as FP32?

It keeps all 8 exponent bits of FP32 and only drops mantissa bits, so the largest and smallest exponents are unchanged.

QWhat is the largest finite FP16 value, and why does this matter for attention?

65504. Attention logits (q dot k) can exceed it for long sequences or large activations, producing inf and then NaN in softmax.

QIf decode is memory-bound, roughly how much faster is FP16 than FP32 for the same model?

About 2x, because half the bytes of weights are read per token and arithmetic is not the bottleneck.

QWhat does torch.autocast do that a plain .half() does not?

It runs numerically sensitive ops (softmax, norms, reductions) in FP32 while running matmuls in 16-bit, instead of casting everything.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 decoder passes the numpy comparison and the table is saved.
  • Can state the bit layout and max value of all three formats from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →