1. Introduction
Model compression is the process of reducing the size, memory usage, and computational cost of a machine learning model while maintaining acceptable prediction performance. The two important model compression techniques are:Main goals
- Reduce model size
- Reduce memory usage
- Improve inference speed
- Reduce deployment cost
- Make models suitable for edge/mobile devices
- Maintain acceptable accuracy
2. Quantization
Quantization converts model parameters and/or computations from a higher numerical precision to a lower precision. A common conversion is:FP32= 32-bit floating pointINT8= 8-bit integer
3. FP32
Most PyTorch models initially usefloat32 values.
For example:
4. INT8
INT8 uses 8 bits to represent values.5. Why Quantization?
Consider a model with:6. Post-Training Quantization
Post-training quantization (PTQ) applies quantization after the model has already been trained.7. Dynamic Quantization
Dynamic quantization is a simple form of post-training quantization. In PyTorch:8. Simple Quantization Example
quantization_demo.py
9. Understanding the Example
Step 1 - Create model
Step 2 - Set evaluation mode
Step 3 - Quantize the model
Step 4 - Create input
Step 5 - Generate original prediction
Step 6 - Generate quantized prediction
10. Important Observation
Quantization does not mean:11. Quantization Trade-off
Quantization provides benefits, but there can be a trade-off.12. Pruning
Pruning is another model compression technique. Instead of reducing the precision of parameters, pruning removes or disables parameters that contribute relatively little to the model. Example:13. Types of Pruning
Unstructured Pruning
Individual weights are removed.Structured Pruning
Entire structures are removed. Examples:- Neurons
- Channels
- Filters
- Attention heads
14. Quantization vs Pruning
15. Quantization + Pruning
Both techniques can be combined.16. Model Compression Workflow
17. Size Comparison
For a compression experiment:
The exact values depend on the model, hardware, runtime, and quantization method.
18. Measuring Model Size
A simple way to measure a saved model:19. Measuring Inference Latency
A simple latency measurement:20. Simple Coding Challenge
File
Objective
Create a small PyTorch model and compare:- Model size
- Inference latency
- Output values
Expected workflow
21. What Should Be Learned From This Challenge?
The important concepts are:Quantization
Pruning
Compression objective
22. MLOps Connection
Model compression fits into the deployment part of an MLOps pipeline:23. Key Terms
24. Final Summary
One-line learning
Quantization reduces the precision of model parameters, while pruning removes unnecessary parameters or structures to make ML models smaller and more efficient.