4301: QAT Foundations¶
Difficulty: βββ Advanced
Estimated Time: 4 hours
Table of Contents¶
- Learning Objectives
- Abstract
- What is QAT?
- QAT vs PTQ
- How QAT Works
- When to Use QAT
- Common Issues
- Implementation Checklist
- Summary
- Further Reading
- References
Learning Objectives¶
After completing this lesson, you will be able to:
- Define QAT as forward-pass fake quantization β round to the INT8 grid then dequantize back, while the weights stay FP32 so the backward pass sees real values
- Choose between PTQ and QAT from the trade-off table β minutes vs hours-days of training, PTQ quality holding at 8-bit but degrading at 4-bit where QAT wins
- Trace the three QAT mechanics β
fake_quantize's clamp(round(x/scale)+zero_point, -128, 127), the STE in theFakeQuantizeautograd.Function passing grad_output through rounding untouched, andQuantizationObserver's momentum-0.01 moving average yielding scale = (maxβmin)/255 - Decide QAT vs PTQ from the scenario lists β QAT for β€4-bit targets, sensitive tasks (translation, code, math), edge deployment, and available training data; PTQ for 8-bit sufficiency, missing data, quick turnaround, limited compute
- Mitigate the three failure modes β activation outliers clipped to [-5, 5] before quantization, early-training divergence handled by enabling QAT after epoch 5, per-channel range mismatch solved with amax-derived channel scales
- Execute the 8-step implementation checklist β fake-quant modules, STE backward, observers, per-channel config, layer selection, gradual QAT enable, accuracy-vs-bit-width evaluation, final export
Abstract¶
Quantization Aware Training (QAT) is a technique that simulates the effects of quantization during model training, allowing the model to adapt and maintain accuracy when deployed at lower precision.
What is QAT?¶
Key Idea: Instead of quantizing after training (PTQ), we simulate quantization during training so the model learns to handle reduced precision.
Training Flow:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Forward Pass β
β ββ FP32 Weights βββ¬ββ Fake Quantize ββ> INT8 (simulated) β
β β β β
β ββ FP32 Input ββββββ΄ββ Fake Quantize ββ> INT8 (simulated) β
β β β
β ββ> Compute in simulated INT8 β
β (round to INT8, but store as FP32 for backward pass) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Backward Pass β
β ββ> Straight-Through Estimator (STE) β
β (gradient bypasses rounding operation) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
QAT vs PTQ¶
| Aspect | PTQ (Post-Training) | QAT (Quantization Aware) |
|---|---|---|
| Training | Not required | Required |
| Time | Minutes | Hours-days |
| Accuracy | Good at 8-bit, degrades at 4-bit | Better at 4-bit and below |
| Complexity | Simple | Moderate |
| Best For | Fast deployment, >8-bit | Extreme compression, edge |
How QAT Works¶
1. Fake Quantization¶
During forward pass, we simulate quantization:
import torch
def fake_quantize(x, scale, zero_point, qmin=-128, qmax=127):
"""Simulate INT8 quantization in forward pass"""
# Quantize
x_quant = torch.clamp(
torch.round(x / scale) + zero_point,
qmin, qmax
)
# Dequantize back to FP32
x_dequant = (x_quant - zero_point) * scale
return x_dequant
# Example
weight = torch.randn(256, 256) # FP32 weights
scale = weight.abs().max() / 127
zero_point = 0
# During training, use fake quantized version
weight_fake_q = fake_quantize(weight, scale, zero_point)
batch = torch.randn(4, 256) # a batch of activation vectors
output = batch @ weight_fake_q.T # [4, 256] @ [256, 256].T = [4, 256]
2. Straight-Through Estimator (STE)¶
During backward pass, gradients need to flow through the rounding operation:
class FakeQuantize(torch.autograd.Function):
@staticmethod
def forward(ctx, x, scale, zero_point, qmin, qmax):
# Quantize-dequantize in forward
x_quant = torch.clamp(
torch.round(x / scale) + zero_point,
qmin, qmax
)
return (x_quant - zero_point) * scale
@staticmethod
def backward(ctx, grad_output):
# STE: Pass gradient through unchanged
# (pretend rounding didn't happen)
return grad_output, None, None, None, None
# Usage
x = torch.randn(100, requires_grad=True)
x_fq = FakeQuantize.apply(x, scale, 0, -128, 127)
loss = x_fq.sum()
loss.backward() # Gradient flows despite rounding
3. Moving Average for Scale/Zero-Point¶
Scale and zero-point use moving averages to stabilize training:
class QuantizationObserver:
def __init__(self, momentum=0.01):
self.min_val = None
self.max_val = None
self.momentum = momentum
def update(self, x):
batch_min = x.min().item()
batch_max = x.max().item()
if self.min_val is None:
self.min_val = batch_min
self.max_val = batch_max
else:
# Moving average
self.min_val = (
self.momentum * batch_min +
(1 - self.momentum) * self.min_val
)
self.max_val = (
self.momentum * batch_max +
(1 - self.momentum) * self.max_val
)
def get_qparams(self):
scale = (self.max_val - self.min_val) / 255
zero_point = -round(self.min_val / scale)
return scale, zero_point
When to Use QAT¶
Use QAT When:¶
- Targeting 4-bit or lower: PTQ accuracy drops significantly below 8-bit
- Sensitive tasks: Translation, code generation, mathematical reasoning
- Edge deployment: Need smallest possible model size
- Have training data: Can afford to fine-tune
Use PTQ When:¶
- 8-bit is sufficient: PTQ usually fine for INT8
- No training data: Can't access original training data
- Quick deployment: Need results in minutes
- Limited compute: Don't have resources for retraining
Common Issues¶
Issue 1: Activation Outliers¶
Problem: Some activations have extreme values that distort quantization range.
Solution:
# Clip outliers before quantization
x_clipped = torch.clamp(x, -5.0, 5.0) # Clip to [-5, 5]
x_fq = fake_quantize(x_clipped, scale, zero_point)
Issue 2: Training Instability¶
Problem: Model diverges when QAT is enabled too early.
Solution:
# Start QAT after initial convergence
for epoch in range(num_epochs):
if epoch > 5: # Enable QAT after epoch 5
enable_quantization(model)
train_epoch(model)
Issue 3: Weight Channels Need Different Scales¶
Problem: Different output channels have different ranges.
Solution:
# Per-channel quantization (for weights)
# amax (not max): max() only takes a single int dim, amax takes lists
linear_w = torch.randn(128, 64) # [out_features, in_features]
scale = linear_w.abs().amax(dim=1, keepdim=True) / 127
# Shape: [out_features, 1] - one scale per output channel, not a scalar
# Conv weights are 4-D [out_c, in_c, kH, kW]: reduce over dims 1-3
conv_w = torch.randn(64, 32, 3, 3)
conv_scale = conv_w.abs().amax(dim=[1, 2, 3], keepdim=True) / 127
# Shape: [out_channels, 1, 1, 1]
Implementation Checklist¶
- Add fake quantization modules to model
- Implement STE for backward pass
- Add observers for scale/zero-point
- Configure per-channel vs per-tensor
- Decide which layers to quantize
- Implement gradual QAT (start after initial training)
- Evaluate accuracy vs bit-width
- Export final quantized model
Summary¶
Quantization Aware Training is the answer to a simple failure mode: post-training quantization costs accuracy because the weights never see quantization during training. QAT inserts fake-quantization ops into the forward pass, so the model adapts its weights to the precision it will actually run at - typically recovering most of the PTQ accuracy gap while keeping the deployment win. The decision rule from this lesson: try PTQ first, and reach for QAT when quantized accuracy misses your target and you have the training data and budget to close it.
Further Reading¶
- Paper: "Quantization and Training of Neural Networks" (Jacob et al., 2018)
- Paper: "Training Low-bit Neural Networks" (Zhou et al., 2024)
- Tutorial: PyTorch QAT Documentation
- Code: Hugging Face
bitsandbyteslibrary
References¶
Related Minder Academy Documents¶
- 4302: Fake Quantization
- 4303: QAT for Transformers
- 4304: Low-bit QAT
- 4305: Quantization Configuration
- CHEAT-SHEET-044: Quantization-Aware Training - the Straight-Through Estimator and the Layer Map
Next Steps¶
- Continue with: 4302: Fake Quantization