Overview

5 Recovering Accuracy with Quantization-Aware Training

The chapter explains when post-training quantization is enough and when it starts to break down. INT8 often remains nearly lossless, but INT4 can push models past an “accuracy cliff,” especially for small networks or workloads with very tight error budgets. To decide whether more intervention is needed, the chapter recommends diagnosing failure modes instead of relying only on aggregate accuracy: check whether degradation is diffuse across many layers or concentrated in a few sensitive ones, examine class-wise failures, and inspect confidence shifts that can reveal collapse even when top-line metrics look acceptable.

When PTQ is insufficient, quantization-aware training provides a way to recover accuracy by teaching the model to operate under quantization during training. Because true rounding blocks gradients, QAT uses fake quantization in the forward pass and the straight-through estimator in the backward pass, letting learning continue with full-precision parameters. The chapter shows how this works in practice, including clipped STE variants, fake-quantized linear and convolutional layers, and numerical safeguards. It also emphasizes that QAT is fine-tuning rather than training from scratch, so successful runs use lower learning rates, shorter training, and gradient clipping.

The chapter then focuses on making QAT efficient and selective. It recommends warming up the learning rate, freezing observer statistics once scale estimates stabilize, and progressively lowering bit-width so the model adapts gently before reaching the target precision. It also shows that per-channel weight quantization usually preserves more gradient signal than per-tensor quantization, making it the default choice for convolution and linear weights. For transformers, the chapter argues for targeted adaptation: keep sensitive components such as LayerNorm, softmax, and GELU in FP32, prioritize the feed-forward layers when needed, and use selective or mixed-precision strategies guided by quick sublayer diagnostics rather than retraining everything indiscriminately.

