export to CoreML
Author: pzoltowskiCreated Apr 19, 2025Updated Sep 23, 2026
I did try to export to CoreML to try to run on edge devices but failed (most likely on model tracing)
The reason I want CoreML rather than ONNXRuntime is that ONNXRuntime 1.21.0 doesn't have MPS provider and current support for CoreML (NPU) provider is not finished and slow ("number of partitions supported by CoreML: 90 number of nodes in the graph: 913 number of nodes supported by CoreML: 737"). On my macbook m2 max original version with MPS is not bad (~70ms per inference on test.jpg) but on ONNXRuntime with CoreML provider ~290ms (I guess too many not supported OPs and too many partitions).
Failed model tracing output:
Tracing the PyTorch model ...
`loss_type=None` was set in the config but it is unrecognised.Using the default loss: `ForCausalLMLoss`.
TracerWarning: Iterating over a tensor might cause the trace to be incorrect. Passing a tensor of different shape won't change the number of iterations executed (and might lead to errors or silently give incorrect results).
TracerWarning: Iterating over a tensor might cause the trace to be incorrect. Passing a tensor of different shape won't change the number of iterations executed (and might lead to errors or silently give incorrect results).
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: torch.as_tensor results are registered as constants in the trace. You can safely ignore this warning if you use this function to create tensors out of constant variables that would be the same every time you call this function. In any other case, this might cause the trace to be incorrect.
TracerWarning: Iterating over a tensor might cause the trace to be incorrect. Passing a tensor of different shape won't change the number of iterations executed (and might lead to errors or silently give incorrect results).
UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at /Users/runner/work/pytorch/pytorch/pytorch/aten/src/ATen/native/TensorShape.cpp:3638.)
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python float might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
TracerWarning: Iterating over a tensor might cause the trace to be incorrect. Passing a tensor of different shape won't change the number of iterations executed (and might lead to errors or silently give incorrect results).
TracerWarning: Iterating over a tensor might cause the trace to be incorrect. Passing a tensor of different shape won't change the number of iterations executed (and might lead to errors or silently give incorrect results).
TracerWarning: Iterating over a tensor might cause the trace to be incorrect. Passing a tensor of different shape won't change the number of iterations executed (and might lead to errors or silently give incorrect results).
Error during torch.jit.trace: Tracer cannot infer type of {'pred_logits': tensor([[[-8.0445, -3.1732, -5.6238, ..., -5.4984, -6.6426, -5.3405],
[-7.8647, -3.1592, -5.5081, ..., -5.3976, -6.4759, -5.2438],
[-8.4119, -3.9196, -6.0874, ..., -6.0168, -7.4106, -6.4237],
...,
[-8.3316, -4.6361, -6.8671, ..., -6.4185, -7.2935, -6.9924],
[-8.0602, -4.7008, -6.7307, ..., -6.1142, -7.4859, -6.9115],
[-8.2329, -4.6211, -6.6878, ..., -6.1766, -7.2224, -6.4051]]],
grad_fn=<SelectBackward0>), 'pred_boxes': tensor([[[0.5018, 0.4988, 1.0022, 0.9953],
[0.5004, 0.4998, 0.9986, 0.9955],
[0.4653, 0.4708, 0.6418, 0.9381],
...,
[0.6593, 0.0716, 0.1782, 0.1335],
[0.6569, 0.6380, 0.1235, 0.1238],
[0.6931, 0.5116, 0.0823, 0.0942]]], grad_fn=<SelectBackward0>), 'aux_outputs': [{'pred_logits': tensor([[[-6.8957, -3.9149, -6.8781, ..., -6.2709, -6.2848, -5.7102],
[-6.9600, -4.2974, -6.4957, ..., -6.4973, -6.6731, -5.7901],
[-7.9513, -3.9613, -7.1307, ..., -6.7055, -7.0152, -6.6234],
...,
[-7.7330, -5.0914, -7.5229, ..., -6.8009, -7.5091, -7.1663],
[-7.7613, -4.4823, -7.5698, ..., -5.9079, -7.6792, -6.4149],
[-7.5736, -5.0675, -6.7377, ..., -6.5704, -7.8077, -6.7850]]],
grad_fn=<UnbindBackward0>), 'pred_boxes': tensor([[[0.5019, 0.5008, 1.0043, 0.9994],
[0.5013, 0.5005, 1.0032, 0.9976],
[0.4729, 0.4999, 0.9432, 0.9956],
...,
[0.6866, 0.1111, 0.1565, 0.2131],
[0.7577, 0.3836, 0.4887, 0.7673],
[0.4989, 0.4994, 1.0060, 0.9915]]], grad_fn=<UnbindBackward0>)}, {'pred_logits': tensor([[[-7.8043, -2.9682, -5.7385, ..., -5.0984, -5.9417, -5.0866],
[-7.9755, -3.5690, -5.8545, ..., -5.3970, -6.7558, -5.3737],
[-8.7203, -3.8038, -6.3814, ..., -5.7858, -6.5796, -6.0313],
...,
[-8.6048, -4.8663, -7.2910, ..., -5.9929, -6.6350, -7.1511],
[-8.4294, -4.9313, -7.6452, ..., -6.2196, -7.7773, -7.5357],
[-8.2790, -4.9296, -6.7772, ..., -6.1936, -7.6878, -6.0923]]],
grad_fn=<UnbindBackward0>), 'pred_boxes': tensor([[[0.5031, 0.4979, 1.0065, 0.9976],
[0.5025, 0.4988, 1.0083, 0.9956],
[0.4114, 0.4732, 0.6480, 0.9447],
...,
[0.6730, 0.1011, 0.1831, 0.1867],
[0.7470, 0.6355, 0.4518, 0.2166],
[0.8370, 0.3410, 0.1408, 0.2074]]], grad_fn=<UnbindBackward0>)}], 'enc_outputs': {'pred_logits': tensor([[[-6.7586, -3.1915, -5.1286, ..., -5.1321, -6.3095, -5.8771],
[-6.7785, -3.7732, -5.5403, ..., -5.8365, -6.8113, -6.0639],
[-6.8637, -3.7820, -5.6441, ..., -6.0389, -6.9331, -6.2711],
...,
[-7.3807, -4.6971, -7.2230, ..., -6.7844, -7.5552, -6.4569],
[-7.4044, -4.6972, -7.2772, ..., -7.0907, -8.2304, -7.1308],
[-7.1247, -4.6979, -7.0655, ..., -6.6143, -7.7592, -6.9069]]],
grad_fn=<CatBackward0>), 'pred_boxes': tensor([[[0.4963, 0.4929, 0.9906, 0.9941],
[0.4954, 0.4850, 0.9935, 1.0008],
[0.4399, 0.4822, 0.8628, 0.9663],
...,
[0.6669, 0.1419, 0.2429, 0.2603],
[0.8027, 0.4136, 0.3766, 0.7382],
[0.5417, 0.4863, 0.8424, 0.9551]]], grad_fn=<CatBackward0>)}}
:Dictionary inputs to traced functions must have consistent type. Found Tensor and List[Dict[str, Tensor]]Script I used for conversion. I'm using python 3.12 and latest coremltools, torch :
import coremltools as ct
import torch
import os
from rfdetr import RFDETRBase
# --- Configuration ---
CONVERT_TO_COREML = True # Set to True for ONNX export, False to attempt direct CoreML conversion
RESOLUTION = 560 # Must be divisible by 56
ONNX_MODEL_DIR = "output" # Directory for ONNX export
ONNX_MODEL_NAME = "model.onnx"
COREML_MODEL_NAME = "RFDETRBase.mlpackage"
# ---------------------
ONNX_MODEL_PATH = os.path.join(ONNX_MODEL_DIR, ONNX_MODEL_NAME)
def _convert_to_onnx(model: RFDETRBase, onnx_model_path: str, onnx_model_dir: str):
"""Exports the provided RFDETRBase model to ONNX format."""
print(f"Exporting model to ONNX format at {onnx_model_path}...")
# Ensure the output directory for ONNX exists
os.makedirs(onnx_model_dir, exist_ok=True)
try:
# The export method saves to the specified path (implicitly output/model.onnx if not changed)
# It handles the internal model structure correctly.
model.export() # Assumes export() doesn't take path, saves to default ONNX_MODEL_PATH
print("ONNX export complete.")
print(f"Model saved to: {onnx_model_path}")
except Exception as e:
print(f"Error during ONNX export: {e}")
def _convert_pytorch_to_coreml(pytorch_model, resolution: int, device: str, coreml_model_name: str):
"""Attempts direct PyTorch -> CoreML conversion via TorchScript trace."""
print("Attempting direct PyTorch -> CoreML conversion ...")
pytorch_model.eval()
# 1. Trace the PyTorch model to get TorchScript
print("Tracing the PyTorch model ...")
example_input = torch.randn(1, 3, resolution, resolution).to(device) # Batch, Channel, H, W
try:
traced_model = torch.jit.trace(pytorch_model, example_input, strict=False)
print("PyTorch model traced successfully.")
except Exception as e:
print(f"Error during torch.jit.trace: {e}")
return
# 2. Define the input image type for Core ML conversion
coreml_input = ct.ImageType(
name="image",
shape=(1, 3, resolution, resolution),
scale=1/255.0,
bias=0.0,
color_layout=ct.colorlayout.RGB,
channel_first=True
)
print(f"Converting traced PyTorch model to Core ML format...")
# 3. Convert the traced model
try:
coreml_model = ct.convert(
traced_model,
inputs=[coreml_input],
convert_to="mlprogram",
compute_units=ct.ComputeUnit.ALL,
minimum_deployment_target=ct.target.iOS17
)
print("Core ML conversion complete.")
except Exception as e:
print(f"Error during coremltools.convert: {e}")
print("Conversion failed. This might be due to tracing issues or unsupported ops.")
return
# 4. Add metadata
coreml_model.author = 'RF-DETR Authors & Conversion Script'
coreml_model.license = 'Apache-2.0'
coreml_model.short_description = f'RF-DETR Base object detection model (Resolution: {resolution}x{resolution}, via PyTorch trace - Experimental)'
coreml_model.input_description["image"] = "Input image (RGB, expects pixel values 0-255)"
# Add output descriptions if conversion succeeds and outputs are known
# 5. Save the Core ML model package
coreml_model_path = coreml_model_name
print(f"Saving Core ML model to {coreml_model_path}...")
coreml_model.save(coreml_model_path)
print("Core ML model saved successfully.")
print(f"\nTo use the model: {coreml_model_path}")
def convert():
"""Loads the model and calls the appropriate conversion function based on the flag."""
print(f"Loading RFDETRBase model with resolution {RESOLUTION}x{RESOLUTION}...")
device = 'cpu' # Explicitly set device for export/tracing example
try:
# Load the main model object
model = RFDETRBase(resolution=RESOLUTION, device=device)
except Exception as e:
print(f"Error loading RFDETRBase model: {e}")
return
if CONVERT_TO_COREML:
pytorch_model = model.model.model
# Call the direct PyTorch -> CoreML conversion function
_convert_pytorch_to_coreml(pytorch_model, RESOLUTION, device, COREML_MODEL_NAME)
else:
# Call the ONNX export function
_convert_to_onnx(model, ONNX_MODEL_PATH, ONNX_MODEL_DIR)
if __name__ == "__main__":
convert() Source: roboflow/rf-detr