A Gentle Introduction to coremltools

Core ML runs models on Apple devices; coremltools converts them. How to pick the format, set image inputs, handle unsupported ops, compress and validate.

A Gentle Introduction to coremltools
Written by TechnoLynx Published on 18 Apr 2024

Core ML is Apple’s framework for running machine learning models inside apps on Apple devices, and coremltools is the Python package that turns a model trained in PyTorch or TensorFlow into the Core ML format. The conversion is more than a file-format change. coremltools translates the model and applies on-device optimisations, and you also choose the format, the preprocessing, how unsupported operations are handled and how far to compress. Each of those choices can move accuracy and latency, so a converted model has to be checked against the original before it ships.

This introduction walks through that path for a computer vision model, from format choice to validation. Deep tuning is left for later.

What Core ML does on an iPhone, and where coremltools fits

A Core ML model asset holds a description of the model’s inputs, outputs and architecture along with its learned parameters. At runtime, Core ML spreads execution across the CPU, GPU and Neural Engine, and Xcode generates a type-safe Swift interface for the model. An empirical study of model conversion published on arXiv in 2022 describes Core ML as optimising on-device performance across those three compute units while keeping memory footprint and power consumption low.

coremltools works before that stage, as a Python package. Apple’s documentation says it converts trained models from libraries such as TensorFlow and PyTorch, and that it can read, write and optimise Core ML models to use less storage, use less power and run with lower latency. Some optimisations happen automatically, such as fusing operations and removing redundant computation. Compression is opt-in.

Inside the converter, much like an ML compiler, the source graph (the “frontend”) becomes a Python object in the Model Intermediate Language (MIL), passes simplify it, and the result is serialised to a backend on disk.

Core ML or Create ML: which one do you need?

They do different jobs. Create ML trains models and Core ML runs them. In its 2019 WWDC session, Apple presented the Create ML app as a tool for training, evaluating and previewing models on a Mac, with templates such as an image classifier built by transfer learning on a feature extractor already in the OS, and the trained models deployable on device. A third-party explainer from 123ofai describes Core ML as the deployment layer, covering model packaging, runtime execution, hardware scheduling and app integration.

So the choice depends on where the model comes from. If a Create ML template fits the task and your data, Create ML trains a model you can deploy on device. If the model already exists in PyTorch or TensorFlow, for example a custom detector or a segmentation network, coremltools converts it to the Core ML format.

What Core ML model format should coremltools produce?

Use the ML program format (mlprogram). Apple’s coremltools guide says the older neuralnetwork format is in maintenance mode with no new features, and that mlprogram is the recommended format, deployable to iOS 15, macOS 12, watchOS 8, tvOS 15 and newer. From coremltools 7.0 onwards, convert() produces an ML program with an iOS 15 / macOS 12 deployment target by default, and you can override that with minimum_deployment_target or convert_to.

The differences matter in practice:

  ML program (mlprogram) Neural network (neuralnetwork)
Status Recommended, new ops added continually Maintenance mode, op set frozen
File .mlpackage only, because weights are stored outside the protobuf .mlmodel or .mlpackage
Precision control Typed intermediate tensors and a compute_precision option for float16 or float32 :
GPU path Metal Performance Shaders Graph, float16 and float32 Float16 only at runtime
Custom layers Not available Supported
Minimum OS iOS 15, macOS 12, watchOS 8, tvOS 15  

The two formats run on different Core ML runtimes. In our view, the only good reason to target neuralnetwork today is a deployment target older than iOS 15 or a dependency on a custom layer.

Converting a PyTorch model to Core ML with coremltools

Convert from PyTorch directly. Apple recommends direct conversion over exporting to ONNX first, and that has been possible since coremltools 4.0. The workflow has two steps: capture the graph from the torch.nn.Module, then pass it to the Unified Conversion API.

There are two ways to capture the graph. torch.jit.trace is the stable, better-performing path and Apple’s current recommendation. Conversion from torch.export arrived in coremltools 8.0 as a beta, and Apple puts its PyTorch op translation test coverage at roughly 70% for that release, with models such as ResNet, ViT, MobileNet and DeepLab converting. Put the model in evaluation mode before tracing so that dropout and batch-norm statistics updates are off. Tracing records one execution path, so data-dependent loops or conditionals will not generalise, and coremltools supports torch.jit.script only to a limited degree.

