Distillation and Quantization
local graph
Chapter 26 — Distillation and Quantization
Section titled “Chapter 26 — Distillation and Quantization”A frontier model is expensive to run, and most deployments cannot afford a 671-billion-parameter model behind every request. Two techniques shrink models for cheap inference without retraining from scratch: distillation transfers the capability of a large “teacher” into a small “student,” and quantization stores an existing model in fewer bits per weight. Together they are how a model that cost millions to train comes to run on a laptop or a single GPU. This chapter, closing Part VI, covers both — and connects back to the FP8 ideas of Chapter 18 and the QLoRA fine-tuning of Chapter 22.
26.1 Knowledge Distillation
Section titled “26.1 Knowledge Distillation”Distillation trains a small student model to imitate a large teacher. The key insight is that the teacher’s full output distribution — its “soft labels” — carries far more information than the single correct token: the relative probabilities it assigns to wrong answers encode how the teacher generalizes (sometimes called dark knowledge). The student is trained to match this distribution, usually with a temperature that softens both sides to expose the structure in the tails:
def distill_loss(student_logits, teacher_logits, T=2.0): s = (student_logits / T).log_softmax(dim=-1) # softened student t = (teacher_logits / T).softmax(dim=-1) # softened teacher target return F.kl_div(s, t, reduction="batchmean") * (T * T) # match distributionsPython — distill.py: soft-target distillation loss
For language models, a simpler and now-dominant variant is sequence-level distillation: just have the teacher generate text, and fine-tune the student on it with ordinary next-token loss. This is exactly what the DeepSeek-R1 distillation of Chapter 25 did — small Qwen and Llama students fine-tuned on R1’s reasoning traces acquired reasoning far beyond their size. Distillation works because learning to imitate a capable model is much easier than discovering the capability from scratch; the teacher has already done the hard search.
26.2 Quantization for Inference
Section titled “26.2 Quantization for Inference”Quantization reduces the number of bits used to store each weight (and sometimes each activation), directly cutting memory and bandwidth — which, per Chapter 2, is what bottlenecks inference. Chapter 18 quantized to FP8 during training; here we quantize an already-trained model for deployment, typically more aggressively, to INT8 or INT4. The arithmetic is the same as FP8’s: scale a group of weights so they fit the small integer range, store the low-bit values and the higher-precision scale, and dequantize on the fly. The fine-grained, group-wise scaling lesson from Chapter 18 returns in force — a single scale per tensor loses too much; a scale per small group preserves quality:
def quantize_int4(w, group=128): wg = w.reshape(-1, group) scale = wg.abs().amax(dim=-1, keepdim=True) / 7.0 # INT4 signed range [-8, 7] q = (wg / scale).round().clamp(-8, 7).to(torch.int8) return q, scale # dequantize as: q.float() * scalePython — quant.py: group-wise INT4 weight quantization
Weight-only quantization is the workhorse for LLM inference: weights dominate memory, and keeping activations in higher precision avoids most of the quality loss. Table 26.1 shows the trade-off.
| Format | Bits | Memory vs FP16 | Quality |
|---|---|---|---|
| FP16 / BF16 | 16 | 1.0× | reference |
| INT8 | 8 | 0.5× | near-lossless |
| INT4 (group-wise) | 4 | 0.25× | small loss, usually acceptable |
Table 26.1 — Inference precision trade-offs (weight-only)
26.3 Post-Training Quantization Methods
Section titled “26.3 Post-Training Quantization Methods”Naive rounding to 4 bits degrades quality noticeably; the well-known methods do better by being smart about which weights to protect. GPTQ quantizes layer by layer while using approximate second-order (curvature) information to minimize the resulting error in each layer’s output — accurate even at 4 bits, in a single pass. AWQ (Activation-aware Weight Quantization) observes that a small fraction of weight channels, identified by the magnitude of the activations that flow through them, matter disproportionately, and scales them to preserve their precision. Both are calibrated on a small sample of data and produce 4-bit models close to the original. Table 26.2 summarizes the common methods and where they are used.
| Method | Approach | Typical use |
|---|---|---|
| GPTQ | layer-wise, error-minimizing (curvature) | 4-bit GPU inference |
| AWQ | protect activation-salient weight channels | 4-bit GPU inference |
| GGUF (llama.cpp) | block “k-quant” formats | CPU and edge inference |
| bitsandbytes (NF4) | on-the-fly 4-bit, normal-float | QLoRA fine-tuning (Chapter 22) |
Table 26.2 — Common quantization methods
26.4 Small, Fast, and Deployable
Section titled “26.4 Small, Fast, and Deployable”The two techniques compose. A common deployment path takes a frontier model, distills its capability into a smaller dense model, quantizes that to 4 bits, and serves it from a single GPU or even a phone — and the same 4-bit base supports QLoRA fine-tuning for a specific task. This is why capability has diffused so quickly from frontier labs to laptops: once a large model exists, distillation and quantization make versions of its abilities cheap and portable. The cost asymmetry of Chapter 20 — millions to train, cents to run a distilled-and-quantized derivative — is the economic engine of the entire open-model ecosystem.
And as with everything in this part, the method is a short, real recipe. Quantizing a model to 4-bit with GPTQ — calibration set, group size, and all — is a few lines through the transformers quantization API:
from transformers import AutoModelForCausalLM, GPTQConfig
# 4-bit GPTQ with group-wise scaling, calibrated on a small setquant = GPTQConfig(bits=4, dataset="c4", group_size=128)model = AutoModelForCausalLM.from_pretrained( "base-model", quantization_config=quant, device_map="auto")model.save_pretrained("model-4bit-gptq") # a quarter the sizePython — huggingface/transformers: GPTQ 4-bit quantization (reproduced, Apache 2.0)
The parameters are exactly the chapter’s ideas: bits=4 is the target precision; group_size=128 is the fine-grained, group-wise scaling that preserves quality (the same 128-element grouping seen in FP8 training and the INT4 code above); and dataset=“c4” is the small calibration sample GPTQ uses to choose its quantization to minimize each layer’s output error. The result loads and serves like any other model — directly into vLLM, as the next chapter’s serving code showed. The distillation idea originates with Hinton et al.; GPTQ and AWQ are the standard 4-bit methods; 11ama.cpp popularized the GGUF formats for CPU and edge inference; and bitsandbytes provides the NF4 quantization behind QLoRA. Together they are the practical toolkit for shipping a large model cheaply — the closing capability of an aligned, reasoning model made small enough to run almost anywhere.
Part VI complete The base model of Part V is now a finished assistant: fine-tuned to follow instructions (Chapter 22), aligned to human preferences (Chapters 23–24), taught to reason by verifiable-reward RL (Chapter 25), and made small and cheap to run (this chapter). What remains is to deploy it well — serving it efficiently at scale and measuring it honestly — and then to build one of your own.
A trained, aligned model is only useful if it can be served to users at acceptable speed and cost, and only trustworthy if it can be evaluated honestly. Part VII turns from building the model to running and judging it, beginning with the mechanics and economics of inference.
26.5 Worked Example: The Distillation Loss
Section titled “26.5 Worked Example: The Distillation Loss”Distillation transfers a large teacher’s knowledge to a small student by matching the teacher’s full output distribution, not merely the hard label — the soft probabilities carry far more information. Temperature softens both distributions so the student sees the teacher’s relative preferences:
torch.no_grad(): t_logits = teacher(x) logits = student(x) # the large model # the small model T = 2.0 loss_kd = F.kl_div( F.log_softmax(s_logits / T, dim=-1), F.softmax(t_logits / T, dim=-1), reduction="batchmean") * (T * T) # T^2 keeps gradients scaled loss = alpha * loss_kd + (1 - alpha) * hard_label_loss # temperature softens targetsPython — distillation: match the teacher’s softened distribution
26.6 Quantization-Aware Training
Section titled “26.6 Quantization-Aware Training”Post-training quantization (Section 26.3) is cheap and, down to about four bits, remarkably good — but push lower and the rounding error starts to cost real accuracy. When it does, quantization-aware training earns its keep: simulate the quantization inside the forward pass during a short fine-tune so the weights can adapt to it. The obstacle is that rounding has a zero gradient almost everywhere; the straight-through estimator sidesteps it by passing the gradient through as if the rounding were the identity:
def fake_quantize(w, bits=4): qmax = 2 ** (bits - 1) - 1 scale = w.abs().max() / qmax wq = torch.round(w / scale).clamp(-qmax - 1, qmax) * scale return w + (wq - w).detach() # forward: wq; backward: to wPython — quant/qat.py: fake quantization with a straight-through estimator
The single expression is the whole trick. Numerically it equals , so the forward pass sees the quantized weight and the network learns under the constraint it will face at inference. But because the difference is detached, autograd treats the operation as for the backward pass, and the gradient flows to the full-precision untouched. Over a few thousand steps the weights migrate toward values that survive rounding cleanly, buying back much of the accuracy that naive low-bit PTQ would have lost.
26.7 Worked Example: Sizing a Quantized Model
Section titled “26.7 Worked Example: Sizing a Quantized Model”Quantization’s first payoff is memory, and the arithmetic is simple enough to do in your head. Parameter storage is just parameter count times bytes per parameter; the precision sets the second factor. For a 7-billion-parameter model:
| Precision | Bits/param | Weight memory | Fits on |
|---|---|---|---|
| FP16 / BF16 | 16 | ~14 GB | one 24 GB GPU |
| INT8 | 8 | ~7 GB | one 12 GB GPU |
| INT4 | 4 | ~3.5 GB | a laptop GPU |
Table 26.1 — Weight memory for a 7B model by precision
The progression is what democratizes access: a model that needs a data-center card at full precision runs on consumer hardware at four bits, which is exactly why the quantization formats of Section 26.3 dominate local deployment (and why GLM-5.2 and DeepSeek-V3 ship INT4 builds for llama.cpp and Ollama, Chapter 33). Two caveats keep the estimate honest: the quantization scales add a few percent of overhead, and the KV cache (Chapter 27) is stored separately — at long context it can rival the weights, and it is quantized on its own terms.
Weights are only half the budget Sizing a deployment means weights plus KV cache plus activation scratch. At short context the weights dominate and these tables hold; at 100K+ tokens the KV cache can exceed the weights, and quantizing it (Chapter 27) becomes as important as quantizing the parameters.
26.8 Distillation with Soft Targets
Section titled “26.8 Distillation with Soft Targets”The original form of knowledge distillation, and still one of the most effective, trains a small student to imitate not a large teacher’s final answer but its entire output distribution. The teacher’s “soft” probabilities — that the answer is 80% one token, 15% another, 5% a third — carry information a hard label discards: how the teacher relates the options, what it considers a near-miss. A temperature smooths the distribution to expose that structure, and the student matches it through a KL divergence:
T = 2.0 # temperature softens bothsoft_teacher = F.softmax(teacher_logits / T, dim=-1)soft_student = F.log_softmax(student_logits / T, dim=-1)loss = F.kl_div(soft_student, soft_teacher, reduction="batchmean") * (T * T)Python — distill/soft.py: matching a temperature-softened teacher
Two details make the recipe work. The temperature applied to both networks flattens the distributions so the student learns from the teacher’s relative confidences rather than only its top choice — the “dark knowledge” that a plain label cannot convey. And the loss is multiplied by to restore the gradient magnitude that the temperature division shrank, so the soft loss can be combined on equal footing with an ordinary label loss on the true targets. Applied across a corpus, this is how a compact student can inherit much of a far larger teacher’s behavior at a fraction of the inference cost — the same logic that produced the distilled reasoning models of Section 25.5, where a small model is trained on the traces of a large one.
The teacher’s uncertainty is the lesson Hard labels say only what is correct; a teacher’s softened distribution says what is almost correct, and that relative structure is what the student learns. Temperature exposes it; the factor keeps the gradient honest.
26.9 Pruning and Structured Sparsity
Section titled “26.9 Pruning and Structured Sparsity”Quantization (Section 26.3) shrinks a model by storing each weight in fewer bits; pruning shrinks it by removing weights entirely. The two are complementary compression axes, and pruning comes in two forms that differ sharply in how much real speedup they deliver. Unstructured pruning zeros out individual weights wherever they are least important; it can remove a large fraction of parameters, but the resulting irregular sparsity is hard for GPUs to exploit, so the memory shrinks while the speed often does not.
Structured pruning instead removes whole units — entire attention heads, FFN neurons, or even layers — leaving a smaller but still dense model that runs faster on ordinary hardware with no special kernels. The cost is that removing whole structures is
blunter and tends to hurt quality more per parameter removed, which is why structured pruning is almost always followed by a short fine-tune to let the remaining weights compensate for what was cut. In practice, pruning is less dominant for large language models than quantization — a 4-bit model (Section 26.7) is usually a better return than a pruned one — but it remains a useful tool, especially structured pruning of heads and layers when a specific latency target must be hit and quantization alone has not reached it.
Removing structures, not scattered weights, buys speed Unstructured pruning shrinks memory but leaves sparsity GPUs cannot use; structured pruning removes whole heads or layers for real speedup, then fine-tunes to recover. For LLMs it complements quantization rather than replacing it.
26.10 GPTQ and AWQ: Post-Training Quantization Methods
Section titled “26.10 GPTQ and AWQ: Post-Training Quantization Methods”Section 26.4 contrasted post-training quantization with quantization-aware training; the reason post-training quantization is so widely used at 4 bits is a pair of clever algorithms that quantize a finished model with surprisingly little quality loss and no retraining. They are what most 4-bit open models actually use, and they work by being smarter than naive rounding.
GPTQ quantizes the weights one layer at a time, and within a layer processes the weight columns in sequence — but crucially, after quantizing each column it compensates the remaining unquantized columns to absorb the error just introduced, using second-order (curvature) information about how much each weight matters. The result is that the quantization error does not simply accumulate; it is continually corrected against as the algorithm proceeds. AWQ takes a different angle, observing that not all weights are equally important: the weights that multiply large activations matter most to the output, so AWQ identifies and protects those salient weights — scaling them so they survive quantization with more precision — while quantizing the rest aggressively. Both achieve good 4-bit fidelity without the cost of
e*training that quantization-aware training demands (Section 6.4), which is exactly why they dominate practical deployment: a model trained once in full precision can be compressed to a quarter of its memory, on a single machine in minutes, with quality good enough that the savings (Section 34.6) are nearly free. They are the workhorses behind the quantized builds that run frontier models on consumer hardware (Section 33.6). Quantize smart, skip the retraining GPTQ corrects error as it quantizes column by column; AWQ protects the weights that multiply large activations. Both hit good 4-bit quality with no retraining — which is why they, not QAT, power most deployed quantized models.