AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
★Advanced & Frontier Topics
  1. Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding
  2. Mixture of Experts: Bigger Models at the Same Compute
  3. Distributed Training: Many GPUs, One Model
  4. Interpretability: Opening the Black Box
  5. AI Safety & Ethics: Bias, Hallucination, Alignment and Regulation
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Advanced & Frontier Topics

Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding

Why serving large models is expensive and the main tricks to make it cheaper: quantization (int8, 4-bit, GPTQ), knowledge distillation, pruning, the KV cache, FlashAttention and speculative decoding.

Advanced~30 min·6 references
Key terms
QuantizationKnowledge distillationPruningKV cacheFlashAttentionSpeculative decodingLatencyGPU

Training a model happens once; Inference happens millions of times a day. For LLMs the bill is dominated by memory: a 7-billion-parameter model in 16-bit floats needs 14 GB just for its weights, and while generating, every new token requires reading *all* of those weights from GPU memory. Making inference efficient means shrinking what must be stored and moved (quantization, distillation, pruning), avoiding recomputation (KV cache), using the hardware smarter (FlashAttention), and producing more tokens per expensive forward pass (speculative decoding). These tricks are why a capable model can run on a laptop or a phone today.

≈
Analogy: moving house on a budget
You can pack tighter (quantization: same items, fewer bits each), hire a smaller truck driven by a trained apprentice (distillation: a small student imitates a large teacher), throw out what you never use (pruning), keep a list of what is already loaded instead of re-checking every box (KV cache), plan trips to avoid going back and forth to the warehouse (FlashAttention), and let an intern pack boxes quickly while the senior only checks them (speculative decoding).

Where the memory and time go

During autoregressive decoding with a small batch, the GPU spends most of its time *waiting for memory*, not computing: each token does roughly 2 FLOPs per parameter but must stream every parameter from high-bandwidth memory (HBM). So a rough upper bound on single-stream speed is memory bandwidth ÷ model size. Halving the bytes per weight roughly doubles tokens per second — which is why quantization helps speed as well as fit.

weights = N_params × bytes/param tokens/s ≲ memory bandwidth / weights e.g. 2 TB/s ÷ 14 GB ≈ 140 tok/s
Real systems reach less than this bound, but the proportionality holds for small-batch decoding.
In words: “the model's size in bytes is parameters × bytes per parameter, and since every generated token must read all of those bytes once, speed can be at most bandwidth divided by size”. Smaller weights (quantization) → proportionally more tokens per second.
Symbols(hover a symbol in the formula)
weights
total bytes of model weights that must be streamed per token
N_params
number of parameters (e.g. 7B = 7 × 10⁹)
bytes/param
storage per parameter: 4 (FP32), 2 (FP16/BF16), 1 (INT8), 0.5 (4-bit)
tokens/s
generation speed for a single sequence
≲
“is at most roughly”: an upper bound real systems do not quite reach
memory bandwidth
how many bytes per second the GPU can read from HBM (e.g. 2 TB/s on an A100 80 GB)
≈
approximately equal
▸Worked example
7B model in FP16: 7 × 10⁹ × 2 bytes = 14 GB 2 TB/s ÷ 14 GB ≈ 143 tokens/s (upper bound) Same model in 4-bit: 7 × 10⁹ × 0.5 = 3.5 GB → 2 TB/s ÷ 3.5 GB ≈ 571 tokens/s
FormatBytes / param7B model70B model
FP32428 GB280 GB
FP16 / BF16214 GB140 GB
INT817 GB70 GB
4-bit (INT4 / NF4)0.53.5 GB35 GB
Weights only; add the KV cache, activations and quantization metadata (scales) on top.

1. Quantization

Quantization stores numbers with fewer bits by mapping a range of real values onto a small grid of integers plus a scale (and sometimes a zero-point). Symmetric absmax quantization scales by the largest absolute value; asymmetric min-max uses the full [min, max] range, wasting fewer levels when values are skewed. Using one scale for a whole tensor is fragile: a single large outlier stretches the grid so most normal weights collapse onto a few levels. Hence per-channel or per-group/block scales (e.g. one scale per 64 or 128 weights).

symmetric (absmax): s = max|w| / (2^(b−1) − 1), q = round(w / s), ŵ = s·q
In words: “pick one scale so that the largest weight maps to the largest integer, divide every weight by that scale and round, then multiply back to use it”. Zero stays exactly zero; the price is that one outlier stretches the scale for everybody.
Symbols(hover a symbol in the formula)
s
the scale: real-valued step size between neighbouring integer levels
max|w|
largest absolute weight value in the tensor (or row/group)
2^(b−1) − 1
largest positive integer with b signed bits: 127 for 8-bit, 7 for 4-bit
b
number of bits per weight
q
the stored integer
round
round to the nearest integer
w
an original (full-precision) weight
ŵ
w-hat: the dequantized approximation of w used in computation
▸Worked example
w = [0.5, −1.2, 0.035, 2.54], b = 8 s = 2.54 / 127 = 0.02 q = round([25, −60, 1.75, 127]) = [25, −60, 2, 127] ŵ = 0.02 · q = [0.5, −1.2, 0.04, 2.54] Error on 0.035 is 0.005 — never more than s/2 = 0.01.
asymmetric (min-max): s = (max − min) / (2^b − 1), z = round(−min / s), q = clamp(round(w / s) + z, 0, 2^b − 1), ŵ = s·(q − z)
b = bits. The rounding error per weight is at most s/2, so a bigger scale (from outliers) means bigger errors for everyone.
In words: “stretch the range [min, max] over all 2^b integer levels and shift it with a zero-point z so that min lands on 0”. Useful when values are lopsided (e.g. mostly positive activations), because no levels are wasted on a range that never occurs.
Symbols(hover a symbol in the formula)
s
scale: size of one integer step
max
largest value in the tensor
min
smallest value in the tensor
2^b − 1
largest unsigned integer with b bits: 255 for 8-bit, 15 for 4-bit
z
zero-point: the integer that represents the real value 0
round
round to the nearest integer
clamp
clamp(x, 0, 2^b − 1) cuts x off at the ends of the integer range
q
the stored unsigned integer
w
original value
ŵ
dequantized approximation of w
▸Worked example
Range [−0.5, 1.5], b = 4 (16 levels) s = 2.0 / 15 = 0.1333, z = round(0.5 / 0.1333) = round(3.75) = 4 w = 0.7: q = round(5.25) + 4 = 9 ŵ = 0.1333 · (9 − 4) = 0.667 w = −0.5: q = round(−3.75) + 4 = 0 ŵ = 0.1333 · (0 − 4) = −0.533

Post-training quantization (PTQ) quantizes a finished model, optionally with a small calibration set; quantization-aware training (QAT) simulates rounding during training so the model adapts. For LLMs, PTQ dominates: LLM.int8() (Dettmers et al., 2022)[1] found that models beyond ~6.7B parameters develop a few huge outlier features and kept those dimensions in 16-bit while the rest runs in int8. GPTQ (Frantar et al., 2022)[2] quantizes weights to 3–4 bits one layer at a time, using approximate second-order information to compensate the error of each rounded weight by adjusting the not-yet-quantized ones — a 175B model in about four GPU hours. QLoRA's NF4 data type places its 16 levels where normally-distributed weights are densest.

Loading interactive…
Quantize a set of weights live: compare the original and quantized histograms, the grid of representable levels, the error, and the memory a 7B model would need.
  • Bits: slide from 16 down to 2 with the symmetric scheme. MSE barely moves until ~6 bits, then grows quickly; at 2 bits only 3–4 levels remain and the histogram becomes a few spikes. Note the 7B memory dropping from 14 GB to under 2 GB.
  • Outliers: at 4 bits, toggle outliers on. With absmax, the grid stretches to reach the outliers and most weights fall into the 1–3 levels around zero — max error and MSE jump.
  • Per-block scaling: with outliers still on, switch to per-block. Only the blocks containing an outlier suffer; the others get tight grids and the MSE drops sharply. Try smaller block sizes and notice the trade-off: better accuracy, but more scales to store.
  • Asymmetric vs symmetric: asymmetric min-max helps most when the distribution is lopsided; for zero-centred weights the two are close.

2. Knowledge distillation

