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.
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.
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
- 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
| Format | Bytes / param | 7B model | 70B model |
|---|---|---|---|
| FP32 | 4 | 28 GB | 280 GB |
| FP16 / BF16 | 2 | 14 GB | 140 GB |
| INT8 | 1 | 7 GB | 70 GB |
| 4-bit (INT4 / NF4) | 0.5 | 3.5 GB | 35 GB |
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).
- 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
- 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
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.
- 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
- 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. 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
- 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
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[
- 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
The knobs
- 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.
- 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).
- 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.
- 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.
- 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
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# 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)▸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
References
- [1]LLM.int8(): 8-bit Matrix Multiplication for Transformers at ScalePaperDettmers et al.2022arxiv.org
- [2]GPTQ: Accurate Post-Training Quantization for Generative Pre-trained TransformersPaperFrantar et al.2022arxiv.org
- [3]Distilling the Knowledge in a Neural NetworkPaperHinton et al.2015arxiv.org
- [4]Deep Compression: Compressing Deep Neural Networks with Pruning, Trained Quantization and Huffman CodingPaperHan et al.2015arxiv.org
- [5]FlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessPaperDao et al.2022arxiv.org
- [6]Fast Inference from Transformers via Speculative DecodingPaperLeviathan et al.2022arxiv.org