PTQ accuracy for ResNet-18 on ImageNette. INT8 is indistinguishable from the FP32 baseline. INT4 drops 12 percentage points—the model is degraded but still functioning.
PTQ accuracy for ResNet-18 on ImageNette. INT8 is indistinguishable from the FP32 baseline. INT4 drops 12 percentage points—the model is degraded but still functioning.
PTQ accuracy for BERT-base on SST-2. INT8 holds with under 0.5% loss. INT4 drops to 50.9%—coin-flip accuracy on a binary task, meaning the model has effectively stopped functioning.
PTQ accuracy for BERT-base on SST-2. INT8 holds with under 0.5% loss. INT4 drops to 50.9%—coin-flip accuracy on a binary task, meaning the model has effectively stopped functioning.
Layer sensitivity analysis for ResNet-18 at INT4. The first convolutional layer (conv1) shows the highest sensitivity at 1.32%, followed by a smooth gradient across the remaining layers. All bars are moderate or low—no single layer dominates the 12% total degradation.
Layer sensitivity analysis for ResNet-18 at INT4. The first convolutional layer (conv1) shows the highest sensitivity at 1.32%, followed by a smooth gradient across the remaining layers. All bars are moderate or low—no single layer dominates the 12% total degradation.
Layer sensitivity analysis for BERT at INT4. One layer dominates everything: layer.4.intermediate.dense causes a 26.4% accuracy drop when quantized alone. The remaining layers are noise in comparison. This is a concentrated failure—a clear target for mixed precision.
Layer sensitivity analysis for BERT at INT4. One layer dominates everything: layer.4.intermediate.dense causes a 26.4% accuracy drop when quantized alone. The remaining layers are noise in comparison. This is a concentrated failure—a clear target for mixed precision.
QAT decision framework. The key branch is whether failure is concentrated or diffuse—this determines whether mixed precision can save you from the cost of QAT.
QAT decision framework. The key branch is whether failure is concentrated or diffuse—this determines whether mixed precision can save you from the cost of QAT.
The straight-through estimator passes gradients unchanged through the non-differentiable rounding operation
The straight-through estimator passes gradients unchanged through the non-differentiable rounding operation
Why clipped STE zeros gradients for out-of-range values. A value clipped to the boundary is already saturated—pushing it further cannot change the quantized output. Zeroing the gradient prevents the optimizer from wasting updates on values stuck at the rails, focusing learning capacity on weights that can still move between grid points.
Why clipped STE zeros gradients for out-of-range values. A value clipped to the boundary is already saturated—pushing it further cannot change the quantized output. Zeroing the gradient prevents the optimizer from wasting updates on values stuck at the rails, focusing learning capacity on weights that can still move between grid points.
Visualizing the clipped STE gradient function. Top: the fake quantization staircase with "quantizable range" and "clipped range." Bottom: gradient behavior - basic STE (dashed) passes gradient 1 everywhere; clipped STE zeros gradients in the clipped regions.
Visualizing the clipped STE gradient function. Top: the fake quantization staircase with "quantizable range" and "clipped range." Bottom: gradient behavior - basic STE (dashed) passes gradient 1 everywhere; clipped STE zeros gradients in the clipped regions.
Weight distributions migrate toward INT4 grid points during QAT. Five snapshots of conv1 weights (epochs 0–49) show the initially Gaussian distribution reorganizing into sharp spikes aligned with quantization levels (dashed lines), demonstrating that QAT actively adapts weights to minimize rounding error rather than passively tolerating it.
Weight distributions migrate toward INT4 grid points during QAT. Five snapshots of conv1 weights (epochs 0–49) show the initially Gaussian distribution reorganizing into sharp spikes aligned with quantization levels (dashed lines), demonstrating that QAT actively adapts weights to minimize rounding error rather than passively tolerating it.
The complete QAT schedule coordinates four components. Bit-width decreases progressively (INT8→INT6→INT4). The learning rate warms up during INT8 calibration, then cosine-decays through the remaining phases. Observers freeze at epoch 8, after they've seen the INT6 distribution. Batch normalization is folded before training begins.
The complete QAT schedule coordinates four components. Bit-width decreases progressively (INT8→INT6→INT4). The learning rate warms up during INT8 calibration, then cosine-decays through the remaining phases. Observers freeze at epoch 8, after they've seen the INT6 distribution. Batch normalization is folded before training begins.
The four-panel view of the scheduled QAT pipeline. Top left: validation accuracy oscillates but stays within ~1 point of FP32 despite dropping to INT4. Top right: training loss spikes at each bit-width transition (dashed verticals at epochs 6 and 11), then recovers. Bottom left: the learning rate (solid) warms up and cosine-decays while bit-width (dashed steps) progresses 8→6→4. Bottom right: observer ΔScale spikes at bit-width transitions, then drops to zero after freezing at epoch 8.
The four-panel view of the scheduled QAT pipeline. Top left: validation accuracy oscillates but stays within ~1 point of FP32 despite dropping to INT4. Top right: training loss spikes at each bit-width transition (dashed verticals at epochs 6 and 11), then recovers. Bottom left: the learning rate (solid) warms up and cosine-decays while bit-width (dashed steps) progresses 8→6→4. Bottom right: observer ΔScale spikes at bit-width transitions, then drops to zero after freezing at epoch 8.
Three views of the gradient survival problem on ResNet-18 conv1 at INT4. Left: fraction of gradients clipped per output channel—per-tensor clips 100% of gradients in several channels, while per-channel stays well below 20%. Center: per-channel scales vs the single per-tensor scale —many channels have scales an order of magnitude smaller than the global maximum. Right: per-channel quantization produces more uniform gradient magnitudes across channels, while per-tensor leaves some channels with zero gradient signal.
Three views of the gradient survival problem on ResNet-18 conv1 at INT4. Left: fraction of gradients clipped per output channel—per-tensor clips 100% of gradients in several channels, while per-channel stays well below 20%. Center: per-channel scales vs the single per-tensor scale —many channels have scales an order of magnitude smaller than the global maximum. Right: per-channel quantization produces more uniform gradient magnitudes across channels, while per-tensor leaves some channels with zero gradient signal.
Left: Test accuracy curves for FP32, per-tensor INT4 QAT, and per-channel INT4 QAT. All three converge to nearly the same accuracy (~87%). Right: Training loss curves are virtually indistinguishable between the two QAT strategies.
Left: Test accuracy curves for FP32, per-tensor INT4 QAT, and per-channel INT4 QAT. All three converge to nearly the same accuracy (~87%). Right: Training loss curves are virtually indistinguishable between the two QAT strategies.
INT4 quantization MSE by axis for five ResNet-18 convolutional layers. Axis 0 produces lower MSE than axis 1 in every layer. The advantage is most pronounced in conv1, where the asymmetry between 64 output and 3 input channels is extreme.
INT4 quantization MSE by axis for five ResNet-18 convolutional layers. Axis 0 produces lower MSE than axis 1 in every layer. The advantage is most pronounced in conv1, where the asymmetry between 64 output and 3 input channels is extreme.
Sublayer sensitivity to per-channel weight fake quantization on BERT-base-uncased. FFN sublayers dominate—16.2× more aggregate output MSE than all four attention projections at INT8, 2.0× at INT4. Dashed line separates attention (below) from FFN (above).
Sublayer sensitivity to per-channel weight fake quantization on BERT-base-uncased. FFN sublayers dominate—16.2× more aggregate output MSE than all four attention projections at INT8, 2.0× at INT4. Dashed line separates attention (below) from FFN (above).
Selective QAT fine-tuning on SST-2 (INT4, 3 epochs). Left: accuracy per epoch. Right: best accuracy by strategy. QAT recovers BERT from the INT4 PTQ catastrophe (50.9%) to within 1.6% of FP32. Attention-only (48 layers at INT4) nearly matches FP32 at just −0.11%. FFN-only (24 layers) costs −0.57%. Quantizing all 72 layers incurs the largest gap (−1.61%).
Selective QAT fine-tuning on SST-2 (INT4, 3 epochs). Left: accuracy per epoch. Right: best accuracy by strategy. QAT recovers BERT from the INT4 PTQ catastrophe (50.9%) to within 1.6% of FP32. Attention-only (48 layers at INT4) nearly matches FP32 at just −0.11%. FFN-only (24 layers) costs −0.57%. Quantizing all 72 layers incurs the largest gap (−1.61%).

