Overview

6 Porting Workflows Across Frameworks

This chapter shows that quantization is not a single portable recipe but a framework-dependent workflow whose results can shift as models move from PyTorch to ONNX to TensorFlow Lite. The central warning is that default choices for granularity, observers, fusion, and calibration differ enough to cause meaningful parity gaps, even when each individual tool appears correct. Because production teams often train, validate, and serve in different ecosystems, the practical goal is not to eliminate all differences, but to make them explicit, reproduce each path deliberately, and verify that the exported artifacts still agree before deployment.

It first demonstrates the PyTorch and TorchAO path as a baseline. TorchAO’s one-line weight-only quantization works well when a model is dominated by linear layers, especially transformers like BERT and large language models such as TinyLlama, where it delivers substantial compression with negligible accuracy loss and portable state-dict serialization. By contrast, convolution-heavy models like ResNet-18 gain almost nothing from this API because its stable configs are built around linear layers; the chapter emphasizes that size reduction is useful, but eager-mode PyTorch quantization does not itself deliver faster inference because computation still runs in floating point.

The chapter then compares TensorFlow Lite and ONNX Runtime as deployment-oriented paths. TFLite offers a simpler all-in-one converter that can produce dynamic range, full integer, or FP16 artifacts, with dynamic range working well for transformers, full integer suiting CNNs on mobile or edge devices, and FP16 serving as a low-risk compression option. ONNX provides a framework-neutral graph format that allows PyTorch models to be exported and then quantized with ORT, where static quantization is best for CNNs and dynamic quantization is best for transformers; the chapter closes by showing how to validate equivalence through logit-level comparison and operator coverage analysis, so teams can distinguish harmless rounding noise from true export errors or unsupported quantization coverage.

