Lab 02 — Quantization-Aware Training (QAT)
Phase: 03 — Quantization & Model Compression | Difficulty: ⭐⭐⭐⭐☆ | Time: 3–4 hours
QAT trains with simulated quantization noise — the model learns to be robust to INT8/INT4 precision.
What you build
FakeQuantize— asymmetric per-tensor fake-quant with Straight-Through Estimator (STE)QATLinear— Linear layer with fake-quantized weightswrap_model_for_qat— replace all Linear layers with QATLinear (deepcopy safe)train_qat— AdamW training loop on QAT modelconvert_to_int8— fold scale/zero_point into INT8 weights post-training
Key concepts
| Concept | What to understand |
|---|---|
| STE | x_out = x + (quant(x) - x).detach() — gradients flow through |
| FakeQuantize | Quantize + dequantize in forward; model learns to minimize error |
| INT8 conversion | After QAT, actual INT8 weights match dequantized FakeQuant output |
| Accuracy vs PTQ | QAT typically +1–3% accuracy over PTQ at same bit width |
Files
| File | Purpose |
|---|---|
lab.py | Stubs with TODO markers |
solution.py | Complete working implementation |
test_lab.py | pytest suite |
requirements.txt | Dependencies |
Run
pip install -r requirements.txt
python lab.py
pytest test_lab.py -v