Summary

  • QAT is warranted when PTQ fails at your target bit-width, but the failure pattern determines the intervention. INT4 PTQ dropped ResNet-18 by 12 percentage points (diffuse, across all layers) and collapsed BERT-base to 50.9% coin-flip accuracy (concentrated in a single FFN layer). Diffuse failure needs QAT; concentrated failure needs mixed precision. Always run layer sensitivity before choosing.
  • Fake quantization inserts quantize-then-dequantize operations into the forward pass so the model trains against quantization noise while gradients flow through the straight-through estimator. The clipped STE—which zeros gradients for out-of-range values—is the recommended default. Use lower learning rates (1e-4 to 1e-5), shorter schedules (5–20 epochs), and gradient clipping.
  • Scheduling reduces QAT cost without sacrificing accuracy. Warm up the learning rate for 10–15% of total epochs, freeze observers once per-layer scale changes drop below 1%, and progress bit-width gradually (INT8→INT6→INT4). Our scheduled pipeline reached 90.30% on SmallCNN at INT4—slightly above the FP32 baseline—with the same wall-clock time as naïve QAT.
  • Per-channel fake quantization prevents gradient starvation during QAT. Per-tensor INT4 quantization clips 100% of gradients in some output channels; per-channel keeps all channels below 20%. Quantize along axis 0 (output channels) for both convolutions and linear layers.
  • Transformer QAT requires selective application. FFN sublayers produce 16.2× more aggregate output MSE than attention projections at INT8. Attention-only QAT recovered BERT from 50.9% to within 0.11% of FP32; quantizing all layers incurred 1.61%. Always keep LayerNorm, softmax, and GELU in FP32—their parameter count is negligible but their numerical sensitivity is high.
  • When diminishing returns set in, stop. Monitor observer ΔScale and validation accuracy jointly—when per-layer scale changes flatten below 1% and accuracy stops recovering after bit-width transitions, further epochs add cost without benefit.

FAQ

When is post-training quantization not enough and QAT becomes necessary?PTQ is usually sufficient for INT8, but it can fail at INT4, on smaller models with little redundancy, or when your accuracy budget is very tight. In those cases, QAT is useful because it teaches the model to adapt to quantization during training instead of merely tolerating it.
What is the main idea behind quantization-aware training?QAT inserts fake quantization into the forward pass during training so the model experiences quantization effects while still keeping full-precision weights for learning. This lets the network adjust its parameters to reduce accuracy loss in the quantized regime.
How do fake quantization and the straight-through estimator work together?Fake quantization simulates quantization in the forward pass, while the straight-through estimator lets gradients flow backward through the non-differentiable rounding step by treating it as if its gradient were 1. Together, they make training possible even though true rounding has zero gradient almost everywhere.
Why does true quantization break backpropagation?The rounding operation used in quantization is not differentiable in a useful way: its derivative is zero almost everywhere. If you use that true derivative during training, gradients vanish and the model cannot learn.
Why is the clipped straight-through estimator preferred over the basic STE?The clipped STE passes gradients through values that remain within the quantization range, but sets gradients to zero for values that were clipped. This prevents the optimizer from wasting effort on saturated weights that cannot change the quantized output anymore.
What training settings are recommended for QAT?QAT is usually treated as fine-tuning, not training from scratch. Common practices include using a lower learning rate, training for fewer epochs, applying gradient clipping, and using cosine annealing to help weights settle onto quantization grid points.
Why should batch normalization be folded before QAT?Batch normalization changes the effective weight distribution at inference time. Folding it before QAT ensures that fake quantization matches the real deployment-time weights, avoiding a silent mismatch between training and export.
Why is a progressive quantization schedule useful?A progressive schedule introduces quantization noise gradually, such as moving from INT8 to INT6 and then to INT4. This gentler transition reduces loss spikes and gives the model time to adapt before reaching the target low-precision format.
Why is per-channel quantization recommended for weights in QAT?Per-channel quantization gives each output channel its own scale, which reduces clipping and preserves more gradients during training. This is especially helpful for pretrained models and low-bit settings where channel magnitudes vary widely.
How should QAT be applied to transformers efficiently?For transformers, use a diagnostic first to see which sublayers are most sensitive. Keep LayerNorm, softmax, and GELU in FP32, use per-channel quantization for linear layers, and consider selective QAT or mixed precision—especially protecting FFN layers when they are the most sensitive.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Quantization and Fast Inference Quantization and Fast Inference ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Quantization and Fast Inference Quantization and Fast Inference ebook for free