Skip to content

Instantly share code, notes, and snippets.

@hollance
Created October 9, 2020 09:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hollance/d78b83accc7a7f433d8755ae0e2a3e95 to your computer and use it in GitHub Desktop.
Save hollance/d78b83accc7a7f433d8755ae0e2a3e95 to your computer and use it in GitHub Desktop.
Workaround for Xcode 12 problems with Core ML models

I ran into a problem with Xcode 12's Core ML compiler, and several people have emailed me about what appears to be the same issue.

The workaround is to use Xcode 11 to compile the Core ML model. This means you still need to have Xcode 11 installed (which is a good idea anyway).

What worked for me is the following...

From the Terminal, switch to the Xcode 11.7 installation (your path may be different):

sudo xcode-select -s /Applications/Xcode11.7.app/Contents/Developer/

Then cd to your project folder and run the Core ML compiler:

xrun coremlc compile YourModel.mlmodel .

This creates a YourModel.mlmodelc folder. Add this folder to your Xcode project.

In Xcode 11, open YourModel.mlmodel and view the auto-generated source code (the mlmodel needs to be part of a project for this). Copy-paste this source code into a new source file, YourModel.swift. Add this source file to your Xcode project too.

Remove YourModel.mlmodel from the project (just the reference, don't delete the file).

Open your project in Xcode 12. Disable automatic code generation for Core ML models.

To load your model, do the following:

let config = MLModelConfiguration()
let url = Bundle.main.url(forResource: "YourModel", withExtension: "mlmodelc")!
let model = try YourModel(contentsOf: url, configuration: config)

It is possible your app will crash when loading the model. If that happens, add the line config.computeUnits = .cpuOnly and try again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment