Model Compression Techniques
“Fitting billion-parameter models into megabytes.”
TL;DR
Model compression makes it possible to deploy deep learning models on resource-constrained devices and shrink models by 10-40x. This article covers quantization (FP32 to INT8/INT4), structured and unstructured pruning including the Lottery Ticket Hypothesis, knowledge distillation with temperature-scaled soft targets, low-rank factorization, hardware-specific optimizations, and mobile deployment via ONNX, TFLite, and Core ML. These techniques complement distributed training for the train-large-deploy-small paradigm used in LLM serving.

1. The Compression Imperative
Modern deep learning models are massive:
- GPT-3: 175B parameters = 700GB (FP32).
- BERT-Large: 340M parameters = 1.3GB (FP32).
- ResNet-50: 25M parameters = 100MB (FP32).
Challenges:
- Deployment: Can’t fit on mobile devices (limited RAM).
- Inference: Slow on CPUs without GPU acceleration.
- Cost: Cloud inference costs scale with model size.
Goal: Reduce model size by 10-100x while maintaining 95%+ accuracy.
2. Taxonomy of Compression Techniques
- Quantization: Reduce numerical precision (FP32 → INT8).
- Pruning: Remove redundant weights or neurons.
- Knowledge Distillation: Train a small model to mimic a large model.
- Low-Rank Factorization: Decompose weight matrices.
- Neural Architecture Search (NAS): Design efficient architectures.
- Weight Sharing: Cluster weights and share values.
3. Quantization
3.1. Post-Training Quantization (PTQ)
Idea: Convert a trained FP32 model to INT8 without retraining.
Algorithm:
- Calibration: Run the model on a small dataset (e.g., 1000 samples).
- Collect Statistics: Record min/max values of activations for each layer.
- Compute Scale and Zero-Point:
- \(\text{scale} = \frac{\max - \min}{255}\) (for 8-bit).
- \(\text{zero\_point} = \text{round}\left(-\frac{\min}{\text{scale}}\right)\).
- Quantize Weights:
- \(W_{\text{int8}} = \text{round}\left(\frac{W_{\text{fp32}}}{\text{scale}}\right) + \text{zero\_point}\).
- Dequantize for Inference:
- \(W_{\text{fp32}} \approx (W_{\text{int8}} - \text{zero\_point}) \times \text{scale}\).
Result: 4x memory reduction, and often a 2-4x speedup on CPUs with INT8 kernels.
Accuracy Drop: Often small for CNNs (torchvision’s PTQ ResNet-50 scores 75.9% top-1 against 76.1% in FP32). Transformers with large activation outliers can lose more unless you use outlier-aware methods such as SmoothQuant or LLM.int8().
3.2. Quantization-Aware Training (QAT)
Idea: Simulate quantization during training so the model learns to be robust to quantization noise.
Algorithm:
- Insert Fake Quantization nodes after each layer.
- During forward pass:
- Quantize activations: \(a_{\text{int8}} = \text{round}\left(\frac{a_{\text{fp32}}}{\text{scale}}\right)\).
- Dequantize: \(a_{\text{fp32}} = a_{\text{int8}} \times \text{scale}\).
- During backward pass:
- Use Straight-Through Estimator (STE): Treat the
round()function as identity for gradients.
- Use Straight-Through Estimator (STE): Treat the
- Train for a few epochs (fine-tuning).
Result: Usually recovers much of the accuracy PTQ loses, most noticeably at INT4 and for small models.
3.3. Dynamic vs Static Quantization
Static Quantization:
- Quantize both weights and activations.
- Requires calibration dataset.
- Use Case: Inference on edge devices.
Dynamic Quantization:
- Quantize only weights. Activations remain FP32.
- No calibration needed.
- Use Case: NLP models (BERT) on CPUs.
4. Pruning
4.1. Unstructured Pruning
Idea: Remove individual weights with small magnitude.
Algorithm (Magnitude-Based Pruning):
- Train the model to convergence.
- Compute the magnitude of each weight: \(\lvert W_{ij} \rvert\).
- Sort weights by magnitude.
- Set the smallest p% of weights to zero (e.g., p = 90).
- Fine-tune the pruned model.
- Repeat (iterative pruning).
Result: On over-parameterized CNNs such as AlexNet and VGG-16, Han et al. (2015) pruned roughly 90% of weights without losing accuracy. Compact models tolerate much less.
Challenge: Sparse matrices are not efficiently supported on most hardware. Speedups need sparse kernels; NVIDIA’s Sparse Tensor Cores accelerate only the 2:4 structured pattern (Section 27).
4.2. Structured Pruning
Idea: Remove entire channels, filters, or attention heads.
Algorithm:
- Compute the importance of each filter (e.g., L1 norm of weights).
- Remove the least important filters.
- Fine-tune.
Result: Smaller dense layers that run faster on standard hardware; how far you can go before accuracy drops depends on how over-parameterized the model is.
4.3. Lottery Ticket Hypothesis
Discovery (Frankle & Carbin, 2019): A randomly initialized network contains a “winning ticket” subnetwork that, when trained in isolation, can match the full network’s accuracy.
Algorithm:
- Train the full network.
- Prune to sparsity p%.
- Rewind weights to their initial values (not random re-initialization).
- Train the pruned network from the initial weights.
Implication: We can find small, trainable networks by pruning and rewinding.
5. Knowledge Distillation
Idea: Train a small “student” model to mimic a large “teacher” model.
Algorithm:
- Teacher: Train a large, accurate model (e.g., BERT-Large).
- Student: Define a smaller model (e.g., a 4-6 layer BERT).
- Distillation Loss:
- Soft Targets: Use the teacher’s softmax probabilities (not hard labels).
- \(L_{\text{distill}} = \text{KL}(P_{\text{teacher}} \parallel P_{\text{student}})\).
- Temperature Scaling: \(P_i = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}\) where T > 1 (e.g., T = 3). Higher temperature makes the distribution “softer” (less peaked), revealing more information about the teacher’s uncertainty.
- Combined Loss:
- \(L = \alpha L_{CE}(y, P_{\text{student}}) + (1 - \alpha) T^2 L_{\text{distill}}\). The \(T^2\) factor (from Hinton et al.) keeps the soft-target gradients on the same scale as T changes.
- Train the student on the same dataset.
Result: Students typically keep most of the teacher’s accuracy; DistilBERT, below, keeps 97% of BERT-Base’s GLUE score with 40% fewer parameters.
5.1. DistilBERT
Architecture:
- 6 layers (vs 12 in BERT-Base).
- Hidden size 768 (same as BERT).
- 40% fewer parameters.
Training:
- Distilled from BERT-Base.
- Triple loss: Distillation + Masked LM + Cosine Embedding (hidden states).
Result:
- 97% of BERT-Base accuracy on GLUE.
- 60% faster inference.
6. Low-Rank Factorization
Idea: Decompose a weight matrix \(W \in \mathbb{R}^{m \times n}\) into \(W = U V^T\) where \(U \in \mathbb{R}^{m \times r}\) and \(V \in \mathbb{R}^{n \times r}\) with \(r \ll \min(m, n)\).
Benefit: Reduce parameters from m × n to r(m + n).
Algorithm (SVD):
- Compute Singular Value Decomposition: \(W = U \Sigma V^T\).
- Keep only the top r singular values.
- \(W_{\text{approx}} = U_r \Sigma_r V_r^T\).
Use Case: Compressing the embedding layer in NLP models.
7. System Design: On-Device Inference Pipeline
Scenario: Deploy a BERT model on a smartphone for real-time text classification.
Constraints:
- Model Size: < 50MB.
- Latency: < 100ms per inference.
- Power: < 500mW.
Solution:
Step 1: Compression
- Distillation: BERT-Base (110M params) → DistilBERT (66M params).
- Quantization: FP32 → INT8 (4x reduction).
- Size Check: 66M params × 1 byte = 66MB, still over the 50MB budget. Close the gap by shrinking the vocabulary/embedding table (about a third of DistilBERT’s parameters), pruning attention heads, or choosing a smaller student such as a 4-layer model.
Step 2: Optimization
- ONNX Runtime: Convert PyTorch model to ONNX for optimized inference.
- Operator Fusion: Fuse bias + GELU, and the residual add + LayerNorm (SkipLayerNorm), into single kernels.
- Graph Optimization: Remove redundant nodes.
Step 3: Hardware Acceleration
- Android: Use LiteRT (formerly TensorFlow Lite) GPU or NPU delegates. NNAPI, the older route, is deprecated as of Android 15.
- iOS: Use Core ML with ANE (Apple Neural Engine).
Step 4: Caching
- Cache embeddings for frequently seen inputs.
8. Deep Dive: Mixed-Precision Quantization
Not all layers need the same precision. Sensitive layers (e.g., first/last layer) can remain FP16, while others are INT8.
Algorithm:
- Sensitivity Analysis: For each layer, measure accuracy drop when quantized to INT8.
- Pareto Frontier: Find the set of layer precisions that maximize accuracy for a given model size.
- AutoML: Use Neural Architecture Search to find the optimal precision for each layer.
Example (MobileNetV2):
- First layer: FP16 (sensitive to quantization).
- Middle layers: INT8.
- Last layer: FP16 (classification head).
9. Deep Dive: Gradient Compression for Distributed Training
In distributed training, gradients are communicated across GPUs. Compressing gradients reduces bandwidth.
Techniques:
1. Gradient Sparsification:
- Send only the top-k largest gradients.
- Accumulate the rest locally.
- Result: Deep Gradient Compression (Lin et al., 2018) reports 270x to 600x gradient compression without losing accuracy.
2. Gradient Quantization:
- Quantize gradients to 8-bit or even 1-bit.
- 1-bit SGD: Send only the sign of the gradient.
3. Error Feedback:
- Track the quantization error and add it to the next gradient.
- Ensures convergence despite lossy compression.
10. Case Study: TensorFlow Lite (LiteRT)
Goal: Run TensorFlow models on mobile and embedded devices. Google renamed TensorFlow Lite to LiteRT in 2024; the tf.lite converter API below still works.
Features:
- Converter: Converts TensorFlow/Keras models to
.tfliteformat. - Quantization: Built-in PTQ and QAT.
- Optimizations: Operator fusion, constant folding.
- Delegates: Hardware acceleration (GPU, DSP, NPU).
Example:
import tensorflow as tf
# Load model
model = tf.keras.models.load_model('model.h5')
# Convert to TFLite with INT8 quantization
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
# Calibration
def representative_dataset():
for data in calibration_data:
yield [data]
converter.representative_dataset = representative_dataset
tflite_model = converter.convert()
# Save
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
11. Interview Questions
- Explain Quantization. What is the difference between PTQ and QAT?
- Knowledge Distillation. Why use soft targets instead of hard labels?
- Pruning. What is the Lottery Ticket Hypothesis?
- Trade-offs. Quantization vs Pruning vs Distillation. When to use which?
- Calculate Compression Ratio. A model has 100M parameters. After 90% pruning and INT8 quantization, what is the final size?
- Original: 100M × 4 bytes = 400MB.
- After pruning: 10M params.
- After quantization: 10M × 1 byte = 10MB.
- Compression: 40x, before the index overhead of storing an unstructured sparse matrix (which can add a lot back).
12. Common Pitfalls
- Quantizing Batch Norm: Batch Norm layers should be fused with Conv layers before quantization.
- Calibration Data: Using too little calibration data leads to poor quantization ranges.
- Pruning Ratio: Pruning too aggressively (>95%) often causes unrecoverable accuracy loss.
- Distillation Temperature: Too high (T > 10) makes the soft targets too uniform (little information). T = 1 keeps the teacher’s ordinary softmax, which is often so peaked that it adds little beyond the hard label.
13. Hardware-Specific Optimizations
13.1. ARM NEON (Mobile CPUs)
NEON is ARM’s SIMD (Single Instruction Multiple Data) instruction set.
Optimization:
- INT8 GEMM: Matrix multiplication using 8-bit integers.
- Vectorization: Process 16 INT8 values in parallel.
- Fused Operations: Combine Conv + ReLU + Quantization in a single kernel.
Performance Gain: INT8 kernels are typically several times faster than FP32 on modern ARM cores, especially with the dot-product instructions (SDOT/UDOT) that cores like the Cortex-A76 support.
13.2. NVIDIA Tensor Cores
Tensor Cores are specialized hardware for matrix multiplication.
Supported Precisions:
- FP16: 312 TFLOPS on A100.
- INT8: 624 TOPS (Tera Operations Per Second).
- INT4: 1248 TOPS.
Optimization:
- Use Automatic Mixed Precision (AMP) in PyTorch.
- Ensure matrix dimensions are multiples of 8 (for FP16) or 16 (for INT8), per NVIDIA’s Tensor Core guidance.
13.3. Google TPU (Tensor Processing Unit)
TPU v4:
- Precision: BF16 (Brain Float 16).
- Systolic Array: Optimized for matrix multiplications.
- Memory: 32GB HBM (High Bandwidth Memory).
Optimization:
- Use XLA (Accelerated Linear Algebra) compiler for graph optimization.
- Batch size should be large (>128) to saturate the TPU.
14. Production Case Study: BERT Compression for Search
Scenario (illustrative): Deploy a BERT-style encoder for semantic search at very high query volume.
Challenges:
- Latency: Must respond in <50ms.
- Cost: Running BERT-Base on every query is expensive at this volume.
Solution:
Step 1: Distillation
- BERT-Base (110M params) → DistilBERT (66M params).
- Result (as reported for DistilBERT): 40% smaller, 60% faster, 97% of BERT-Base’s GLUE score.
Step 2: Quantization
- DistilBERT FP32 → INT8.
- Result: 4x smaller (about 264MB → 66MB), usually faster on CPUs with INT8 kernels.
Step 3: Pruning
- Structured pruning: Remove about 30% of attention heads.
- Result: Attention projections are only part of the parameter count (the embedding table and feed-forward layers are most of it), so size drops modestly; measure the latency gain.
Step 4: Caching
- Cache embeddings for the most frequent queries.
- Hit Rate: With hit rate h, encoder compute falls by roughly h.
Final Result:
- Measure latency, cost and accuracy against the BERT-Base baseline on your own traffic. Each step’s savings compound, and so do its accuracy losses, so gate every step on an offline evaluation.
15. Advanced Technique: Neural Architecture Search for Compression
Problem: Manually designing compressed architectures is tedious.
Solution: Use NAS to automatically find efficient architectures.
Approaches:
1. Once-for-All (OFA) Networks:
- Train a single “super-network” that contains all possible sub-networks.
- At deployment, extract a sub-network that fits the target device.
- Benefit: No need to retrain for each device.
2. ProxylessNAS:
- Search directly on the target hardware (e.g., mobile phone).
- Objective: Maximize accuracy subject to latency < 50ms.
3. EfficientNet:
- Use compound scaling: scale depth, width, and resolution together.
- Result: EfficientNet-B0 (5.3M parameters) slightly beats ResNet-50’s ImageNet accuracy with about 5x fewer parameters.
16. Compression Benchmarks
Model: ResNet-50 (25.6M params, about 100MB in FP32). Sizes follow from the arithmetic; accuracy figures are torchvision’s published ImageNet top-1 numbers where they exist, and the rest you have to measure.
| Technique | Size (MB) | What to Expect |
|---|---|---|
| Baseline (FP32) | ~100 | 76.1% top-1 |
| INT8 PTQ | ~25 | 75.9% top-1 (torchvision’s quantized ResNet-50); CPU speedup depends on INT8 kernels |
| 50% channel pruning | ~50 | Real speedup on standard hardware; needs fine-tuning to recover accuracy |
| Distill into ResNet-18 | ~47 | ResNet-18 trained alone reaches 69.8%; distillation recovers part of the gap |
| Pruning + INT8 | ~12.5 | Size gains compound, and so do accuracy losses |
| ResNet-18 student + INT8 | ~12 | Smallest and fastest, with the largest accuracy gap |
Observation: Combining techniques yields the best compression ratio.
17. Deep Dive: Weight Clustering
Idea: Cluster weights into K centroids (e.g., 256). Store only the centroid index (8 bits) instead of the full weight (32 bits).
Algorithm (K-Means):
- Flatten all weights into a 1D array.
- Run K-Means clustering with
K = 256. - Replace each weight with its cluster centroid.
- Store: (1) Codebook (256 centroids), (2) Indices (8 bits per weight).
Compression Ratio:
- Original: 32 bits/weight.
- Compressed: 8 bits/weight + codebook overhead.
- Result: ~4x compression.
Accuracy: Usually a small drop for K = 256.
18. Deep Dive: Dynamic Neural Networks
Idea: Adapt the model size based on input complexity.
Techniques:
1. Early Exit:
- Add intermediate classifiers at different layers.
- For easy inputs, exit early (use fewer layers).
- For hard inputs, use the full network.
- Example: BranchyNet, MSDNet.
2. Adaptive Computation Time (ACT):
- Each layer decides whether to continue processing or stop.
- Benefit: Variable compute based on input.
3. Slimmable Networks:
- Train a single network that can run at different widths (e.g., 0.25x, 0.5x, 0.75x, 1x).
- At runtime, choose the width based on available resources.
19. Production Deployment: Model Serving
Scenario: Serve a compressed model in production.
Architecture:
1. Model Repository:
- Store compressed models in S3/GCS.
- Version control (v1, v2, v3).
2. Model Server:
- TensorFlow Serving: Supports TFLite models.
- TorchServe: Supports quantized PyTorch models.
- ONNX Runtime: Cross-framework support.
3. Load Balancer:
- Distribute requests across multiple model servers.
4. Monitoring:
- Track latency (P50, P95, P99).
- Track accuracy (A/B test compressed vs full model).
- Track resource usage (CPU, memory).
5. Auto-Scaling:
- Scale up during peak hours.
- Scale down during off-peak to save cost.
20. Cost-Benefit Analysis
Scenario (illustrative, assuming one request at a time per instance): Deploying a compressed model for image classification (1M requests/day).
Baseline (FP32 ResNet-50):
- Latency: 100ms/request.
- Compute: 1M requests × 100ms = 100K seconds/day = 27.8 hours/day.
- Cost: 27.8 hours × $0.17/hour (roughly the c5.xlarge on-demand rate in us-east-1) = $4.72/day = about $1,720/year.
Compressed (INT8 ResNet-50):
- Latency: 30ms/request (3x faster).
- Compute: 1M requests × 30ms = 30K seconds/day = 8.3 hours/day.
- Cost: 8.3 hours × $0.17/hour = $1.42/day = about $520/year.
Savings: About $1,200/year (70% cost reduction). The percentage is what carries over to larger fleets.
Accuracy Trade-off: 76.1% → 75.9% (0.2-point drop, torchvision’s quantized ResNet-50).
ROI: If the accuracy drop is acceptable, compression is a no-brainer.
21. Ethical Considerations
Bias Amplification:
- Compression can amplify biases in the training data.
- Example: A pruned model might be less accurate on underrepresented groups.
- Solution: Evaluate fairness metrics (e.g., demographic parity) after compression.
Environmental Impact:
- Training large models consumes energy (carbon footprint).
- Compression reduces inference energy, but the compression process itself (e.g., NAS) can be energy-intensive.
- Solution: Use efficient compression methods (PTQ instead of NAS).
22. Future Trends
1. Extreme Quantization:
- Binary Neural Networks (BNNs): 1-bit weights and activations.
- Ternary Neural Networks (TNNs): Weights in {-1, 0, 1}.
- Challenge: Large accuracy drops on hard tasks such as ImageNet, though recent binary networks have narrowed the gap.
2. Hardware-Software Co-Design:
- Design hardware specifically for compressed models.
- Example: Google Edge TPU optimized for INT8.
3. On-Device Learning:
- Fine-tune compressed models on-device using user data.
- Challenge: Privacy (Federated Learning).
23. Key Takeaways
Model compression is essential for deploying deep learning at scale. The key is to combine multiple techniques (quantization + pruning + distillation) to achieve the best compression ratio while maintaining acceptable accuracy.
In Short:
- Quantization: 4x compression with minimal accuracy drop.
- Pruning: 50-90% sparsity, but requires specialized hardware for speedup.
- Distillation: 10x compression, but requires retraining.
- Hardware Matters: Optimize for the target device (ARM, NVIDIA, TPU).
- Production: Monitor latency, accuracy, and cost.
The future of AI is edge AI. As models grow larger, compression will become even more critical. Mastering these techniques is a must for ML engineers.
24. Deep Dive: ONNX (Open Neural Network Exchange)
Problem: Models trained in PyTorch can’t run on TensorFlow Serving. Models trained in TensorFlow can’t run on ONNX Runtime.
Solution: ONNX is a universal format for neural networks.
Workflow:
- Train in PyTorch/TensorFlow/Keras.
- Export to ONNX format.
- Optimize using ONNX Runtime.
- Deploy on any platform (mobile, edge, cloud).
Example (PyTorch → ONNX):
import torch
import torch.onnx
# Load PyTorch model: rebuild the architecture, then load the weights
# (torch.load defaults to weights_only=True since PyTorch 2.6)
model = MyModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()
# Dummy input
dummy_input = torch.randn(1, 3, 224, 224)
# Export to ONNX
torch.onnx.export(
model,
dummy_input,
"model.onnx",
export_params=True,
opset_version=13,
do_constant_folding=True,
input_names=['input'],
output_names=['output'],
dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}}
)
ONNX Runtime Optimizations:
- Graph Optimization: Fuse operators, eliminate redundant nodes.
- Quantization: INT8 quantization.
- Execution Providers: CPU, CUDA, TensorRT, DirectML, CoreML.
25. Mobile Deployment: iOS (Core ML)
Core ML is Apple’s framework for on-device ML.
Workflow:
- Train model in PyTorch/TensorFlow.
- Convert to Core ML format (an
.mlpackageML program;.mlmodelis the older neural network format). - Integrate into iOS app.
Conversion (PyTorch → Core ML):
import coremltools as ct
import torch
# Load PyTorch model
model = MyModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()
# Trace the model
example_input = torch.rand(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)
# Convert to Core ML
mlmodel = ct.convert(
traced_model,
inputs=[ct.ImageType(name="input", shape=(1, 3, 224, 224))],
convert_to="mlprogram" # the default in coremltools 7+; "neuralnetwork" is legacy
)
# Save
mlmodel.save("model.mlpackage")
Optimization:
- Quantization: Use
ct.optimize.coreml.linear_quantize_weights(). - Pruning: Use
ct.optimize.coreml.prune_weights(). - Neural Engine: Optimize for Apple’s ANE (Neural Engine).
26. Mobile Deployment: Android (TensorFlow Lite)
TensorFlow Lite (renamed LiteRT in 2024) is Google’s framework for mobile/edge ML.
Workflow:
- Train model in TensorFlow/Keras.
- Convert to TFLite format (
.tflite). - Integrate into Android app.
Conversion:
import tensorflow as tf
# Load Keras model
model = tf.keras.models.load_model('model.h5')
# Convert to TFLite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()
# Save
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
Optimization:
- GPU Delegate: Use GPU for inference.
- NNAPI Delegate: Use Android’s Neural Networks API (deprecated as of Android 15; prefer vendor NPU delegates).
- Hexagon Delegate: Use Qualcomm’s DSP.
27. Advanced Technique: Sparse Tensor Cores (NVIDIA)
NVIDIA Ampere (A100, RTX 3090) introduced Sparse Tensor Cores that accelerate 2:4 structured sparsity.
2:4 Sparsity: In every 4 consecutive weights, at least 2 must be zero.
Example:
Original: [0.5, 0.3, 0.1, 0.2]
2:4 Sparse: [0.5, 0.3, 0.0, 0.0] ✓ (2 zeros out of 4)
Speedup: Up to 2x the dense math throughput on Sparse Tensor Cores; end-to-end gains are smaller because not every operation is a sparse matmul.
Training with 2:4 Sparsity:
import torch
from apex.contrib.sparsity import ASP # NVIDIA's Automatic SParsity tool
model = MyModel().cuda()
optimizer = torch.optim.AdamW(model.parameters())
# Compute 2:4 masks from the trained weights and keep them applied
ASP.prune_trained_model(model, optimizer)
# Fine-tune normally to recover accuracy
28. Deep Dive: Huffman Coding for Weight Compression
Idea: Use variable-length encoding for weights. Frequent weights get shorter codes.
Algorithm:
- Cluster weights into
Kcentroids (e.g., 256). - Count frequency of each centroid.
- Build Huffman Tree: Assign shorter codes to frequent centroids.
- Encode: Replace each weight with its Huffman code.
Compression Ratio:
- Fixed-length (8 bits): 8 bits/weight.
- Huffman: ~5-6 bits/weight (depending on distribution).
Trade-off: Decoding overhead during inference.
29. Production Case Study: MobileNet Deployment
Scenario: Deploy MobileNetV2 for image classification on a smartphone.
This walkthrough uses published model sizes and accuracies; latency depends on the phone, so measure it there.
Baseline (FP32):
- Size: 14MB (3.5M parameters).
- Accuracy: About 72% top-1 (ImageNet).
Optimization Pipeline:
Step 1: Quantization (INT8)
- Size: 3.5MB (4x reduction).
- Accuracy: Usually a small drop with good calibration; depthwise convolutions make MobileNets more sensitive than ResNets, so QAT is common.
Step 2: Channel Pruning (50%)
- Size: About 1.75MB (2x reduction).
- Accuracy: Must be measured; MobileNets are already compact and tend to lose more from pruning than over-parameterized networks.
Step 3: Switch to a Smaller Student (MobileNetV3-Small, Distilled from MobileNetV2)
- Size: 2.5M parameters, about 2.5MB in INT8.
- Accuracy: About 67.7% top-1 for torchvision’s MobileNetV3-Small trained alone; distillation can add some of the gap back.
Final Result:
- Size: About 2.5MB (roughly 5.5x smaller than the FP32 baseline) for the INT8 student, or less if you also prune it.
- Accuracy: About 4 points below the baseline, which may be acceptable for a mobile use case.
30. Advanced Technique: Neural ODE Compression
Neural ODEs (Ordinary Differential Equations) model continuous transformations.
Compression:
- Instead of a stack of residual blocks with separate weights, one block’s weights are shared across continuous “time”.
- Benefit: Parameter count does not grow with effective depth, and the adjoint method keeps training memory constant.
- Trade-off: Slower inference (need to solve ODE).
Use Case: Mostly a research idea; it is rarely used for production compression.
31. Monitoring Compressed Models in Production
Metrics to Track:
- Latency Distribution: P50, P95, P99. Alert if P95 > SLA.
- Accuracy Drift: Compare predictions with a “shadow” full-precision model.
- Resource Usage: CPU, memory, battery drain (for mobile).
- Error Analysis: Which classes have the highest error rate after compression?
A/B Testing:
- Control: Full-precision model (10% of traffic).
- Treatment: Compressed model (90% of traffic).
- Metrics: Latency, accuracy, user engagement.
Rollback Strategy:
- If compressed model’s accuracy drops > 2%, automatically rollback to full-precision.
32. Interview Deep Dive: Compression Trade-offs
Q: When would you use quantization vs pruning vs distillation?
A:
- Quantization: When you need fast inference on CPUs/mobile. Works well for CNNs. Minimal accuracy drop.
- Pruning: When you have specialized hardware (Sparse Tensor Cores) or can tolerate irregular sparsity. Best for very large models.
- Distillation: When you can afford to retrain. Best for transferring knowledge from an ensemble to a single model. Works well for NLP.
Q: How do you choose the quantization precision (INT8 vs INT4)?
A:
- INT8: Standard. 4x compression, usually a small accuracy drop.
- INT4: 8x compression versus FP32. Weight-only INT4 (GPTQ, AWQ) is now common for LLM inference with small quality loss; INT4 activations are much harder and cost more accuracy.
- Mixed Precision: Use INT4 for less sensitive layers, INT8 for sensitive layers.
33. Future Research Directions
1. Learned Compression:
- Use a neural network to learn the optimal compression strategy for each layer.
- Example: AutoML for compression.
2. Post-Training Sparsification:
- Prune without retraining (like PTQ for quantization).
- Challenge: Maintaining accuracy.
3. Hardware-Aware Compression:
- Compress specifically for the target hardware (e.g., iPhone 15 Pro’s A17 chip).
- Benefit: Maximize performance on that specific device.
34. Conclusion & Best Practices
Best Practices:
- Start with Quantization: Easiest, fastest, minimal accuracy drop.
- Combine Techniques: Quantization + Pruning + Distillation for maximum compression.
- Profile First: Measure latency bottlenecks before optimizing.
- Test on Target Device: Don’t rely on desktop benchmarks.
- Monitor in Production: Track accuracy drift and latency.
Compression Checklist:
- Benchmark baseline model (size, latency, accuracy)
- Apply INT8 quantization (PTQ or QAT)
- Measure accuracy drop (<2% acceptable)
- Apply structured pruning (30-50%)
- Fine-tune pruned model
- Consider distillation if retraining is feasible
- Convert to target format (ONNX, TFLite, Core ML)
- Test on target hardware
- Deploy with monitoring
- Set up A/B test
- Monitor and iterate
The art of model compression is balancing the three-way trade-off: Size, Speed, Accuracy. There’s no one-size-fits-all solution. The best approach depends on your use case, hardware, and constraints. Mastering these techniques will make you indispensable in the era of edge AI.
FAQ
What is the difference between post-training quantization and quantization-aware training?
Post-training quantization (PTQ) converts a trained FP32 model to INT8 using a small calibration dataset to determine scale and zero-point values for each layer, with no retraining needed. Quantization-aware training (QAT) inserts fake quantization nodes during training so the model learns to be robust to quantization noise, using the straight-through estimator to approximate gradients through the rounding operation. QAT usually recovers much of the accuracy PTQ loses, especially at low bit widths, but requires retraining, making it worthwhile for production-critical models.
When should you use quantization vs pruning vs knowledge distillation?
Start with quantization as it provides 4x compression with minimal accuracy drop and no retraining required. Use pruning when you have specialized hardware (NVIDIA Sparse Tensor Cores support 2:4 structured sparsity with up to 2x math throughput) or need aggressive compression. Use distillation when you can afford to retrain and want to create an architecturally different, smaller student model. Combining all three yields the best compression ratios, as the BERT compression walkthrough illustrates.
What is the Lottery Ticket Hypothesis?
Frankle and Carbin (2019) discovered that randomly initialized networks contain sparse subnetworks (“winning tickets”) that, when trained from their original initialization, match the full network’s accuracy. The key insight is rewinding weights to their initial values rather than random re-initialization after pruning. This suggests that the structure of the initialization matters, and we can find small, trainable networks through iterative pruning and weight rewinding.
How do you deploy a compressed ML model on mobile devices?
The pipeline involves distillation to reduce parameter count, INT8 quantization for 4x size reduction, conversion to the target format (ONNX Runtime for cross-platform, TFLite for Android, Core ML for iOS), operator fusion and graph optimization, and using hardware acceleration via LiteRT (TensorFlow Lite) GPU/NPU delegates on Android or the Apple Neural Engine on iOS. Caching embeddings for frequent inputs further reduces compute. Always benchmark on the actual target device since desktop performance does not translate to edge hardware.