Assuming your model is built in your app bundle, I believe this is what happens:
-
When you build your app with Xcode, Xcode compiles your .mlpackage into .mlmodelc, which contains hardware-agnostic intermediate representations (MIL).
-
When you load the .mlmodelc the first time, the system specializes the MIL into an execution plan specifically tailored for the device's ANE, and cache it (in Library/Caches). The specialization takes time.
-
From then on, Core ML then uses a key, which is generated based on the info of the .mlmodelc, to find the cached model. No specialization is needed any more.
-
When you do an app update, or build and run the app with Xcode, the app bundle's absolute path changes, and the .mlmodelc can change as well because Xcode may re-compile the model.
-
When you load the .mlmodelc again, Core ML generates a new key and uses it to locate the cached model. This fails because the new key doesn't match the old cached model. The system hence needs to specialize the .mlmodelc again. This is the issue you see.
To avoid the issue, consider the following if your model is relatively small:
-
In your app's first launch session, copy the .mlmodelc from your app to a folder that remains stable across app updates, the .applicationSupportDirectory folder, for example, and then exclude the bundle from backup by setting the isExcludedFromBackup resource value to true
-
Do the copy again ONLY when you change the model so the .mlmodelc remains stable across app updates.
-
Load your model from the stable folder (and not from the app bundle). This avoids triggering the model specialization unnecessarily.
Note that this technically doubles the disk footprint of your model, and hence only fits when your model is small.
If your model is large, consider deploying your model on a server, as described in this article.
The cached model will still be invalidated when:
- Your app is completely removed and re-installed
- The cached model, which locates in
Library/Caches, is purged.
This probably doesn't happen frequently, but you'd still prepare for that (by offloading the model specialization to background, for example).
Best,
——
Ziqiao Chen
Worldwide Developer Relations.