Advanced about 5 h
The picture
01
Trained model
bf16
02
Quantise
8 or 4 bit
03
Measure
quality, speed, memory
04
Distil
teacher → student
05
Deploy
GGUF, vLLM
Quantisation in one picture
Store weights with fewer bits. Map the float range onto a small integer range with a scale:
import torch
def quantise_sym(w: torch.Tensor, bits: int = 8):
qmax = 2 ** (bits - 1) - 1
s = w.abs().max() / qmax
q = torch.clamp(torch.round(w / s), -qmax, qmax)
return q.to(torch.int8), s
w = torch.randn(4096, 4096)
for bits in (8, 4):
q, s = quantise_sym(w, bits)
err = (w - q.float() * s).pow(2).mean().sqrt().item()
print(bits, "bit, RMS error", round(err, 5))
One scale for a whole tensor is crude: a single outlier stretches the range for everyone. Real schemes use per-channel or per-group scales (for example groups of 64 or 128 weights), and handle outlier features specially (LLM.int8).
The methods you will meet
- Weight-only, round to nearest (bitsandbytes 8-bit and NF4): simplest; good for loading and QLoRA.
- GPTQ: quantises layer by layer using second-order information to minimise output error; strong 4-bit quality.
- AWQ: protects the small fraction of weights that matter most for activations by scaling them first.
- GGUF (llama.cpp): a file format with many quantisation types, for CPU and mixed CPU/GPU inference, used by local runners.
- FP8 and activation quantisation: speed up compute as well as memory on supporting hardware.
# GGUF with llama.cpp
python convert_hf_to_gguf.py ./out/merged --outfile model-f16.gguf
./llama-quantize model-f16.gguf model-Q4_K_M.gguf Q4_K_M
./llama-cli -m model-Q4_K_M.gguf -p "Explain KV caching in two sentences."
Always measure the loss
Quantisation lowers memory and often raises throughput, but it can hurt quality, more so on smaller models, long reasoning and low-resource languages. Evaluate on your task:
def compare(models, eval_set, score):
for name, generate in models.items():
acc = sum(score(generate(x["prompt"]), x["answer"]) for x in eval_set) / len(eval_set)
print(f"{name:12s} acc={acc:.3f}")
Report accuracy, peak memory, tokens per second and cost per million tokens for 16-bit, 8-bit and 4-bit.
Distillation
Train a small student to imitate a large teacher.
- Logit distillation: match the teacher's soft probabilities, which carry more information than hard labels. A temperature softens both distributions.
- Sequence-level (data) distillation: have the teacher generate high-quality outputs and SFT the student on them. Simple and the dominant approach for LLMs, including distilling reasoning traces.
import torch.nn.functional as F
def distill_loss(student_logits, teacher_logits, labels, T=2.0, alpha=0.5):
kd = F.kl_div(F.log_softmax(student_logits / T, -1), F.softmax(teacher_logits / T, -1), reduction="batchmean") * (T * T)
ce = F.cross_entropy(student_logits.view(-1, student_logits.size(-1)), labels.view(-1), ignore_index=-100)
return alpha * kd + (1 - alpha) * ce
Check the teacher's licence and terms of use: some providers forbid training competing models on their outputs.
A deployment path
Fine-tune with LoRA, merge into a full-precision base, distil or quantise, evaluate against the baseline, then serve with an engine that supports the format (vLLM for GPU serving, llama.cpp or Ollama locally).
Common mistakes
- Quantising a model and never re-running the evaluation set.
- Quantising an adapter-merged model before checking the merge.
- Distilling from outputs you have not filtered for correctness.
Exercises
- Produce Q8 and Q4 versions of a fine-tuned model and plot quality against memory.
- Distil answers from a stronger model into a 0.5B student for a narrow task and compare with direct fine-tuning on human labels.
You are done when you can…
- Quantise a tensor symmetrically and compute its error
- Compare 16-bit, 8-bit and 4-bit versions on quality, memory and throughput
- Implement a distillation loss and explain the role of temperature