Lecture 4 · Quantization: Number Formats, Block Scaling, and What Bits Cost

Hardware Accelerators for Machine Learning · Lecture 04。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 4 · Thu 01/15/2026 · Quantization. HW1 is out: analytical modeling of LLM arithmetic performance. Reading (from the schedule):

  • B. Rouhani et al., With shared microexponents, a little shifting goes a long way, ISCA 2023;
  • NVIDIA, the NVFP4 format (technical blog, 2025);
  • W. Jang, T. Tambe, BlockDialect: block-wise fine-grained mixed format quantization for energy-efficient LLM inference, 2025.

Basis: The slides are not public. The format definitions follow the specifications: IEEE 754, the OCP 8-bit floating point (FP8) formats of Micikevicius et al. (2022), the OCP Microscaling (MX) v1.0 specification (2023), and NVIDIA’s description of NVFP4. The quantization techniques follow the cited papers (LLM.int8(), SmoothQuant). Numbers quoted from papers are labelled. All experiments use synthetic, seeded data and 45 nm cost models written for these notes (numfmt.py, quant.py, arith_cost.py); they do not reflect what was said in class and report error metrics, not model accuracy. Code: code/lecture04/ (4 scripts + 3 modules; each runs in 1–4 s) Reading time: 4–5 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain the three things a smaller number format buys: cheaper arithmetic (multiplier cost grows ~quadratically with significand width), less memory traffic and energy (linear in bits), and more model per memory capacity. Say which of them matters for which workload.
  2. Decode any binary format bit by bit — sign, exponent, bias, mantissa, subnormals, special values — and compute its range, precision and dynamic range: INT8/4, FP32, FP16, BF16, FP8 E4M3/E5M2, FP6 E2M3/E3M2, FP4 E2M1.
  3. Round a real number into a format with round-to-nearest-even, explain stochastic rounding, and explain why narrow accumulators fail.
  4. Quantize a tensor with per-tensor, per-channel and per-group scales. Predict the error from the “6 dB per bit” rule and from the data’s tails, and use clipping where it pays.
  5. Explain block floating point and the modern block formats: MXFP8/6/4 and MXINT8 (32 elements per power-of-two scale), NVFP4 (16 elements per FP8 scale, plus a tensor scale), two-level shared microexponents, and per-block format selection (BlockDialect).
  6. Explain why LLM weights quantize easily and activations do not (outlier channels), and how FP8, block scales and SmoothQuant respond.
  7. Price a format in hardware: multiplier energy and area, the dominance of the FP32 accumulator, exact fixed-point block accumulation, and prologue vs epilogue scaling (HW2).
  8. Predict the effect of the weight format on an LLM’s footprint, decode throughput and prefill time (HW1).

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 1: energy table, roofline, decode is memory-boundnumber formats, rounding, scales, block formatswhere scaling happens in the datapath (L6, HW2)
Lecture 3: energy accountingquantization error metrics, outliers, SmoothQuantquantized weights in memory systems and compression (L7)
binary numbers, 2k2^kthe cost of arithmetic vs formatFP8/FP4 tensor cores in GPUs (L11, L17)

0.3 Map

§1  why quantize: three savings and one constraint
§2  number formats bit by bit; rounding; accumulation                          ← code 01
§3  quantizing a tensor: scales, granularity, tails, clipping                  ← code 02 (Parts 1, 2, 5)
§4  block formats: BFP, shared microexponents, MX, NVFP4, BlockDialect         ← code 02 (Parts 3, 4)
§5  quantizing LLMs: weights vs activations, outliers, SmoothQuant, accumulation ← code 03
§6  what formats cost in hardware; prologue vs epilogue (HW2)                   ← code 04 (Parts 1-3)
§7  system-level impact on LLM inference (HW1)                                 ← code 04 (Part 4)
§8  quantization for training
§9 summary   §10 pitfalls   §11 exercises   §12 further reading   §13 next lecture

0.4 Notation

SymbolMeaning
EeeMmma float format with ee exponent bits and mm mantissa bits (plus a sign bit)
p=m+1p = m + 1significand width (the mantissa plus the hidden leading 1)
biasvalue subtracted from the exponent field
epsgap between 1.0 and the next value, 2−m2^{-m}
ssa scale: real value ≈ s×s \times (stored value)
SQNRsignal-to-quantization-noise ratio, 10log⁡10(∑x2/∑(x−x^)2)10\log_{10}(\sum x^2/\sum(x - \hat x)^2) dB
g128one scale per group of 128 elements
WaaAbbweights in aa bits, activations in bb bits

1. Why quantize?

1.1 Intuition: measuring with a coarser ruler

A measurement is only as good as the ruler’s marks. If you know that you only ever measure things between 1 m and 2 m, and only need centimetres, a ruler with 100 marks suffices — no need for a laser interferometer. Quantization is choosing the coarsest ruler that still does the job, and placing its marks where the values actually are. A number format is a ruler with a fixed set of marks; a scale slides and stretches it.

1.2 What fewer bits buy

The previous lectures showed three costs, and every one shrinks with the number of bits:

  1. Arithmetic. A multiplier is an array of partial products. Its area and energy grow roughly with the square of the significand width (Horowitz’s integer multipliers: exponent ≈ 1.8, Lecture 1). Halving the bits gives ~3–4× more multipliers per mm² and per joule.
  2. Data movement. Every buffer, register and DRAM access costs energy proportional to the bytes moved (Lecture 3). Batch-1 LLM decode spends 97% of its energy on reading weights from DRAM. Halving the bits halves that energy, and — since decode is bandwidth-bound — doubles its speed (Lecture 1).
  3. Capacity. A 70-billion-parameter model needs 141 GB in BF16, which does not fit on one 80 GB GPU; in FP8 it does (§7).

And one constraint: the model must still work. Quantization error is noise injected into every operation. Most of this lecture is about putting the few available values where they hurt least.

1.3 A brief history

