Maps to: CMU 11-711 Spring 2026, Lecture 19 (03/26), “Quantization”, Sean Welleck; slides
anlp-s2026-19-quantization.pdf; course code19_quantization/(basics.ipynb,llamacpp.ipynb). Readings: T. Dettmers et al., LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale (NeurIPS 2022); T. Dettmers et al., QLoRA: Efficient Finetuning of Quantized LLMs (NeurIPS 2023). Additional: T. Dettmers et al., 8-bit Optimizers via Block-wise Quantization (ICLR 2022); T. Dettmers, L. Zettlemoyer, The case for 4-bit precision: k-bit Inference Scaling Laws (ICML 2023). Sources: the public slides and notebooks, the readings, and the papers cited in each section. Numbers quoted from papers are attributed to them. Every number labelled “measured” comes fromcode/lecture19/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code:code/lecture19/— six demos, each under 70 seconds once the model is cached. Reading time: ~90 minutes for the prose; ~20 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Read the bits of an integer (unsigned, two’s complement) and of a floating-point number, and say what the exponent and mantissa widths of fp32, fp16, bf16, fp8 and fp4 buy.
- Quantize a tensor with absmax and zero-point quantization, at any granularity (per tensor, per row, per block), and predict the error from the step size.
- Multiply quantized matrices the way an int8 kernel does, and explain why the accumulator must be wider than the operands.
- Explain why outlier features break 8-bit activation quantization, and how LLM.int8()‘s mixed-precision decomposition and SmoothQuant’s scale migration fix it.
- Compare 4-bit data types (int4, FP4, NF4, NVFP4, MXFP4, llama.cpp’s Q4_K), account for the bits their scales cost, and reason about bits vs parameters at a fixed memory budget.
- Describe quantization-aware training (fake quantization, straight-through estimator) and QLoRA (NF4 + double quantization + paged optimizers + LoRA), and compute the memory each saves.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 5: the Transformer’s linear layers, RMSNorm, SwiGLU.
- Lecture 7: Fact World and scaling laws.
- Lecture 8: LoRA.
- Lecture 9: why decoding is memory-bound.
- Scope: the slides’ three parts: representing numbers, quantizing for inference (absmax, zero-point, LLM.int8(), GGML/llama.cpp, new formats), and quantizing with training (QAT, QLoRA). The readings add NF4, double quantization and k-bit scaling.
- Not in scope:
- Quantization kernels and their speed (everything here is simulated; §7 says what that hides).
- Second-order methods such as GPTQ, beyond a paragraph (§5.8).
- Pruning and sparsity, the other route to smaller models.
- Low-precision training from scratch (fp8 training), beyond a paragraph (§6.3).
0.3 Section → code map
| Section | Idea | Demo in code/lecture19/ |
|---|---|---|
| §2 | integers, floating point, what goes wrong with few bits | 01_number_formats.py (+ numfmt.py) |
| §3.2–3.5 | absmax, zero-point, error vs bits, outliers, granularity | 02_quantizers.py Parts A–D (+ quant.py) |
| §3.6 | int8 × int8 → int32 matrix multiplication | 02_quantizers.py Part E |
| §4 | outlier features, LLM.int8(), SmoothQuant | 03_outliers_llm_int8.py (+ fact_lm.py) |
| §5.2–5.6 | 4-bit data types, double quantization, k-quants, which facts are lost | 04_four_bits.py |
| §5.7 | bits vs parameters at a fixed budget | 05_bits_vs_params.py |
| §6 | quantization-aware training; QLoRA | 06_qat_qlora.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| number of bits of a quantized code | |
| largest magnitude of a symmetric signed code (127 for int8) | |
| scale: | |
| zero-point: | |
| step size: the gap between neighbouring quantized values | |
| the input of a linear layer: tokens, features | |
| a weight matrix; the slides write with , the code uses PyTorch’s with | |
| a matrix in 16-bit floats, and its int8 version |
1. Why make numbers smaller?
1.1 The memory wall
The slides start with one model. Qwen3-8B has 8 billion parameters. In 16-bit precision each parameter takes 2 bytes:
Running it needs more than the weights: activations, the KV cache (Lecture 9), buffers. The slides’ rule of thumb is about 1.5× the weights, so 24 GB. A MacBook Air has 16 GB of memory shared between CPU and GPU, and inference would swap to disk. A T4 GPU (the free Colab GPU) has 16 GB, and inference runs out of memory.
The fix the slides propose is simple to state: represent each weight with fewer bits. At 4 bits the same model needs roughly 5–6 GB, and runs on the laptop. Demo 01 Part D does the arithmetic for each format:
| format | weights | × 1.5 for inference | fits in 16 GB? |
|---|---|---|---|
| fp32 | 32.0 GB | 48.0 GB | no |
| bf16 / fp16 | 16.0 GB | 24.0 GB | no |
| int8 | 8.0 GB | 12.0 GB | yes |
| 4-bit + scales (4.5 bits) | 4.5 GB | 6.8 GB | yes |
| NF4 + double quantization (4.127 bits) | 4.1 GB | 6.2 GB | yes |
Memory is not the only gain. Lecture 9 showed that generating one token at a time is memory-bound: the GPU spends its time reading weights from memory, not multiplying them. Reading 4-bit weights instead of 16-bit ones moves a quarter of the bytes, so a well-written 4-bit kernel also decodes faster. The same holds for fine-tuning (fit a bigger model on the same GPU) and, with more care, for pretraining (more tokens per second).
1.2 Where the bits are
What should be quantized? The slides cite Ilharco et al. (2020): in large Transformer LMs, the linear layers (attention projections and feed-forward matrices) hold about 95% of the parameters and 65–85% of the computation. Embeddings, norms and softmax are a small remainder. So the plan of this lecture:
- quantize the linear layers’ parameters to fewer bits (e.g. bf16 → int8 or 4 bits);
- multiply with low-precision arithmetic where the hardware supports it;
- keep the small, sensitive remainder (norm gains, often the output head) in 16 bits.
1.3 The price: information loss, and how we will measure it
Fewer bits means fewer distinct values, so most numbers must be rounded. The question of the whole lecture is when rounding hurts. Two answers come up again and again:
- a few unusually large numbers (outliers) can wreck the precision of everything that shares their scale (§3.5, §4);
- below about 4 bits per weight, damage grows quickly whatever we do (§5).
To measure damage we need a model whose behavior is sensitive to its weights. The code uses a LLaMA-style Transformer (Lecture 5) pretrained on Fact World (Lecture 7): 2,500 people with Zipf-distributed popularity, each with a city, a job and a pet, so 7,500 facts. The d = 128, 3-layer model (684,160 parameters) recalls 68.4% of them after one minute of training. It knows all facts of the 100 most popular people, 98.9% for ranks 101–500, and 60.8% in the tail (ranks 501–2,500). “Recall” is the share of facts whose value is the model’s top prediction; demos report it before and after quantization.
Why not Errand World? The plan was to quantize a model of Lecture 3’s Errand World and measure perplexity. A prototype showed it is almost indestructible. 4-bit weights added 0.0002 nats per token, and even planted outliers 60× larger than normal cost only 0.004 nats per token. Errand World is easy, and the model learns it with capacity to spare, so rounding noise rarely changes a prediction. A model that must memorize thousands of arbitrary facts uses its weights with little slack, like a real LLM. That makes Fact World the more honest test. It is also a meaningful one: Allen-Zhu & Li (2024) measure LMs’ knowledge capacity in bits per parameter, and report that int8 quantization keeps it while int4 reduces it.
2. Representing numbers on a computer
2.1 Bits and integers
Everything is stored as bits (0 or 1), grouped in bytes of 8. What a pattern means depends on the number type.
An unsigned integer gives bit (counted from the right, starting at 0) the value , and the number is the sum over the positions holding a 1. The slides’ example:
bit pattern 0 1 0 1 0 1 1 0
bit value 128 64 32 16 8 4 2 1 01010110 = 64 + 16 + 4 + 2 = 86
bits hold : uint8 is 0–255, uint16 0–65,535, uint32 0–4,294,967,295.
A signed integer in two’s complement stores as : “flip all bits of , add 1”. Demo 01 Part A:
86 = 01010110
flip = 10101001
+1 = 10101010 = -86
Two’s complement has two useful properties:
- Ordinary addition works for both signs. 86 + (−86) in plain binary is 1 0000 0000, and dropping the carry leaves 0.
- The leftmost bit is the sign. int8 covers −128 … 127, one more negative number than positive, because 0 uses a “positive” pattern.
The price is wraparound: 127 + 1 in int8 is −128 (measured). No error is raised. Integers are exact inside their range and silently wrong outside it.
2.2 Floating point
Real numbers need a scale as well as digits, like scientific notation. A floating-point number has a sign bit, an exponent field and a mantissa (significand) field:
The bias lets the exponent be stored as an unsigned integer. The slides’ example, as stored in fp32 (demo 01 Part B reads the bits back from memory):
0 10000001 01100000000000000000000
sign 0 -> +
exponent 129 -> 129 - 127 = 2
mantissa 1.011 -> 1 + 1/4 + 1/8 = 1.375
value -> 1.375 x 2^2 = 5.5
The leading “1.” is implicit: it is not stored, which buys one bit of precision for free. When the exponent field is all zeros, the number is subnormal: . Subnormals fill the gap between 0 and the smallest normal number evenly. IEEE formats reserve the all-ones exponent for infinity and NaN.
The intuition to keep: exponent bits buy range, mantissa bits buy precision. Between two consecutive powers of two, a format with mantissa bits has exactly evenly spaced values. The relative gap between neighbours is about , called machine epsilon.
2.3 The family of formats
Demo 01 enumerates every value of each format with 16 bits or fewer, and computes fp32’s from its fields:
| format | sign + exponent + mantissa | max | epsilon | ~ decimal digits | finite values | values in [1, 2) |
|---|---|---|---|---|---|---|
| fp32 | 1 + 8 + 23 | 3.4e38 | 1.19e-07 | 7.2 | 4,278,190,079 | 8,388,608 |
| fp16 | 1 + 5 + 10 | 65,504 | 9.8e-04 | 3.3 | 63,487 | 1,024 |
| bf16 | 1 + 8 + 7 | 3.4e38 | 7.8e-03 | 2.4 | 65,279 | 128 |
| fp8 E4M3 | 1 + 4 + 3 | 448 | 0.125 | 1.2 | 253 | 8 |
| fp8 E5M2 | 1 + 5 + 2 | 57,344 | 0.25 | 0.9 | 247 | 4 |
| fp4 E2M1 | 1 + 2 + 1 | 6 | 0.5 | 0.6 | 15 | 2 |
fp16 and bf16 spend the same 16 bits differently, and the slides ask for the pros and cons of bfloat16:
- Pro: fp32’s range. bf16 is fp32 with the mantissa cut to 7 bits, so anything fp32 can hold without overflowing, bf16 can too. Converting is trivial, and training in bf16 rarely overflows or underflows.
- Con: precision. Epsilon is 7.8e-3, 8× coarser than fp16’s. Small differences between large numbers vanish.
fp4 E2M1 has just 15 distinct values: ±{0, 0.5, 1, 1.5, 2, 3, 4, 6}. A format that small only works with a scale factor that moves each block of numbers into its range. That is the step from formats to quantization (§3).
2.4 What goes wrong with too few bits
Demo 01 Part C rounds to the format after every operation, as hardware does:
| computation | exact | fp16 | bf16 |
|---|---|---|---|
| 300 × 300 (overflow) | 90,000 | inf | 90,112 |
| a gradient of 1e-8 (underflow) | 1e-08 | 0 | 1.0e-08 |
| … scaled by , rounded, unscaled | 1e-08 | 1e-08 | — |
| 256 + 1 (lost addition) | 257 | 257 | 256 |
| running sum of 10,000 × 0.01 | 100 | 32 | 4 |
Each line is a lesson:
- Overflow and underflow are fp16’s problems. Activations above 65,504 become inf, and gradients below 6e-8 become 0. Mixed-precision training in fp16 (Micikevicius et al., 2018) therefore multiplies the loss by a large factor before backpropagation (loss scaling) and divides the gradients afterwards. The table’s third row is exactly that trick. bf16 needs none of it.
- Lost additions are bf16’s problem. With 8 significant bits, 256 + 1 rounds back to 256.
- Sums stall. Once the running total is large enough that half the gap between neighbouring values exceeds 0.01, adding 0.01 rounds to nothing. fp16 stalls at 32 and bf16 at 4; fp32 reaches 100.003. This is why every low-precision system accumulates in higher precision: int8 matrix products sum into int32 (§3.6), and bf16 training keeps fp32 copies of weights and fp32 reductions.
And for weight-like numbers (normal, standard deviation 0.02), the median relative rounding error is 1.7e-4 in fp16, 1.35e-3 in bf16, and 3.6e-2 in fp8 E4M3. E4M3 even rounds 3.9% of them to 0. Eight bits of float are too coarse without a scale factor.
3. Quantization: from floats to a few integers
3.1 The idea
Quantization maps values from a large set to a smaller one: float32 to int8, say, or a real number to the nearest integer, . The quantization error is the difference between a value and its quantized version: errs by 0.4, by 0.2.
For neural networks the recipe has three parts:
- Scale a group of numbers into the range of a -bit code.
- Round to integers and store them, together with the scale.
- Dequantize when needed: multiply back by the scale. Or better, compute directly with the integers and rescale the result once (§3.6).
3.2 Absmax (symmetric) quantization
Divide by the largest magnitude, so the group lies in , stretch to , round:
Dequantization is . Why 127 and not 128? int8 reaches −128 but only +127. Using keeps the code symmetric, so and quantize to and .
Demo 02 reproduces the course notebook exactly:
- : , codes , dequantized , MSE 9.3e-05;
- : codes , MSE 7.95e-05.
3.3 Zero-point (asymmetric) quantization
Absmax wastes codes when the data are one-sided. After a ReLU, every value is and all negative codes go unused. Zero-point quantization maps onto all codes:
On : , zero-point , codes , MSE 6.9e-05. That is a little better than absmax, because it uses all 256 codes. The cost: one more number per group, and an extra term in matrix products (the zero-point must be subtracted).
3.4 How the error falls with bits
Rounding to a grid with step makes an error spread uniformly over , whose mean square is . Each extra bit halves , so it divides the error by 4: about 6 dB of signal-to-quantization-noise ratio (SQNR) per bit. Demo 02 Part C, one absmax scale for a million numbers:
| bits | step | measured MSE | SQNR | |
|---|---|---|---|---|
| 8 | 0.0375 | 1.172e-04 | 1.171e-04 | 39.3 dB |
| 6 | 0.154 | 1.96e-03 | 1.97e-03 | 27.1 dB |
| 4 | 0.680 | 3.85e-02 | 3.86e-02 | 14.1 dB |
| 3 | 1.587 | 0.210 | 0.210 | 6.8 dB |
| 2 | 4.761 | 0.945 | 1.889 | 0.2 dB |
The rule holds down to 3 bits. At 2 bits the codes are −1, 0, 1 with a step of 4.8, so almost every number rounds to 0. Only 0.2 dB of signal is left, and the rule (which assumes many steps across the data) breaks.
Note the step at 8 bits: 4.76 / 127. The step is set by the single largest value, 4.76 for a million normal samples. That is the seed of the next two sections.
3.5 Outliers and granularity
The notebook’s outlier example (demo 02 Part B): eleven values of size 0.1–0.4, plus one value of 100.
| array | method | MSE on the 11 small values | distinct codes among them |
|---|---|---|---|
| with the outlier | absmax | 0.0655 | 2 |
| with the outlier | zero-point | 0.0153 | 3 |
| without | absmax | 1.0e-06 | 4 |
| without | zero-point | 7.0e-07 | 4 |
With the outlier, the step is , and the eleven small values become two codes: the outlier is stored well, everything else is not. The slides’ figure shows the same thing. Information loss is “particularly extreme in the presence of outliers”, because normalization uses the min and the max.
The general remedy is granularity: give fewer numbers a shared scale, so an outlier only spoils its own group.
- Per tensor: one scale for the whole matrix; the cheapest and most fragile option.
- Per row: one scale per output channel of a weight, or per token of an activation.
- Per group (block): one scale per consecutive weights of a row.
Scales cost memory. One fp16 scale per 64 weights adds bits per weight. Demo 02 Part D quantizes the 21 weight matrices of the Fact World model:
| one scale per | relative MSE, 8 bits | 4 bits | 3 bits | extra bits per weight |
|---|---|---|---|---|
| tensor | 1.30e-04 | 4.28e-02 | 0.227 | 0 |
| row | 4.41e-05 | 1.45e-02 | 0.079 | +0.106 |
| group of 128 | 4.15e-05 | 1.37e-02 | 0.075 | +0.125 |
| group of 64 | 3.48e-05 | 1.15e-02 | 0.063 | +0.250 |
| group of 32 | 2.82e-05 | 9.32e-03 | 0.051 | +0.500 |
The weights are not heavy-tailed: their kurtosis is 3.0, as for a normal distribution. Smaller groups help anyway, because the largest of more numbers is larger. For a whole matrix the maximum is 4.5 standard deviations; for a group of 64 it is 2.5 (medians over matrices). With a smaller maximum, the typical weight gets more steps. This is why every 4-bit format uses small blocks: NVFP4 16 weights, Q4_K 32, NF4 64, GPTQ and AWQ commonly 128.
3.6 Quantized matrix multiplication
Storing integers saves memory. Computing with integers also saves time on hardware with int8 units. For , quantize both operands and pull the scales out of the sum:
The integer product is accumulated in an int32 buffer: each term is at most , and terms are summed. With one scale per tensor, one division at the end undoes both scales.
Vector-wise quantization (LLM.int8(), section 3.2) gives each row of (each token) and each column of (each output) its own scale. Every entry of is then rescaled by its own pair:
i.e. is divided elementwise by the outer product of the two scale vectors. The cost is negligible, and the gain is robustness: one bad token no longer spoils the others.
Demo 02 Part E checks this on a real layer, the first FFN projection of block 0 on 256 calibration sentences (: 1,792 × 128, : 128 × 384):
- the int8 × int8 → int32 path equals simulated quantization (round, dequantize, multiply in float) to 3e-06, and full precision to a relative MSE of 5e-05;
- the integer sums reach 235,290, so an int16 accumulator would overflow in 175,793 of 688,128 outputs. int32 is safe for any inner dimension up to .
All later demos use simulated (“fake”) quantization: they round to the format’s values and multiply in float32. This check is why that is legitimate: the numbers are the same as an integer kernel’s.
The notebook’s last cell multiplies an whose column 1 was scaled by 100. Demo 02 repeats it:
| method | max abs error |
|---|---|
| absmax per tensor | 1.34 |
| vector-wise | 1.09 |
| column 1 in 16-bit, the rest vector-wise | 0.038 |
Vector-wise scales help only partly: the outlier sits in every row. Taking its column out and multiplying it in 16-bit fixes the product. That is LLM.int8() in miniature.
4. Outlier features and LLM.int8()
4.1 What Dettmers et al. found
Int8 quantization worked well for smaller Transformers. Dettmers et al. (2022) found that it collapses for models beyond a few billion parameters. Zero-shot accuracy of naively int8-quantized models falls far below the 16-bit baseline from about 6.7B parameters on (the slides’ figure). The culprit is outlier features: a few hidden dimensions whose values are far larger than all others. The paper defines an outlier by three conditions:
- magnitude of at least 6;
- in at least 25% of the layers;
- in at least 6% of the sequence positions.
Their key observations:
- Outliers are systematic. They live in the same few feature dimensions across layers and tokens. In a 6.7B model, about 150,000 outliers per sequence are concentrated in just 6 of the 4,096 hidden dimensions.
- They emerge with scale, in a phase shift. Around 6.7B parameters they suddenly affect all layers and about 75% of sequence positions.
- They matter. Zeroing them destroys the model’s predictions: the network uses them.
The slides’ summary: in models with ≥ 6.7B parameters an outlier occurs in 100% of the layers, yet only ~0.1% of activation features are outliers.
4.2 Why they break int8
Consider the input of an attention projection with one outlier feature of magnitude 60 in every token, all other features of size ~1:
- Per tensor: the step is . Every ordinary feature rounds to a few levels, and most of the information is gone.
- Vector-wise (per token): every token’s row contains the outlier, so every row’s step is still ~0.5. Nothing improves.
- Per feature (per column): would isolate the outlier. But a column scale of multiplies the inner dimension of , so it cannot be pulled out of the sum as one factor per output. Int8 matrix multiplication needs scales on the outer dimensions (rows of , columns of ).
4.3 Mixed-precision decomposition
LLM.int8()‘s answer: compute the outlier columns in 16-bit and everything else in int8.
where is the set of feature dimensions in which any value has magnitude (threshold ). Because outliers occupy a handful of dimensions, more than 99.9% of the multiply-adds still run in int8. The paper reports no performance degradation up to 175B parameters (OPT-175B, BLOOM-176B), halving inference memory. The price is speed: decomposing and merging add work, and LLM.int8() was designed to save memory rather than time.
X (T x h) W (h x o)
┌──────┬─┬──────┐ ┌─────────┐
│ │o│ │ │ │
│ int8 │u│ int8 │ x ├─────────┤ <- row of the outlier dimension: 16-bit
│ │t│ │ │ int8 │
└──────┴─┴──────┘ └─────────┘
outlier column = (16-bit outer product) + (int8 product), merged in 16-bit
4.4 Measured: our model’s activations, and planted outliers
Our model’s own activations (demo 03 Part A, 256 calibration sentences):
| layer input | max | columns with | kurtosis |
|---|---|---|---|
| attention input (Q, K, V) | 4.9 | 0.0% | 3.7 |
| attention output () | 5.8 | 0.0% | 5.4 |
| FFN input (, ) | 6.1 | 0.5% | 4.7 |
| FFN down projection () | 100.9 | 81.9% | 165 |
Large values appear in one place: the input of the FFN down projection, where SwiGLU multiplies two branches. They are spread over 82% of the columns and all token positions. That is a heavy tail (kurtosis 165, against 3 for a normal distribution and 9 for a product of two independent normals), not Dettmers’ handful of systematic dimensions. Yang et al. (2024) report such “activation spikes” at the down-projection input of GLU-based LLMs. The inputs that come out of an RMSNorm stay near or below 6.
Planting outlier features. Our 0.7M-parameter model cannot grow 6.7B-scale outliers, but we can give it their structure without changing what it computes. In a pre-norm block the Q/K/V projections read . Multiply the gain of feature by and divide column of every weight that reads it by :
The product is unchanged, but feature of the layer inputs is now times larger. This is not artificial: Wei et al. (2022) trace real models’ outlier features to large LayerNorm gains in a few channels. Demo 03 plants two features (1.6% of 128) in all three blocks. At :
- the logits change by 5e-06, and recall stays at 68.4%;
- the attention inputs now reach magnitude 380, with exactly 1.6% of their columns above 6.
Int8 schemes vs the size of the outliers (demo 03 Part C, recall of 7,500 facts; full precision 68.4% throughout):
| scheme | no planting | |||
|---|---|---|---|---|
| weight-only int8 (per row) | 68.4% | 68.3% | 68.3% | 68.1% |
| W8A8 per-tensor | 67.9% | 67.3% | 59.4% | 10.9% |
| W8A8 vector-wise | 68.5% | 68.4% | 67.6% | 56.0% |
| LLM.int8() (vector-wise + 16-bit columns ≥ 6) | 68.4% | 68.4% | 68.4% | 68.1% |
| SmoothQuant () + W8A8 per-tensor | 68.1% | 68.1% | 68.1% | 68.2% |
| SmoothQuant () + W8A8 vector-wise | 68.4% | 68.4% | 68.4% | 68.4% |
This is the paper’s story in one table:
- Per-tensor activation quantization collapses as outliers grow.
- Vector-wise scales do not save it, because the outliers are in every row.
- The decomposition keeps everything.
- Weight-only int8 never quantizes activations, so the outliers cannot hurt it.
The threshold (Part D, ): at the decomposition sends exactly the planted columns (1.6%) of the attention inputs to 16-bit. It also sends 73% of the down-projection columns, because of their natural heavy tail. At nothing is decomposed and recall falls to 56.0%; at only the planted columns remain, and recall stays at 67.9%. In this small model the down projections would gain little from int8. The method’s efficiency rests on outliers being rare.
4.5 The other fix: migrate the difficulty (SmoothQuant)
LLM.int8() treats outliers as an exception. SmoothQuant (Xiao et al., 2023) removes them before quantizing. For any positive vector ,
so we can divide feature of by and multiply column of by for free. The factors can even be folded into the previous norm’s gains. Choosing
with splits the range evenly between activation and weight. Activations are hard to quantize: their range changes from token to token and is only known at run time. Weights are easy: they are fixed and get per-row scales. The outlier’s magnitude moves into a weight column, where per-row scales absorb it. Measured: 68.2% (per-tensor) and 68.4% (vector-wise) at , without a single 16-bit column. SmoothQuant’s factors come from calibration data (here 256 sentences), a step LLM.int8() does not need.
Notice that SmoothQuant is our planting run backwards: planting moved magnitude from into , and SmoothQuant moves it back.
4.6 Weight-only or weights and activations?
Two families of methods serve two regimes:
- Weight-only (W8A16, W4A16: GPTQ, AWQ, NF4, GGUF). The weights are stored in few bits and dequantized to 16-bit right before the multiplication. This saves memory and memory bandwidth, which is what matters for decoding one token at a time (memory-bound, Lecture 9). Activation outliers are irrelevant.
- Weights and activations (W8A8: LLM.int8(), SmoothQuant; FP8 inference). The multiplication itself is low-precision, which matters when it is compute-bound: long prompts (prefill), large batches, training. Activation outliers are the central difficulty.
5. Four bits and below
5.1 Why 4 bits?
Going from 16 to 8 bits halves memory and, as measured above, is free with any per-row scheme. Going to 4 bits halves it again. Dettmers & Zettlemoyer (2022) ran more than 35,000 experiments on models from 19M to 176B parameters, asking: for a fixed number of total model bits, which precision gives the best zero-shot accuracy? Their answer, across families (OPT, BLOOM, Pythia, GPT-2, …): 4-bit is almost universally optimal. A model with twice the parameters at 4 bits beats one at 8 bits of the same size in memory. Below 4 bits, precision losses outweigh the extra parameters. Two levers improve 4-bit quality further: small blocks and better data types.
5.2 Block-wise quantization and the choice of 16 values
A 4-bit “data type” is just a list of 16 values, a codebook. Each block of weights is scaled by its absmax into , and every weight is replaced by the index of the nearest codebook value. Three choices (demo 04 Part A, blocks of 64):
| codebook | values (× block absmax) | relative MSE on the model’s weights | code entropy |
|---|---|---|---|
| int4 (absmax) | 15 evenly spaced: | 0.0115 | 3.51 bits |
| FP4 E2M1 | 0.0112 | 3.82 bits | |
| NF4 | 16 values at normal quantiles | 0.0084 | 3.89 bits |
NormalFloat (NF4) comes from QLoRA. Pretrained weights are roughly normally distributed (ours have kurtosis 3.0). A code is used best if each of its 16 values is equally likely to be the nearest one, i.e. if the values sit at quantiles of the distribution (an information-theoretically optimal “quantile quantization”). QLoRA wants an exact zero as well, so it takes 8 positive and 7 negative quantiles of plus 0, and normalizes to :
with instead of 1, whose quantile is infinite. numfmt.nf4_codebook() computes it this way and matches bitsandbytes’ published table to 2e-07.
“Code entropy” measures how many of the 4 bits the codes actually carry. Int4’s outer levels are rarely used (most weights are near 0), so its codes carry only 3.51 bits. NF4’s carry 3.89, and its error is 27% lower.
5.3 Double quantization
Blocks cost bits: one fp32 absmax per 64 weights is bits per weight, an eighth of the 4-bit budget. QLoRA’s double quantization quantizes those constants again. They are positive, so subtract their mean, store them as 8-bit floats, and keep one fp32 scale per 256 of them:
a saving of 0.373 bits per parameter, about 3 GB for a 65B model (QLoRA’s numbers). Measured: NF4 with double quantization (4.127 bits per weight) recalls 67.7%, exactly as much as NF4 with fp32 constants (4.5 bits).
5.4 GGML, GGUF and llama.cpp
The slides’ practical stack for running quantized models on laptops:
- GGML: a tensor library with its own quantization formats and backends (Metal, ARM, CUDA, …);
- GGUF: a file format storing an architecture and its (quantized) tensors;
- llama.cpp: LLM inference built on both. The course notebook serves
Qwen3-8B-GGUF:Q4_K_Mwithllama-serveron an M4 MacBook.
The k-quants (llama.cpp PR #1684) are block formats with a second level of scales. Q4_K groups weights into super-blocks of 256 = 8 blocks × 32 weights. Each block stores asymmetric 4-bit codes with its own scale and minimum:
where and are 6-bit integers and , are fp16 numbers per super-block. Bits per weight: . Q6_K uses 6-bit codes in blocks of 16 with 8-bit scales: 6.5625 bits per weight. The file variants mix them:
- Q4_K_S uses Q4_K for all tensors;
- Q4_K_M uses Q6_K for half of the attention-V and FFN-down tensors (
attention.wv,feed_forward.w2) and Q4_K elsewhere.
5.5 New hardware formats
GPUs now support small floats natively, with block scales:
- NVFP4 (NVIDIA Blackwell): E2M1 values, blocks of 16, one FP8 (E4M3) scale per block plus one fp32 scale per tensor. 4.5 bits per weight.
- MXFP4 (OCP Microscaling): E2M1 values, blocks of 32, one power-of-two scale (8-bit exponent) per block. 4.25 bits per weight. Power-of-two scales are cheap to apply but coarse: a block’s largest value lands somewhere in [4, 8), and anything above 6 is clipped.
5.6 Measured: what four bits (and fewer) cost
Demo 04 Part B quantizes the model’s 21 block matrices (weight-only; embeddings and head stay full precision):
| scheme | bits / weight | recall | value loss (nats) |
|---|---|---|---|
| fp32 | 32 | 68.4% | 0.248 |
| bf16 | 16 | 68.5% | 0.248 |
| int8, one scale per row | 8.106 | 68.4% | 0.248 |
| Q6_K | 6.562 | 68.3% | 0.248 |
| int4, one scale per tensor | 4 | 65.2% | 0.283 |
| int4, one scale per row | 4.106 | 67.2% | 0.261 |
| int4, groups of 64 | 4.25 | 67.5% | 0.258 |
| FP4 E2M1, blocks of 64 | 4.5 | 67.4% | 0.258 |
| NF4, blocks of 64 | 4.5 | 67.7% | 0.256 |
| NF4 + double quantization | 4.127 | 67.7% | 0.256 |
| MXFP4 | 4.25 | 66.6% | 0.263 |
| NVFP4 | 4.5 | 67.5% | 0.257 |
| Q4_K | 4.5 | 68.3% | 0.253 |
| Q4_K_M-like (Q6_K for , ) | 5.135 | 68.3% | 0.251 |
| int3, groups of 64 | 3.25 | 62.2% | 0.314 |
| int2, groups of 64 | 2.25 | 18.3% | 2.056 |
Reading the table:
- 8 bits are free, and so is Q6_K.
- At 4 bits, granularity matters most. One scale per tensor costs 3.2 points; any blocked scheme costs 0.2–1.8.
- The data type adds a little. NF4 beats int4 and FP4 at the same block size.
- Llama.cpp’s asymmetric Q4_K, with blocks of 32, comes closest to full precision. Our implementation even skips llama.cpp’s search for the best scales.
- Power-of-two scales (MXFP4) cost a point against NVFP4’s FP8 scales.
- Below 4 bits the curve bends. 3 bits lose 6 points and 2 bits destroy the model.
Which facts go first? (Part C, recall by popularity rank)
| scheme | ranks 1–100 | 101–500 | 501–2,500 |
|---|---|---|---|
| full precision | 100.0% | 98.9% | 60.8% |
| NF4 | 100.0% | 98.8% | 59.9% |
| int4 per tensor | 100.0% | 98.5% | 56.7% |
| int3, groups of 64 | 100.0% | 97.8% | 53.2% |
| int2, groups of 64 | 52.3% | 33.4% | 13.6% |
Popular facts are robust; the long tail goes first. Popular facts were seen hundreds of times in training, and their margins are large. Rare facts were barely learned, and a little noise tips them over. This is a warning about how quantized models are evaluated: average perplexity on common text can look fine while rare knowledge erodes.
Which layers are sensitive? (Part D: one kind of layer at 3 bits, the rest full precision.) Per 10% of the block weights, attention V and lose 1.44 and 1.51 points, the FFN matrices 0.33–0.38. In this model the attention value and output path is about four times as sensitive per weight. Q4_K_M upgrades attention V (consistent) and FFN down (not especially sensitive here). Mixed schemes spend bits where they matter, and where is an empirical question per model.
5.7 Measured: bits vs parameters
Demo 05 trains five models (d = 24 … 96, 31k to 393k parameters) with the same recipe and quantizes each at seven precisions. Every matrix is quantized, embeddings included, and the totals count the scales. Recall (total size in Mbit):
| d | 16 bits | 8 bits | 6 bits | 5 bits | 4 bits | 3 bits | 2 bits |
|---|---|---|---|---|---|---|---|
| 24 | 26.8% (0.49) | 26.8% (0.26) | 26.4% (0.19) | 25.5% (0.16) | 21.6% (0.13) | 10.1% (0.10) | 1.3% |
| 32 | 38.3% (0.82) | 38.3% (0.42) | 37.9% (0.32) | 36.9% (0.27) | 30.9% (0.22) | 16.1% (0.17) | 1.8% |
| 48 | 57.0% (1.71) | 57.0% (0.88) | 56.9% (0.67) | 55.7% (0.56) | 50.1% (0.46) | 27.2% (0.35) | 3.6% |
| 64 | 65.5% (2.92) | 65.4% (1.51) | 65.6% (1.14) | 64.5% (0.96) | 60.1% (0.78) | 38.9% (0.60) | 4.1% |
| 96 | 70.1% (6.29) | 70.1% (3.25) | 69.8% (2.46) | 69.1% (2.07) | 66.9% (1.68) | 51.0% (1.29) | 5.3% |
At equal size in memory, more parameters at lower precision win:
- Within 0.85 Mbit, the best 16-bit model (d = 32) recalls 38.3%, and the best 4-bit model (d = 64, 3.6× the parameters) 60.1%.
- On the frontier, the configurations no smaller model beats, 16 bits never appear. 4, 5 and 6 bits have five points each; 8 bits appear only where the next size is out of reach; 2–3 bits only below the smallest model.
That is Dettmers & Zettlemoyer’s shape in miniature. Here the efficient range is 4–6 bits rather than exactly 4, with round-to-nearest quantizers on tiny models. Better quantizers (§5.8) and QAT (§6.1) move it lower.
One complication was itself instructive: the d = 128 model recalls less than d = 96 (68.4% vs 70.1%). With 3,000 training steps the rarest people appear a few times or never, so above d ≈ 96 the data, not the parameters, limit recall. Demo 05 uses models that are limited by their size, the regime the k-bit question is about.
5.8 Beyond rounding to nearest
Everything above rounds each weight independently. Two widely used methods do better at 3–4 bits:
- GPTQ (Frantar et al., 2022) quantizes a layer’s weights one column at a time and adjusts the not-yet-quantized columns to compensate each rounding error. It uses second-order information from calibration inputs (an approximate inverse Hessian) and runs in a few GPU hours for 175B models.
- AWQ (Lin et al., 2023) observes that the weights multiplying large activations matter most, and protects them by scaling, as SmoothQuant does, before rounding.
Both are weight-only and post-training. They are why 4-bit models in the wild lose less than the round-to-nearest numbers above suggest.
6. Quantization and training
6.1 Quantization-aware training (QAT)
Post-training quantization (PTQ) rounds a model that never saw rounding. QAT fine-tunes the model so that it is “prepared” for quantization. The slides’ basic idea: insert artificial quantize-dequantize operations (“fake quantization”) into the computational graph. The forward pass uses rounded weights, so the loss measures the quantized model.
The problem is the backward pass. Rounding is a staircase: its derivative is 0 almost everywhere, so no gradient would ever reach the weights. The straight-through estimator (Bengio et al., 2013) pretends rounding is the identity in the backward pass:
where sg is stop-gradient (.detach() in PyTorch). The full-precision latent weights keep accumulating small updates. Whenever they cross a rounding boundary, the quantized value changes. quant.add_fake_quant registers exactly this as a PyTorch parametrization.
Measured (demo 06 Part A, 800 steps at learning rate 3e-4 on pretraining sentences):
| quantized to | PTQ | control: train fp32 | control, then PTQ | QAT, quantized | QAT latent fp32 |
|---|---|---|---|---|---|
| int3, groups of 64 | 62.2% | 75.4% | 68.1% | 72.2% | 70.7% |
| int2, groups of 64 | 18.3% | 75.4% | 17.6% | 41.9% | 59.9% |
- QAT recovers much of what rounding destroys: +10 points at 3 bits, +24 at 2 bits.
- The control matters. Extra training on the pretraining data (a second look at it) alone raises the fp32 model from 68.4% to 75.4%. Quantizing that model gives 68.1% and 17.6%. QAT beats it by 4 and 24 points: the gain comes from training with the rounding, not from more training. Many QAT comparisons omit this control.
- QAT optimizes the rounded network. At 3 bits the quantized model recalls more than its own latent weights (72.2% vs 70.7%): rounding has stopped being damage. At 2 bits the grid is too coarse for that.
A first attempt failed instructively: 300 steps on fresh sentences at learning rate 1e-3 gave 60.2% at 3 bits, worse than PTQ. Continued training on new data made the model forget rare facts faster than QAT could help. QAT needs the training distribution and a gentle learning rate.
6.2 QLoRA
Fine-tuning needs much more memory than inference: gradients and optimizer states come on top of the weights. QLoRA (Dettmers et al., 2023) makes it fit on one GPU with three ingredients, plus a finding about where LoRA goes:
- A 4-bit NF4 base model with double quantization, frozen. The base weights are dequantized to bf16 on the fly for each matrix multiplication.
- LoRA adapters in 16-bit (Lecture 8) on top: . Gradients flow through the frozen quantized weights into only.
- Paged optimizers: optimizer states live in unified memory and move to CPU RAM when the GPU runs out, which avoids out-of-memory spikes on long sequences.
- The finding: adapters on all linear layers are needed to match 16-bit full fine-tuning. The original LoRA adapted only and .
The paper fine-tunes LLaMA 65B on a single 48 GB GPU, where 16-bit fine-tuning needs more than 780 GB. Its Guanaco models reached 99.3% of ChatGPT’s level on the Vicuna benchmark after 24 hours on one GPU.
Measured (demo 06 Part B). The task teaches the model a new template for facts it already knows: “kemi dorasu resides in lima” instead of “lives in” (“works as”, “keeps a”). The words are new to the model. Training uses 1,500 new-template sentences about 500 people. The test asks the new template about 500 other people, on the 1,406 of their facts that the base model recalls in the old template. Success therefore means transferring the template, not memorizing.
| setup | trainable parameters | new template, held-out people | fine-tuning people | old template (all facts) |
|---|---|---|---|---|
| no fine-tuning | 0 | 19.7% | 19.7% | 68.4% |
| full fine-tuning (fp32) | 684,160 | 70.3% | 98.3% | 59.9% |
| LoRA, all linear layers, fp32 base | 61,440 | 76.1% | 91.2% | 59.6% |
| LoRA, query + value only | 12,288 | 49.1% | 51.9% | 51.6% |
| QLoRA: NF4 + double-quant base, all linear | 61,440 | 74.8% | 90.1% | 59.3% |
| LoRA on an int3 base, all linear | 61,440 | 70.4% | 88.9% | 54.9% |
- QLoRA matches LoRA within about a point (74.8% vs 76.1%), training 9% of the parameters.
- Placement matters more than the base’s precision. Adapters on query and value only reach 49.1%, QLoRA’s finding in miniature.
- A worse base costs knowledge that adapters cannot restore. On a 3-bit base, transfer falls to 70.4% and old-template recall to 54.9%.
- Everything forgets part of the old template (68.4% → 52–60%), because the fine-tuning data contain only the new one. Mixing in old-template sentences (“replay”) is the standard remedy.
- LoRA transfers better than full fine-tuning here (76.1% vs 70.3%), while fitting its training people less (91.2% vs 98.3%). Full fine-tuning partly memorizes the 500 people instead of learning the template.
Memory (demo 06 Part C, weights + gradients + Adam states; activations come on top):
| model | full fine-tuning | LoRA on a 16-bit base | QLoRA (NF4 + DQ base) | LoRA r = 64 parameters |
|---|---|---|---|---|
| LLaMA-7B | 80 GB | 15.3 GB | 5.4 GB | 160M (2.4%) |
| LLaMA-65B | 782 GB | 140 GB | 43 GB | 800M (1.2%) |
Full fine-tuning counts 12 bytes per parameter: 16-bit weights and gradients plus 32-bit Adam moments. The QLoRA paper’s “>780 GB” for 65B matches. QLoRA’s ~43 GB is one 48 GB GPU, and paged optimizers absorb the spikes.
6.3 Low-precision training, briefly
Training itself has been moving down the same ladder: fp32 → mixed precision with fp16 and loss scaling (Micikevicius et al., 2018) → bf16, now standard → fp8 with fine-grained scales (Micikevicius et al., 2022; DeepSeek-V3 trained in FP8). The lessons of §2.4 apply in every step: keep fp32 master weights and fp32 accumulations, and give each block of numbers its own scale. Dettmers et al.’s 8-bit optimizers (2022) apply block-wise quantization to Adam’s two moment vectors, cutting optimizer memory by 75%. They are the origin of the block-wise idea used throughout this lecture.
7. Trade-offs in practice
- Memory, quality, speed: pick a point. Quantization always reduces memory; whether it reduces latency depends on kernels. A simulated 4-bit model (this lecture’s code) is slower than fp32, since it rounds and then multiplies in float. Real speed comes from kernels that read packed 4-bit weights and dequantize in registers (llama.cpp, Marlin, …), or from int8/fp8 tensor cores.
- When quantization is free. Weight-only 8-bit, and 4–6-bit k-quants, lose almost nothing here and in practice. W8A8 is free only if activation outliers are handled (LLM.int8(), SmoothQuant).
- When it is not. Below 4 bits round-to-nearest breaks; GPTQ/AWQ help at 3–4 bits; QAT goes further but needs training.
- Measure on your task, including its tail. Perplexity on common text can hide the loss of rare knowledge (§5.6). Report task metrics, and the parts of the distribution you care about.
- The slides’ last word: many other methods exist (AWQ, GPTQ, HQQ, bitsandbytes, torchao, …; the Hugging Face quantization overview lists them). The ideas behind them are the ones above: scales, granularity, data types, outliers, error compensation, and training through the rounding.
8. Summary
- Formats. Exponent bits buy range, mantissa bits buy precision.
- fp16 overflows above 65,504; bf16 keeps fp32’s range at 8× coarser precision.
- Measured: a running sum stalls at 32 (fp16) and 4 (bf16), so always accumulate in higher precision.
- Quantization = scale, round, store the scale.
- Absmax uses ; zero-point adds an offset for one-sided data.
- Error ≈ , about 6 dB per bit; the step is set by the largest value in the group.
- Granularity. Smaller groups mean smaller maxima and finer steps, at a cost of bits for the scales.
- Measured, 4-bit relative MSE: 4.3e-02 per tensor vs 1.2e-02 for groups of 64 (+0.25 bits).
- Int8 matmul. , vector-wise, with an int32 accumulator.
- Measured: equal to simulated quantization to 3e-06; sums up to 235,290.
- Outliers and LLM.int8(). Systematic outlier features (from ~6.7B parameters) break per-tensor and vector-wise int8.
- LLM.int8() multiplies the outlier columns in 16-bit; SmoothQuant moves their magnitude into the weights.
- Measured with planted outliers (): 10.9% / 56.0% / 68.1% / 68.4% recall (full precision 68.4%).
- Four bits. Blocks plus a good data type (NF4) or llama.cpp’s Q4_K lose under 1 point; double quantization makes NF4 4.127 bits.
- The long tail of rare facts is lost first.
- Measured: 2 bits collapse to 18.3%.
- Bits vs parameters. At a fixed memory budget, more parameters at 4–6 bits beat fewer at 16 or 8.
- Measured: 60.1% vs 38.3% at 0.85 Mbit.
- Training. QAT trains through the rounding with a straight-through estimator.
- Measured: +10 points at 3 bits and +24 at 2 bits over PTQ, and it beats the equal-steps control.
- QLoRA fine-tunes an NF4 base through 16-bit LoRA on all linear layers, matching LoRA (74.8% vs 76.1%) and fitting 65B fine-tuning into ~43 GB.
Common pitfalls
- Accumulating in the storage precision. Sums in fp16/bf16 (or int8) stall or overflow; accumulate in fp32/int32.
- One scale for a whole tensor. A single outlier sets the step for millions of values. Use per-row or block-wise scales.
- Quantizing activations without looking at them. Check the per-feature maxima first; outlier features call for LLM.int8() or SmoothQuant, heavy tails for finer granularity.
- Forgetting the bits of the scales. “4-bit” NF4 with fp32 block constants is 4.5 bits; compare formats at equal bits per weight.
- Judging a quantized model by average perplexity alone. Rare knowledge degrades first.
- Claiming a QAT gain without the control. Extra training alone also helps; compare with the same steps without fake quantization.
- Assuming fake quantization is fast. Simulated quantization measures quality only; speed needs real kernels.
- Adapting only and in QLoRA. Put adapters on every linear layer.
Exercises
-
Bits. Write −5 in int8 (two’s complement). Decode the fp16 pattern
0 10010 0100000000.Answer
5 = 00000101; flip → 11111010; +1 → 11111011. fp16: sign + ; exponent 10010 = 18, minus bias 15 = 3; mantissa 1.01 = 1.25; value 1.25 × 2³ = 10. -
Overflow or rounding? For each, say whether fp16 or bf16 is the safer choice, and why: (a) storing attention logits that can reach 100,000; (b) storing a weight update of 1e-4 added to a weight of 1.0; (c) storing gradients of size 1e-9.
Answer
(a) bf16: fp16 overflows above 65,504. (b) Neither is safe for the update itself: bf16's epsilon at 1.0 is 7.8e-3, and fp16's spacing at 1.0 is 9.8e-4, so 1 + 1e-4 rounds back to 1 in both. Keep fp32 master weights. (c) bf16 (range down to ~1e-38); fp16's smallest subnormal is 6e-8, so 1e-9 underflows to 0 unless the loss is scaled. -
Absmax by hand. Quantize to int8 with absmax, dequantize, and give the largest error. Then do the same at 4 bits ().
Answer
8 bits: $s = 127/2 = 63.5$; codes round(31.75, −63.5, 127, 15.875) = [32, −64, 127, 16] (−63.5 rounds half to even → −64); dequantized [0.504, −1.008, 2.0, 0.252]; largest error 0.008. 4 bits: $s = 3.5$; codes round(1.75, −3.5, 7, 0.875) = [2, −4, 7, 1]; dequantized [0.571, −1.143, 2.0, 0.286]; largest error 0.143 (for −1.0). The step grew from 0.016 to 0.29, ≈ 2^4 times larger. -
The cost of scales. A 7B model is quantized to 4 bits with one fp16 scale and one fp16 zero-point per group of 128 weights. How many bits per weight, and how many GB? What would one fp32 scale per 32 weights cost?
Answer
4 + (16 + 16)/128 = 4.25 bits → 7e9 × 4.25 / 8 = 3.72 GB. With one fp32 scale per 32: 4 + 32/32 = 5 bits → 4.38 GB, a quarter more for the same codes. Hence double quantization and super-blocks. -
Why vector-wise fails. An activation matrix has a feature of magnitude 50 in every token and other features of magnitude ≈ 1. Estimate the int8 step for (a) per-tensor, (b) per-token scales. What does LLM.int8() do instead, and what fraction of the matmul stays int8 if the model has 4,096 features and 6 outlier dimensions?
Answer
(a) and (b) both ≈ 50/127 ≈ 0.39: every token row contains the outlier, so per-token scaling does not help, and ordinary features get only ~2–3 levels each side. LLM.int8() multiplies the 6 outlier columns of X (and the 6 matching rows of W) in 16-bit and the other 4,090 in int8: 4,090/4,096 = 99.85% of the multiply-adds stay int8. -
SmoothQuant by hand. One feature has and its weight column has ; a typical feature has , . With , compute and the new maxima. Why is the result easier to quantize?
Answer
$s_j = \sqrt{64}/\sqrt{0.25} = 8/0.5 = 16$. New activation max 64/16 = 4; new weight column max 0.25 × 16 = 4. For the typical feature $s = 1/0.5 = 2$: activation 0.5, weight 0.5. The activation range across features shrank from 64:1 to 8:1, and the weight column that grew is absorbed by the per-row weight scales (each output row's scale now covers a column of size 4). -
NF4 vs int4. Explain in one paragraph why NF4 has lower error than int4 on normally distributed weights, using the idea of equal-probability bins. Why does QLoRA insist on an exact zero?
Answer
Int4's 15 levels are evenly spaced over [−absmax, absmax], but normal weights crowd near 0: the central bins hold most weights and are too wide for them, while the outer bins are almost empty (measured code entropy 3.51 of 4 bits). NF4 places its 16 levels at quantiles of N(0,1), so each bin holds about the same share of weights. The levels are dense where weights are dense, and the code carries 3.89 bits. An exact zero matters because zero is special: padding, pruned weights and ReLU-like structure should quantize without error, and a symmetric code with an even number of levels would have no zero at all. -
Bits vs parameters. You have 4 GB for weights. Options: a 2B model in bf16; a 4B model at 8 bits; an 8B model at 4 bits (with 0.25 bits of scales); a 10.7B model at 3 bits (+0.25). Which does the k-bit scaling result favor, and what would make you doubt it?
Answer
2B × 16 = 32 Gbit = 4 GB; 4B × 8.x ≈ 4 GB; 8B × 4.25 = 34 Gbit ≈ 4.25 GB (slightly over: choose a smaller block or a 7.5B model); 10.7B × 3.25 ≈ 4.3 GB. Dettmers & Zettlemoyer (and demo 05) favor ~4 bits: the largest model before precision losses dominate. Doubts: if the bigger model is data-limited (demo 05's d = 128 recalls less than d = 96), if the task depends on rare knowledge that low bits erode first, or if a better method (GPTQ, QAT) makes 3 bits competitive. -
QAT and its control. A paper reports: “PTQ to 3 bits: 61%; after 1,000 steps of QAT: 72%.” What experiment is missing, and what would each outcome mean?
Answer
The same 1,000 steps without fake quantization, then PTQ. If that also reaches ~72%, the gain is from extra training, not from QAT. If it stays near 61–68% (demo 06: 68.1%), the gain is from training through the rounding. Also report the full-precision model after both trainings, so readers see how much the extra steps themselves changed it.
Related assignment (concepts only)
- Assignment 1 (Build your own LLaMa) and later projects run models on limited hardware. Before quantizing:
- measure memory per component;
- check activation maxima per layer;
- compare formats at equal bits per weight on your task, including its rare cases;
- keep a full-precision baseline.
- Assignments 3–4: if you fine-tune a large model, QLoRA (NF4 base, LoRA on all linear layers) is usually the cheapest way to fit it. Report the base’s precision with your results.
- These notes do not provide assignment code.
Further reading
- T. Dettmers, M. Lewis, Y. Belkada, L. Zettlemoyer, “LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale”, NeurIPS 2022 (course reading); T. Dettmers, A. Pagnoni, A. Holtzman, L. Zettlemoyer, “QLoRA: Efficient Finetuning of Quantized LLMs”, NeurIPS 2023 (course reading).
- T. Dettmers, M. Lewis, S. Shleifer, L. Zettlemoyer, “8-bit Optimizers via Block-wise Quantization”, ICLR 2022; T. Dettmers, L. Zettlemoyer, “The case for 4-bit precision: k-bit Inference Scaling Laws”, ICML 2023.
- G. Xiao et al., “SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models”, ICML 2023; X. Wei et al., “Outlier Suppression: Pushing the Limit of Low-bit Transformer Language Models”, NeurIPS 2022; J. Yang, H. Kim, Y. Kim, “Mitigating Quantization Errors Due to Activation Spikes in GLU-Based LLMs”, 2024.
- E. Frantar, S. Ashkboos, T. Hoefler, D. Alistarh, “GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers”, ICLR 2023; J. Lin et al., “AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration”, MLSys 2024.
- B. Jacob et al., “Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference”, CVPR 2018; Y. Bengio, N. Léonard, A. Courville, “Estimating or Propagating Gradients Through Stochastic Neurons”, 2013.
- P. Micikevicius et al., “Mixed Precision Training”, ICLR 2018; P. Micikevicius et al., “FP8 Formats for Deep Learning”, 2022; OCP, “Microscaling Formats (MX) Specification”, 2023.
- Z. Allen-Zhu, Y. Li, “Physics of Language Models: Part 3.3, Knowledge Capacity Scaling Laws”, 2024; T. Kumar et al., “Scaling Laws for Precision”, 2024.
- llama.cpp k-quants: github.com/ggml-org/llama.cpp/pull/1684; Hugging Face Transformers, “Quantization overview” (the slides’ last link).
Preview of Lecture 20 — Parallelism and distributed training
Quantization shrinks a model so it fits on one device. The other way to handle large models is to use many devices. Lecture 20 starts from the memory anatomy of a training step:
- weights, gradients, Adam states, activations (the same bytes per parameter as §6.2’s table);
- activation recomputation and gradient accumulation;
- then data, tensor and pipeline parallelism, and ZeRO, which shards optimizer states, gradients and weights across GPUs.
All of them are simulated in one process, and each is checked to give exactly the same training step as a single device.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| quantization / dequantization | 量化 / 反量化 |
| bit / byte | 比特 / 字节 |
| unsigned integer / two’s complement / wraparound | 无符号整数 / 二进制补码 / 回绕 |
| floating point / sign / exponent / mantissa (significand) | 浮点数 / 符号位 / 指数位 / 尾数(有效数字) |
| bias / subnormal number | 偏置 / 次正规数 |
| machine epsilon / dynamic range / precision | 机器精度 / 动态范围 / 精度 |
| half precision (fp16) / bfloat16 / fp8 / fp4 | 半精度 / 脑浮点 16 / 8 位浮点 / 4 位浮点 |
| overflow / underflow / loss scaling | 上溢 / 下溢 / 损失缩放 |
| mixed-precision training / master weights | 混合精度训练 / 主权重 |
| accumulator | 累加器 |
| quantization error / step size / SQNR | 量化误差 / 量化步长 / 信号量化噪声比 |
| absmax (symmetric) quantization | 绝对值最大(对称)量化 |
| zero-point (asymmetric) quantization | 零点(非对称)量化 |
| scale / zero-point / calibration | 缩放因子 / 零点 / 校准 |
| granularity: per-tensor / per-row (per-channel) / per-token / block-wise | 粒度:逐张量 / 逐行(逐通道) / 逐词元 / 分块 |
| vector-wise quantization | 向量级量化 |
| outlier feature / emergent feature / phase shift | 离群特征 / 涌现特征 / 相变 |
| mixed-precision decomposition | 混合精度分解 |
| activation spike / heavy tail / kurtosis | 激活尖峰 / 重尾 / 峰度 |
| SmoothQuant / migration of quantization difficulty | 平滑量化 / 量化难度迁移 |
| weight-only quantization / W8A8 | 仅权重量化 / 权重与激活均 8 位 |
| memory-bound / compute-bound | 访存受限 / 计算受限 |
| codebook / data type / quantile quantization | 码本 / 数据类型 / 分位数量化 |
| NormalFloat (NF4) / double quantization | 正态浮点 4 位 / 双重量化 |
| k-quants / super-block / GGUF | k 量化 / 超块 / GGUF 文件格式 |
| microscaling (MX) / block scale | 微缩放格式 / 块缩放因子 |
| total model bits / k-bit scaling law | 模型总比特数 / k 比特缩放定律 |
| post-training quantization (PTQ) | 训练后量化 |
| quantization-aware training (QAT) / fake quantization | 量化感知训练 / 伪量化 |
| straight-through estimator / latent weights | 直通估计器 / 潜在权重 |
| QLoRA / adapter / paged optimizer | QLoRA / 适配器 / 分页优化器 |
| catastrophic forgetting / replay | 灾难性遗忘 / 回放 |
| second-order error compensation (GPTQ) | 二阶误差补偿 |
| fact recall / long tail / knowledge capacity | 事实召回 / 长尾 / 知识容量 |