Knowledge distillation (Hinton et al., 2015)[3] trains a small student to match a large teacher's output distribution, not just the hard labels. The teacher's “soft targets” carry *dark knowledge*: for a picture of a cat, “dog 8%, car 0.01%” tells the student which mistakes are reasonable. A temperature T > 1 softens both softmaxes so these small probabilities matter. DistilBERT kept ~97% of BERT's language-understanding performance while being 40% smaller and 60% faster; many small open LLMs are distilled from larger ones using the teacher's generated text or logits.

L = α · T² · KL( softmax(z_teacher / T) ‖ softmax(z_student / T) ) + (1 − α) · CE(y, softmax(z_student))
The T² factor keeps the soft-target gradients on the same scale as the hard-label ones.
In words: “a mix of two lessons: match the teacher's softened probabilities (which classes it thinks are similar), and still get the true label right”. A temperature T > 1 flattens both distributions so the small “dark knowledge” probabilities become visible.
Symbols(hover a symbol in the formula)
L
total distillation loss for the student
α
alpha (0–1): weight of the soft-target term vs. the hard-label term
T²
temperature squared: rescales soft-target gradients, which shrink like 1/T²
T
temperature (e.g. 2–5); dividing logits by T softens the softmax
KL(
Kullback–Leibler divergence between teacher and student distributions
‖
separates the two distributions compared by KL
softmax
turns logits into probabilities that sum to 1
z_teacher
logits of the large teacher model
z_student
logits of the small student model
CE(
cross-entropy with the true label
y
the true (hard) label
▸Worked example
3 classes, true class 0, T = 2, α = 0.5 teacher z = [4, 1, 0] → softmax(z/T) = [0.736, 0.164, 0.100] (at T = 1: [0.936, 0.047, 0.017]) student z = [3, 1.5, 0] → softmax(z/T) = [0.590, 0.279, 0.132] KL ≈ 0.0486 → T² · KL ≈ 0.194 CE = −ln(softmax(z_student)[0]) = −ln(0.786) ≈ 0.241 L = 0.5 · 0.194 + 0.5 · 0.241 ≈ 0.218

3. Pruning

Pruning removes weights that matter little. Unstructured pruning zeroes individual weights (usually smallest magnitude) and can remove 80–90% of some networks with little loss after fine-tuning — Deep Compression (Han et al., 2015)[4] combined pruning, quantization and Huffman coding to shrink AlexNet 35× and VGG-16 49×. But scattered zeros rarely speed up GPUs. Structured pruning removes whole neurons, attention heads, channels or layers, giving real speedups at a larger accuracy cost. NVIDIA GPUs since Ampere accelerate a middle ground: 2:4 sparsity (2 of every 4 consecutive weights are zero).

4. The KV cache

In a decoder Transformer, each new token attends to the keys and values of all previous tokens. Recomputing them every step would make generation quadratic; the KV cache stores them instead. The price is memory that grows with sequence length and batch size — often more than the weights for long contexts. Remedies: grouped-query / multi-query attention (several query heads share one K/V head), quantizing the cache to 8 or 4 bits, and paged cache management (as in vLLM) that avoids fragmentation so more requests fit in a batch.

KV bytes = 2 × layers × kv_heads × head_dim × seq_len × batch × bytes/value
Llama-2-7B (32 layers, 32 KV heads × 128, FP16): 0.5 MB per token → 2 GB for one 4,096-token sequence.
In words: “for every layer, every KV head and every token in every sequence, the cache stores one key vector and one value vector”. Memory grows linearly with context length and batch size, which is why long contexts are expensive and why grouped-query attention (fewer KV heads) helps.
Symbols(hover a symbol in the formula)
KV bytes
total memory of the key–value cache
2 ×
one key and one value per position
layers
number of Transformer layers
kv_heads
number of key/value heads (equal to query heads in classic attention, fewer with GQA/MQA)
head_dim
size of each head's vector (often 128)
seq_len
tokens in the context so far (prompt + generated)
batch
number of sequences served at once
bytes/value
2 for FP16/BF16, 1 for an 8-bit cache
▸Worked example
Llama-2-7B: 32 layers, 32 KV heads × 128, FP16 per token: 2 × 32 × 32 × 128 × 2 B = 524,288 B = 0.5 MB 4,096 tokens, batch 1: 0.5 MB × 4,096 = 2 GB batch 8: 16 GB — more than the 14 GB of weights! With 8 KV heads (GQA): 2 GB / 4 = 0.5 GB per sequence.

5. FlashAttention

Standard attention writes the full N × N score matrix to slow GPU memory, applies softmax, and reads it back. FlashAttention (Dao et al., 2022)[5] is IO-aware: it splits Q, K, V into tiles that fit in fast on-chip SRAM, computes attention tile by tile with an online softmax (running max and sum), and never materialises the full matrix. The result is exact attention — not an approximation — with memory linear in sequence length and several-fold speedups, which is a big part of why context windows grew so quickly. In PyTorch it is used automatically through scaled_dot_product_attention on supported GPUs.

6. Speculative decoding

Because decoding is memory-bound, checking 5 tokens in one forward pass costs about the same as generating 1. Speculative decoding (Leviathan et al., 2022)[6] exploits this: a small, fast draft model proposes γ tokens; the large target model scores all of them in parallel; each draft token is accepted with probability min(1, p_target / p_draft), and at the first rejection a corrected token is sampled from the leftover distribution. The output distribution is provably identical to sampling from the target model alone — no quality loss — with typical 2–3× speedups when the draft agrees often.

E[tokens per target pass] = (1 − a^(γ+1)) / (1 − a)
a = average acceptance rate. With a = 0.8 and γ = 4: ≈ 3.4 tokens per expensive pass instead of 1.
In words: “the average number of tokens you get for each expensive target-model pass”. It is a geometric series: you always get at least 1 token, and each extra draft token survives with probability a, up to γ + 1 tokens in total.
Symbols(hover a symbol in the formula)
E[
expected value: average over many rounds
a
acceptance rate: probability a draft token is accepted (how well the draft agrees with the target)
γ
gamma, number of draft tokens proposed per round (e.g. 3–7)
a^(γ+1)
a raised to the power γ + 1
▸Worked example
γ = 4, a = 0.8: (1 − 0.8⁵) / (1 − 0.8) = (1 − 0.32768) / 0.2 ≈ 3.36 tokens per pass γ = 4, a = 0.5: (1 − 0.03125) / 0.5 ≈ 1.94 γ = 4, a = 0.9: (1 − 0.59049) / 0.1 ≈ 4.10 (max possible is γ + 1 = 5)
Loading interactive…
One round of speculative decoding. Walk through the steps: the draft guesses, the target checks all guesses in one pass, and the round always ends with at least one new token. Tap Correction token to see why the output distribution stays exactly the target model's.

The knobs

knobbits (weight precision)
What it is
Number of bits per stored weight (16, 8, 4, 3, 2…).
↑ If you increase it
Closer to the original model's quality; more memory and slower memory-bound decoding.
↓ If you decrease it
Smaller and usually faster; 8-bit is nearly lossless, 4-bit costs a little, 3-bit and below degrade noticeably — small models suffer more than large ones.
Typical values
8-bit for safety, 4-bit (NF4, GPTQ, AWQ, GGUF Q4) as the popular sweet spot for local LLMs.
knobgroup / block size
What it is
How many weights share one scale (and zero-point) in group-wise quantization.
↑ If you increase it
Fewer scales to store (lower overhead), but each group is more likely to contain an outlier, raising error.
↓ If you decrease it
Tighter grids and lower error, but more metadata: at group size 32 with FP16 scales, a 4-bit weight effectively costs 4.5 bits.
Typical values
64 or 128 (bitsandbytes NF4 uses 64).
knobdistillation temperature T (and α)
What it is
T softens teacher and student distributions; α balances soft-target loss against the normal hard-label loss.
↑ If you increase it
Higher T exposes more “dark knowledge” in small probabilities; too high flattens everything into noise. Higher α relies more on the teacher.
↓ If you decrease it
T = 1 uses raw probabilities, which are often near one-hot, so the student learns little beyond the labels.
Typical values
T = 2–5, α = 0.5–0.9.
knobsparsity (pruning ratio)
What it is
Fraction of weights (or structures) removed.
↑ If you increase it
Smaller model; beyond a point accuracy falls off a cliff, and needs fine-tuning to recover.
↓ If you decrease it
Safer accuracy, little saving.
Typical values
50% (2:4) for GPU speedups; up to 80–90% unstructured for compression-only use.
knobdraft length γ (num_assistant_tokens)
What it is
How many tokens the draft model proposes before the target verifies.
↑ If you increase it
More tokens per target pass when the draft is accurate, but wasted draft work after an early rejection.
↓ If you decrease it
Less waste, but fewer tokens gained per verification.
Typical values
3–8; some libraries adapt it automatically based on acceptance.

In code

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",              # NormalFloat4 levels
    bnb_4bit_use_double_quant=True,         # also quantize the scales
    bnb_4bit_compute_dtype=torch.bfloat16,  # matmuls run in bf16
)
name = "Qwen/Qwen2.5-7B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, quantization_config=bnb,
                                             device_map="auto")
print(f"{model.get_memory_footprint() / 1e9:.1f} GB")   # ~5 GB instead of ~15 GB
4-bit loading with bitsandbytes through Hugging Face Transformers (needs a CUDA GPU).
python
# Speculative (assisted) decoding: a small draft model from the same family
draft = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct",
                                             torch_dtype=torch.bfloat16, device_map="auto")