ML hardware has walked down the precision ladder:

  • FP32: GPUs before 2017.
  • FP16 and BF16 tensor cores (2017–2020). BF16 came first on TPUs because it keeps FP32’s range.
  • INT8 inference: TPU v1, 2015.
  • FP8 (E4M3 and E5M2): NVIDIA H100, 2022, standardized jointly by NVIDIA, Arm and Intel.
  • Block-scaled 4–8-bit formats: the OCP MX specification (2023, AMD, Arm, Intel, Meta, Microsoft, NVIDIA, Qualcomm), building on Microsoft’s shared-microexponent work (this lecture’s ISCA reading); and NVIDIA’s NVFP4 on Blackwell (2024–2025).

Each step needed a new idea to keep accuracy: wider exponent ranges, scaling, and finally scales per small block of elements.


2. Number formats bit by bit

2.1 Integers and fixed point

A kk-bit integer stores q∈[−2k−1,2k−1−1]q \in [-2^{k-1}, 2^{k-1}-1] (two’s complement), and with a scale ss it represents x≈s qx \approx s\,q. The grid is uniform: the step is ss everywhere. For quantization, a symmetric range [−(2k−1−1),2k−1−1][-(2^{k-1}-1), 2^{k-1}-1] is common, so that +x+x and −x-x quantize alike and zero is exact. Fixed point is the same thing with a power-of-two scale fixed at design time.

2.2 Floating point

A binary float stores a sign SS, an exponent field EE (ee bits) and a mantissa field MM (mm bits):

x=(−1)S×2E−bias×1.M(normal,E>0),x=(−1)S×21−bias×0.M(subnormal,E=0).x = (-1)^S \times 2^{E - \text{bias}} \times 1.M \quad (\text{normal}, E > 0), \qquad x = (-1)^S \times 2^{1 - \text{bias}} \times 0.M \quad (\text{subnormal}, E = 0).

Each binade [2e,2e+1)[2^e, 2^{e+1}) holds 2m2^m equally spaced values, spaced 2e−m2^{e-m} apart. So the relative precision is the same in every binade: eps =2−m= 2^{-m}. Exponent bits buy range; mantissa bits buy precision. Subnormals continue the smallest binade’s spacing down to zero (“gradual underflow”). The top exponent code may be reserved for specials: IEEE formats use it for ±∞ and NaN; FP8 E4M3 keeps it for numbers except a single NaN pattern; the MX FP6/FP4 formats have no specials at all.

Script 01, Part 1 tabulates the formats used in ML:

formatlayoutbiasmaxmin normalmin subnormalepsrange (decades)specials
FP32E8M231273.4e381.2e-381.4e-451.2e-783inf, NaN
FP16E5M101565,5046.1e-56.0e-89.8e-412inf, NaN
BF16E8M71273.4e381.2e-389.2e-417.8e-379inf, NaN
FP8 E4M3E4M374480.01560.001950.1255.4NaN only
FP8 E5M2E5M21557,3446.1e-51.5e-50.259.6inf, NaN
FP6 E2M3E2M317.510.1250.1251.8none
FP6 E3M2E3M23280.250.06250.252.7none
FP4 E2M1E2M11610.50.51.1none

Some details worth noticing:

  • FP16 vs BF16: the same 16 bits, split differently. BF16 keeps FP32’s 8-bit exponent and so its range. It converts to and from FP32 by rounding away or padding 16 bits, and almost never overflows — which made it the default for training. FP16 has 8× finer precision but a max of 65,504 and a min of ~6e-8; gradients underflow, hence “loss scaling” (§8).
  • E4M3 vs E5M2: E4M3 gives up infinities and keeps only one NaN pattern (S.1111.111) to reach a max of 1.75×28=4481.75 \times 2^8 = 448 with 3 mantissa bits. It is used for weights and activations. E5M2 keeps IEEE conventions and range (57,344) and is used for gradients.
  • FP4 E2M1 has exactly 15 values: 0,±0.5,±1,±1.5,±2,±3,±4,±60, \pm 0.5, \pm 1, \pm 1.5, \pm 2, \pm 3, \pm 4, \pm 6. Alone it is nearly useless; with a scale per small block it runs LLMs (§4).

2.3 The grids

Script 01, Part 2 draws the same 4 bits as FP4 and as INT4 scaled to the same maximum:

FP4 E2M1    0 |    |    |    |    |         |         |                   | 6
INT4 x 6/7  0 |        |       |        |       |        |       |        | 6

FP4 spends its codes near zero (0.5 apart) and spreads them at the top (2 apart). INT4 spaces them evenly. Which is better depends on the data: bell-shaped data has most of its values near zero, which favors the float.

2.4 Rounding to bits

To quantize xx: find its binade (exactly, with frexp), clamp the exponent at the subnormal minimum, divide by the binade’s spacing, round to an integer, multiply back, and saturate at the max. The default rounding is round to nearest, ties to even. A value exactly halfway between two neighbours goes to the one with an even mantissa, so ties do not bias sums upward. In FP4, 2.5 → 2 and 3.5 → 4. Script 01, Part 3 shows bit patterns, e.g. 0.1 in E4M3 is 0 0011 101 = 0.1016.

The implementation is checked against independent references:

  • FP16 agrees with numpy’s float16 cast on 100,000 / 100,000 random values;
  • BF16 agrees with the classic “add 0x7FFF + LSB, shift by 16” bit trick on 100,000 / 100,000;
  • every code of every 4–8-bit format survives decode → encode;
  • the self-test compares rounding with a brute-force nearest-value search, including exact midpoints.

2.5 Relative vs absolute error

Script 01, Part 4 quantizes values from 10−810^{-8} to 10710^{7} without any scaling (median relative error):

|x|FP16BF16FP8 E4M3FP8 E5M2INT8, scale 1/127
1e-64.0e-3 (subnormal)1.4e-3lostlostlost
1e-21.7e-41.4e-32.5e-24.4e-25.4e-2
11.7e-41.4e-32.2e-24.5e-2lost (saturated)
1e42.0e-41.4e-3lost5.3e-2lost