Three quantization paths from a trained PyTorch model to deployment-ready artifacts. Arrows represent conversion steps: downward arrows feed the FP32 model into each framework's quantization pipeline, horizontal arrows carry the model through quantization and optimization stages, and converging arrows at the bottom feed all three artifacts into a shared validation step. Each path makes independent decisions about quantization semantics, operator fusion, and calibration.
Three quantization paths from a trained PyTorch model to deployment-ready artifacts. Arrows represent conversion steps: downward arrows feed the FP32 model into each framework's quantization pipeline, horizontal arrows carry the model through quantization and optimization stages, and converging arrows at the bottom feed all three artifacts into a shared validation step. Each path makes independent decisions about quantization semantics, operator fusion, and calibration.
TorchAO INT8 weight-only compression across three architectures. Compression scales with the fraction of parameters in nn.Linear: 1.03× for the Conv2d-dominated ResNet-18, 2.40× for BERT-base, and 3.38× for TinyLlama-1.1B.
TorchAO INT8 weight-only compression across three architectures. Compression scales with the fraction of parameters in nn.Linear: 1.03× for the Conv2d-dominated ResNet-18, 2.40× for BERT-base, and 3.38× for TinyLlama-1.1B.
ORT quantization results for ResNet-18 on ImageNette. Dynamic quantization (MatMul only) gives 1.03× - identical to TorchAO's Linear-only result. Static quantization (all operators, with calibration) gives 3.95× with 0.10 pp accuracy loss. The size gap between these two results is the cost of Conv layers staying in FP32.
ORT quantization results for ResNet-18 on ImageNette. Dynamic quantization (MatMul only) gives 1.03× - identical to TorchAO's Linear-only result. Static quantization (all operators, with calibration) gives 3.95× with 0.10 pp accuracy loss. The size gap between these two results is the cost of Conv layers staying in FP32.
Cross-framework compression comparison. Left: ResNet-18. TorchAO and ORT dynamic both achieve 1.03× (Linear/MatMul only); ORT static gives 3.95× by quantizing all Conv layers. Right: BERT-base. TorchAO gives 2.40× (nn.Linear only), while TFLite dynamic (3.94×), ORT dynamic (3.97×), and ORT static (3.97×) all converge near 4× because they quantize all weight tensors including embeddings. The compression difference between TorchAO and the other frameworks is format scope, not quantization quality.
Cross-framework compression comparison. Left: ResNet-18. TorchAO and ORT dynamic both achieve 1.03× (Linear/MatMul only); ORT static gives 3.95× by quantizing all Conv layers. Right: BERT-base. TorchAO gives 2.40× (nn.Linear only), while TFLite dynamic (3.94×), ORT dynamic (3.97×), and ORT static (3.97×) all converge near 4× because they quantize all weight tensors including embeddings. The compression difference between TorchAO and the other frameworks is format scope, not quantization quality.
Top: per-layer quantization sensitivity for ResNet-18. Bars extending right indicate layers that benefit from staying in FP32. The four most sensitive layers (conv 1, 2, 5, 15) are each the first convolution in a residual stage. Bottom: precision allocation map for four strategic configurations. Each row is one configuration; each column is a layer. Hatched cells are layers kept in FP32; solid cells are quantized to INT8. Accuracy and model size are annotated on the right.
Top: per-layer quantization sensitivity for ResNet-18. Bars extending right indicate layers that benefit from staying in FP32. The four most sensitive layers (conv 1, 2, 5, 15) are each the first convolution in a residual stage. Bottom: precision allocation map for four strategic configurations. Each row is one configuration; each column is a layer. Hatched cells are layers kept in FP32; solid cells are quantized to INT8. Accuracy and model size are annotated on the right.
Cross-framework numerical equivalence for ResNet-18 (top) and BERT-base (bottom). Bars show max |Δ logit| vs the PyTorch FP32 baseline on a log scale. ONNX FP32 export introduces negligible divergence (~10-5). Quantization shifts logits by 10-1 to 100, but prediction agreement remains above 99% for all variants. The largest divergence is ORT Dynamic INT8 on BERT — cosine similarity 0.9736 — where the narrow 2-class output space amplifies quantization error.
Cross-framework numerical equivalence for ResNet-18 (top) and BERT-base (bottom). Bars show max |Δ logit| vs the PyTorch FP32 baseline on a log scale. ONNX FP32 export introduces negligible divergence (~10-5). Quantization shifts logits by 10-1 to 100, but prediction agreement remains above 99% for all variants. The largest divergence is ORT Dynamic INT8 on BERT — cosine similarity 0.9736 — where the narrow 2-class output space amplifies quantization error.
Logit-level agreement: FP32 baseline vs quantized variant. Left: ResNet-18 vs ORT Static INT8 (1000 logits × 100 samples). Points cluster tightly along the y = x identity line across the full [-10, +30] range despite 100% operator coverage. Right: BERT-base vs ORT Dynamic INT8 (2 logits × 100 samples). Visible scatter away from the diagonal, especially for negative logits around -4, with several points drifting by more than 1 unit. The narrow output range makes the same absolute error proportionally larger.
Logit-level agreement: FP32 baseline vs quantized variant. Left: ResNet-18 vs ORT Static INT8 (1000 logits × 100 samples). Points cluster tightly along the y = x identity line across the full [-10, +30] range despite 100% operator coverage. Right: BERT-base vs ORT Dynamic INT8 (2 logits × 100 samples). Visible scatter away from the diagonal, especially for negative logits around -4, with several points drifting by more than 1 unit. The narrow output range makes the same absolute error proportionally larger.
Operator quantization coverage by ONNX variant. Left: ResNet-18 ORT Dynamic — 4% coverage, only 1 MatMulInteger node (the classification head's Gemm) out of 51 compute ops. All 20 Conv and 17 Relu stay in FP32. Center: ResNet-18 ORT Static — 100% coverage, all 20 Conv, 8 Add, and the Gemm wrapped in QDQ pairs. Right: BERT-base ORT Dynamic — 28% coverage, 74 MatMulInteger nodes (the linear projections) quantized, but LayerNormalization, Softmax, Div, and Sqrt remain in FP32.
Operator quantization coverage by ONNX variant. Left: ResNet-18 ORT Dynamic — 4% coverage, only 1 MatMulInteger node (the classification head's Gemm) out of 51 compute ops. All 20 Conv and 17 Relu stay in FP32. Center: ResNet-18 ORT Static — 100% coverage, all 20 Conv, 8 Add, and the Gemm wrapped in QDQ pairs. Right: BERT-base ORT Dynamic — 28% coverage, 74 MatMulInteger nodes (the linear projections) quantized, but LayerNormalization, Softmax, Div, and Sqrt remain in FP32.

Summary

  • Quantization workflows diverge across frameworks in default semantics, operator fusion rules, and calibration implementations. Parity requires tensor-level validation, not just accuracy checks.
  • TorchAO's quantize_() targets nn.Linear only—compressing BERT-base by 2.40× and TinyLlama by 3.38×, but leaving Conv2d-dominated ResNet-18 at 1.03×.
  • TFLite's converter handles quantization, optimization, and serialization in one pass. Dynamic range achieves 3.68× on MobileNetV2 with no calibration data.
  • ONNX export is essentially lossless (max logit divergence ~10-⁵). Larger divergence in quantized variants comes from quantization arithmetic, not the export.
  • ORT dynamic quantization targets MatMul/Gemm, effective for transformers (3.97× on BERT) but not CNNs (1.03× on ResNet-18). ORT static with QDQ format quantizes all operators (3.95× on ResNet-18).
  • Accuracy preservation does not guarantee numerical equivalence. BERT under ORT Dynamic showed one prediction flip in 100 samples despite maintaining 96% overall accuracy.
  • Operator coverage determines speedup—low op-count coverage can still be effective if those operators dominate compute.
  • When validation fails, compare ONNX FP32 against the PyTorch baseline first to isolate export error from quantization error.

FAQ

```html
What are the main reasons quantization workflows diverge across frameworks?Frameworks diverge because they make different default choices about quantization semantics, operator fusion and graph rewriting, and calibration range estimation. Even when two tools both say “INT8 quantization,” they may use different granularity, observers, rounding behavior, or activation handling, which can lead to measurable accuracy differences.
Why can a model quantized in PyTorch lose accuracy after being exported to ONNX?Accuracy can drop after export because the ONNX path may use different quantization defaults, fusion rules, or calibration behavior than PyTorch. The export itself is often lossless, but the quantization decisions made during the ONNX pipeline can change outputs enough to flip some predictions.
When should I use TorchAO's quantize_() API?Use TorchAO’s quantize_() when your model is dominated by nn.Linear layers, especially in transformers. It gives fast, simple, weight-only INT8 compression with negligible accuracy loss, but it is not a good fit for CNNs where Conv2d layers hold most of the parameters.
Why does TorchAO give little compression on ResNet-18?ResNet-18 is mostly Conv2d layers, while TorchAO’s stable weight-only configs primarily target nn.Linear. Since only the final classification head is linear, very little of the model is quantized, so compression stays close to 1×.
Does quantization in eager-mode PyTorch automatically make inference faster?No. In eager-mode PyTorch, quantization reduces stored model size but does not speed up inference by itself. The model often dequantizes INT8 weights back to FP32 at matmul time and still runs standard FP32 kernels, so latency can even increase slightly.
What is the difference between TFLite dynamic range and full integer quantization?Dynamic range quantization converts weights to INT8 and computes activation scales at inference time, so it needs no calibration data and is usually safer for transformers. Full integer quantization calibrates activations ahead of time and bakes static INT8 ranges into the model, which works well for CNNs but can fail badly on transformer activations.
Why is full integer quantization not recommended for BERT in TFLite?BERT’s activations vary too much across inputs for a single static calibration range to represent them well. As a result, full integer quantization can collapse accuracy, while dynamic range quantization adapts to each input and preserves accuracy much better.
How do I export a PyTorch model to ONNX correctly?Use torch.onnx.export with the right opset version, names, and dynamic axes. For many models in this chapter, the legacy dynamo=False path was the safer choice because the newer dynamo exporter could fail or produce incorrect results in some cases.
What does ONNX Runtime static quantization do differently from dynamic quantization?Dynamic quantization mainly targets MatMul and Gemm and applies activation scaling on the fly. Static quantization instead calibrates representative data, inserts QuantizeLinear/DequantizeLinear nodes throughout the graph, and can quantize a much larger portion of the model, including Conv layers.
How should I verify that a quantized model ported across frameworks is really equivalent?Run the same inputs through each artifact and compare raw logits, not just accuracy. Check metrics like max absolute difference, mean absolute difference, cosine similarity, and top-1 agreement to tell whether differences are harmless rounding noise, export problems, or real prediction flips.
```

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