Skip to content
ImagineWorld

FP8 and Mixed-Precision Training

node_idnode-book_building-frontier-llm-from-scratch_chapter-18-fp8-and-mixed-precision-training
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num18
chapter_titleFP8 and Mixed-Precision Training
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 18 — FP8 and Mixed-Precision Training

Section titled “Chapter 18 — FP8 and Mixed-Precision Training”

Precision is leverage. Every halving of the bits per number roughly halves memory and doubles arithmetic throughput, and the industry has marched from FP32 to BF16 to FP8 in a few years. DeepSeek-V3 was among the first models of its size trained natively in FP8, and that choice is a substantial part of why it trained so cheaply. But FP8 is not free to use — its tiny numeric range will destroy a naive training run — and the techniques that make it work are some of the most instructive systems engineering in modern deep learning. This chapter explains them.

The case is purely economic. A model’s weights, activations, gradients, and optimizer state all occupy memory proportional to their bit width, and matrix-multiply throughput on modern GPUs is far higher in low precision — an FP8 matmul can run at roughly twice the rate of BF16 on hardware that supports it. For a run measured in GPU-months, halving the cost of the dominant operation is transformative. The formats themselves were introduced in Chapter 2 (Table 2.5); the question is how to use the smallest of them without losing the model.

The established baseline is mixed-precision training, seen in the loop of Chapter 3: compute the forward and backward passes in a low-precision format (BF16) under autocast, but keep a master copy of the weights and the optimizer state in FP32 so that the many tiny updates accumulate accurately. BF16 is forgiving because it keeps FP32’s full exponent range and sacrifices only mantissa bits, so it rarely overflows. (FP16, with its narrow range, additionally needs loss scaling — multiplying the loss before backprop to keep small gradients from underflowing — which is why BF16 became the default once hardware supported it.) FP8 pushes this idea one step further and reaches the point where range, not just precision, becomes the problem.

The E4M3 format used for FP8 forward passes has a maximum magnitude of about 448 and only three mantissa bits. Two difficulties follow. First, neural-network tensors contain outliers — a few values far larger than the rest — and a single value above 448 overflows to infinity, corrupting the result. Second, if you scale a whole tensor down by one global factor to fit its largest value, the many small values lose almost all their precision to the three-bit mantissa. A single scale per tensor cannot serve both the outliers and the bulk. This is the core obstacle, and the solution is to stop using a single scale.

18.4 Fine-Grained Quantization and DeepGEMM

Section titled “18.4 Fine-Grained Quantization and DeepGEMM”

DeepSeek-V3’s answer is fine-grained (block-wise) quantization: instead of one scale per tensor, use a separate scale for each small block. Activations are scaled per small tile (a row segment of 128 channels), and weights are scaled per 128 × 128 block. Each block’s scale is chosen from its own maximum, so a block of outliers gets a large scale while a block of small values keeps its precision — and the scales are stored in higher precision alongside the FP8 values. The quantization itself is short:

import torch
FP8_MAX = 448.0 # E4M3 maximum magnitude
def quantize_blockwise(x, block=128):
xb = x.reshape(-1, block) # split into blocks
scale = xb.abs().amax(dim=-1, keepdim=True) / FP8_MAX # per-block scale
scale = scale.clamp(min=1e-12)
q = (xb / scale).to(torch.float8_e4m3fn) # FP8 values
return q, scale # dequantize as: q.float() * scale

Python — fp8.py: block-wise FP8 quantization (the core idea)

One more ingredient makes it correct: accumulation in FP32. An FP8 matrix multiply sums many products, and summing them in FP8 would lose precision catastrophically; so the products are accumulated in FP32 (or promoted periodically), giving FP8 inputs but a high-precision sum. DeepSeek released DeepGEMM, a library of FP8 matrix-multiply kernels implementing exactly this fine-grained scaling and high-precision accumulation, which is what makes FP8 training both fast and stable in practice. Sensitive parts of the network — embeddings, normalization, the attention softmax, and the output head — are kept in BF16, because their dynamic range or precision sensitivity does not tolerate FP8. Table 18.1 shows the resulting precision map.

ComponentPrecisionWhy
Main GEMM inputs (weights, activations)FP8 E4M3, block-scaledthroughput and memory
GEMM accumulationFP32summing many products needs range
Master weights, optimizer stateFP32 / BF16tiny updates must accumulate
Embeddings, norms, softmax, LM headBF16precision/range sensitive

Table 18.1 — Precision by component in FP8 training (DeepSeek-V3 style)

Key point FP8 training is not “cast everything to 8 bits.” It is a careful split: FP8 where throughput dominates and the values are well-behaved in small blocks, higher precision where accumulation or sensitivity demands it. The enabling trick is fine-grained scaling — many small scales instead of one — which is a general lesson about quantization that returns in Chapter 26 when we quantize models for inference.