A float keeps about eps/5 relative error everywhere inside its range, and loses everything outside it. An integer with a fixed scale has a constant absolute step, so it is precise only near the top of its range. That is why integer formats need scales fitted to each tensor, channel or block, and why floats with few exponent bits (E4M3: 5.4 decades) need scales too.

2.6 Accumulation and stochastic rounding

Script 01, Part 5 adds 0.001 ten thousand times (exact result 10), keeping the running sum in a given format:

running sum kept inresult
FP32, nearest10.0004
FP16, nearest4.0
BF16, nearest0.5
BF16, stochastic rounding (5 runs)9.19 – 10.44

Once half the spacing of the sum’s binade exceeds the increment, every addition rounds back to the same value and the sum stalls. In FP16 this happens at 4 (spacing 2⁻⁸ in [4, 8)), in BF16 at 0.5. Two consequences:

  • Hardware accumulates wide. Tensor cores multiply FP16/BF16/FP8/FP4 and accumulate in FP32 (or INT32 for integers).
  • Training adds tiny updates to weights all the time. It keeps FP32 “master” weights, or uses stochastic rounding: round up with probability equal to the fractional distance, so that the expected result is exact.

3. Quantizing a tensor

3.1 Scales

A format’s grid is fixed; the data’s range is not. Scaling maps one onto the other: x≈s⋅Q(x/s)x \approx s \cdot Q(x/s), where QQ rounds to the format. The simplest choice is max scaling, s=max⁡∣x∣/(format max)s = \max|x| / \text{(format max)}: the largest value lands on the largest code, and nothing saturates. Asymmetric (affine) quantization adds a zero point for one-sided data such as post-ReLU activations. The symmetric version suffices for this lecture.

3.2 Six dB per bit — and the tails

Each extra bit halves a uniform quantizer’s step and cuts the noise power by 4: +6.02 dB per bit. Script 02, Part 1 (per-tensor max scaling):

dataINT4INT8dB per bitmax / std
Gaussian13.738.96.35
Laplace7.532.26.211
Student-t (3 dof, heavy tails)0.813.63.292
LLM-like weights9.734.86.38

The Student-t tensor has one value 92 standard deviations out. Max scaling stretches the grid to reach it, and the typical values land on a handful of levels: per-tensor INT8 on heavy-tailed data (13.6 dB) is worse than INT4 on Gaussian data. Trained networks are full of heavy tails, which is why per-tensor max scaling is rarely good enough.

3.3 Granularity: per tensor, per channel, per group

Finer scales fit the data locally. Script 02, Part 2, INT4 with FP16 scales:

datatensorrow (channel)g128g64g32g16
Student-t0.85.213.014.916.919.1
LLM-like weights9.716.118.619.420.321.4
bits / element4.00~4.004.1254.254.55.0

Per-channel scales absorb the spread between output channels (9.7 → 16.1 dB on the weights). Groups confine each outlier’s damage to its own group: on Student-t data, g16 recovers 18 dB over per-tensor. Each halving of the group size buys ~1–2 dB for 16 more scale bits per group, and below g32 the scales cost more bits than they save. Weight-only LLM quantization standardized on INT4 with an FP16 scale per 128 weights (g128) for this reason.

3.4 Clipping

Max scaling wastes the grid on rare extremes. Mapping a fraction of the maximum, c⋅max⁡∣x∣c \cdot \max|x|, onto the top code saturates a few values but refines the grid for all others. Script 02, Part 5 searches for the MSE-optimal clip ratio:

dataquantizerSQNR at clip 1best clipSQNR at best clip
GaussianINT4 per row16.00.6618.7
Student-tINT4 per row5.30.348.4
GaussianINT8 per tensor39.40.8240.5
Student-tINT8 per tensor13.70.5416.7

Clipping pays most when bits are few (+2.7 to +3.7 dB for INT4 on all three distributions) or tails are heavy (+3.0 dB for INT8 on Student-t, +1.2 on Gaussian). Choosing scales to minimize error on calibration data, rather than from the maximum, is the first step of every post-training quantization recipe. Methods such as GPTQ and AWQ go further, adjusting the rounding of each weight to minimize the layer’s output error rather than each weight’s own error.


4. Block formats

4.1 Block floating point

Push granularity to the extreme: give every block of a few elements its own scale, and make the scale a power of two (just an exponent) so that applying it is a shift. That is block floating point (BFP): a block shares one exponent, and each element stores a sign and a few mantissa bits. It is an old DSP idea. Its attraction for hardware is that a dot product of two BFP blocks is an integer dot product followed by one exponent addition:

∑i(2Xai)(2Ybi)=2X+Y∑iaibi.\sum_i (2^{X} a_i)(2^{Y} b_i) = 2^{X+Y} \sum_i a_i b_i .

4.2 Shared microexponents (the ISCA reading)

A single shared exponent is set by the block’s largest element. Elements much smaller than it lose bits, and the larger the block, the worse. Rouhani et al. (ISCA 2023) propose two-level scaling: a block of 16 shares an 8-bit exponent, and each pair of elements shares an extra 1-bit microexponent that shifts the pair’s scale down by one when both elements are small. Average storage: element bits + 8/16 + 1/2 bits. The family’s names count the average bits per element (MX9, MX6, MX4), and the paper’s title sums up the finding: one extra bit of shifting per pair recovers much of what the shared exponent loses. numfmt.smx_quantize implements the idea in simplified form. With 4 magnitude bits (6 bits per element in all) it reaches 26–28 dB in script 02, Part 3.

4.3 OCP Microscaling (MX)

The industry standard that followed, the OCP MX specification v1.0 (2023), keeps a single level but standardizes the pieces:

  • a block of 32 elements;
  • one E8M0 scale per block: an 8-bit exponent, i.e. a power of two between 2−1272^{-127} and 21272^{127};
  • elements in FP8 (E4M3 or E5M2), FP6 (E2M3 or E3M2), FP4 (E2M1) or INT8 (MXINT8: 8-bit two’s complement with an implicit 2−62^{-6});
  • the scale rule: shared exponent X=⌊log⁡2max⁡∣x∣⌋−emax⁡elemX = \lfloor \log_2 \max|x| \rfloor - e_{\max}^{\text{elem}}, so the block’s largest element lands in the element format’s top binade, and elements are converted with saturation.

