Inference & Deployment
Model Compression: Quantization, Pruning and Knowledge Distillation
Advanced 40 min For: Developers / Researchers
Key takeaways
- ▸Every token generated in decoding reads all the weights once, so the number of bytes in the weights directly determines memory use and bandwidth cost. Qwen3-8B’s BF16 weights are about 16.4GB; in Qwen’s official GGUF files, Q8_0 is 8.71GB (average 8.51 bits per weight) and Q4_K_M is 5.03GB (average 4.91 bits per weight).
- ▸Quantisation maps floating-point numbers to integers: r = S(q − Z). Whether the scale is computed per tensor, per channel or per group (for example every 128 weights) is the main trade-off between accuracy and overhead; at a given bit width, finer groups give smaller error but require extra storage for the scales.
- ▸Activations in large models contain a few channels with very large values, which makes activations harder to quantise than weights. LLM.int8() keeps dimensions that contain outliers in 16-bit arithmetic; SmoothQuant uses sⱼ = max|Xⱼ|^α / max|Wⱼ|^(1−α) to move difficulty from activations to weights and thereby enable W8A8.
- ▸Weight-only quantisation at 4 bits and below needs calibration data. GPTQ quantises column by column and uses the inverse Hessian to push the error onto columns not yet quantised; AWQ scales up salient channels by activation magnitude before quantising, without back-propagation. In this lesson’s measurements on Qwen3-0.6B, both clearly beat round-to-nearest (RTN) at 3 bits with groups of 128.
- ▸Pruning and distillation change the model itself. SparseGPT and Wanda can prune large models to 50% sparsity without retraining, and 2:4 semi-structured sparsity can be accelerated by NVIDIA Ampere Sparse Tensor Cores; knowledge distillation trains a student on the teacher’s outputs, and DeepSeek-R1 distilled reasoning ability into 1.5B–70B Qwen and Llama models with about 800k samples.
Overview: Model compression aims to cut a model’s storage, memory, bandwidth and compute costs while losing as little quality as possible. The common methods fall into three groups: quantisation lowers the bit width of each number, pruning removes some weights or structures, and knowledge distillation trains a smaller student model to imitate a large one. This lesson first explains why compression directly lowers inference cost, then covers the basic forms of quantisation, the outlier problem in large models, LLM.int8(), SmoothQuant, GPTQ, AWQ and common formats, followed by pruning and distillation, and finally measures each method on Qwen3-0.6B. Figures come from the cited papers, official documentation and model files, or from the runnable example at the end.
This lesson belongs to the Quantization, Pruning & Distillation unit; the prerequisite is LLM inference. For running quantised models locally see Running LLMs locally, for inference-engine support of quantised formats see Serving engines, and for fine-tuning after quantisation see Fine-tuning and LoRA. Related algorithm cards: LLM.int8() and outliers, SmoothQuant, GPTQ, AWQ, QLoRA, BitNet b1.58, SparseGPT, Knowledge distillation, Mixed precision and FP8 training, KV cache.
Why compression lowers inference cost
Each token generated in autoregressive decoding requires reading all the weights from memory into the compute units once; at small batch sizes the compute units spend most of their time waiting for data, and decoding speed is limited mainly by memory bandwidth (see LLM inference). The number of bytes the weights occupy therefore decides two things at once: whether the model fits in memory, and how much data must be moved at each step. Weight memory can be estimated as:
weight bytes ≈ parameters × bits per weight ÷ 8
Take Qwen3-8B (8.191B parameters in total, computed from the official config.json; see Modern LLM architectures). Converting the file sizes in Qwen’s official GGUF repository (part 2 of the example at the end):
| Format | File size | Average bits per weight |
|---|---|---|
| BF16 (original weights) | 16.38 GB | 16 |
| Q8_0 | 8.71 GB | 8.51 |
| Q6_K | 6.73 GB | 6.57 |
| Q5_K_M | 5.85 GB | 5.71 |
| Q4_K_M | 5.03 GB | 4.91 |
Going from BF16 to Q4_K_M shrinks the weights to about 31% of their size. Only weights are counted here; long-context inference also needs memory for the KV cache, which can itself be quantised. Quantisation saves memory and bandwidth but not necessarily compute: weight-only quantisation (such as W4A16) dequantises the weights back to 16 bits before computing, and computation itself is accelerated only when both weights and activations are quantised (such as W8A8) and the hardware has matching integer or low-precision matrix-multiply units.
The basic form of quantisation
Affine quantisation. Jacob et al. (2017) write quantisation as an affine mapping from integers q to real numbers r:
r = S · (q − Z)
where S is the scale and Z the zero point. Asymmetric b-bit quantisation divides the interval [min, max] evenly into 2ᵇ − 1 steps: S = (max − min) / (2ᵇ − 1), Z = round(−min / S), and q = clamp(round(r / S) + Z, 0, 2ᵇ − 1). Symmetric quantisation sets Z = 0 and derives S from max|r|; it is simpler to implement, but wastes part of the code space when values are not centred on zero.
Granularity. A scale can be shared by a whole tensor (per-tensor), assigned to each output channel of a weight matrix (per-channel), or assigned to every g consecutive weights (grouped, commonly g = 128 or 32). Finer granularity means a smaller range per group and smaller error, but more scales to store: one 16-bit scale and one 16-bit zero point per 128 four-bit weights adds about 0.25 bits per weight on average. QLoRA’s “double quantisation” quantises the scales themselves; the paper reports a saving of about 0.37 bits per parameter on average (about 3GB for a 65B model).
Post-training quantisation and quantisation-aware training. The white paper by Nagel et al. (2021) divides methods into two groups: post-training quantisation (PTQ) needs only the trained model and a small amount of calibration data, without retraining; quantisation-aware training (QAT) simulates quantisation during training so that the model adapts to the error, which works better but costs more. Compression of large models relies mainly on PTQ; LLM.int8(), SmoothQuant, GPTQ and AWQ in this lesson are all PTQ methods.
Data types. Besides integers, low-bit floating point can be used. FP8 has two encodings, E4M3 (4 exponent bits, 3 mantissa bits) and E5M2 (5 exponent bits, 2 mantissa bits) (Micikevicius et al., 2022); the former is more precise, the latter has more range. The 4-bit NormalFloat (NF4) introduced by QLoRA builds on quantile quantisation for normally distributed weights; the paper describes it as information-theoretically optimal for normally distributed data and reports better empirical results than 4-bit integers and 4-bit floats.
Outliers and LLM.int8()
Weights are usually tightly distributed; activations are not. Dettmers et al. (2022) found that at around 6.7B parameters, very large outlier features appear in all Transformer layers. They are concentrated in a few hidden dimensions and make up only about 0.1% of all input features, yet setting those dimensions to zero lowers the top-1 attention softmax probability mass by more than 20% and worsens validation perplexity by 600–1000%. Under a single per-tensor scale, a few outliers stretch the scale and squeeze all other values into a handful of integer levels.
LLM.int8() handles this in two parts. Vector-wise quantisation gives each row of the input and each column of the weight in a matrix multiplication its own scale; mixed-precision decomposition then takes out every feature dimension in which any element exceeds the threshold α = 6.0 and computes it in 16 bits, while more than 99.9% of values are multiplied in 8 bits. The paper reports that a 175B 16/32-bit checkpoint can be converted to Int8 and used directly, halving inference memory without performance loss. Part 1 of the example measures the per-channel maxima of linear-layer inputs in Qwen3-0.6B and shows the same pattern of a few channels far above the median.
SmoothQuant: migrating difficulty from activations to weights
To speed up computation with integer matrix multiplication, activations must be quantised too (W8A8). SmoothQuant (Xiao et al., 2022) starts from the observation that weights are easy to quantise and activations are not. For a linear layer Y = X·W, dividing each input channel j of the activation by sⱼ and multiplying the matching row of the weight by sⱼ leaves the product unchanged:
Y = (X · diag(s)⁻¹) · (diag(s) · W), sⱼ = max|Xⱼ|^α / max|Wⱼ|^(1−α)
When the input comes from a preceding linear or normalisation layer, the scaling can be fused into that layer’s parameters offline, so inference needs no extra scaling operation. α controls how much difficulty is migrated; the paper finds α = 0.5 well balanced for most models such as OPT and BLOOM, and a larger α for models with more severe outliers (such as GLM-130B). The paper reports that SmoothQuant lets all matrix multiplications in a range of large models run in INT8, with up to 1.56× speed-up and half the memory at negligible accuracy loss.
GPTQ: compensating quantisation error with second-order information
At 4 bits and below, the errors of rounding each weight to the nearest level (round-to-nearest, RTN) accumulate noticeably. GPTQ casts the quantisation of each linear layer as a reconstruction problem: on calibration inputs X, keep the quantised layer’s output as close as possible to the original,
minimise ‖W·X − Ŵ·X‖², whose Hessian is H = 2·X·Xᵀ
It descends from Optimal Brain Surgeon-style methods: each time one weight is quantised, H⁻¹ is used to adjust the not-yet-quantised weights in the same row to offset the error. Optimal Brain Compression (Frantar et al., 2022) applied this framework to both quantisation and pruning, but processes weights in greedy order, with cost growing cubically in the number of columns. GPTQ makes three changes:
- Arbitrary order: all rows are quantised in the same column order; the paper finds the loss relative to greedy order small, and all rows can then share one H⁻¹;
- Lazy batch updates: columns are processed in blocks of 128, with column-by-column updates inside the block and updates outside it accumulated and applied with one matrix multiplication at the end of the block, raising compute density;
- Cholesky decomposition: a Cholesky decomposition of H⁻¹ is computed up front, and a small damping term is added to the diagonal of H to avoid accumulating numerical error.
The paper reports that GPTQ quantises a 175B-parameter model to 3 or 4 bits per weight in about four GPU hours with negligible accuracy loss, running a 175B model on a single GPU for the first time, with end-to-end speed-ups of about 3.25× on A100 and 4.5× on A6000. The obs function in part 1 of the example implements this procedure following the paper’s algorithm.
AWQ: protecting salient channels by activation
AWQ (Lin et al., 2023) observes that weights are not equally important: there is a small fraction (0.1–1%) of salient weights, and leaving them unquantised greatly reduces quantisation loss; to identify the salient channels one should look at the magnitude of the activations, not of the weights themselves. Keeping those weights in FP16 would create mixed precision, which is awkward for hardware, so AWQ uses an equivalent scaling instead: the weights of salient input channels are multiplied by s > 1 before quantisation and the activations divided by s. Because quantisation error comes mainly from rounding, the scaled-up weights have smaller relative error. The scale is
s = s_X^α, α* = argmin of the layer’s output error after quantisation
where s_X is the average activation magnitude of each input channel and α is found by grid search over [0, 1]. AWQ uses no back-propagation and does not reconstruct weights from calibration data as GPTQ does; the paper argues that it therefore overfits the calibration set less: when calibrating across the PubMed and Enron domains, AWQ’s perplexity rises by only 0.5–0.6 against 2.3–4.9 for GPTQ. The paper also released the 4-bit inference framework TinyChat, reporting more than 3× speed-up over the Hugging Face FP16 implementation on desktop and mobile GPUs.
Common formats and tools
In practice a quantisation method is usually tied to a file format and an inference engine:
| Format or tool | Quantisation | Typical use |
|---|---|---|
| GGUF (llama.cpp) | Block quantisation: Q8_0, the K family (Q6_K, Q5_K, Q4_K, etc.) and the IQ family; optional calibration with an importance matrix (imatrix) | Local inference on CPUs and consumer GPUs, tools such as Ollama and LM Studio |
| bitsandbytes | LLM.int8(), 4-bit NF4/FP4, quantised on the fly at load time | Loading directly in Transformers, QLoRA fine-tuning |
| GPTQ and AWQ weights | Weight-only quantisation at about 4 bits, needs calibration data | GPU inference engines such as vLLM |
| FP8, INT8 W8A8 | Both weights and activations quantised | Data-centre GPUs with FP8/INT8 matrix multiplication |
Hugging Face’s GGUF documentation describes the structure of each type: Q8_0 uses blocks of 32 weights with one scale per block; Q4_K uses super-blocks of 8 blocks (32 weights each), stores scales and minimums in 6 bits each, and comes to 4.5 bits per weight; Q6_K is 6.5625 bits per weight; IQ4_XS reaches 4.25 bits per weight with the help of an importance matrix. Types with an _S, _M or _L suffix are built mainly on one base type and switch some tensors to other types: according to the llama.cpp source (src/llama-quant.cpp), Q4_K_M is based on Q4_K but uses Q6_K for the attention V projection and ffn_down weights of some layers. Together with small unquantised tensors and metadata in the file, this is why Qwen3-8B’s Q4_K_M in the table above averages 4.91 bits per weight rather than 4.5. For quantising a model with llama.cpp see its llama-quantize guide; for loading the various quantised weights in Transformers see the quantisation overview; for the formats vLLM supports see its quantisation documentation; and quantised and sparse weights for vLLM can be produced with llm-compressor.
Fine-tuning after quantisation. QLoRA (Dettmers et al., 2023) quantises the frozen base model to 4-bit NF4 and back-propagates gradients through the quantised model into LoRA adapters; the paper reports fine-tuning a 65B model on a single 48GB GPU while preserving the task performance of full 16-bit fine-tuning. See Fine-tuning and LoRA for the procedure.
Low-bit training: BitNet b1.58
All the methods above quantise after training. Another route uses extremely low bit widths from the start of training. BitNet (Wang et al., 2023) replaces nn.Linear with a BitLinear layer and trains 1-bit weights from scratch; BitNet b1.58 (Ma et al., 2024) restricts every weight to the three values {−1, 0, +1} (log₂3 ≈ 1.58 bits) with an absmean quantisation function, which divides by the mean absolute value of the weight matrix and then rounds and clips to [−1, 1], with 8-bit activations. The paper reports that from the 3B scale onwards, BitNet b1.58 matches FP16 models of the LLaMA architecture in perplexity and end-task performance at the same model size and number of training tokens; the 3B model uses 1/3.55 of the memory with 1/2.71 of the latency and reaches a perplexity of 9.91 (against 10.04), and at 70B its throughput is 8.9 times that of LLaMA 70B. Such models must be trained from scratch or specifically trained further; they cannot be obtained by converting an ordinary model directly. The official inference framework is bitnet.cpp.
Pruning: unstructured, semi-structured and structured
Pruning zeroes out or removes some weights. By sparsity pattern there are three kinds:
| Kind | Method | Condition for speed-up |
|---|---|---|
| Unstructured | Weights at any position can be zeroed | Needs dedicated sparse kernels; dense GPU matrix multiplication rarely benefits |
| Semi-structured (N:M) | At least N of every M consecutive weights are zero, e.g. 2:4 | Sparse Tensor Cores on NVIDIA Ampere and later |
| Structured | Remove whole layers, attention heads, channels or FFN intermediate dimensions | Yields a smaller dense model that runs faster on any hardware |
Magnitude pruning simply removes the weights with the smallest absolute values and is the simplest baseline. Deep Compression by Han et al. (2015) combined pruning, trained quantisation and Huffman coding to cut network storage by 35–49× without affecting accuracy, but the network has to be retrained after pruning. For large models retraining is too expensive, which led to one-shot pruning methods:
- SparseGPT (Frantar and Alistarh, 2023) belongs to the same OBS framework as GPTQ: it decides column by column which weights to prune and uses H⁻¹ to update the weights not yet processed to compensate for the error. The paper reports processing OPT-175B and BLOOM-176B in under 4.5 hours, reaching 60% unstructured sparsity with a negligible increase in perplexity, and extending to 2:4 and 4:8 patterns and to combination with weight quantisation.
- Wanda (Sun et al., 2023) scores each weight by its magnitude times the L2 norm of the corresponding input activation, |W|·‖X‖₂, and compares scores within each output channel, pruning the lowest. It does not update the remaining weights and needs only one forward pass to collect activation norms; the paper says computing its pruning metric is about 300 times faster than SparseGPT.
2:4 semi-structured sparsity (Mishra et al., 2021) requires 2 of every 4 consecutive weights to be zero, so the compressed format stores only the non-zero values and 2-bit indices; the benefits listed in the paper are efficient memory access, a low-overhead compressed format and 2× math throughput on the NVIDIA Ampere architecture.
Structured pruning combined with distillation is now a practical route to small models. Minitron (Muralidharan et al., 2024) prunes Nemotron-4 15B along depth, width, attention heads and MLP dimensions and then retrains with knowledge distillation to obtain 8B and 4B models; the paper reports up to 40 times fewer training tokens per model than training from scratch, 1.8× compute savings for the whole model family, and MMLU up to 16% higher than training from scratch.
Knowledge distillation
Soft targets and temperature. Hinton et al. (2015) proposed training a small model (the student) to fit the output distribution of a large model (the teacher) at temperature T:
pᵢ = exp(zᵢ / T) / Σⱼ exp(zⱼ / T)
A larger T gives a smoother distribution, making the relative probabilities of wrong classes (for example, whether this 2 looks more like a 3 or a 7) easier for the student to learn. Student and teacher use the same T in training, and T is set to 1 at inference. The paper notes that the gradients produced by soft targets scale as 1/T², so when hard and soft targets are used together the soft-target loss should be multiplied by T² to keep their relative contributions unchanged as the temperature varies. Part 2 of the example shows the distribution of one set of logits at T = 1, 2 and 4 and checks that the gradient magnitude stabilises after multiplying by T². DistilBERT (Sanh et al., 2019) applied this kind of distillation during pre-training with a triple loss of language modelling, distillation and cosine distance, producing a model 40% smaller and 60% faster than BERT that retains 97% of its language-understanding capability.
Distilling generative models. For language models, token-level distribution matching has two directions. Standard distillation minimises the forward KL(p‖q), with p the teacher and q the student, which makes the student cover every region of the teacher’s distribution; MiniLLM (Gu et al., 2023) uses the reverse KL(q‖p) instead, which the paper says prevents the student from overestimating low-probability regions of the teacher distribution, and derives an on-policy optimisation method for it. Part 2 of the example fits a unimodal Gaussian student to a bimodal teacher: forward KL yields a wide distribution with mean 0 and standard deviation 3.16 (covering both peaks and the low-probability region between them), while reverse KL converges to one of the peaks (mean 2.98, standard deviation 1.02). GKD (Agarwal et al., 2023) points out that training the student on fixed output sequences causes a mismatch between the distributions seen in training and at inference, so it has the student receive teacher feedback on sequences it generates itself, and allows a choice of divergences.
Supervised fine-tuning on teacher-generated data (sequence-level distillation) is the simplest and most common approach; it needs only the teacher’s output text, not its logits. The DeepSeek-R1 technical report fine-tunes Qwen2.5-Math-1.5B, Qwen2.5-Math-7B, Qwen2.5-14B, Qwen2.5-32B, Llama-3.1-8B and Llama-3.3-70B-Instruct for 2–3 epochs on about 800k samples to produce the DeepSeek-R1-Distill series. Its comparison found that the 32B model distilled from DeepSeek-R1 performs significantly better across all benchmarks than large-scale reinforcement learning applied directly to Qwen2.5-32B, concluding that distilling stronger models into smaller ones is economical and effective, while advancing beyond the boundaries of human intelligence may still require stronger base models and larger-scale reinforcement learning. For training reasoning models see Reasoning models.
Measurements: quantisation and pruning on Qwen3-0.6B
To compare the methods under the same conditions, this lesson implements and runs RTN, GPTQ, AWQ, SmoothQuant, magnitude pruning, Wanda and SparseGPT on Qwen3-0.6B (code in part 1 of the example in the next section). The setup:
- Only the linear layers of the 28 decoder layers are processed (the q/k/v/o projections and the gate/up/down projections); the embedding and output layers are left unchanged;
- Calibration data are 32 random 512-token segments from the WikiText-2 training set; evaluation uses the first 32 windows of 512 tokens of the WikiText-2 test set (16,384 tokens in total), measured by perplexity (lower is better);
- Quantisation is simulated: weights are quantised and immediately dequantised back to floating point for computation, so only accuracy loss is measured, not speed; for W8A8 the activations are dynamically quantised to INT8 per tensor in every forward pass.
| Method | Setting | Perplexity |
|---|---|---|
| BF16 original weights | — | 26.23 |
| RTN | W8, per-channel | 26.24 |
| RTN | W4, per-channel | 43.22 |
| RTN | W4, group 128 | 31.05 |
| GPTQ | W4, per-channel | 30.61 |
| GPTQ | W4, group 128 | 27.64 |
| AWQ | W4, group 128 | 29.12 |
| RTN | W3, group 128 | 100.35 |
| GPTQ | W3, group 128 | 43.00 |
| AWQ | W3, group 128 | 54.86 |
| W8A8 | per-tensor activations, no smoothing | 44.59 |
| SmoothQuant | W8A8, α = 0.5 | 31.70 |
| Magnitude pruning | 50% unstructured | 1331.68 |
| Wanda | 50% unstructured | 43.70 |
| SparseGPT | 50% unstructured | 37.24 |
| Magnitude pruning | 2:4 | 15197.48 |
| Wanda | 2:4 | 256.22 |
| SparseGPT | 2:4 | 64.37 |
The results show the following:
- 8-bit weight-only quantisation is almost lossless (26.24 against 26.23). Losses appear mainly at 4 bits and below.
- Granularity matters: for 4-bit RTN, per-channel gives 43.22 and groups of 128 bring it down to 31.05.
- Calibrated methods matter more at low bit widths: with groups of 128, 4-bit GPTQ and AWQ reach 27.64 and 29.12; at 3 bits RTN rises to 100.35 while GPTQ and AWQ reach 43.00 and 54.86. In this experiment GPTQ beats AWQ, whereas the AWQ paper reports AWQ ahead of GPTQ at 3 and 4 bits (group 128) on LLaMA and Llama-2. The difference may come from model size and calibration settings, and from this lesson’s simplified implementation (the weight-clipping search of the AWQ paper is not implemented); it should not be generalised.
- Activation outliers are the main obstacle to W8A8: W8A8 without smoothing gives 44.59, SmoothQuant (α = 0.5) 31.70. The statistics show that the largest per-channel maximum absolute value of the down_proj input in layer 27 is 1686.4, 42.1 times the median over channels (40.01); for the q_proj input the ratio is 6.3, 10.1 and 6.9 in layers 0, 13 and 27.
- One-shot pruning needs activation information: at 50% unstructured sparsity, magnitude-only pruning raises perplexity to 1331.68, against 43.70 for Wanda and 37.24 for SparseGPT; the stricter 2:4 pattern gives 15197.48, 256.22 and 64.37. Small models are more sensitive to pruning; the large-model results in the SparseGPT and Wanda papers are much better.
Note that a 0.6B model has less redundancy than a large one, and the same method usually loses less on models of 7B and above; perplexity is also no substitute for downstream evaluation.
Runnable example
The code below was run on PyTorch 2.15 (CPU) with Transformers 5.23; all figures in the text come from the output of these two parts.
Part 1: comparing quantisation and pruning methods on Qwen3-0.6B. It downloads the Qwen3-0.6B weights and WikiText-2 data from Hugging Face. Calibration statistics (H = 2XᵀX/n and others for each linear layer) are collected in 4 batches of layers and cached on disk (about 1.8 GB), and each configuration’s result is written to results.json, so a rerun after interruption skips finished parts; the 18 configurations are evaluated one by one on the CPU and take a long time.
# Model compression example: comparing quantisation and pruning methods on Qwen3-0.6B (PyTorch 2.15 CPU, transformers 5.23)
import io, os, json, time, math, urllib.request, torch, torch.nn as nn, pyarrow.parquet as pq
from transformers import AutoModelForCausalLM, AutoTokenizer
from huggingface_hub import hf_hub_download
from safetensors import safe_open
torch.manual_seed(0); torch.set_num_threads(6)
M = 'Qwen/Qwen3-0.6B'
URL = 'https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-2-raw-v1/'
def text(split):
b = urllib.request.urlopen(URL + f'{split}-00000-of-00001.parquet').read()
return '\n\n'.join(pq.read_table(io.BytesIO(b)).column('text').to_pylist())
tok = AutoTokenizer.from_pretrained(M)
SEQ, NEVAL, NCAL = 512, 32, 32
test = tok(text('test'), return_tensors='pt').input_ids[0][:SEQ*NEVAL].view(NEVAL, SEQ)
train = tok(text('train'), return_tensors='pt').input_ids[0]
starts = torch.randint(0, len(train) - SEQ, (NCAL,))
calib = torch.stack([train[s:s+SEQ] for s in starts])
model = AutoModelForCausalLM.from_pretrained(M, dtype=torch.float32).eval()
lin = {n: m for n, m in model.model.layers.named_modules() if isinstance(m, nn.Linear)}
sf = safe_open(hf_hub_download(M, 'model.safetensors'), 'pt') # original BF16 weights, read from disk on demand to save memory
W0 = lambda n: sf.get_tensor(f'model.layers.{n}.weight').float()
def restore():
for n, m in lin.items(): m.weight.data = W0(n)
@torch.no_grad()
def ppl(): # cross-entropy per window; the output layer runs in chunks of 128 positions to avoid materialising all logits at once
nll, n = 0.0, 0
for i in range(NEVAL):
h, y = model.model(test[i:i+1]).last_hidden_state[0, :-1], test[i, 1:]
for j in range(0, len(y), 128):
nll += nn.functional.cross_entropy(model.lm_head(h[j:j+128]), y[j:j+128], reduction='sum').item()
n += len(y)
return math.exp(nll / n)
# 1) Collect input statistics for every linear layer on calibration data: H = 2XᵀX/n, per-channel max|x| and mean|x|
stats = {}
def hook(name):
def f(mod, inp):
x = inp[0].reshape(-1, inp[0].shape[-1]).float()
s = stats.setdefault(name, {'H': 0, 'n': 0, 'amax': 0, 'amean': 0})
s['H'] = s['H'] + 2 * x.T @ x; s['n'] += len(x)
s['amax'] = torch.maximum(torch.as_tensor(s['amax']), x.abs().amax(0)); s['amean'] = s['amean'] + x.abs().sum(0)
return f
key = lambda n: n.replace('k_proj', 'q_proj').replace('v_proj', 'q_proj').replace('up_proj', 'gate_proj')
L = len(model.model.layers)
for part in range(4): # collect in 4 batches (7 layers each); statistics are saved to disk and read back with mmap to limit peak memory
if os.path.exists(f'stats_{part}.pt'): continue # skip if already cached
hs = [m.register_forward_pre_hook(hook(n)) for n, m in lin.items()
if key(n) == n and int(n.split('.')[0]) * 4 // L == part]
with torch.no_grad():
for i in range(NCAL): model(calib[i:i+1])
for h in hs: h.remove()
for s in stats.values(): s['H'] /= s['n']; s['amean'] /= s['n']
torch.save(stats, f'stats_{part}.pt'); stats.clear()
for part in range(4): stats.update(torch.load(f'stats_{part}.pt', mmap=True))
S = lambda n: stats[key(n)]
# 2) Quantiser: asymmetric min-max, per output channel (group=None) or one group per `group` input channels
def qparams(w, bits):
lo, hi = w.amin(-1, keepdim=True).clamp(max=0), w.amax(-1, keepdim=True).clamp(min=0)
s = (hi - lo).clamp(min=1e-8) / (2**bits - 1); return s, torch.round(-lo / s)
def qdq(w, s, z, bits): return (torch.clamp(torch.round(w / s) + z, 0, 2**bits - 1) - z) * s
def rtn(w, bits, group=None):
O, I = w.shape; g = group or I; x = w.reshape(O, I // g, g)
return qdq(x, *qparams(x, bits), bits).reshape(O, I)
# 3) GPTQ / SparseGPT: one framework that processes columns in order and uses H⁻¹ to push the error onto unprocessed columns
def obs(W, H, bits=None, group=None, sparsity=0, nm=None, block=128):
W = W.clone(); O, I = W.shape; H = H.clone()
dead = torch.diag(H) == 0; H[dead, dead] = 1; W[:, dead] = 0
H += 0.01 * torch.mean(torch.diag(H)) * torch.eye(I)
Hinv = torch.linalg.cholesky(torch.cholesky_inverse(torch.linalg.cholesky(H)), upper=True)
Q = torch.zeros_like(W)
if bits and not group: sz = qparams(W, bits)
for i1 in range(0, I, block):
i2 = min(i1 + block, I); W1 = W[:, i1:i2].clone(); E = torch.zeros_like(W1); Hi = Hinv[i1:i2, i1:i2]
if sparsity and not nm:
sc = W1**2 / torch.diag(Hi)**2; mask = sc <= sc.flatten().sort()[0][int(sc.numel() * sparsity)]
for j in range(i2 - i1):
w, d = W1[:, j], Hi[j, j]
if nm and j % nm[1] == 0:
sc = W1[:, j:j+nm[1]]**2 / torch.diag(Hi)[j:j+nm[1]]**2
mask = torch.zeros_like(W1, dtype=torch.bool)
mask[:, j:j+nm[1]].scatter_(1, sc.topk(nm[1] - nm[0], dim=1, largest=False)[1], True)
if bits:
if group and (i1 + j) % group == 0: sz = qparams(W1[:, j:j+group], bits)
q = qdq(w.unsqueeze(1), *sz, bits).squeeze(1)
else:
q = w.clone(); q[mask[:, j]] = 0
Q[:, i1+j] = q; err = (w - q) / d
W1[:, j:] -= err.unsqueeze(1) @ Hi[j, j:].unsqueeze(0); E[:, j] = err
W[:, i2:] -= E @ Hinv[i1:i2, i2:]
return Q
# 4) AWQ: scale salient input channels by s = mean|x|^α, quantise, then divide back; grid-search α over [0,1) by the layer output error tr(ΔW·H·ΔWᵀ)
def awq(W, st, bits, group=128, grid=20):
best, bq = float('inf'), None
for a in [i / grid for i in range(grid)]:
s = st['amean'].clamp(min=1e-4)**a; s = s / (s.max() * s.min()).sqrt()
q = rtn(W * s, bits, group) / s; d = q - W; e = ((d @ st['H']) * d).sum().item()
if e < best: best, bq = e, q
return bq
# 5) Pruning: magnitude, Wanda (|W|·‖x‖, compared within each output row), optional N:M pattern
def prune(W, score, sparsity=0.5, nm=None):
if nm:
sc = score.reshape(W.shape[0], -1, nm[1]); m = torch.zeros_like(sc, dtype=torch.bool)
m.scatter_(2, sc.topk(nm[1] - nm[0], dim=2, largest=False)[1], True); m = m.reshape(W.shape)
else:
m = torch.zeros_like(W, dtype=torch.bool)
m.scatter_(1, score.topk(int(W.shape[1] * sparsity), dim=1, largest=False)[1], True)
return W.masked_fill(m, 0)
# 6) W8A8: activations dynamically quantised to INT8 per tensor; SmoothQuant moves difficulty from activations to weights with s = max|x|^α / max|w|^(1-α)
def qact(x): s = x.abs().amax().clamp(min=1e-8) / 127; return torch.round(x / s).clamp(-127, 127) * s
def w8a8(smooth=None):
hooks = []
for n, m in lin.items():
W = W0(n); s = torch.ones(W.shape[1])
if smooth is not None:
s = (S(n)['amax'].clamp(min=1e-5)**smooth / W.abs().amax(0).clamp(min=1e-5)**(1 - smooth))
m.weight.data = rtn(W * s, 8) # weights INT8 per channel
hooks.append(m.register_forward_pre_hook(lambda mod, inp, s=s: (qact(inp[0] / s),)))
return hooks
R = json.load(open('results.json')) if os.path.exists('results.json') else {} # result cache: a rerun after interruption skips configurations already done
def run(label, fn=None, hooks=None):
if label not in R:
restore()
if fn:
for n, m in lin.items(): m.weight.data = fn(n, W0(n))
hk = hooks() if hooks else []
R[label] = round(ppl(), 2); [h.remove() for h in hk]
json.dump(R, open('results.json', 'w'), ensure_ascii=False, indent=1)
print(f'{label:<32s} PPL {R[label]:7.2f}', flush=True)
mag = lambda W: W.abs()
wanda = lambda n, W: W.abs() * S(n)['H'].diag().sqrt()
run('BF16 (original weights)')
# Outliers: per-channel max|x| of linear-layer inputs and its ratio to the median
for i in (0, 13, 27):
for k in ('self_attn.q_proj', 'mlp.down_proj'):
a = stats[f'{i}.{k}']['amax']
print(f'layer {i:2d} {k.split(".")[1]:<9s} input: channel max|x| largest {a.max():7.1f}, median {a.median():6.2f}, ratio {a.max()/a.median():5.1f}')
run('RTN W8 per-channel', lambda n, W: rtn(W, 8))
run('RTN W4 per-channel', lambda n, W: rtn(W, 4))
run('RTN W4 g128', lambda n, W: rtn(W, 4, 128))
run('RTN W3 g128', lambda n, W: rtn(W, 3, 128))
run('GPTQ W4 per-channel', lambda n, W: obs(W, S(n)['H'], bits=4))
run('GPTQ W4 g128', lambda n, W: obs(W, S(n)['H'], bits=4, group=128))
run('GPTQ W3 g128', lambda n, W: obs(W, S(n)['H'], bits=3, group=128))
run('AWQ W4 g128', lambda n, W: awq(W, S(n), 4))
run('AWQ W3 g128', lambda n, W: awq(W, S(n), 3))
run('W8A8 per-tensor (no smoothing)', hooks=lambda: w8a8(None))
run('W8A8 SmoothQuant α=0.5', hooks=lambda: w8a8(0.5))
run('Magnitude 50%', lambda n, W: prune(W, mag(W)))
run('Wanda 50%', lambda n, W: prune(W, wanda(n, W)))
run('SparseGPT 50%', lambda n, W: obs(W, S(n)['H'], sparsity=0.5))
run('Magnitude 2:4', lambda n, W: prune(W, mag(W), nm=(2, 4)))
run('Wanda 2:4', lambda n, W: prune(W, wanda(n, W), nm=(2, 4)))
run('SparseGPT 2:4', lambda n, W: obs(W, S(n)['H'], nm=(2, 4)))
Output:
BF16 (original weights) PPL 26.23
layer 0 q_proj input: channel max|x| largest 3.6, median 0.58, ratio 6.3
layer 0 down_proj input: channel max|x| largest 6.5, median 1.16, ratio 5.6
layer 13 q_proj input: channel max|x| largest 36.7, median 3.63, ratio 10.1
layer 13 down_proj input: channel max|x| largest 27.9, median 3.45, ratio 8.1
layer 27 q_proj input: channel max|x| largest 271.3, median 39.47, ratio 6.9
layer 27 down_proj input: channel max|x| largest 1686.4, median 40.01, ratio 42.1
RTN W8 per-channel PPL 26.24
RTN W4 per-channel PPL 43.22
RTN W4 g128 PPL 31.05
RTN W3 g128 PPL 100.35
GPTQ W4 per-channel PPL 30.61
GPTQ W4 g128 PPL 27.64
GPTQ W3 g128 PPL 43.00
AWQ W4 g128 PPL 29.12
AWQ W3 g128 PPL 54.86
W8A8 per-tensor (no smoothing) PPL 44.59
W8A8 SmoothQuant α=0.5 PPL 31.70
Magnitude 50% PPL 1331.68
Wanda 50% PPL 43.70
SparseGPT 50% PPL 37.24
Magnitude 2:4 PPL 15197.48
Wanda 2:4 PPL 256.22
SparseGPT 2:4 PPL 64.37
Part 2: memory estimates and knowledge distillation. It reads the file list of Qwen’s official GGUF repository to convert sizes into average bits per weight (file metadata only, no weights are downloaded), and demonstrates temperature, T² scaling and the difference between forward and reverse KL; it finishes in a few seconds.
# Memory estimates, distillation temperature and forward/reverse KL (PyTorch 2.15 CPU)
import json, urllib.request, torch
torch.manual_seed(0); torch.set_num_threads(3)
# 1) Weight memory: parameters × bits per weight, checked against the actual sizes of Qwen’s official GGUF files
api = json.load(urllib.request.urlopen('https://huggingface.co/api/models/Qwen/Qwen3-8B-GGUF/tree/main'))
N = 8.191e9 # Qwen3-8B total parameters (including embedding and output layers, computed from config.json; see the “Modern LLM architectures” lesson)
print(f'BF16: {N*2/1e9:.2f} GB (16 bits/weight)')
for f in sorted(api, key=lambda f: f['size']):
if f['path'].endswith('.gguf'):
print(f"{f['path']:<22s} {f['size']/1e9:5.2f} GB, average {f['size']*8/N:.2f} bits/weight")
# 2) Temperature softening: one set of logits at different T
z = torch.tensor([6.0, 3.0, 2.0, -1.0])
for T in (1, 2, 4):
print(f'T={T}: ' + ' '.join(f'{p:.3f}' for p in torch.softmax(z / T, 0)))
# 3) Soft-target gradients shrink as 1/T²; multiplied by T² their magnitude no longer depends on T
zs = torch.tensor([2.0, 1.0, 0.5, 0.0], requires_grad=True)
for T in (1, 2, 4, 8):
zs.grad = None
loss = torch.nn.functional.kl_div(torch.log_softmax(zs / T, 0), torch.softmax(z / T, 0), reduction='sum')
loss.backward(); g = zs.grad.norm().item()
print(f'T={T}: gradient norm {g:.4f}, times T² {g*T*T:.4f}')
# 4) Forward vs reverse KL: fitting a unimodal (Gaussian) student to a bimodal teacher
x = torch.linspace(-8, 8, 801); dx = x[1] - x[0]
def normal(m, s): return torch.exp(-0.5 * ((x - m) / s)**2) / (s * (2 * torch.pi)**0.5)
p = 0.5 * normal(-3, 1) + 0.5 * normal(3, 1)
for name in ('forward KL(p‖q)', 'reverse KL(q‖p)'):
m = torch.tensor(1.5, requires_grad=True); ls = torch.tensor(0.0, requires_grad=True)
opt = torch.optim.Adam([m, ls], lr=0.05)
for _ in range(2000):
q = normal(m, ls.exp()) + 1e-12
kl = (p * (p.add(1e-12).log() - q.log())).sum() * dx if name.startswith('forward') else (q * (q.log() - p.add(1e-12).log())).sum() * dx
opt.zero_grad(); kl.backward(); opt.step()
print(f'{name}: student mean {m.item():.2f}, std {ls.exp().item():.2f}')
Output:
BF16: 16.38 GB (16 bits/weight)
Qwen3-8B-Q4_K_M.gguf 5.03 GB, average 4.91 bits/weight
Qwen3-8B-Q5_0.gguf 5.72 GB, average 5.59 bits/weight
Qwen3-8B-Q5_K_M.gguf 5.85 GB, average 5.71 bits/weight
Qwen3-8B-Q6_K.gguf 6.73 GB, average 6.57 bits/weight
Qwen3-8B-Q8_0.gguf 8.71 GB, average 8.51 bits/weight
T=1: 0.935 0.047 0.017 0.001
T=2: 0.720 0.161 0.097 0.022
T=4: 0.497 0.235 0.183 0.086
T=1: gradient norm 0.4161, times T² 0.4161
T=2: gradient norm 0.1805, times T² 0.7218
T=4: gradient norm 0.0522, times T² 0.8357
T=8: gradient norm 0.0136, times T² 0.8686
forward KL(p‖q): student mean -0.00, std 3.16
reverse KL(q‖p): student mean 2.98, std 1.02
Exercises
- Unit project: convert one 7B-class model to GGUF with llama.cpp and quantise it to Q8_0, Q4_K_M and Q3_K_M (see the llama-quantize guide); evaluate each with its bundled perplexity tool on the same text, record file size, memory after loading and generation speed, and plot the trade-off between bits, perplexity and speed.
- In Transformers, load the same model with bitsandbytes (8-bit and NF4), GPTQ and AWQ weights (see the quantisation overview) and compare memory use and the outputs for a fixed set of prompts.
- Modify part 1 of the example: change GPTQ’s column processing order to decreasing diagonal of H and give AWQ a weight-clipping search, and observe how the 3-bit results change; then switch the calibration data to code or Chinese text and compare how sensitive GPTQ and AWQ are to the calibration distribution.
- Do the pruning, quantisation and distillation labs of MIT 6.5940.
- Use llm-compressor to produce W8A8 or 2:4-sparse weights for a small model, load them in vLLM and compare throughput with the BF16 version.
Suggested reading order
Start with the quantisation white paper by Nagel et al. (2021) for the basics of scales, zero points, granularity, PTQ and QAT. Then read the method sections of the large-model quantisation papers in this order: LLM.int8() (outliers and mixed-precision decomposition), SmoothQuant, GPTQ and AWQ, comparing each with the implementation in part 1 of the example. For formats and tools, rely on Hugging Face’s GGUF documentation and the Transformers quantisation overview. For pruning, read the method sections of SparseGPT and Wanda and the description of 2:4 sparsity by Mishra et al. (2021); for distillation, read Hinton et al. (2015), MiniLLM and GKD, then the distillation experiments in the DeepSeek-R1 report. After that, continue with Serving engines and Running LLMs locally to see how quantised weights are used in deployment.
FAQ
How much does 4-bit quantisation hurt the model?
It depends on model size, method and group size; there is no single figure. The GPTQ paper reports only a small rise in perplexity for large models such as OPT-175B at 4 bits; smaller models are more sensitive. In this lesson’s measurements on Qwen3-0.6B (WikiText-2, 512-token windows), BF16 perplexity is 26.23; 4-bit RTN, GPTQ and AWQ with groups of 128 all show a visible rise, and at 3 bits RTN degrades markedly while GPTQ and AWQ lose much less. Evaluate on your own tasks before deploying rather than relying on perplexity alone.
Why is GGUF’s Q4_K_M not exactly 4 bits?
K-family quantisation divides weights into super-blocks and blocks, each storing scales and minimums; Hugging Face’s GGUF documentation gives Q4_K as 4.5 bits per weight and Q6_K as 6.5625 bits per weight. Q4_K_M also uses higher-bit types for some tensors, and the file contains small unquantised tensors and metadata, so Qwen’s official Qwen3-8B Q4_K_M file averages 4.91 bits per weight.
Should I choose GPTQ or AWQ?
Both are weight-only methods at around 4 bits and both need a small amount of calibration data. GPTQ compensates error column by column with second-order information; AWQ only scales channels and does not alter the relations among weights. The AWQ paper reports that it is less sensitive to the calibration distribution (when calibrating on a different domain, perplexity rises by only 0.5–0.6, against 2.3–4.9 for GPTQ). In practice the choice often depends on the formats and kernels the inference engine supports; see the quantisation documentation of vLLM and Transformers.
Does pruning make a model faster?
Not necessarily. Unstructured sparsity (zeros at arbitrary positions) compresses storage, but general GPU matrix multiplication rarely benefits; 2:4 semi-structured sparsity (at least 2 zeros in every 4 consecutive weights) can be accelerated by NVIDIA Ampere Sparse Tensor Cores, with 2× math throughput according to the paper; structured pruning that removes layers, attention heads or channels yields a smaller dense model and gives the most direct speed-up, but usually needs distillation or continued training to recover accuracy, as in Minitron.
Is distillation the same as fine-tuning a small model on data generated by a large one?
The latter is one form of distillation. The classic approach of Hinton et al. (2015) has the student fit the teacher’s full output distribution at temperature T (soft targets). For generative language models a common alternative is supervised fine-tuning directly on teacher-generated text (sequence-level distillation); the DeepSeek-R1 distilled models use about 800k samples with SFT only. MiniLLM and GKD let the student receive token-level feedback from the teacher on sequences it generates itself (on-policy distillation) to reduce the mismatch between training and inference distributions. Distilling from the outputs of closed models is also subject to their terms of service.