inputs = tok("Jelaskan apa itu kuantisasi dalam dua kalimat.", return_tensors="pt").to(model.device)
out = model.generate(**inputs, assistant_model=draft, max_new_tokens=120)
print(tok.decode(out[0], skip_special_tokens=True))

# Knowledge distillation loss (PyTorch)
import torch.nn.functional as F
def distill_loss(s_logits, t_logits, labels, T=2.0, alpha=0.7):
    soft = F.kl_div(F.log_softmax(s_logits / T, -1), F.softmax(t_logits / T, -1),
                    reduction="batchmean") * T * T
    return alpha * soft + (1 - alpha) * F.cross_entropy(s_logits, labels)
Draft and target must share a tokenizer. Speedups are largest at batch size 1 and on predictable text.
!
Common pitfalls
Evaluate on your task: perplexity may barely move while accuracy on math, code or low-resource languages (including Indonesian) drops more — always run your own Evals. Smaller isn't always faster: without optimized kernels, dequantizing can make int8/4-bit *slower* than FP16, especially at large batch sizes, which are compute-bound. Calibration data matters for GPTQ/AWQ: calibrate on text similar to your use. Speculative decoding helps latency at small batch sizes; on a saturated server it can reduce throughput. Distilled students inherit the teacher's biases and errors.
▸Go deeper: arithmetic intensity and the roofline

