Model Compression: Distillation, Quantization, Pruning
Q: Your model is too slow/big for production. What are your options?
- Knowledge distillation: train a small student on the teacher's soft targets (probabilities at temperature T) plus the true labels:
L = α·CE(y, s) + (1 − α)·T²·KL(softmax(t/T) ‖ softmax(s/T)). Soft targets carry "dark knowledge" (which wrong classes are close). LLMs distill from teacher-generated data or logits. - Quantization: store/compute weights (and activations) in int8/int4/fp8 instead of fp32/bf16 → 2–8× smaller, faster on supporting hardware. Post-training quantization needs only calibration data; quantization-aware training simulates rounding during training for better accuracy. Per-channel scales, outlier handling (LLM.int8, SmoothQuant), GPTQ/AWQ for LLM weights.
- Pruning: remove weights (unstructured magnitude pruning: sparse but rarely faster on GPUs) or whole channels/heads/layers (structured: real speedups); NVIDIA 2:4 sparsity is a hardware-supported middle ground. Fine-tune after pruning.
- Architecture: efficient blocks (depthwise-separable convs, MobileNet/EfficientNet), smaller/shallower models, low-rank factorization, early exit, caching.
- Serving tricks: batching, compiling (TensorRT, ONNX Runtime, torch.compile), mixed precision, caching embeddings/results.
- Always measure the accuracy drop on the metric that matters and the real latency on the target hardware.