Model Compression & Optimization
What You'll Learn
- 1Compute size, FLOPs and GPU count for a model under quantization and pruning
- 2Choose PTQ versus QAT from the accuracy budget rather than habit
- 3Combine quantization, pruning and distillation into a measured compression pipeline
- 4Detect when a compressed model got no faster because of kernel fallback
Why This Matters
Large models are expensive to deploy - slow inference, high memory usage, and massive compute costs. Model compression techniques reduce model size and latency while preserving accuracy, making production deployment feasible and cost-effective.
Architecture Overview
Core Components
1. Quantization
Quantization reduces weight precision from FP32 to lower bit-widths:
- Asymmetric quantization: Maps the real-valued range [rmin, rmax] to integer range [qmin, qmax] using scale = (rmax - rmin) / (qmax - qmin) and zero_point = qmin - rmin/scale.
- Symmetric quantization: Centers the range around zero, setting zero_point = 0. Uses scale = abs_max / qmax.
- Mixed precision quantization: Assigns different bit-widths to different layers based on sensitivity scores. High-sensitivity layers keep FP32/FP16; low-sensitivity layers use INT8.
- Per-channel quantization: Computes separate quantization parameters per output channel for better accuracy.
2. Advanced Pruning
Pruning removes redundant weights to create efficient sparse models:
- Magnitude pruning: Removes weights with smallest absolute values, below a percentile threshold.
- Structured pruning: Removes entire channels or filters by computing L2 norms per output channel and pruning channels with lowest norms.
- Movement pruning: Prunes weights that move toward zero during training, identifying weights the optimization wants to remove.
- Lottery ticket hypothesis: Identifies sparse subnetworks (winning tickets) by iterative pruning and rewinding to initial weights.
- Iterative pruning: Gradually increases sparsity over multiple rounds, evaluating accuracy at each step to find the best trade-off.
3. Knowledge Distillation
Knowledge distillation transfers knowledge from a large teacher to a smaller student:
- Soft loss: KL divergence between temperature-scaled teacher and student softmax outputs captures dark knowledge.
- Hard loss: Standard cross-entropy on ground-truth labels.
- Feature loss: MSE between intermediate feature maps of teacher and student.
- Combined loss: Weighted sum of hard loss, soft loss, and feature loss.
- Self-distillation: A model's later layers teach its earlier layers.
4. ONNX Runtime Optimization
ONNX Runtime applies graph-level optimizations:
- Operator fusion: Combines consecutive operations (Conv+BN, MatMul+Add) into single fused operators.
- Identity elimination: Removes no-op operations.
- Transpose elimination: Removes redundant transpose operations.
- Report: Tracks original vs optimized node counts, number of fusions, and estimated speedup.
Sizing the Compression
Every compression technique answers the same two questions: how many bytes does it save, and how many FLOPs does it save. Those are separate, and confusing them is the most common mistake in this area.
Size follows parameters times bit width:
A 10 GB FP32 model is roughly 2.5 billion parameters at 32 bits; quantizing weights to INT8 halves that to 5 GB if activations stay FP16, and a weight-only INT8 pass gives 2.5 GB, a 4x reduction. Add 20 percent structured pruning and the compressed artifact lands near 2 GB, an effective 5x against the original. The ratio you report to a stakeholder is:
Compute scales with the fraction of channels you actually remove:
Structured pruning that removes 20 percent of output channels () cuts convolution FLOPs by 20 percent, giving a 1.25x speedup on hardware that runs dense kernels. The same 20 percent spent as unstructured sparsity gives almost no speedup on a GPU without sparse tensor cores, because the zeros still travel through the dense matrix multiply. Speedup equals the FLOPs ratio only when the kernel actually exploits the structure.
Distillation is what lets you cut deeper than quantization alone. The student minimizes a blend of hard labels and temperature-scaled teacher logits:
The factor compensates for the softmax flattening as temperature rises, so gradients keep their scale when goes from 4 to 8. Distilling a 7 billion parameter teacher into a 500 million parameter student costs for the teacher's forward pass plus a full student training run, yet the deployed model is 14x smaller and, on a task with a narrow answer space, retains well over 90 percent of teacher accuracy.
Failure Modes
The first is a compressed model that scores fine in aggregate while failing a critical slice: quantization rarely hurts average accuracy but often hurts the rare cases, such as low-resolution faces or long-tail codes. Gate per slice against the FP16 baseline. The second is a compression win that never appears in latency because the runtime fell back to a slow path for an unsupported operator or dense kernel ran where you expected sparse, so benchmark on the target hardware and read the operator profile rather than trusting the FLOPs math. The third is distilling from a teacher that was itself never validated on the target distribution, which faithfully transfers the teacher's blind spot into a smaller, cheaper package.
Common Mistakes
Treating size reduction and speedup as the same claim
Fix: Report both separately: INT8 cuts bytes 4x, but latency only drops if integer kernels are actually used end to end.
Applying unstructured pruning and expecting a GPU speedup
Fix: Use structured channel or head pruning on dense hardware, or verify sparse tensor core support before promising latency gains.
Accepting one aggregate accuracy number after compression
Fix: Compare every critical slice against the FP16 baseline, because quantization damage concentrates in rare inputs.
Best Practices
- Quantize first, prune second, distill last: each step gets its own accuracy budget
- Benchmark on the target runtime and inspect the operator profile for CPU fallbacks
- Keep the uncompressed model as the reference for per-slice regression gates
Key Takeaways
- Size is P x b / 8: a 10 GB FP32 model becomes 2.5 GB at INT8, a 4x cut
- Structured pruning removing 20 percent of channels cuts FLOPs 20 percent for a 1.25x dense speedup
- Unstructured sparsity buys nothing on hardware without sparse kernels, so bytes saved does not imply latency saved
- Distillation loss carries a T squared term so raising temperature does not shrink the gradient
Frequently Asked Questions
When should I use PTQ instead of QAT?
Post-training quantization is the right default: it needs no training loop, takes minutes, and usually costs under a point at INT8. Reach for quantization-aware training when the accuracy gate fails, when you are going to INT4, or when the model has sensitive components such as attention logits or very small channels. QAT costs a full training run, so earn it by proving PTQ misses the budget.
Structured or unstructured pruning, which one?
Structured if you want latency on ordinary hardware, because removing whole channels reduces FLOPs and dense kernels speed up directly. Unstructured only when the deployment runtime has sparse kernel support, which is rare outside of specific GPU inference stacks. On mobile and edge targets, structured is effectively the only choice that delivers measurable speed.
Does distillation replace quantization?
No, they compose. Distillation changes the architecture, letting you train a genuinely smaller model that behaves like a large one. Quantization changes the numeric representation of a given model. The standard pipeline quantizes the teacher for cheap evaluation, distills to a smaller student, then quantizes the student, validating each step against its own accuracy gate.
Interview Questions
Q1: What is the difference between PTQ and QAT?
PTQ quantizes a trained model with no retraining, using a calibration set to pick scales. It is fast, typically minutes, and loses under a point at INT8. QAT simulates quantization during training with fake-quantize nodes so the weights adapt, which costs a training run but recovers accuracy, and it is what you need at INT4 or for models with sensitive layers. Choose PTQ first and escalate only when the per-slice gate fails.
Q2: How do you choose between structured and unstructured pruning?
Structured pruning removes whole channels, filters or attention heads, so FLOPs drop and any dense runtime gets the speedup. Unstructured pruning zeroes individual weights and only pays off on hardware with sparse kernels. Choose structured for edge, mobile and general GPU inference; choose unstructured only after confirming the target runtime dispatches sparse kernels for that operator.
Q3: What is knowledge distillation and what are its variants?
A smaller student learns from a teacher's softened outputs rather than only hard labels. Variants are response based, matching temperature-scaled logits; feature based, matching intermediate representations with MSE; attention based, matching attention maps; self-distillation, where deeper layers teach shallower ones; and online distillation, where teacher and student train together. Response-based with a T squared correction is the default because it needs no architectural alignment.