Sub topic 5
Exporting and Converting a Model
This chapter assumes you can train or load a PyTorch or Keras image model and that you know what float32 and int8 tensors are. You should also have read the quantization chapter, because conversion is where quantization gets applied to a real file.
What export and conversion do
A trained model lives inside a framework. A PyTorch nn.Module is Python code plus weights, and a Keras model is a graph of layers plus weights. A phone has neither framework. It has a small runtime that reads a fixed file format and runs a list of operators.
Export means turning the framework model into a portable graph. Conversion means translating that graph into the format a specific runtime reads. Sometimes one tool does both. The result is a file such as .onnx or .tflite.
| Format | Produced from | Read by | Typical use |
|---|---|---|---|
| ONNX (`.onnx`) | PyTorch, TensorFlow, others | ONNX Runtime, and converters to other formats | Portable interchange, Android and iOS via ONNX Runtime |
| TensorFlow Lite (`.tflite`) | Keras, SavedModel | TensorFlow Lite interpreter | Android, embedded Linux, microcontrollers |
| Core ML (`.mlpackage`) | PyTorch, ONNX, TensorFlow via coremltools | Core ML on Apple devices | iOS and macOS with Neural Engine access |
| ExecuTorch (`.pte`) | PyTorch `torch.export` | ExecuTorch runtime | PyTorch-native on-device |
The next chapter compares the runtimes. Here the focus is producing a correct file.
The conversion pipeline
The last comparison step is not optional. Conversion can succeed and still produce a model that behaves differently.
Exporting from PyTorch to ONNX
PyTorch exports by tracing. It runs the model once on a dummy input and records the operators that execute. This has two consequences. The model must be in eval mode, and the dummy input defines the shapes the graph is recorded with.
import torch
import torchvision
model = torchvision.models.mobilenet_v3_small(weights="DEFAULT").eval()
dummy = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model,
dummy,
"mobilenet_v3_small.onnx",
input_names=["input"],
output_names=["logits"],
opset_version=17,
)Three details matter here.
.eval()switches off dropout and makes batch normalization use its stored running statistics. Exporting in training mode bakes in the wrong behavior.input_namesandoutput_namesgive the tensors stable names. Your app code refers to these names, so choose them deliberately.opset_versionselects the operator set. A higher opset supports more operators, but the runtime on the device must support that opset too. If a runtime rejects the file, lowering the opset is one of the first things to try.
The dummy input also sets the layout. PyTorch uses NCHW (batch, channels, height, width). Many mobile pipelines produce NHWC images, so you will need to transpose at some point.
Dynamic versus fixed shapes
By default, tracing records the exact shape you gave it. A fixed shape is usually the right choice for mobile. Runtimes can plan memory once, and hardware accelerators often refuse dynamic shapes. If you need variable batch size, pass dynamic_axes to torch.onnx.export, but test the result on your target accelerator before relying on it.
Control flow
Tracing records only the path the dummy input took. A Python if that depends on tensor values will be frozen into whichever branch ran. Detection models with data-dependent post-processing, such as non-maximum suppression, are the usual victims. Either export the backbone and run post-processing in app code, or use an exporter that supports the control flow you need.
Converting from Keras to TensorFlow Lite
TensorFlow Lite conversion starts from a Keras model or a SavedModel and goes straight to a .tflite file. Quantization is configured in the same step.
import numpy as np
import tensorflow as tf
model = tf.keras.applications.MobileNetV2(
weights="imagenet", input_shape=(224, 224, 3)
)
def representative_dataset():
# Replace the random data with about 100 real, preprocessed images.
for _ in range(100):
yield [np.random.rand(1, 224, 224, 3).astype(np.float32)]
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
tflite_model = converter.convert()
with open("mobilenet_v2_int8.tflite", "wb") as f:
f.write(tflite_model)Each setting does a specific job.
Optimize.DEFAULTturns on post-training quantization.representative_datasetis a generator that feeds sample inputs through the model so the converter can measure the range of each activation tensor. These ranges determine the int8 scale and zero point for each tensor.TFLITE_BUILTINS_INT8demands that every operator run in integer arithmetic. If an operator has no int8 kernel, conversion fails instead of silently leaving it in float. That failure is useful, because you learn about the problem at build time.inference_input_typeandinference_output_typeset the model's boundary types to uint8. Without them, the model keeps float32 inputs and outputs, with quantize and dequantize operators at the edges.
The placeholder data in the example is random noise. Calibrating on noise produces ranges that do not match real images, which can badly hurt accuracy. Use around 100 real images that went through the same preprocessing your app will use.
Inspecting the converted file
Always load the converted model and read what it actually expects, instead of trusting what you intended. The TensorFlow Lite interpreter reports shape, dtype, and quantization parameters.
import numpy as np
import tensorflow as tf
interpreter = tf.lite.Interpreter(model_path="mobilenet_v2_int8.tflite")
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]
image = np.zeros(inp["shape"], dtype=inp["dtype"]) # stand-in for a real image
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
scores = interpreter.get_tensor(out["index"])
print("top class:", int(scores.argmax()))inp["shape"] and inp["dtype"] tell you the layout and type your app must produce. Keras models use NHWC, so the shape here is [1, 224, 224, 3], which differs from the PyTorch export above. inp["quantization"] holds the (scale, zero_point) pair. The mapping from a real value to an integer is q = round(x / scale) + zero_point.
For ONNX files, load the model with ONNX Runtime and print session.get_inputs() to see the names, shapes, and types. The same habit applies: read the file, do not assume.
Verifying the converted model
A converted model needs a numerical check against the original. The procedure is simple.
- Pick a set of real images, say 50 to 200.
- Run each through the original framework model and through the converted model, using identical preprocessing.
- Compare outputs.
For a float conversion, outputs should agree to a small tolerance. A common starting point is a maximum absolute difference near 1e-4 to 1e-5 on logits. A large gap points to a conversion bug, such as wrong layout, wrong preprocessing, or a model exported in training mode.
For a quantized conversion, outputs will differ by design. Compare top-1 agreement and task accuracy on a labeled set instead. The accuracy validation chapter covers this in depth.
Common failures and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Predictions are random after export | Model left in training mode, or preprocessing differs | Call `.eval()`, match normalization and channel order |
| Export raises an unsupported operator error | Operator missing from the chosen opset or converter | Raise or lower `opset_version`, or rewrite the layer with supported operators |
| Output is correct for one input size only | Shape was frozen during tracing | Export at the deployment size, or declare dynamic axes and test |
| Integer-only conversion fails | An operator has no int8 kernel | Allow float fallback, or replace the operator |
| Quantized accuracy drops sharply | Calibration data unrepresentative | Calibrate with real, correctly preprocessed images |
| Colors look swapped in results | RGB versus BGR, or NCHW versus NHWC mismatch | Check channel order and layout on both sides |
| Large file size | Float32 weights kept | Apply quantization or float16 weights |
Two points are worth stating explicitly. First, an operator that converts successfully can still run on the CPU instead of an accelerator, which the troubleshooting chapter addresses. Second, keep the conversion script in version control with pinned framework versions. Converter behavior changes between releases, and a model that converted last quarter may produce a different file today.
Practical checklist
- Put the model in eval mode before export.
- Fix the input shape to the deployment size.
- Name inputs and outputs explicitly.
- Record the layout, dtype, and quantization parameters of the final file.
- Calibrate with real preprocessed images, not random data.
- Compare converted outputs against the original on real images before shipping.
Exercise
You export a PyTorch classifier to ONNX with torch.onnx.export, but forget to call model.eval() first. The export succeeds without errors. Why is this a problem, and how would you catch it?
Show answer
In training mode, dropout is active and batch normalization uses batch statistics instead of stored running statistics. Tracing records that behavior into the graph, so the exported model gives different and often worse results than the model you trained. You would catch it by running the same real images through the original model (in eval mode) and the ONNX model with ONNX Runtime, then comparing logits. A large difference signals the bug. The fix is to call .eval() before exporting.
Exercise
A fully integer-quantized TensorFlow Lite model reports an input dtype of uint8 and shape [1, 224, 224, 3]. Your app has a float32 image normalized to the range 0 to 1. What must you read from the model, and what must you compute before calling set_tensor?
Show answer
Read the input's quantization parameters, the scale and zero point, from get_input_details()[0]["quantization"]. Then compute q = round(x / scale) + zero_point for each value and clip to 0 to 255 before casting to uint8. The data must also be in NHWC layout and the same preprocessing used during calibration.