Code reference — deepseek-ai/DeepSeek-V3 (FP8 training recipe, technical report) · deepseek-ai/DeepGEMM · NVIDIA/TransformerEngine

The DeepSeek-V3 report details the block-wise scaling factors and which operations stay in higher precision; DeepGEMM provides the FP8 kernels; and NVIDIA’s TransformerEngine is the widely used general-purpose FP8 training library. Reading the report’s precision section against this chapter shows how the core idea scales to a production recipe.

FP8 makes each GPU’s arithmetic cheap. But a 671-billion-parameter model does not fit on one GPU at all — not its weights, not its optimizer state, not its activations. Training it requires splitting the model and the data across thousands of devices and orchestrating their communication, which is the substantial systems problem of the next chapter.

18.5 Worked Example: Casting a Tensor to FP8

Section titled “18.5 Worked Example: Casting a Tensor to FP8”

FP8’s range is tiny, so the working technique (Chapter 18) is to scale each tensor into that range before casting, run the matmul in FP8, accumulate in higher precision, then unscale. Per-tensor scaling is the minimal version:

def to_fp8(x, fp8_dtype=torch.float8_e4m3fn):
amax = x.abs().max()
scale = FP8_MAX / amax.clamp(min=1e-12) # fit the tensor into FP8 range
x_fp8 = (x * scale).to(fp8_dtype) # cast down to 8 bits
return x_fp8, scale # keep scale to undo later
# matmuls run in FP8; products accumulate in fp32, then unscale by 1/scale.
# DeepSeek-V3 (Chapter 45) trained its entire run in FP8 this way

Python — FP8: scale into range, cast, keep the scale to undo

FP8’s dynamic range is so narrow that every tensor must be multiplied by a scaling factor before it is cast, chosen so the tensor’s largest magnitude lands near the top of the FP8 range without overflowing. Computing that maximum (the amax) fresh on every step would add a device-wide reduction in the hot path. Delayed scaling hides the cost: keep a short history of recent amax values and use it to pick the scale for the next step.

FP8_MAX = 448.0 # max magnitude of e4m3
def update_scale(x, amax_history):
amax_history = torch.roll(amax_history, 1)
amax_history[0] = x.abs().max() # newest amax at the front
amax = amax_history.max() # worst case over the window
scale = FP8_MAX / torch.clamp(amax, min=1e-12)
return scale, amax_history
def to_fp8(x, scale):
return (x * scale).to(torch.float8_e4m3fn), 1.0 / scale # value, inv

Python — fp8/scaling.py: delayed scaling with an amax history

Taking the maximum over a window rather than the single latest value buys a safety margin: a sudden spike in one tensor cannot immediately push the next step into overflow, because the window still remembers the calmer recent past. The stored 1.0 / scale is the dequantization factor applied after the FP8 matmul to bring the result back to true scale.

18.7 Worked Example: What Stays in High Precision

Section titled “18.7 Worked Example: What Stays in High Precision”

FP8 is applied surgically, not everywhere. The inputs to the big matrix multiplies are cast to FP8; almost everything that governs the correctness of the update stays in higher precision. The division of labor is worth memorizing:

ComponentPrecisionWhy
Linear / attention GEMM inputsFP8 (e4m3)where the FLOPs are
GEMM accumulationFP32avoid drift over K
Master weightsFP32tiny updates must register
Optimizer moments (Adam)FP32second moment is fragile
Gradients (communicated)BF16 / FP8bandwidth vs. fidelity
Norms, softmax, residualsBF16 / FP32sensitive to rounding

Table 18.4 — Precision by component in an FP8 training run

The pattern is consistent: spend FP8 on the throughput-dominating matrix multiplies, and keep high precision wherever a small number must survive — the master weights that absorb each step’s minuscule update, the Adam second moment, and the reductions in normalization and softmax. This is why an FP8 run still allocates FP32 master weights (Section 18.2): the FP8 copy is a fast shadow used only inside the GEMM, regenerated each step from the authoritative FP32 parameters.

Rule of thumb If a value is summed over a long dimension (an accumulation, a softmax denominator, a running optimizer statistic) or must accumulate many tiny updates (a master weight), keep it in FP32. If it merely feeds a matrix multiply, FP8 is fair game.

18.8 The Granularity of Scaling: Per-Tensor to Per-Block

Section titled “18.8 The Granularity of Scaling: Per-Tensor to Per-Block”

Section 18.6 introduced the scaling factor that maps a tensor into the FP8 range; a question it left open is how many scales to use. The coarsest choice is one scale for the whole tensor — simple, but a single large outlier then sets the scale for millions of well-behaved values, crushing their precision. Finer granularities give each region its own scale:

GranularityOne scale perTrade-off
Per-tensorentire tensorcheapest; outliers hurt all values
Per-channelrow or columnhandles per-feature variation
Per-block (tile)small tile, e.g. 128×128fine precision; more bookkeeping