Bits per element: MXFP8 8.25, MXFP6 6.25, MXFP4 4.25, MXINT8 8.25.

4.4 NVFP4

NVIDIA’s NVFP4 (Blackwell GPUs) keeps FP4 E2M1 elements but changes the scaling in two ways:

  • blocks of 16 instead of 32: finer granularity;
  • an E4M3 scale instead of E8M0. With 3 mantissa bits the scale can map the block’s maximum exactly onto FP4’s top value 6, instead of somewhere in [4, 8) as a power of two does.

E4M3 has only 5.4 decades of range, so a per-tensor FP32 scale g=max⁡∣x∣/(448⋅6)g = \max|x| / (448 \cdot 6) positions the tensor in it. Storage: 4 + 8/16 = 4.5 bits per element.

4.5 BlockDialect: let each block choose its format

Blocks of an LLM tensor differ in shape: some are nearly uniform, others have one large value and many small ones. BlockDialect (Jang & Tambe, 2025) gives each block a choice of 4-bit format (“dialect”) from a small format book, chosen to fit the block, and stores the choice in a few extra bits. The paper’s book consists of FP4 variants with different large values, designed for hardware that decodes them cheaply. quant.dialect_quantize is a simpler illustration with three grids — FP4 E2M1, uniform (INT4-like) and logarithmic — on NVFP4-style scales.

4.6 Experiment: fourteen formats on four tensors

Script 02, Part 3 (SQNR in dB):

formatbits/elemGaussianLaplaceStudent-tLLM weights
MXINT88.2541.740.137.942.0
MXFP8 E4M38.2530.630.029.430.5
MXFP8 E5M28.2525.425.225.025.3
INT8 per-tensor838.932.213.634.8
MXFP6 E2M36.2530.930.329.231.0
shared microexp. (6 bits)628.327.326.428.4
4-bit format selector, blocks of 164.62522.121.622.122.1
NVFP44.520.420.720.920.4
INT4 g32 (FP16 scale)4.520.318.316.920.3
MXFP44.2518.818.017.018.8
INT4 g1284.12518.615.913.018.6

Four lessons:

  1. Block scaling makes the error nearly independent of the distribution. MXFP8 E4M3 ranges only from 29.4 to 30.6 dB across the four tensors, where per-tensor INT8 ranges from 13.6 to 38.9.
  2. Inside a scaled block, mantissa bits decide; exponent bits are wasted. MXFP6 E2M3 equals MXFP8 E4M3 (both have 3 mantissa bits), MXFP6 E3M2 equals MXFP8 E5M2 (2 mantissa bits), and MXINT8 — 7 magnitude bits — beats MXFP8 E4M3 by ~10 dB at the same storage. The block scale already supplies the range. E4M3 even clips slightly more, because the OCP scale rule maps a block’s max into [256, 512) while E4M3 stops at 448.
  3. At ~4.5 bits, the scale matters. NVFP4 beats MXFP4 by 1.6–3.9 dB with finer (E4M3) scales on smaller (16) blocks. Letting each block choose its format adds another ~1.4 dB on average for 2 selector bits per block. On the Student-t tensor our selector picked FP4 for 55% of blocks, the uniform grid for 38% and the log grid for 7%.
  4. Storage overhead is small but real: +0.25 bits for MX, +0.5 for NVFP4, plus decoding and scale arithmetic in hardware (§6).

SQNR vs bits

Figure (script 02): SQNR vs storage bits per element for all formats and datasets. Block formats cluster tightly across datasets; per-tensor INT8 does not.

4.7 Block size

Script 02, Part 4 sweeps the block size for 4-bit elements on the Student-t tensor:

scaleblock 8163264128256
E8M0 (MX-style)17.717.517.016.215.113.7
E4M3 (NVFP4-style)22.520.919.518.016.414.7
FP16, INT4 elements21.519.116.914.913.011.2

Smaller blocks always help, and finer scales help more at small blocks. The power-of-two scale gains little from smaller blocks: it wastes up to one bit per block whatever the block size, by placing the maximum anywhere in [max/2, max] of the element grid. Each halving of the block doubles the scale storage, and (§6) the scale arithmetic per MAC.


5. Quantizing LLMs

5.1 Weights are easy, activations are hard

Weights are fixed: they can be analyzed offline, given per-channel or per-group scales, and even re-rounded with care (GPTQ, AWQ). Activations change with every input and must be quantized on the fly. And LLM activations have a peculiar structure. Dettmers et al. (LLM.int8(), 2022) observed that beyond a few billion parameters, a handful of feature dimensions carry values up to 20–100× larger than the rest, in almost every token. quant.llm_activations imitates this: 256 tokens × 2048 channels, 6 of which are 40× larger.

Script 03, Part 1 measures what each activation quantizer does to the normal channels:

activation quantizerSQNR, normal channels (dB)
INT8 per tensor5.8
INT8 per token12.7
FP8 E4M3 per tensor31.5
MXFP8 E4M3 (blocks of 32 channels)30.5
MXINT825.5
INT4 per token0.0
NVFP4 (blocks of 16 channels)15.5

Under per-tensor INT8, the step is set by the outliers (2.0), and a typical normal channel (max |x| ≈ 3.1) uses about 2 of the 127 levels. Per-token scales hardly help, because every token contains the outliers. FP8’s exponent solves it: small values sit in their own binades with the same relative precision as large ones. Block formats confine the damage to the few blocks that contain an outlier. This is why FP8 became the default for activations on H100-class hardware, and why 4-bit activations need block scales.

5.2 One layer, fourteen schemes

Script 03, Part 2 computes Y=XW⊤Y = XW^\top (256 tokens, 2048 → 2048) under each scheme (relative output error):