Arithmetic intensity is FLOPs performed per byte moved. A GPU like the H100 can do roughly a few hundred FLOPs in the time it moves one byte from HBM, so any operation below that ratio is memory-bound. Decoding one token at batch size 1 performs ~2 FLOPs per 2-byte weight — an intensity of ~1 — hopelessly memory-bound. Batching many users together multiplies the FLOPs per weight read, which is why serving engines (vLLM, TensorRT-LLM, TGI) use continuous batching, and why quantization, speculative decoding and FlashAttention all attack memory traffic rather than raw compute.

Quiz

1.
Roughly how much memory do the weights of a 13B-parameter model need in 4-bit?
2.
With symmetric absmax quantization at 4 bits, one weight in the tensor is 50× larger than the rest. What happens?
3.
Why does speculative decoding not reduce output quality?
4.
What does FlashAttention change compared to standard attention?
5.
You prune 60% of a model's weights unstructured, but inference on a GPU is not faster. Why?
Score: 0/5

References

  1. [1]
    LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale
    PaperDettmers et al.2022arxiv.org
  2. [2]
    GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers
    PaperFrantar et al.2022arxiv.org
  3. [3]
    Distilling the Knowledge in a Neural Network
    PaperHinton et al.2015arxiv.org
  4. [4]
    Deep Compression: Compressing Deep Neural Networks with Pruning, Trained Quantization and Huffman Coding
    PaperHan et al.2015arxiv.org
  5. [5]
    FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
    PaperDao et al.2022arxiv.org
  6. [6]
    Fast Inference from Transformers via Speculative Decoding
    PaperLeviathan et al.2022arxiv.org
← Previous
CI/CD, continuous training & feature stores
Next →
Mixture of Experts: Bigger Models at the Same Compute