Sub topic 14
Packaging, delivering, and updating models
This chapter covers how a converted and validated model reaches users' devices and how you replace it later. It assumes you can export and quantize a model, and that you know which runtime your app uses (TensorFlow Lite, ONNX Runtime, Core ML, or ExecuTorch). It also assumes you have benchmarked and checked accuracy as covered in earlier chapters. You don't need to have shipped a mobile app.
A model is a versioned dependency
A model file is not just an asset like an icon. It depends on three other things:
- Preprocessing code. Resize method, normalization constants, and channel order must match what the model was trained with.
- Postprocessing code. Class label lists, anchor boxes, and score thresholds belong to a specific model.
- Runtime and delegate versions. A model converted with one opset or converter version may not load in an older runtime.
If you update the model file alone, these can drift apart. A new model with a different input size, a different label order, or a new operator will fail or, worse, return plausible but wrong results. Treat the model, its preprocessing settings, and its label file as one unit with one version number.
Bundle or download?
You have two basic delivery options, and many apps use both.
| Approach | Strengths | Weaknesses |
|---|---|---|
| Bundled in the app package | Works offline on first launch. No download failures. Updated through the normal store review. | Increases install size. Every model change needs an app release. |
| Downloaded after install | Small install. You can update models without an app release. You can serve different models per device class. | Needs network and storage handling. Needs integrity checks. First use may be delayed. |
| Bundled fallback plus downloaded updates | Always works. Improves over time. | Two code paths to test. |
A common rule: bundle a small, safe baseline model, and download larger or newer models later. The bundled model also acts as your fallback when a download is corrupt, incompatible, or missing.
Platform delivery mechanisms
- Android app bundles. Large models can go into an asset pack, which Google Play Asset Delivery can install with the app, shortly after install, or on demand. Check the current Play size limits before you plan around them.
- iOS. On-Demand Resources can host model files outside the main app binary. You can also download a model yourself and load it from the app's storage.
- Firebase ML. Firebase can host custom models and let the app download them, with the app choosing when to update.
- Your own server or CDN. This gives the most control. You manage hosting, signing, and rollout yourself.
Two packaging details cause real bugs:
- On Android, files in the assets folder are compressed by default. TensorFlow Lite can memory-map a model file, but only if the file is stored uncompressed. Mark the
.tfliteextension as not compressed in your Gradle build, or the app loads a copy into memory instead. - Core ML models are compiled for the device. If you download an
.mlmodelfile, the app has to compile it on the device before use, which takes time and should happen in the background. A model compiled at build time ships as.mlmodelc, and a download of that compiled form skips this step.
The manifest: describing a model release
Do not make the app guess what a downloaded file is. Publish a small manifest next to every model. The app reads the manifest first, decides whether the model is compatible, and only then downloads the file.
A useful manifest contains:
version: a monotonically increasing number or semantic version.sha256: the hash of the model file, used to verify the download.size_bytes: lets you check storage space and detect truncated downloads.input: shape, data type, and normalization settings.labels_versionor an embedded label file hash.min_app_versionandruntime: compatibility requirements.url: where to fetch the file.
The script below builds a manifest for a model file. It runs as shown with Python 3.9 or later, given a model file named mobilenet_v2_int8.tflite in the working directory (for example, the one produced in the export chapter).
import hashlib
import json
from pathlib import Path
def sha256_of(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def build_manifest(model_path: str, version: int) -> dict:
path = Path(model_path)
return {
"version": version,
"file": path.name,
"sha256": sha256_of(path),
"size_bytes": path.stat().st_size,
"runtime": "tflite",
"min_app_version": "2.4.0",
"input": {
"shape": [1, 224, 224, 3],
"dtype": "uint8",
"resize": "bilinear",
},
}
if __name__ == "__main__":
manifest = build_manifest("mobilenet_v2_int8.tflite", version=7)
Path("manifest.json").write_text(json.dumps(manifest, indent=2))
print(json.dumps(manifest, indent=2))Installing a download safely
A download can be interrupted, truncated, or tampered with. The safe procedure is:
- Download to a temporary file, never directly to the live model path.
- Check
size_bytesandsha256against the manifest. - Load the file with the runtime and run one test inference. This catches a file that is intact but incompatible.
- Move the file into place with an atomic rename.
- Keep the previous model until the new one has run successfully in the app.
The logic below shows steps 2, 4, and 5 in Python. On a phone you would write the same sequence in Kotlin or Swift, but the structure is identical.
import hashlib
import os
import shutil
from pathlib import Path
def verify(path: Path, expected_sha256: str, expected_size: int) -> bool:
if path.stat().st_size != expected_size:
return False
digest = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest() == expected_sha256
def install(tmp_file: Path, live_file: Path, manifest: dict) -> bool:
if not verify(tmp_file, manifest["sha256"], manifest["size_bytes"]):
tmp_file.unlink(missing_ok=True)
return False
if live_file.exists():
shutil.copy2(live_file, live_file.with_suffix(".previous"))
os.replace(tmp_file, live_file) # atomic when both paths are on the same filesystem
return TrueThe temporary file must be in the same directory (or at least the same filesystem) as the live file. Otherwise the rename is not atomic and a crash can leave a half-written model.
A hash proves the file matches the manifest. It does not prove the manifest is genuine. If an attacker can change the manifest, they can change the hash too. Serve manifests over HTTPS, and for sensitive apps sign the manifest and verify the signature with a public key stored in the app.
The update flow
The diagram shows the decision path at app start or during a background check.
Rollout, monitoring, and rollback
A model that passed your offline validation can still behave badly on real devices. Real cameras, lighting, and chipsets differ from your test set. Release gradually.
- Staged rollout. Release to 1%, then 10%, then everyone. Hold at each stage long enough to see the metrics.
- Remote control. Keep a server-side switch that sets the active version per cohort. Then rollback means changing a number, not shipping an app.
- Device targeting. Different phones may need different files, such as a float16 model for GPUs and an int8 model for NPUs. Select by device capability, not only by OS version.
- Telemetry. Record model version, runtime, delegate in use, and latency percentiles. Without the version in the data you cannot tell which release caused a regression. Collect only what you need, and respect privacy limits. Images should not leave the device unless users have agreed to it.
- Ground truth is scarce on device. Proxy signals help: confidence score distributions, fraction of "no detection" results, user corrections, and crash rate. A sudden shift in the score distribution after a release is a strong warning.
Edge cases and gotchas
- Cached delegate artifacts. Some GPU and NPU delegates cache compiled kernels. After a model swap, the first run is slow while the cache rebuilds. Do a warm-up inference in the background before showing the model's results to the user, and do not record that first run as normal latency.
- ONNX external data. Large ONNX models can store weights in a separate data file. Ship and verify both files as one release, or the load fails.
- Label mismatch. If class order changes in a retrain, an old label file produces confidently wrong names. Version labels with the model.
- Storage pressure. Check free space before downloading. Delete old versions after the new one is confirmed, but keep the last known-good one.
- Network conditions. Large downloads should respect Wi-Fi-only and battery settings, resume after interruption, and run in the background through the OS scheduler rather than in the foreground.
- Store policy. App stores restrict downloading executable code. Downloading model weights as data is generally accepted, but check the current guidelines of each store, especially if the model changes app behavior in a significant way.
- Downgrade. An app rollback may meet a model newer than it understands. The
min_app_versionandmax_app_versionfields in the manifest prevent this.
Exercise
Your app downloads a new model version. The file hash matches the manifest, but after the swap the app shows wrong class names. List two likely causes related to packaging and one safeguard for each.
Show answer
Likely cause 1: the label file was not updated together with the model, or the class order changed in retraining. Safeguard: version the labels with the model and include the label file hash in the manifest. Likely cause 2: preprocessing no longer matches, for example different normalization or input size. Safeguard: store the input shape, dtype, and normalization in the manifest and have the app read them or refuse the model if it cannot honor them. A test inference against a known reference image before the swap would also catch both problems.
Exercise
Why should a downloaded model be written to a temporary file in the same directory as the live model before it is renamed into place?
Show answer
A rename within one filesystem is atomic, so the app sees either the old complete file or the new complete file, never a partial one. If the temporary file is on a different filesystem, the move becomes a copy, and a crash or power loss during the copy can leave a corrupt live model.