schemeW bitsA bitsoutput error
W INT8 per channel, A BF168160.008
W INT4 per channel4160.147
W INT4 g1284.125160.117
W MXFP44.25160.113
W NVFP44.5160.094
W8A8 INT, A per tensor880.170
W8A8 INT, A per token880.077
W8A8 FP8 E4M3 per tensor880.038
MXFP8 both8.258.250.050
MXFP6 both6.256.250.051
W4A8 (INT4 g128 / INT8 per token)4.12580.140
W4A4 INT4.12540.354
MXFP4 both4.254.250.189
NVFP4 both4.54.50.112

(These are output errors of a synthetic layer, not task accuracy. Real 4-bit weight-only models typically lose little accuracy because errors average out over many layers and tokens; the ranking of schemes is the point.)

  • INT8 weights alone are almost free (0.008).
  • Quantizing activations to INT8 with one scale costs 20× more (0.170): the outliers.
  • FP8 for both operands gives 0.038, better than MXFP8 (0.050). Per-tensor E4M3 has enough range for both the outliers and the normal channels, and no top-binade clipping.
  • 4-bit activations are usable only with fine-grained float block scales. INT4 per token gives 0.354; NVFP4 for both operands gives 0.112, about the same as NVFP4 weights alone (0.094).

Layer error

Figure (script 03): relative output error of one LLM-like layer; blue = weight-only, orange = weights and activations.

5.3 SmoothQuant: move the difficulty into the weights

Since Y=XW⊤=(Xdiag⁡(s)−1)(Wdiag⁡(s))⊤Y = XW^\top = (X \operatorname{diag}(s)^{-1})(W \operatorname{diag}(s))^\top exactly, a per-channel factor sjs_j can be moved from activations to weights. SmoothQuant (Xiao et al., 2023) chooses sj=max⁡∣Xj∣α/max⁡∣Wj∣1−αs_j = \max|X_j|^\alpha / \max|W_j|^{1-\alpha}, shrinking the outlier channels and enlarging the matching weight columns, and folds ss into the previous layer offline. Script 03, Part 3:

αactivation max / median channel maxW8A8 per-tensor errorW4A8 error
085.60.1760.147
0.2528.20.0600.063
0.59.30.0230.068
0.753.00.0270.116
1.01.00.0740.157

At α = 0.5 the W8A8 error falls 7.6× to 0.023, at zero runtime cost. With 4-bit weights the best α is lower (0.25): 4-bit weights have less room to absorb the range. Pushed to α = 1, the weights inherit the whole problem.

5.4 Accumulation again

A quantized dot product multiplies narrow numbers but adds many of them. Script 03, Part 4 sums 2,048 products of BF16 values (each product exact), keeping partial sums in a given format:

accumulatorrunning sumadder tree
FP323.7e-76.5e-8
FP165.9e-38.1e-4
BF164.7e-26.0e-3

A BF16 accumulator makes a 2048-long dot product wrong by ~5%, more than any input quantization in §5.2. A tree is ~8× better than a running sum, because it adds numbers of similar magnitude at every level. Multiply narrow, accumulate wide is a design rule, not an option — and it is what makes the accumulator a major cost (§6).


6. What formats cost in hardware

6.1 Multipliers and MACs

arith_cost.py prices integer units with Horowitz’s power-law fits. It prices float units by significand width pp (a power law through Horowitz’s FP16, p=11p = 11, and FP32, p=24p = 24): a float multiplier is essentially a p×pp \times p integer multiplier plus a small exponent adder. Script 04, Part 1 (45 nm):

formatmultiply pJmultiplier µm²per FP16 areaMAC pJaccumulatormultiplier share
FP323.707,7000.2×4.60FP3280%
FP161.101,6401×2.00FP3255%
BF160.678721.9×1.57FP3243%
INT80.202825.8×0.30INT3267%
FP8 E4M30.232217.4×1.13FP3220%
INT40.058020.5×0.15INT3234%
FP4 E2M10.085629.4×0.98FP328%

Multipliers shrink fast: an FP8 multiplier fits 7× more per area than an FP16 one, and FP4 29× more. This is the source of the “2× TOPS per halving of the bits” in every GPU generation. But a MAC is a multiply and an add. With an FP32 accumulator, the multiply is only 20% of an FP8 MAC and 8% of an FP4 MAC: below FP16, the accumulator decides the energy.

6.2 Exact block accumulation

Narrow float products have a small dynamic range. Every product of two FP4 E2M1 values is a multiple of 0.25 between 0.25 and 36, so it is a small integer in units of 0.25. A sum of 32 such products fits exactly in a 14-bit integer: no rounding, no exponent alignment, no normalization. Script 04, Part 2:

element formatexact accumulator for 32 termspJ/MAC, FP32 accumulatepJ/MAC, fixed-point tree + 1 FP32 add per block
FP8 E4M342 bits1.130.38
FP8 E5M270 bits1.050.37
FP6 E2M318 bits1.130.32
FP4 E2M114 bits0.980.16 (6.3×)

This is the hardware argument for block formats with small element exponents. The block’s dot product becomes an integer adder tree, and the expensive FP32 machinery is touched once per block. E5M2’s range makes exact accumulation impractical (70 bits), one more reason it is reserved for gradients.

6.3 Prologue vs epilogue scaling (HW2)

Where should the block scales be applied? Since ∑i(sai)(tbi)=st∑iaibi\sum_i (s a_i)(t b_i) = st \sum_i a_i b_i, there are two options:

  • Prologue: rescale every element on arrival — for power-of-two scales, an 8-bit exponent addition per element per operand, turning MX elements into BF16 — then use a BF16 datapath with FP32 accumulation.
  • Epilogue: multiply the narrow elements, sum them exactly in the block’s integer adder tree, then apply s⋅ts \cdot t once per block (add two 8-bit exponents) and add the block result into FP32.

Script 04, Part 3:

format (block 32)prologue pJ/MACepilogue pJ/MACratio
MXFP8 E4M31.630.384.2×
MXFP6 E2M31.630.325.1×
MXFP41.630.1610.5×
per 32-element blockprologueepilogue
scale operations641
multiplies32 in BF1632 in the narrow format
accumulations32 in FP3231 exact integer adds + 1 FP32 add

The epilogue wins because the scales factor out of the dot product. The prologue throws away the narrow format’s advantage by widening every element before the arithmetic. The price of the epilogue is that the datapath must understand the block structure: the dot-product unit’s reduction must align with the scale blocks. That is a constraint on mapping (Lecture 9) and on the vector unit that handles everything else (Lecture 6). Smaller blocks cost more per MAC (0.237 pJ at block 8 vs 0.135 at block 128) — the hardware side of §4.7’s accuracy gain.

Cost per format

Figure (script 04): left, MAC energy split into multiply and accumulate; right, multipliers per FP16-multiplier area.


7. System-level impact on LLM inference (HW1)

HW1 asks for analytical models of LLM arithmetic performance. With Lecture 1’s roofline tools and the bits per element of this lecture, script 04, Part 4 estimates Llama 3 at batch 1 with a 2,048-token context:

modelweightsweight bytesH100: fits?H100 decode tok/sB200 decode tok/sB200 prefill (2,048 tokens)
Llama 3 8BBF1616.1 GByes21952318.9 ms
FP88.0 GByes4291,02512.5 ms
INT4 g1284.1 GByes8041,9209.3 ms
NVFP44.5 GByes7411,7719.3 ms
Llama 3 70BBF16141 GBno(24 if it fit)57155 ms
FP870.6 GByes4811492.5 ms
NVFP439.7 GByes8420061.3 ms

Three effects, three mechanisms:

  • Decode is bandwidth-bound (Lecture 1), so its speed is inversely proportional to the bytes of weights: NVFP4 weights decode 3.4× faster than BF16 on the same GPU. The extra scale bits show: INT4 g128 (4.125 bits) beats NVFP4 (4.5 bits) on speed, though not on accuracy.
  • Capacity: the 70B model fits on one H100 only from FP8 down.
  • Prefill is compute-bound, so it gains from low-precision arithmetic: FP4 tensor cores on the B200 halve the 8B prefill time. That is only 2× despite a 4× higher peak, because the unfused attention operators are memory-bound and now dominate (softmax alone is 2.2 of 9.3 ms). Amdahl again; fusion (Lecture 10) is the fix.

8. Quantization for training

Training is harder than inference: gradients span many decades, and weight updates are tiny compared with the weights. The established techniques:

  • Mixed precision with loss scaling (FP16 era): compute in FP16, keep FP32 master weights, and multiply the loss by a large factor so that small gradients do not underflow FP16’s 6e-8 minimum. BF16, with FP32’s range, made loss scaling unnecessary.
  • FP8 training (Micikevicius et al., 2022): E4M3 for weights and activations in the forward pass, E5M2 for gradients, with per-tensor scales. The scales are typically chosen from the amax history of previous iterations (“delayed scaling”), so the hardware does not have to compute a max before every operation. Accumulation and master weights stay in FP32.
  • Block-scaled training: MX formats were proposed for training as well as inference, with MXFP8 as the conservative choice. NVIDIA has described pretraining LLMs with NVFP4 for most GEMMs, with care around sensitive layers and stochastic rounding of gradients. Treat 4-bit training as active research.
  • Stochastic rounding (§2.6) keeps small updates from vanishing in low-precision weights.

9. Summary

  1. Fewer bits buy cheaper arithmetic (~quadratic in significand width), less data movement (linear) and more capacity. The constraint is accuracy.
  2. A float format is sign + exponent + mantissa: exponent bits buy range, mantissa bits buy precision. FP16 vs BF16 and E4M3 vs E5M2 are the same trade at 16 and 8 bits. FP4 E2M1 has 15 values.
  3. Round to nearest-even; saturate on overflow. Accumulate wide: FP16/BF16 running sums stall (4.0 and 0.5 instead of 10), and a BF16 accumulator is ~5% wrong on a 2048-long dot product. Stochastic rounding is unbiased.
  4. Uniform quantizers give ~6 dB per bit, but heavy tails ruin max scaling. Finer granularity (channel, group) and clipping recover the loss.
  5. Block formats (MX: 32 per E8M0 scale; NVFP4: 16 per E4M3 scale plus a tensor scale) make error nearly distribution-independent. Inside a block mantissa bits decide (MXFP6 E2M3 = MXFP8 E4M3; MXINT8 is best at 8 bits). Finer scales and smaller blocks win at 4 bits. Per-block format choice (BlockDialect) adds more.
  6. LLM activations have outlier channels: per-tensor INT8 leaves normal channels ~2 levels. FP8, block scales or SmoothQuant (W8A8 error 0.176 → 0.023) fix it; 4-bit activations need fine block scales.
  7. In hardware, the FP32 accumulator dominates low-precision MACs. Exact integer block accumulation (14 bits for 32 FP4 products) and epilogue scaling (10× cheaper than the prologue for MXFP4) are what make block formats efficient.
  8. For LLM inference, weight bits set decode speed and capacity (3.4× faster decode with NVFP4 than BF16; 70B fits one H100 from FP8), while compute formats set prefill, up to Amdahl’s limit.

10. Common pitfalls

  • “More bits in the element format = more accurate.” Not inside a scaled block: exponent bits beyond what the block needs are wasted (MXFP6 E2M3 = MXFP8 E4M3).
  • “FP8 is FP8.” E4M3 and E5M2 differ in range by 128× and in precision by 2×; they are used for different tensors.
  • “Per-token scales fix activation outliers.” Not when the outliers live in fixed channels of every token (12.7 vs 5.8 dB).
  • “Quantization error = input rounding error.” Accumulation in a narrow format can be worse than any input format.
  • “An FP4 MAC costs a quarter of an FP16 MAC.” Not with an FP32 accumulator (0.98 vs 2.00 pJ); only with block-level exact accumulation (0.16 pJ).
  • “Apply the scale when you load the data.” That is the prologue: 4–10× more energy than applying it once per block.
  • “4-bit weights make inference 4× faster than BF16.” Decode gets up to the ratio of bytes (3.4–3.7× here, minus scale overhead); prefill gets the arithmetic speedup only up to Amdahl’s limit (2× here).
  • “The MX scale rule is optimal.” It can clip the block maximum (E4M3: [448, 512) of the top binade); see Exercise 11.

11. Exercises

Exercise 1 (encoding by hand). Encode 0.3 in FP8 E4M3. Give the bits, the stored value and the relative error.

Answer

0.3 is in the binade [0.25, 0.5) = [2⁻², 2⁻¹), with spacing 2⁻²⁻³ = 0.03125. Then 0.3 / 0.03125 = 9.6, which rounds to 10, giving 10 × 0.03125 = 0.3125 = 1.25 × 2⁻². Exponent field −2 + 7 = 5 = 0101; mantissa 0.25 = .010. Bits 0 0101 010; value 0.3125; relative error 4.2%.

Exercise 2 (why BF16 trains and FP16 needs loss scaling). Gradients of a large model often lie between 1e-8 and 1e-3. Which of them can FP16 represent? BF16? What does loss scaling by 1,024 change?

Answer

FP16’s smallest subnormal is 6.0e-8 and its smallest normal 6.1e-5. Values below ~3e-8 flush to zero, and those between 6e-8 and 6e-5 keep only a few significant bits. BF16’s range reaches 1e-38, so all of them are representable, with 8 significant bits. Multiplying the loss (hence all gradients) by 1,024 shifts the range up by 2¹⁰ to ~1e-5 to 1, inside FP16’s normal range. The scale is divided out before the weight update, in FP32.

Exercise 3 (the MX scale rule). A block of 32 values has max |x| = 3.7. With MXFP4, what is the shared exponent, what happens to 3.7, and what would a “no-clip” rule X=⌈log⁡2(max⁡∣x∣/6)⌉X = \lceil \log_2(\max|x| / 6) \rceil give?

Answer

OCP rule: X=⌊log⁡23.7⌋−2=1−2=−1X = \lfloor \log_2 3.7 \rfloor - 2 = 1 - 2 = -1, scale 0.5. Then 3.7 / 0.5 = 7.4 exceeds FP4’s max of 6 and saturates, so it is stored as 6 × 0.5 = 3.0, a 19% error on the block’s largest element. The numfmt.mx_quantize call in the author’s check returns 3.0. No-clip rule: ⌈log⁡20.617⌉=0\lceil \log_2 0.617 \rceil = 0, scale 1, and 3.7 rounds to 4, an 8% error — but every other element of the block now sees a 2× coarser grid. Which rule is better on average depends on the format (Exercise 11).

Exercise 4 (NVFP4 by hand). The same block, in an NVFP4 tensor whose max |x| is 100. Compute the tensor scale, the block scale and the stored value of 3.7.

Answer

g=100/(448⋅6)=0.0372g = 100 / (448 \cdot 6) = 0.0372. Block scale s=3.7/6/g=16.57s = 3.7 / 6 / g = 16.57. In E4M3 that lies in the binade [16, 32) with spacing 2, so it rounds to 16, and the scale becomes 16 × 0.0372 = 0.595. Then 3.7 / 0.595 = 6.22 saturates to 6, stored as 6 × 0.595 = 3.57 (3.5% error; the author’s check of nvfp4_quantize returns 3.571). Rounding the E4M3 block scale down caused the small saturation — the edge case documented in nvfp4_quantize.

Exercise 5 (bits per element and footprint). Compute the weight footprint of Llama 3 70B (70.55 B parameters) in BF16, FP8, INT4 g128 (FP16 scales), MXFP4 and NVFP4. Which fit in 80 GB with a 2,048-token BF16 KV cache (0.67 GB)?

Answer

Bits per element: 16, 8, 4.125, 4.25, 4.5, giving 141.1, 70.6, 36.4, 37.5 and 39.7 GB (script 04 Part 4). With the KV cache: 141.8 does not fit; 71.2, 37.0, 38.1 and 40.4 fit. Real deployments also need activations, the runtime and fragmentation headroom, so FP8 on one 80 GB GPU is tight in practice.

Exercise 6 (6 dB per bit). Per-tensor INT4 gives 13.7 dB on the Gaussian tensor. Predict INT6 and INT8 from the 6 dB rule and compare with script 02, Part 1. Why is the rule’s prediction a little off at 4 bits?

Answer

Prediction: 13.7 + 12 = 25.7 dB (INT6) and 37.7 dB (INT8); measured 26.6 and 38.9. At low bit counts, the max-scaled grid’s outermost levels are almost never used by Gaussian data, so each extra bit also adds levels where the data actually are. The effective gain is slightly above 6 dB per bit in this range (6.3 measured). With heavy tails, the gain per bit is lower (3.2 dB for Student-t from 4 to 8 bits): most added levels land where there is no data.

Exercise 7 (exact accumulators). Compute the width of an exact accumulator for a 32-term dot product of FP6 E2M3 values, and of INT4 values. Compare with script 04, Part 2.

Answer

FP6 E2M3: products are multiples of 0.125² = 1/64 up to 7.5² = 56.25, so log⁡2(56.25⋅64)=log⁡23600=11.8→12\log_2(56.25 \cdot 64) = \log_2 3600 = 11.8 → 12 bits of magnitude, plus log⁡232=5\log_2 32 = 5, plus a sign bit: 18 bits (matches). INT4 (symmetric, |q| ≤ 7): products ≤ 49, i.e. 6 bits (the formula uses 2(k−1)=62(k-1) = 6), + 5 + 1 = 12 bits.

Exercise 8 (counting scale operations). A 4,096-long dot product of two MXFP4 vectors (blocks of 32). How many scale operations does the prologue perform, and how many does the epilogue? What changes for NVFP4 (blocks of 16, E4M3 scales)?

