Which route should you use to deploy a PyTorch model on iPhone?
Start with a direct PyTorch-to-Core ML conversion for an iOS-first product. Keep an ONNX Runtime path when a shared model artifact across platforms has real value. Use MLX for Apple Silicon experiments or for a compatible Swift implementation that you can benchmark on the intended device. Verify numerical parity before optimizing and measure the exported model inside the app.
1. Define the model contract before you export
Write down the deployment target, input and output shapes, dtypes, preprocessing and postprocessing. For an image classifier, include the camera orientation, expected resize or crop, RGB channel order, numerical range and label order. If you trained with normalization, decide whether it lives in the exported graph or in app code. One normalization should run on each input. A successful conversion can still produce poor results when the app feeds the wrong pixels.
Set the PyTorch model to evaluation mode and run a fixed reference set through it. Save the original tensors, output scores and final decisions. Include edge cases such as an unusual crop or a low-confidence prediction near a threshold. Record the framework version, checkpoint and commit alongside the fixture. Later, compare logits or model outputs numerically as well as comparing the resulting product decisions.
Write a device budget in units you can measure. Include model download or bundle size, cold load time, steady inference and peak memory. Set the minimum supported operating system and oldest supported device. For a camera workflow, include frame format conversion and postprocessing in the end-to-end budget. You can meet a model-only latency target while missing a frame deadline in the app.
2. Convert directly with coremltools for an iOS-first model
Apple recommends direct conversion for PyTorch models. Use a supported export path for your model, such as a traced TorchScript model or a compatible torch.export program, and check the documentation for the versions you pin. A trace records the operations exercised by sample inputs. When the model branches based on its input, test representative branches and use an export approach that preserves the behaviour you need. Apple’s PyTorch conversion guide.
For an illustrative fixed-size image input, the Python steps inside your build script are model.eval(), example = torch.zeros(1, 3, 224, 224) and traced = torch.jit.trace(model, example), followed by ct.convert(traced, inputs=[ct.TensorType(name="image", shape=example.shape)], convert_to="mlprogram", minimum_deployment_target=ct.target.iOS16). Save the result as an .mlpackage. This example assumes torch and coremltools, imported as ct, plus your own initialized model. Choose your real deployment target and input contract before copying the dimensions.
Run the fixtures through a macOS conversion check where supported and again on the phone. Integrate the model into Xcode and feed the same preprocessed input to the Core ML model. If shapes or output labels differ, check the resolved model interface in Xcode. If the runtime result is numerically different, compare against a full-precision reference before blaming quantization or device dispatch. Change one variable at a time.
3. Keep ONNX when a portable artifact earns its maintenance
If Android, Windows or a service must run the same graph, try exporting from PyTorch to ONNX and running it with ONNX Runtime on the relevant targets. Choose an opset and dynamic shape configuration supported by your deployment runtime. Compare PyTorch and ONNX outputs in development before adding a mobile execution provider. PyTorch ONNX export documentation.
On Apple platforms, ONNX Runtime has a Core ML execution provider for supported operators. The runtime can divide the graph between execution providers. A successful run does not tell you how much of the model took the acceleration path. Inspect profiling and benchmark the complete app. The Core ML-specific path can make shared deployment practical, but an extra binary, partial graph support and copying between operators can change size and performance. ONNX Runtime’s Core ML execution provider guide.
If your training team uses TensorFlow, preserve the training framework if it supports your work and convert a compatible model to Core ML for Apple deployment as appropriate. TensorFlow and Core ML can occupy different stages of the same pipeline. An existing cross-platform mobile runtime can also remain a candidate. Compare artifact support and end-device results instead of judging performance from the training library’s name.
4. Compare FP16 and INT8 under the same accuracy test
Begin with a working baseline and a frozen test set. FP16 uses a lower-precision floating-point representation and can reduce storage or computation compared with a full-precision variant where supported. INT8 weight compression can reduce model size further. Actual runtime precision and acceleration depend on the model format, operations, hardware and optimization applied. Weight compression alone is a storage change and does not establish that every activation or operation runs in INT8.
Create variants with one documented change at a time. Keep the same preprocessed examples, output interpretation and target device. For a classifier, check overall accuracy, per-class results and changes near the manual-review threshold. For a detector, inspect missed and duplicate detections as well as the aggregate metric. If you quantize activations with a workflow that uses calibration data, use inputs that represent the supported range and reserve a separate set for evaluation.
Measure compressed package size, actual app download impact, warm inference and peak memory. A small artifact can load faster without improving steady execution. A format change can also shift results for rare classes even when overall accuracy looks similar. Read the exact methods and target requirements in Apple’s quantization overview and retain a fallback variant for the comparison.
5. Profile Neural Engine, GPU and CPU on real devices
Core ML can use available compute units across the CPU, GPU and Neural Engine. Compute-unit settings define allowed hardware. They do not promise that a particular operation runs on the Neural Engine. Compare appropriate options such as all units, CPU only and CPU plus GPU using MLModelConfiguration.computeUnits. Profile with Xcode or Instruments where supported and record device and operating-system versions. Apple’s MLComputeUnits reference.
Measure cold and warm requests separately. Run repeated workloads long enough to see slow-tail latency and thermals. For a live view, measure capture-to-result time, frame drops and main-thread interruptions. A small image model might meet a business need at one prediction per second even if the camera captures dozens of frames each second. Test with the same intended cadence on the oldest device you support.
Local inference can avoid per-call cloud inference charges and let the model process data when the network is unavailable. It also moves compute, storage and energy use onto the device. Check startup, asset delivery, crash reporting and any optional network features before claiming that sensitive inputs remain local. An airplane-mode test is a practical way to verify the core task once assets are present.
Worked example: choose a runtime for a small visual classifier
Imagine a warehouse iPhone app that identifies one of several visible package labels for a human to confirm. Export a fixed-size Core ML baseline and use a frozen set of warehouse photos. Simulate imperfect lighting, rotated labels and cropped edges. If two classes become harder to distinguish after quantization, compare models at the confidence threshold for sending a result to a human. Record accuracy and latency together for the same old and new devices.
Prototype a separate architecture on an Apple Silicon Mac with MLX if you want quick tensor experiments or an existing MLX implementation. For an iOS MLX route, use MLX Swift where the required model, device and build are supported. Benchmark its Metal GPU route and memory needs on your phone. For a fixed model with straightforward Core ML conversion, a native Core ML artifact keeps the deployment work focused on Xcode integration and device profiling.
Keep the runtime decision tied to the app’s constraints. A team supporting Android may accept extra ONNX Runtime integration work for a common model artifact. An Apple-only team may choose Core ML after confirming compatibility with its lowest supported device. Read the INGOAMPT ONNX and Core ML comparison for the ecosystem distinction and use current framework docs to confirm implementation details.
Core ML, ONNX Runtime and MLX compared
| Route | Best fit | Test first |
|---|---|---|
| Direct PyTorch to Core ML | A native iOS app with a supported graph | Output parity, OS target, hardware scheduling |
| ONNX Runtime | Shared artifacts across device and server platforms | Opset, runtime size, supported partitions and copies |
| MLX on Mac or MLX Swift | Apple Silicon experiments or a supported MLX deployment | Operator support, Metal build, latency and memory |
| Remote model service | Models that exceed device or distribution constraints | Network latency, operational cost and permitted data transfer |
Frequently asked questions
Do I need to convert PyTorch to ONNX before Core ML?
Apple documents direct PyTorch conversion with coremltools. Consider ONNX separately if you need a portable artifact or already run ONNX Runtime.
Will INT8 make iPhone inference faster?
It can reduce model size. Speed depends on the graph, hardware and actual computation path. Measure the exported model on the target device and check accuracy.
Can I force the entire model onto the Neural Engine?
Compute-unit settings govern allowed hardware. Core ML decides how the supported workload is scheduled, so verify actual behaviour with profiling.
When should I choose MLX over Core ML?
Choose according to your model and deployment needs. MLX is useful for Apple Silicon experiments and compatible apps, while Core ML offers native model integration and scheduling across Apple compute units.
