Sub topic 5
Exporting and Converting a Model
This chapter assumes you know basic Python, tensors, and either PyTorch or TensorFlow. You should also understand image preprocessing and the difference between training and inference.
A trained model is usually stored in a framework-specific format. That format may contain Python objects, training metadata, and operators that are convenient during development but unsuitable for a phone. Exporting records the model as a portable computation graph. Converting changes that graph into the format expected by a target runtime, sometimes applying optimizations such as quantization.
The deployment path
A typical path looks like this:
Export captures operations such as convolutions, matrix multiplication, and activation functions. The export also records input names, output names, tensor shapes, and data types. Conversion then checks whether the target runtime supports those operations.
A deployment format does not automatically make a model fast. The runtime, hardware delegate, input shape, and data type all affect performance.
| Format | Common runtime | Typical use |
|---|---|---|
| ONNX | ONNX Runtime | Cross-platform deployment |
| `.tflite` | TensorFlow Lite | Android and embedded devices |
| Core ML model | Core ML | Apple devices |
| ExecuTorch program | ExecuTorch | PyTorch-based edge deployment |
Exporting a PyTorch model to ONNX
The example below exports a MobileNet classifier with a fixed batch size of one and an image size of 224 by 224 pixels.
import torch
from torchvision.models import (
mobilenet_v3_small,
MobileNet_V3_Small_Weights,
)
weights = MobileNet_V3_Small_Weights.DEFAULT
model = mobilenet_v3_small(weights=weights).eval()
example_input = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model,
example_input,
"mobilenet_v3_small.onnx",
input_names=["input"],
output_names=["logits"],
opset_version=17,
)eval() disables training-only behavior such as dropout. The example input tells the exporter the tensor layout and shape. Here, the layout is NCHW: batch, channels, height, and width.
The ONNX operator set, or opset, identifies the version of operations used in the graph. A newer opset may support more operations, but the target runtime must support it too. A fixed shape often enables better optimization, while a dynamic shape supports more input sizes at the cost of possible performance.
Common export errors
Check the exported model before putting it in an app.
- An unsupported operation can stop export or force part of the graph onto the CPU.
- A Python-side condition may not become a portable graph operation.
- A tensor may have the wrong layout or data type.
- Dynamic dimensions may be accepted by the exporter but rejected by a mobile delegate.
- The exported output may differ from the framework output because of preprocessing, unsupported operators, or numerical precision.
Run the original and exported models on the same input and compare their outputs. For classification, compare the top class and the numerical difference between logits. Test several normal inputs, not only an all-zero tensor.
> callout note > Keep the exported model, preprocessing code, class labels, and conversion settings together as one versioned artifact. A model without its input contract is not reproducible.
Conversion is a contract check
For TensorFlow Lite, conversion can also apply integer quantization. A representative dataset is used to estimate activation ranges. It should contain realistic, preprocessed images from the deployment domain. Random data may produce a model that converts successfully but performs poorly.
After conversion, inspect the model's input shape and data type. The app must provide exactly what the runtime expects, including scaling and zero-point rules for quantized tensors.
Exercise
Why should you compare an exported model with the original model before deploying it?
Show answer
Export can alter operations, shapes, or numerical precision. Comparing both models on the same inputs detects these differences before they reach the app.