Area 01 // LLMsLesson 29 / 14014 min read
Quantization and distillation
Quantization shrinks a model by storing its weights with fewer bits (16 → 8 → 4), and distillation trains a small "student" model to copy a big "teacher" model; both make models cheaper and faster to run with only a small loss in quality.
Think of it like this
Analogy
Quantization is like saving a photo as a smaller JPEG. At high quality you can't see the difference and the file is a quarter of the size; squeeze too hard and it gets blocky.
Distillation is a master chef training an apprentice. The apprentice never reads all the books the master read, but by watching thousands of the master's dishes, they learn to cook most of them nearly as well, faster and for a lower wage.
The problem it solves
Big models are expensive to run. A 70B model in 16-bit needs about 140 GB of GPU memory just for its weights, which means several expensive GPUs per copy. Even an 8B model at 16-bit (16 GB) won't fit on most laptops. Meanwhile many tasks don't need a giant model's full ability.
Teams need ways to make models smaller and faster without losing what matters for their task. Quantization and distillation are the two main tools, and they're why you can run decent models on a laptop with Ollama.
How it works: quantization
- Weights are normally stored as 16-bit numbers (BF16/FP16): 2 bytes each.
- Quantization stores them with fewer bits: 8-bit (1 byte), 4-bit (half a byte), even lower. Each block of weights gets a scale factor; each weight becomes a small integer.
- At run time, values are scaled back (approximately) for the maths, or the maths runs directly in low precision on hardware that supports it.
- Memory drops roughly in proportion to bits (VRAM is often the limit), and generation often gets faster because less data moves through memory for each token.
- Quality drops slightly: usually negligible at 8-bit, small at good 4-bit methods, more noticeable at 3-bit and below. Smart methods (GPTQ, AWQ, k-quants) protect the most important weights.
- Formats you'll meet: GGUF (llama.cpp, Ollama, LM Studio; names like
Q4_K_M,Q8_0), AWQ/GPTQ (GPU serving with vLLM), FP8 (data-centre GPUs). - The KV cache can be quantized too, freeing memory for longer contexts and more users.
How it works: distillation
- Pick a strong teacher (a large model) and a small student architecture.
- Generate training data with the teacher: its answers to many prompts (and sometimes its full probability distribution over next tokens, which carries more information than the single answer).
- Train the student to reproduce the teacher's outputs (SFT on teacher answers, or matching its distributions).
- Result: a model several times smaller that keeps much of the teacher's ability on the distilled tasks, at a fraction of the cost and latency.
- Task-specific distillation is common in companies: use a top model to label or answer 50,000 of your real requests, then fine-tune a small model on them (LoRA).
- Check the terms: some providers' terms restrict using their outputs to train competing models.
See it in code
- Install
pip install numpy- Needs
- Python 3.10+
Memory at each precision, then quantizing real numbers to 8-bit and measuring the error.
import numpy as np
# 1) Memory for the weights of an 8-billion-parameter model at different precisions.
params = 8e9
for name, bits in [("FP32", 32), ("FP16/BF16", 16), ("INT8", 8), ("4-bit", 4)]:
print(f"{name:9}: {params * bits / 8 / 1e9:5.1f} GB")
# 2) Quantize some weights to 8-bit integers and back, and measure the error.
rng = np.random.default_rng(0)
w = rng.normal(0, 0.02, size=10_000).astype(np.float32) # typical small weights
scale = np.abs(w).max() / 127 # map the largest weight to 127
q = np.round(w / scale).astype(np.int8) # store 1 byte per weight instead of 4
w_back = q.astype(np.float32) * scale # what the model uses at run time
print("int8 values look like:", q[:6])
print(f"average error: {np.abs(w - w_back).mean():.6f} (weights are around {np.abs(w).mean():.4f})")FP32 : 32.0 GB
FP16/BF16: 16.0 GB
INT8 : 8.0 GB
4-bit : 4.0 GB
int8 values look like: [ 4 -4 21 3 -17 12]
average error: 0.000154 (weights are around 0.0160)The 8-bit version is off by about 1% of a typical weight, which models tolerate well. In Ollama, the default download of most models is already 4-bit (ollama pull llama3.2 gets a Q4 GGUF); tags let you choose others.
A real example
Example
From four GPUs to one
A company served a 70B open model for internal search at 16-bit on four large GPUs. They tried an AWQ 4-bit version: it fit on one GPU, generated faster, and scored within one point of the original on their 400-question eval. Three GPUs were freed.
For their highest-volume feature (tagging documents), they went further: a top closed model labelled 40,000 real documents, and they fine-tuned an 8B student on those labels. The student matched the teacher on 94% of a held-out set and costs a small fraction to run. Quantization saved hardware; distillation saved a whole model tier.
The easy way
Start here
On a laptop, just use Ollama's default 4-bit models; that's quantization done for you. If you self-host on GPUs, start with an official FP8 or AWQ/GPTQ 4-bit version of your model and compare it with the full-precision one on your evals before switching.
When you grow: the production setup
Production teams treat quantized and distilled models as new model versions: benchmark quality per task, latency and throughput, check safety behaviour, register them, roll out with canaries, and monitor for quality drift. Distillation pipelines need data governance (provider terms, user data consent) and periodic refresh from the teacher.
Trade-offs
What you gain
- Quantization cuts memory 2–4× and often speeds up generation, with small quality loss.
- Distillation produces small, cheap, fast models for specific tasks.
- Together they let good models run on laptops, phones and single GPUs.
What it costs you
- Some quality loss, larger at very low bit widths and on hard tasks (maths, code).
- Distilled students are narrower than their teachers and need training infrastructure.
- Formats and tools vary by hardware and serving engine.
When not to use it
- Quality is critical and hardware isn't the constraint: serve full precision.
- You use closed API models: providers already handle this internally (their smaller models are your "distilled" option).
Common mistakes
- Going straight to the smallest quant (2–3 bit) and not measuring the quality drop.
- Forgetting KV cache and runtime memory when checking if a quantized model fits.
- Distilling from a provider's model without checking its terms.
- Comparing models at different quantization levels as if they were the same.
- Not re-running evals after changing quantization.
Interview questions
Try answering out loud first, then open the model answer.
What is quantization and what are the trade-offs?
Model answer
Quantization represents weights (and possibly activations and KV cache) with fewer bits, e.g. INT8 or 4-bit with per-block scales. It reduces memory roughly proportionally and often increases throughput because inference is memory-bandwidth-bound. Trade-offs: some accuracy loss (small at 8-bit, task-dependent at 4-bit, larger below), calibration effort for methods like GPTQ/AWQ, and hardware/kernel support constraints.
How does knowledge distillation work?
Model answer
A large teacher model generates targets (answers, or soft probability distributions) for many inputs; a smaller student is trained to match them, often with a loss on the teacher's soft labels plus ground-truth labels. Soft labels carry information about similarities between outputs, so the student learns more per example. The student keeps much of the teacher's task performance at lower cost and latency.
How would you fit an 8B model on a 12 GB GPU and still serve long prompts?
Model answer
Use a 4-bit quantized version (~4.5–5.5 GB of weights), leaving room for the KV cache; quantize the KV cache to 8-bit if supported; limit max context and concurrent sequences; use an efficient serving engine with paged KV memory; and benchmark quality on evals versus the 16-bit model. If quality drops too much, try 8-bit weights with a shorter context.
Quiz
Pick an answer to see whether it’s right and why.
0 of 6 answered
Key terms
- Quantization
- Storing a model's numbers with fewer bits (e.g. 4-bit instead of 16-bit) to save memory and speed it up, with a small quality loss.
- Distillation
- Training a small student model to imitate a large teacher model's outputs, keeping much of its quality at lower cost.
- GGUF
- A file format for quantized models used by llama.cpp, Ollama and LM Studio.
- Teacher and student models
- In distillation, the large model that produces answers (teacher) and the smaller model trained to copy them (student).
- VRAM
- The memory on a GPU. Model weights, the KV cache and activations must fit in it, so it usually limits which models a GPU can run.
Before and after
Progress is saved in this browser only.