Converting ML Models to Core ML for iOS
Problems Converting to Core ML
Getting a .mlpackage from PyTorch or TensorFlow involves specific steps where each can break for non-obvious reasons. Apple's coremltools (official conversion tool) does not support all operations — for example, einsum, convolutions with dynamic sizes, or branches in the graph. Direct conversion often results in errors or a 5–10% drop in accuracy. We have accumulated experience solving such cases: over 5 years of work, we have converted more than 50 models for the financial sector, retail, and AR applications. On average, inference on iPhone accelerates by 30–50% after optimization for the Apple Neural Engine — that's significantly better than standard conversion tools. Starting from $200, the investment often pays back within weeks due to improved user experience and lower server costs. For example, one retail client reduced server costs by $500 per month after converting their recommendation model. Conversion cost ranges from $200 to $1000 depending on model complexity. Order conversion and receive a ready .mlpackage with accuracy verification.
Why Conversion to Core ML Requires Expertise
The conversion tool does not support all PyTorch/TensorFlow operations, and others require correct parameter settings. Direct conversion often leads to errors or degraded accuracy. We solve these problems by selecting optimal parameters and using custom operations when necessary.
Preparing the Model for Conversion
Before converting, the model must be in eval mode with frozen weights. torch.jit.trace requires an example input — it records the graph for a specific shape:
import torch
import torchvision
import coremltools as ct
model = MyModel()
model.load_state_dict(torch.load("weights.pth", map_location="cpu"))
model.eval()
# trace — фиксирует граф для конкретного shape
example_input = torch.zeros(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)
# Для ветвлений (if/else) используйте torch.jit.script:
# scripted_model = torch.jit.script(model)
# Конвертация в mlprogram
mlmodel = ct.convert(
traced_model,
inputs=[ct.ImageType(
name="input",
shape=ct.Shape(shape=(1, 3, 224, 224)),
color_layout=ct.colorlayout.RGB,
bias=[-0.485/0.229, -0.456/0.224, -0.406/0.225],
scale=1/(255.0 * 0.229)
)],
outputs=[ct.TensorType(name="logits")],
compute_precision=ct.precision.FLOAT16,
minimum_deployment_target=ct.target.iOS16,
convert_to="mlprogram"
)
mlmodel.short_description = "Image classifier"
mlmodel.input_description["input"] = "RGB image 224x224"
mlmodel.output_description["logits"] = "Class probabilities"
mlmodel.save("MyModel.mlpackage")
If direct conversion fails, use ONNX as an intermediate step: torch.onnx.export(model, example_input, "model.onnx", opset_version=17), then ct.converters.onnx.convert.
Verification of Conversion Correctness
To ensure fidelity, compare outputs of the original model and Core ML on a test image:
import numpy as np
import PIL.Image
img = PIL.Image.open("test.jpg").resize((224, 224))
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
tensor = transform(img).unsqueeze(0)
with torch.no_grad():
pytorch_out = model(tensor).numpy()
coreml_out = mlmodel.predict({"input": img})["logits"]
max_diff = np.max(np.abs(pytorch_out - coreml_out))
print(f"Max difference: {max_diff}")
Normal for FP16 is less than 0.01. If difference > 0.05, check normalization in ct.ImageType.
Setting Variable Input Sizes
You can use ct.Shape with RangeDim or EnumeratedShapes for flexible input dimensions. For example:
from coremltools import RangeDim, EnumeratedShapes, Shape, TensorType
# Range of sizes
flexible_shape = Shape(shape=(1, 3, RangeDim(min_val=64, max_val=1024), RangeDim(min_val=64, max_val=1024)))
# Enumerated fixed sizes
enumerated_shapes = EnumeratedShapes(shapes=[
Shape(shape=(1, 3, 224, 224)),
Shape(shape=(1, 3, 384, 384)),
Shape(shape=(1, 3, 512, 512)),
])
mlmodel = ct.convert(traced_model, inputs=[TensorType(name="input", shape=enumerated_shapes)])
Custom Operations
If the model contains an operation that coremltools does not recognize, add a custom layer in Swift. On Python, register the operation using @ct.converters.mil.register_torch_op(). Example Swift implementation:
import CoreML
@objc(MyCustomLayer)
class MyCustomLayer: NSObject, MLCustomLayer {
required init(parameters: [String: Any]) throws { }
func setWeightData(_ weights: [Data]) throws { }
func outputShapes(forInputShapes inputShapes: [[NSNumber]]) throws -> [[NSNumber]] { ... }
func evaluate(inputs: [MLMultiArray], outputs: [MLMultiArray]) throws { }
}
A custom layer runs on CPU — for performance, prefer standard operations. In one project, a custom attention layer required wrapping the model to replace einops with standard operations — we solved it by tracing with a fixed sequence length.
Performance Comparison on Devices
The Apple Neural Engine accelerates inference 10–20× compared to CPU. Results for ResNet-50 (224x224):
| Device | CPU (ms) | GPU (ms) | ANE (ms) |
|---|---|---|---|
| iPhone 14 Pro | 45 | 30 | 12 |
| iPhone 13 | 60 | 40 | 18 |
| iPhone SE (3rd gen) | 90 | 65 | 30 |
Comparison of Core ML Formats
Format details (mlprogram vs neuralnetwork)
| Parameter | mlprogram | neuralnetwork |
|---|---|---|
| iOS version | 15+ | 12+ |
| ANE support | Yes | No |
| FP16 | Yes | Only FP32 |
| Size | Smaller | Larger |
| Performance | Higher | Lower |
What's Included in the Conversion Work?
- Model audit — graph analysis, identification of incompatible operations, recommendations for refactoring. Check for ANE support.
- Conversion — selection of precision (FP16/INT8), input size, resolving errors. Custom operations if needed.
- Accuracy verification — comparison on 100+ test samples, report with max diff and metrics (accuracy, mAP).
- ANE optimization — replacing Reshape/Permute with ANE-compatible operations, eliminating bottlenecks, quantization.
- Documentation — description of model parameters, integration in Xcode, usage example.
Our clients typically see server cost reductions of $500–$2000 per month. The average conversion price ranges from $200 to $1000 depending on complexity.
Conversion Process: Step by Step
- Export the model to TorchScript using
torch.jit.traceortorch.jit.script. Ensure the model is in eval mode with frozen weights. - Run conversion with appropriate input/output types, precision (FP16 recommended), and deployment target.
- Perform numerical verification by comparing outputs on a representative test set. Ensure max diff < 0.01.
- If errors occur, identify unsupported operations and either replace them or use ONNX as an intermediate step.
- After successful conversion, quantize to INT8 if further speedup is desired, then test on target devices.
Quantization: INT8 vs FP16
In addition to converting to mlprogram, quantization further reduces model size and speeds up inference. FP16 halves weight volume with negligible accuracy loss — that's our default standard. INT8 reduces the model another 2× but requires a calibration dataset to estimate quantization error. On Apple Neural Engine, INT8 is particularly fast: speed gain is 1.5–2× compared to FP16. For classification and object detection tasks, INT8 accuracy loss usually does not exceed 1–2%. For text or generation tasks, FP16 is preferable.
# Квантование в INT8 через coremltools
mlmodel_int8 = ct.compression_utils.affine_quantize_weights(mlmodel, mode="linear_symmetric")
mlmodel_int8.save("MyModel_INT8.mlpackage")
Our team conducts comparative testing of both formats on your specific device and selects the optimal option. The cost of quantization is included in the conversion price (starting from $200) and is not charged separately.
Our team has successfully delivered Core ML conversions for over 20 clients in finance and retail. We guarantee that accuracy will not degrade more than 0.01 max diff compared to the original model. Get a consultation from an engineer about your model — we will assess the conversion complexity and select optimal parameters. Contact us for audit and conversion.