Worked example: MobileNetV2 with an image input

This follows the shape of Apple’s torchvision tutorial: load a pretrained model, trace it, describe the image preprocessing and convert to an ML program.

import torch
import torchvision
import coremltools as ct

model = torchvision.models.mobilenet_v2(weights="IMAGENET1K_V1").eval()
example = torch.rand(1, 3, 224, 224)
traced = torch.jit.trace(model, example)

image_input = ct.ImageType(
    name="image",
    shape=example.shape,
    scale=1 / (0.226 * 255.0),
    bias=[-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.225],
)

mlmodel = ct.convert(
    traced,
    inputs=[image_input],
    convert_to="mlprogram",
    minimum_deployment_target=ct.target.iOS15,
)
mlmodel.save("MobileNetV2.mlpackage")

Here is where the scale and bias values come from: torchvision normalises each channel as (input − mean) / std, with mean [0.485, 0.456, 0.406] and std [0.229, 0.224, 0.225] for its pretrained models. Core ML applies one global scale first and then adds a per-channel bias. Because the three std values are close, Apple’s guide averages them: 0.226 = (0.229 + 0.224 + 0.225) / 3. With pixels arriving in the 0 to 255 range, (x/255 − mean) / std is approximately x / (255 × 0.226) − mean / std, so the scale is 1/(0.226 × 255) and the bias for each channel is −mean/std. The averaging is an approximation. If your model is sensitive to it, compare outputs on real images rather than assuming it is harmless.

ct.convert also takes compilation flags such as compute_units (ALL, CPU_ONLY, CPU_AND_GPU) and compute_precision, which controls whether intermediate tensors are float16 in an ML program.

Setting up ImageType inputs for a vision model

Declare image inputs as ImageType and not as the default multi-array. By default the converter produces inputs and outputs of type MLMultiArray. Apple’s guide warns that an inefficient MLMultiArray copy can become a bottleneck, and that ImageType is the efficient way to pass a CVPixelBuffer into a Core ML prediction. An ImageType input also lets the Vision framework preprocess and resize images for you on device, and image outputs come back as CVPixelBuffer instances that other iOS and macOS functions can use directly.

Three ImageType parameters deserve attention beyond scale and bias:

  • color_layout: RGB, BGR, grayscale or grayscale float16. The enumeration is the recommended form, and the older string values are a trap: 'RGB' maps to ct.colorlayout.BGR and 'BGR' maps to ct.colorlayout.RGB.
  • channel_first: defaults to channel-first for PyTorch and channel-last for TensorFlow.
  • shape: required for PyTorch inputs. For flexible inputs on a model that already runs on the Neural Engine, Apple recommends EnumeratedShapes, since a fully dynamic reshape can push layers off the Neural Engine. With mlprogram, a RangeDim needs a finite upper bound.

TensorFlow models handle image inputs differently, so check the model’s training recipe. Apple’s TensorFlow MobileNet example expects inputs normalised to [−1, 1] and uses a scale of 1/127.5.

When coremltools hits an op Core ML does not support

When a PyTorch conversion fails on an unsupported op, coremltools lists the supported and unsupported ops it found in the model. Apple’s guidance puts the fixes in an order.

Start with a composite operator. Apple’s guide says most unsupported operations can be handled by building them from existing MIL operations. Its worked example takes an Einsum, works out which specific notation the model uses (a batched matrix multiplication with a transpose), rebuilds it from MIL ops and registers the function with a decorator so the converter calls it whenever that op appears. For Einsum, you only need the particular notation your model uses.

Custom operators are the last resort. They are hard to implement, Apple recommends them only when the functionality is missing from Core ML and cannot be expressed as a composite, and a composite is more efficient and compiles to all of the device’s hardware backends. Custom layers also work only with the neuralnetwork backend. Using one therefore means targeting neuralnetwork, the format in maintenance mode.

Even when conversion succeeds, op support affects performance. The 123ofai explainer notes that one unsupported op can move computation off the Neural Engine.

Quantising and compressing a Core ML model for on-device use

coremltools offers three ways to compress a model, and they can be combined:

  • Palettisation clusters weights and stores an index into a lookup table, at 1, 2, 3, 4, 6 or 8 bits per weight.
  • Linear quantisation maps float weights into an integer range with a scale and zero point. Core ML supports INT8 and INT4 for weights and INT8 for activations, and symmetric quantisation is the default in coremltools.
  • Pruning zeroes near-zero weights and stores them sparsely.