Answer

Prologue: 2 × 4,096 = 8,192 element rescalings (exponent additions). Epilogue: 4,096 / 32 = 128 block scalings (one exponent addition each), plus 128 FP32 additions of block results. NVFP4: 256 blocks per vector, and each block scaling is now an E4M3 × E4M3 multiplication (a small float multiply) instead of an exponent addition. That is still per block, plus one FP32 multiply by the two tensor scales per dot product.

Exercise 9 (decode throughput by hand). Reproduce the 741 tok/s of Llama 3 8B with NVFP4 weights on an H100 (3.35 TB/s): which bytes does one decode step read? Why is the answer not simply 8.03 B × 4.5 / 8 / 3.35 TB/s?

Answer

Per step: the weights of all layers and of the output head, plus the KV cache (2 × 32 layers × 8 KV heads × 128 × 2 B = 131 kB per token × 2,048 = 0.27 GB), plus small activations. The embedding table (128,256 × 4,096 = 0.53 B parameters) is not read in full: only one row is looked up. So weight bytes ≈ (8.03 − 0.53) B × 0.5625 B = 4.22 GB. Total ≈ 4.49 GB / 3.35 TB/s = 1.34 ms → ~745 tok/s, matching the script’s 741 (which also counts activations). The naive estimate (4.52 GB of weights only) gives 1.35 ms and happens to land nearby, but for the wrong reasons.

Exercise 10 (SmoothQuant by hand). An activation channel has max |x| = 200 and the matching weight column max |w| = 0.05. Compute ss for α = 0.5 and the new maxima. Why is α = 0.5 a natural default?

Answer

s=2000.5/0.050.5=14.14/0.224=63.2s = 200^{0.5} / 0.05^{0.5} = 14.14 / 0.224 = 63.2. The new activation max is 200 / 63.2 = 3.16 and the new weight max is 0.05 × 63.2 = 3.16. At α = 0.5 the two maxima become equal (both 200⋅0.05\sqrt{200 \cdot 0.05}), splitting the difficulty evenly between two operands quantized with the same number of bits. When the weights get fewer bits than the activations (W4A8), a smaller α is better (0.25 in script 03).

Exercise 11 (programming: the MX scale rule). Add a rule="ceil" option to numfmt.mx_quantize that uses X=⌈log⁡2(max⁡∣x∣/elem max)⌉X = \lceil \log_2(\max|x| / \text{elem max}) \rceil (never clips), and compare SQNR with the OCP rule for all MX element formats on the Gaussian tensor of script 02.

Answer

In the author’s run: MXFP8 E4M3 30.6 → 31.5 dB (+0.9); E5M2, E2M3 and E3M2 +0.1; MXFP4 18.8 → 18.8 (no change). The ceil rule avoids clipping the block maximum but doubles the step for every element of the blocks whose max falls in the clipped zone. E4M3 gains the most: its top binade is cut at 448 by the NaN code, and with 3 mantissa bits a clipped maximum loses a lot relative to the small gain in step. For FP4, the clipped zone [6, 8) is a quarter of the top binade, but the element grid is so coarse that doubling the step costs as much as clipping saves.

Exercise 12 (programming: a bigger format book). Add two FP4 variants to quant.DIALECTS — the E2M1 values with the top value 6 replaced by 5, and by 8 — and rerun the selector (blocks of 16) on the Gaussian, Laplace and Student-t tensors. How much does SQNR improve, at what storage cost?

Answer

In the author’s run, SQNR rises from 22.1 → 22.7 dB (Gaussian), 21.6 → 22.5 (Laplace) and 22.1 → 23.1 (Student-t). The selector needs 3 bits instead of 2 per block of 16: 4.6875 instead of 4.625 bits per element. The new variants are chosen for 30–34% (top 5) and 6–22% (top 8) of the blocks; heavier tails choose the larger top more often. This is the BlockDialect idea in miniature: a richer book fits more block shapes, for a few selector bits and a decoder that must handle every dialect.

12. Further reading

  • B. Rouhani et al., “With shared microexponents, a little shifting goes a long way”, ISCA 2023; and B. Rouhani et al., “Microscaling data formats for deep learning”, 2023 (arXiv:2310.10537).
  • Open Compute Project, OCP Microscaling Formats (MX) Specification v1.0, 2023.
  • P. Micikevicius et al., “FP8 formats for deep learning”, 2022 (arXiv:2209.05433).
  • NVIDIA, “Introducing NVFP4 for efficient and accurate low-precision inference” (technical blog, 2025).
  • W. Jang, T. Tambe, “BlockDialect: block-wise fine-grained mixed format quantization for energy-efficient LLM inference”, 2025 (arXiv:2501.01144).
  • T. Dettmers et al., “LLM.int8(): 8-bit matrix multiplication for transformers at scale”, NeurIPS 2022.
  • G. Xiao et al., “SmoothQuant: accurate and efficient post-training quantization for large language models”, ICML 2023.
  • E. Frantar et al., “GPTQ: accurate post-training quantization for generative pre-trained transformers”, ICLR 2023; J. Lin et al., “AWQ: activation-aware weight quantization”, MLSys 2024.
  • P. Micikevicius et al., “Mixed precision training”, ICLR 2018 — loss scaling and FP32 master weights.
  • A. Gholami et al., “A survey of quantization methods for efficient neural network inference”, 2021.

13. Next lecture

Lecture 5, Systolic arrays, returns to the compute fabric. The MAC units of this lecture’s formats must be fed with operands at a rate of thousands per cycle without a thousand register-file reads. H. T. Kung’s 1982 answer is to pump data rhythmically through a grid of PEs, so that every value fetched from memory is used by a whole row or column. We will build a cycle-accurate systolic array with weight-, output- and input-stationary dataflows, watch data move through it cycle by cycle, model TPU v1’s 256 × 256 matrix unit and its roofline, and ask why TPU v4 used several 128 × 128 arrays instead of one big one.

← 返回课程目录