Table 18.2 — Scaling granularity in low-precision training

The trend at the frontier is toward finer granularity where it pays. DeepSeek-V3’s FP8 training uses tile-wise (per-block) scaling for exactly the reason the table implies: in a large weight matrix, different tiles have genuinely different magnitude distributions, and giving each its own scale recovers precision that a single tensor-wide scale would throw away. The cost is bookkeeping — more scales to compute, store, and apply — which is why per-block scaling became practical only once the kernels (DeepGEMM, Section 18.4) were written to handle it efficiently. The general lesson generalizes to integer quantization (Chapter 26): the right granularity is the coarsest one that does not let an outlier dominate.

Finer scales, fewer wasted bits A single scale per tensor lets one outlier set the precision for everything. Per-block scaling gives each tile its own range — more bookkeeping, but far better use of the few bits FP8 provides. The kernels exist precisely to make this affordable.

FP8 is not a single format but two, distinguished by how they split their eight bits between exponent and mantissa — that is, between range and precision. The choice between them is not arbitrary; each phase of training uses the one suited to the numbers it handles:

FormatBits (E / M)Trades forUsed by
E4M34 exp / 3 mantmore precision, less rangeweights, activations
E5M25 exp / 2 mantmore range, less precisiongradients

Table 18.3 — The two FP8 formats

The division follows the statistics of what each tensor holds. Weights and forward activations sit in a relatively narrow band of magnitudes, so they prize the extra precision of E4M3’s larger mantissa. Gradients span a far wider dynamic range — some tiny, some occasionally large — so they prefer E5M2’s extra exponent bit, accepting coarser precision to avoid the overflow and underflow that would clip them. This is the same range-versus-precision tension that motivated the scaling factors of Section 18.6, now resolved at the level of the number format itself: choose the representation whose shape matches the distribution it must carry.

Match the format to the magnitudes E4M3 for the narrow-range, precision-sensitive weights and activations; E5M2 for the wide-range gradients. Eight bits is too few to be both precise and wide, so FP8 ships both and lets each tensor pick.

Section 18.7 solved the “swamping” problem — a tiny gradient added to a large weight rounding away to nothing — by keeping an FP32 master copy of the weights. Stochastic rounding is a different and complementary answer to the same problem, one that lets low precision preserve small updates on its own. Ordinary rounding goes to the nearest representable value, which systematically discards any update too small to cross half a step. Stochastic rounding instead rounds up or down probabilistically, with a probability set by how close the true value lies to each option.

The consequence is that the rounding is unbiased: a value 30% of the way from one representable number to the next rounds up 30% of the time and down 70% of the time, so that in expectation it lands exactly where it should. A small update that nearest-rounding would erase every time instead nudges the weight upward on the right fraction of steps, and over many steps those probabilistic nudges accumulate to the correct total. This is why stochastic rounding can, in some regimes, allow training in low precision without a full FP32 master copy — the unbiasedness recovers what deterministic rounding would lose. It is a subtle but elegant idea: by adding randomness to the rounding, you remove the systematic bias that randomness is usually blamed for, trading a little per-step noise for correctness in the long-run average.

Round randomly to round without bias Nearest-rounding silently discards updates too small to cross half a step; stochastic rounding rounds up or down in proportion to proximity, so small updates survive in expectation. Randomness here buys unbiasedness, not error.

A clarifying fact underlies much of this book’s systems engineering: the overwhelming majority of a transformer’s compute is matrix multiplication. The attention projections (Chapter 7), the feed-forward networks (Section 8.6), the mixture-of-experts layers (Chapter 11) — nearly every expensive operation is, at bottom, a large matmul (a GEMM, for general matrix-multiply). The softmax, the normalizations, the activations are real but comparatively cheap; the matmuls are where the FLOPs go.

This single observation explains a remarkable amount. It is why GPUs — hardware built to do matrix multiplication at enormous throughput, with dedicated tensor cores — dominate this field rather than general-purpose processors. It is why low precision (this chapter’s subject) matters so much: the matmuls are the bottleneck, and FP8 makes exactly those matmuls faster and smaller. It is why the FLOP estimate of Appendix D (roughly six times parameters times tokens) is dominated by the matmuls and ignores almost everything else. And it focuses optimization effort with a clear rule: making the matmuls faster — better GEMM kernels (Section 18.4), lower precision, fuller use of the tensor cores — is making the model faster, because almost nothing else takes meaningful time. When you understand that a transformer is, computationally, a tall stack of matrix multiplications with some inexpensive glue between them, the hardware choices, the precision work, and the kernel engineering of the surrounding chapters all fall into place as attacks on the one operation that matters.

A transformer is mostly matmuls Attention projections, FFNs, and experts are all GEMMs, and they dominate the compute. That is why GPUs and tensor cores rule, why low precision pays off so well, and why optimizing the matrix multiply optimizes the model — almost nothing else takes meaningful time.