Some of these workflows run directly on the converted .mlpackage. Others need gradients, so they run on the PyTorch model before conversion through coremltools.optimize.torch. Apple’s FAQ notes that PyTorch’s own quantisation defaults are not optimal for the Core ML stack, and that the coremltools APIs apply suitable defaults automatically.

The trade-off is accuracy. Apple’s ResNet50 optimisation guide shows this:

ResNet50 variant (Apple coremltools guide) Top-1 accuracy Notes
Float16 baseline 76.13% 49 MB .mlpackage
8-bit palettisation 76.09% Marginal loss
6-bit palettisation 75.55% Marginal loss
4-bit palettisation 66.81% Large drop
3-bit palettisation 23.09% Unusable
2-bit palettisation, training-time 75.51% 6.3 MB
1-bit palettisation, training-time 71.22% 3.4 MB, over 15x smaller
90% sparse, fine-tuned 74.6% 0.86 ms latency measured at 90% sparsity, before fine-tuning
INT8 weights and activations, 128 calibration samples 76.1% 1.07 ms latency

Post-training methods are quicker to set up, while training-time methods give a better accuracy-to-compression trade-off. At WWDC24, Apple added a middle option, post-training compression with calibration data, which needs a small amount of data and no fine-tuning. In the same session Apple explained that per-tensor 4-bit palettisation gives a whole tensor only 16 centroids, which introduces more error on large matrices. Finer granularity, such as per-channel or per-block quantisation, is there to improve accuracy.

Apple’s guidance names a minimum to consider: 6- or 8-bit palettisation or 8-bit weight-only quantisation usually costs little accuracy, takes minutes, and is worth considering for any model currently shipping in float16. Hardware matters too. On A17 Pro and M4 devices, quantising both weights and activations to INT8 can use optimised Neural Engine compute and help latency in compute-bound models. Whether compression, distillation or both fit your device range is its own decision, and our guide on distillation versus quantisation for multi-platform edge targets covers that choice.

Converted is not the same as correct

Check the converted model against the source model on the same inputs. In Apple’s MobileNetV2 tutorial the converted model’s raw scores closely match the original, but that is one well-behaved model. The 2022 arXiv study found converted models’ accuracy broadly at the level of the originals, but Core ML models showed larger prediction offsets than ONNX models, with possible causes such as structural changes during conversion or numerical defects. It also found high misclassification rates for converted ResNet-18 and VGG-16, meaning the deployed system labelled some inputs differently from the tested one. In a few cases converted models also ran very slowly, especially PyTorch models. The study used coremltools 5.0b3. We read it as a reason to check every conversion rather than as a measurement of today’s converter.

A practical check after each conversion looks like this:

  1. Numerics. Compare outputs on a fixed set of golden inputs, including label agreement and not only score error, because small numeric errors can still flip labels. If error is high, Apple’s FAQ suggests running a neural network on CPU_ONLY to use the higher-precision Float32 path, and for ML programs, compute_precision gives the same control.
  2. Preprocessing parity. Recheck scale and bias against the model’s training recipe.
  3. Op placement and latency. Xcode shows expected prediction latency, load times and where each operation is supported and executed on a connected device, and it can now display the full model architecture.
  4. Device coverage. 123ofai recommends benchmarking on the oldest device you plan to support.

The study also found Core ML models more vulnerable to adversarial inputs than ONNX ones. If robustness matters for your application, it belongs in the same check.

Who can port our vision model to Core ML?

TechnoLynx’s AI Porting & Deployment Pack gets a trained vision model running on edge and embedded targets. This work sits within our computer vision R&D practice. We treat reaching a new deployment target as engineering in its own right, best scoped against a concrete trigger such as a device constraint or a latency ceiling.

Not every project needs outside help. If your model is a standard architecture that converts cleanly with torch.jit.trace, Apple’s tutorials and the coremltools guides will get you there. If a Create ML template covers your task, you may not need conversion at all. Outside help is most useful when conversion fails on custom ops, when accuracy drifts after conversion, or when compression has to hold up across a wide range of devices.

Back See Blogs
arrow icon