Core ML Tools
Core ML Tools is an open-source Python package developed by Apple for converting, optimizing, and validating machine learning models into Apple's Core ML format. It supports models from popular frameworks like TensorFlow, PyTorch, scikit-learn, XGBoost, and LibSVM. The library is actively maintained, with frequent releases, and is currently at version 9.0, adding support for Python 3.13, PyTorch 2.7, and new iOS/macOS deployment targets.
Warnings
- breaking Core ML Tools 4.0 introduced the Unified Conversion API (`ct.convert`). Older converters like `onnx-coreml` (for PyTorch) and `coremltools.keras.convert` (for Keras/TF1) are no longer maintained or officially deprecated.
- breaking Core ML Tools 5.0 introduced the `.mlpackage` directory format for Core ML models, replacing the older `.mlmodel` protobuf file format.
- breaking coremltools 8.0 updated its dependency compatibility, requiring a newer `protobuf` Python package version. Incompatible `protobuf` versions can lead to serialization errors or conversion failures.
- gotcha Incorrect image preprocessing parameters during conversion (e.g., `scale`, `bias`, `is_bgr`) are a common cause of wrong predictions on device. Models expect specific normalization, pixel ranges (0-1, -1 to 1), and channel order (RGB vs BGR).
- gotcha While coremltools supports flexible input shapes, using `EnumeratedShapes` or `RangeDim` can impact performance. Models with fully dynamic shapes or `RangeDim` might not fully utilize the Apple Neural Engine (ANE) for acceleration.
- gotcha When converting PyTorch models, `torch.jit.trace` is currently the stable and generally more performant path. `torch.export` is newer (introduced in coremltools 8.0) and is still in beta, mirroring its status in PyTorch.
Install
-
pip install coremltools
Imports
- coremltools
import coremltools as ct
- ct.convert
mlmodel = ct.convert(model=pytorch_model, inputs=[ct.TensorType(shape=input_shape)])
- ct.TensorType
inputs=[ct.TensorType(shape=(1, 3, 224, 224))]
Quickstart
import coremltools as ct
import torch
import torchvision
# 1. Define a PyTorch model
model = torchvision.models.mobilenet_v2(pretrained=True)
model.eval()
# 2. Create a dummy input for tracing
example_input = torch.rand(1, 3, 224, 224)
# 3. Trace the model (or use torch.export in newer PyTorch/coremltools versions)
traced_model = torch.jit.trace(model, example_input)
# 4. Convert the traced model to Core ML format
# Specify inputs explicitly for correct type and shape handling
# For image inputs, use ct.ImageType with appropriate preprocessing parameters
mlmodel = ct.convert(
traced_model,
inputs=[
ct.ImageType(name="input_1", shape=example_input.shape, scale=1/255.0, bias=, channel_first=True)
],
convert_to='mlprogram',
minimum_deployment_target='iOS16'
)
# 5. Save the Core ML model
mlmodel.save("MobileNetV2.mlpackage")
print("Model converted and saved as MobileNetV2.mlpackage")