Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an onnx model to coreml?

I am trying to convert an onnx model to a .mlmodel for use in ios. My ultimate goal is to use an ml model from Huggingface on ios. So far, the only way to convert a ml model to a .mlmodel file is by using coremltools.converters. I made a script to convert the model from huggingface to onnx, and onnx to mlmodel. It seems to be converting to an onnx fine, but then it runs into an error with coremltools.converters.onnx.convert. After some research, it turns out that you have to use just coremltools.convert, but I am running into a different error. spec.ParseFromString(f.read()) google.protobuf.message.DecodeError: Error parsing message with type 'CoreML.Specification.Model'

Here's how I am converting from onnx to coreml:

import coremltools
# print(coremltools.converters.onnx.convert)
# Load the ONNX model
onnx_model_path = "model.onnx"
onnx_model = coremltools.utils.load_spec(onnx_model_path)


model = coremltools.convert(onnx_model)

# Set the model's input and output descriptions (optional)
coreml_model.input_description["input"] = "Input image"
coreml_model.output_description["output"] = "Output class label"

# Save the Core ML model to disk
coreml_model.save("model.mlmodel")


like image 279
Jakdad Jakdad Avatar asked Sep 13 '25 23:09

Jakdad Jakdad


1 Answers

Newer versions of Coremltools no longer support ONNX conversion.

But you still have some options:

  • Convert the original Pytorch/ TensorFlow model directly in CoreML model using the new unified api conversion tools. (Highly recommended).
  • Install an older version of Coremltools (v3.2) that supports ONNX conversion. You will have to manually download and install this package. This will give you access to the old conversion method:
import coremltools as ct
ct.converters.onnx.convert(your_onnx_model)
  • Install and include the onnx_coreml package and call the converter method directly:
import onnx_coreml
coreml_model = onnx_coreml.convert(your_onnx_model)
like image 91
asyncCollection Avatar answered Sep 15 '25 14:09

asyncCollection