ClamNotes records a class and transcribes it on the device. Depending on how much memory the iPhone has, it uses one, two or three speech models: Parakeet Ultra (about 0.6 GB), Canary 1B v2 in INT8 (1.1 GB) or FP16 (1.9 GB), and Whisper large-v3 (0.95 GB). That adds up to about 4.6 GB of Core ML files. This post covers how those files get from Hugging Face onto a student's phone: the packaging script, the App Store Connect side, the Swift that finds and downloads them, and the bug that made a TestFlight build report a working model as broken.
Why the models can't live in the app bundle
The obvious first idea is to put everything in the bundle. Three things rule it out.
Size. App Store Connect's maximum build file sizes put an iOS app at 4 GB uncompressed. All four models together are past that before the app's own code is counted.
Not every device uses every model. The app reads ProcessInfo.physicalMemory and picks a tier. A 4 GB iPhone runs Parakeet Ultra and Canary INT8. An 8 GB one adds Whisper. A 12 GB one swaps Canary INT8 for FP16. If everything shipped in the bundle, an iPhone 13 would carry gigabytes of weights it can never load, and every app update would ship them again.
The old answer is going away. In the iOS 27 SDK, NSBundleResourceRequest (On-Demand Resources) is marked API_DEPRECATED("Use Background Assets instead."), and it was never available on macOS. My Mac app shares most of its code with the iPhone app, so I wanted one mechanism for both.
The other option was my own CDN. That means hosting, resumable downloads, retries, Wi-Fi rules and cleanup, all written and run by me. I do have a version of that (more on it below), but as a fallback, not as the main path. Apple-hosted asset packs, introduced in the WWDC25 session Discover Apple-Hosted Background Assets, give you all of it from the system (docs): Apple hosts up to 200 GB of compressed assets per app, the system downloads packs at install time or on request, keeps them updated, and continues while the app is closed.
| Pack ID | Model | Files | Policy | Used on |
|---|---|---|---|---|
speech-canary-int8 | Canary 1B v2, INT8 encoder | 1.10 GB | prefetch | 4 to 8 GB devices |
speech-canary-fp16 | Canary 1B v2, FP16 | 1.89 GB | onDemand | 12 GB devices |
speech-whisper | Whisper large-v3 (947 MB build) | 0.95 GB | onDemand | 8 and 12 GB devices |
| (none, in the app) | Parakeet Ultra | 0.63 GB | bundled | every device |
The fourth row used to be a pack too. Why it moved back into the app is its own section further down.
From Hugging Face to an .aar
The packs are built by one script, iOS/scripts/package-models.py. It doesn't convert anything. The Core ML conversions already exist on Hugging Face, and the app's fallback path downloads from the same repositories. So the script does four things for each pack:
- Asks Hugging Face which commit
mainpoints to now, and lists the files at that commit, so the listing and the downloads belong to one commit. The commit hashes go into<id>.sources.jsonnext to the archive, so I can always tell which weights a pack version holds. - Downloads only the files the loader needs, resuming partial files, and checks each file's size and hash: SHA-256 for LFS files, the Git blob ID for the rest.
- Compiles any
.mlpackageinto an.mlmodelcwithxcrun coremlcompiler. The app loads compiled models straight from the pack folder, so nothing gets compiled on the device. - Writes the manifest, checks it with
ba-package evaluate, and packs it withba-package package.
Here is the manifest it writes for the prefetched pack, exactly as it is on disk:
{
"assetPackID": "speech-canary-int8",
"downloadPolicy": {
"prefetch": {
"installationEventTypes": [
"firstInstallation",
"subsequentUpdate"
]
}
},
"fileSelectors": [
{
"directory": "speech-canary-int8"
}
],
"platforms": [
"iOS",
"macOS"
],
"sourceRoot": "root"
}
The on-demand packs have "downloadPolicy": { "onDemand": {} } instead. Apple's Creating managed asset packs describes the three policies: essential is part of the install and counts toward the progress people see on the Home Screen, prefetch starts during the install but carries on in the background, and onDemand waits until the app asks.
The important line is fileSelectors. Each pack holds a single directory named after its own ID. On the device, the system merges every downloaded pack into one namespace, as if all the packs had been unpacked into one folder. The documentation for url(for:) says that when two packs contain the same path, which one wins is undefined. Canary INT8 and Canary FP16 both have a vocab.json and an encoder with the same name. Without a folder per pack, they would collide.
def manifest(pack_id, policy):
# No userInfo: App Store Connect doesn't take it for Apple-hosted packs.
return {"assetPackID": pack_id, "downloadPolicy": policy, "fileSelectors": [{"directory": pack_id}],
"platforms": ["iOS", "macOS"], "sourceRoot": "root"}
def xcrun(*args, **kwargs):
"""`xcrun` with the release Xcode's tools, whatever xcode-select points at."""
env = {**os.environ, "DEVELOPER_DIR": developer_dir()} # exits if it is Xcode-beta.app
return subprocess.run(["xcrun", *args], check=True, env=env, **kwargs)
# For each pack, once every file is downloaded and checked (simplified):
compile_packages(root)
xcrun("ba-package", "evaluate", manifest_path, cwd=work, stdout=subprocess.DEVNULL)
xcrun("ba-package", "package", manifest_path, "--output-path", archive, "--quiet", cwd=work)
That xcrun wrapper is there for a reason. My xcode-select sometimes points at Xcode-beta, and App Store Connect refuses builds archived with a beta Xcode ("Unsupported SDK or Xcode version"). I didn't want to learn after a 4 GB download whether packs get the same treatment, so the script pins DEVELOPER_DIR to the release Xcode, prints the version it used, and exits before a long download if the selected Xcode's name contains "beta".
speech-canary-int8.aar as built on 9 Octoberspeech-canary-fp16.aarspeech-whisper.aarUploading and versioning in App Store Connect
The App Store Connect website has no upload button for packs. Apple's upload page lists Transporter, iTMSTransporter, altool and the App Store Connect API. I use altool with an App Store Connect API key (a team key with the App Manager role), which lets a script do the upload with no browser involved:
python3 -I iOS/scripts/package-models.py # all three packs, about 4 GB to download
python3 -I iOS/scripts/package-models.py --only whisper
xcrun altool --upload-asset-pack dist/asset-packs/speech-whisper.aar \
--apple-id <app-apple-id> --api-key <key-id> --api-issuer <issuer-id>
xcrun altool --list-asset-packs --apple-id <app-apple-id> --api-key <key-id> --api-issuer <issuer-id>
--apple-id here is the app's numeric Apple ID, not a person's. altool also has --asset-pack-status, --list-asset-pack-versions and a --wait flag on upload that blocks until processing finishes.
A pack is identified by its assetPackID plus the app. Uploading a new .aar with the same ID creates a new version, and the version number goes up by itself. You never set it. In practice:
- Changing a model's weights means building and uploading that pack again. The app sees a new version and the system updates it in the background.
- Changing a pack's ID is a code change. The ID appears in the manifest, in the Swift enum that maps models to packs, and in the probe paths the app uses to find files (next section). In my repo these three live in
package-models.py,SpeechPackandSpeechModelFiles, and the project notes say they change together. - Packs are not part of a build. Apple's docs describe them as uploaded and updated independently of app builds. That's good, because a weights update doesn't need an app review. It's also a trap: a build and a pack version can drift apart, so the app has to handle a pack laid out the way the previous build expected.
I uploaded the three packs on 9 October as version 1. After processing, the API reported them ready for testing. Each upload came with an ITMS-91139 warning, because the manifests list macOS while the app record had no Mac platform at the time. It's harmless, but it is confusing the first time you see it.
TestFlight has a split you need to know about. According to Apple's TestFlight asset pack page, internal testers automatically get the latest processed version of a pack. For external testers, you submit a specific pack version to TestFlight App Review, separately from the build, and only one version of each pack can be in external testing at a time. Once your build is approved, check that the packs are too. The limits per app record are 200 GB in total and 200 packs (size limits).
The downloader extension decides what gets prefetched
Apple-hosted packs need a downloader extension in the app (extension point com.apple.background-asset-downloader-extension), an App Group shared by the app and the extension, and three Info.plist keys on the app: BAHasManagedAssetPacks, BAUsesAppleHosting and BAAppGroupID. The extension can be nearly empty. The system provides the downloading, and you can override one method to filter what it fetches. Mine is all of it:
import BackgroundAssets
import ExtensionFoundation
import NotesCore
import StoreKit
@main
struct ClamNotesAssets: StoreDownloaderExtension {
func shouldDownload(_ assetPack: AssetPack) -> Bool {
let defaults = UserDefaults(suiteName: SpeechPack.appGroup)
let present = defaults?.stringArray(forKey: SpeechPack.presentElsewhereKey) ?? []
let needed = defaults?.stringArray(forKey: SpeechPack.neededKey).map(Set.init)
return SpeechPack.shouldPrefetch(assetPack.id, tier: .current,
presentElsewhere: Set(present), needed: needed)
}
}
StoreDownloaderExtension comes from StoreKit and refines Background Assets' ManagedDownloaderExtension. The rule behind shouldPrefetch is simple: say no to a pack this memory tier doesn't use (Canary INT8 on a 12 GB device, which runs FP16), no to a pack whose model the app already has from somewhere else, and, once the app has run, no to a pack the person's class language doesn't need. Packs it doesn't know about are left to the system.
The extension runs on its own, often before the app has ever launched, so it can't ask the app anything. The app writes its answers into the App Group's UserDefaults and the extension reads them. When there's no list yet, as on a first install, needed is nil and the extension lets the tier decide.
A related cleanup: a prefetch can finish before the app has said it already has that model from an older download. At launch the app checks for that and gives the space back with AssetPackManager.shared.remove(assetPackWithID:). Apple's docs are explicit that the system won't remove your packs while the app is installed. Cleaning up is your job.
Finding a model on the device
A model can come from three places: the app bundle (Parakeet Ultra), a complete Hugging Face download (older installs, or the fallback), or its pack. The lookup is one line:
/// Inside the app, then a whole Hugging Face download, then the pack.
func files(_ engine: SpeechEngine) -> ModelFiles? {
bundledFiles(engine) ?? hubFiles(engine) ?? packFiles(engine)
}
/// One file of each pack, under the folder named after the pack.
static func probe(_ pack: SpeechPack) -> String {
switch pack {
case .canaryInt8, .canaryFP16: return pack.rawValue + "/vocab.json"
case .whisper: return pack.rawValue + "/" + WhisperTranscriber.variant + "/config.json"
case .ultra: return pack.rawValue + "/parakeet-ultra-coreml/parakeet_vocab.json"
}
}
/// `url(for:)` gives a path even for a pack that isn't there,
/// so the files themselves are looked for.
func packFiles(_ engine: SpeechEngine) -> ModelFiles? {
let pack = pack(engine)
guard !pack.isBundled,
let probe = try? AssetPackManager.shared.url(for: FilePath(Self.probe(pack))),
FileManager.default.fileExists(atPath: probe.path) else { return nil }
let folder = probe.deletingLastPathComponent()
// The model's main .mlmodelc must be there too (name per engine; simplified).
guard FileManager.default.fileExists(atPath: folder.appendingPathComponent(encoder(engine)).path) else { return nil }
return ModelFiles(folder: folder, source: .pack)
}
Why url(for:) and not contents(at:), which Apple recommends as more efficient? Because Core ML loads a compiled model from a directory URL, and url(for:) is the API that can return a directory. The docs also warn not to keep that URL beyond the current process. The app doesn't: it resolves the path again at every launch.
That fileExists check is the most important line in this post. It wasn't there in the first version.
The build 9 bug: a pack that wasn't there
TestFlight build 9 went out on 9 October. Two testers came back within the day. An iPhone 15 said not ready, trying again soon. An iPhone 13 Pro Max said the speech models don't work on this iPhone. Both were on iOS 26.6, both were fresh installs, both were 6 GB devices. My own iPhone has 12 GB, so I had never run that tier, and the packs hadn't been uploaded yet, so every install should have fallen back to Hugging Face.
It didn't. Here is the chain:
files(engine)found no bundle copy and no Hugging Face download, so it asked for the pack's path.AssetPackManager.url(for:)returned a well-formed URL for a pack that had never been downloaded. I saw this in the Simulator, and the documentation says so too: it "will return a well formed URL even if no item exists at the specified relative path in any asset pack".- The download step starts with
if files(engine) != nil { return }. The model looked present, so nothing was downloaded. - Every load failed with "The model is not found". The app counted the failures, and after enough of them it marked the model as not working on that device. That is the message the tester saw.
A device that already had a Hugging Face copy never reached the pack lookup, because hubFiles comes first. That is why it worked everywhere I tested. The fix is the probe file and the encoder check above. The same round also tightened how failures are counted: only while the app is in front, kept across launches, and keyed by OS version and app build, so one bad build can't brand a model as unusable forever. That story has more to do with the Neural Engine than with Background Assets, so I'll leave it for another post.
Downloading: ensureLocalAvailability and a wait that may never end
When the model isn't on the device, the app asks for its pack. AssetPackManager.assetPack(withID:) throws when App Store Connect has no such pack for this install. That covers packs that haven't been uploaded yet and development builds without a test server, and it's the signal to fall back. If the pack exists, the app awaits ensureLocalAvailability(of:) and watches statusUpdates(forAssetPackWithID:) for progress:
private func assetPack(_ pack: SpeechPack) async throws -> AssetPack {
if #available(iOS 27, macOS 27, *) {
guard let found = try await AssetPackManager.shared.manifest.assetPack(withID: pack.rawValue) else {
throw ManagedBackgroundAssetsError.assetPackNotFound(withID: pack.rawValue)
}
return found
}
return try await AssetPackManager.shared.assetPack(withID: pack.rawValue)
}
private func fetch(_ pack: AssetPack, progress: @escaping @Sendable (Double, Bool) -> Void) async throws {
let size = Int64(pack.downloadSize)
try ModelDownloads.checkSpace(size, at: Self.base) // plus a 300 MB margin
try await Self.firstToEnd([
{
if #available(iOS 26.4, macOS 26.4, *) {
try await AssetPackManager.shared.ensureLocalAvailability(of: pack, requireLatestVersion: false)
} else {
try await AssetPackManager.shared.ensureLocalAvailability(of: pack)
}
},
{
var done = 0.0
for await update in AssetPackManager.shared.statusUpdates(forAssetPackWithID: pack.id) {
switch update {
case .downloading(_, let status):
done = status.fractionCompleted
progress(done, false)
case .paused:
// A pause for want of room comes without an error: make it one.
try ModelDownloads.checkSpace(Int64(Double(size) * (1 - done)), at: Self.base)
default:
break
}
}
while !Task.isCancelled { try await Task.sleep(for: .seconds(3600)) }
},
])
}
Three details took some time to get right.
The API moved twice within a year. In the iOS 27 SDK, AssetPackManager.assetPack(withID:) is deprecated in favor of manifest.assetPack(withID:), which returns an optional instead of throwing. The single-argument ensureLocalAvailability(of:) was renamed in 26.4 to ensureLocalAvailability(of:requireLatestVersion:). The app supports iOS 26, so both paths stay behind #available.
A full disk looks like a pause. When there isn't enough space, the system pauses the download and doesn't throw. Awaiting ensureLocalAvailability alone would leave the status line at 45% forever. So the progress loop runs its own space check on .paused and throws a notEnoughSpace error with the number of bytes missing, which the UI turns into "iPhone storage is full". The system's download keeps going once space frees up, and the app's setup retries by itself.
A task group would wait forever. The natural way to run both closures is withThrowingTaskGroup, cancelling the other child when one finishes. But a task group waits for every child, and the system's wait for a paused download may not return on cancellation. firstToEnd is a small helper built on a checked continuation and a lock: it resumes as soon as the first operation finishes or throws, cancels the rest and doesn't wait for them. It's about forty lines, and it's the difference between "storage is full" and a frozen setup.
Why the smallest model moved back into the app
The first design, on 7 October, had four packs, including speech-ultra with a prefetch policy. Two days later, Parakeet Ultra moved into the app bundle (SpeechModels.bundle, filled by package-models.py --bundle, checked by size and SHA-256, ignored by Git).
The reason is the first minute. A prefetched pack starts with the install, but it isn't guaranteed to be there when the app first opens, and the app's whole point is to record a class. With Ultra in the bundle, local transcription works right after installing, on any device, while the bigger models arrive in the background. It also works in places where packs never arrive: development builds, and ClamNotes for Mac downloaded from my website. Apple-hosted packs are only for apps installed from the App Store or TestFlight, so the website build of the Mac app gets the other models from Hugging Face.
The cost is about 0.6 GB on every install. The 0.7 (12) upload, with Ultra inside, was 588 MB. That's a trade I'd make again for one small model that works everywhere, and I wouldn't make it for the large ones.
Moving a model between sources needs a migration: at launch, the app deletes an older downloaded copy of Ultra once the bundled one is there.
The fallback you'll need anyway
Even with Apple hosting, I kept a direct download path. It covers the website Mac build, development builds without a test server, and the window between shipping a build and getting its packs processed. It uses the same Hugging Face repositories and commits the packs are built from:
- A background
URLSession, so it continues while the app is suspended. One model at a time, all of its files at once. allowsExpensiveNetworkAccess = false, so it waits for Wi-Fi rather than using cellular data. The status line says waiting for Wi-Fi.- Resumes from
resumeDataand retries each file up to 5 times at growing intervals. - A free-space check first (the model plus a 300 MB margin, since Core ML also writes what it optimizes to disk), each file's size checked, and the
Modelsfolder set toisExcludedFromBackup.
To test packs before uploading them, Apple provides a local server, xcrun ba-serve, which serves your .aar files over HTTPS with a certificate your test device must trust (Testing asset packs locally). On iOS you enter its URL under Settings, Developer, Development Overrides. On a Mac, use xcrun ba-serve url-override. I haven't run the iPhone side of this yet. Until now the fallback has been my development path, which is also why the build 9 bug got through: in development, the pack path never ran.
What I'd tell myself on day one
- One model per pack, one folder per pack. The namespace is shared and collisions are undefined. Name the folder after the pack ID and the problem goes away.
- Never trust a path from
url(for:). Check a file you know is in the pack, and the model's main file too. - Treat "paused" as a possible error. Check disk space yourself and give the person a number.
- Don't await the system's download in a task group. Race it against your own status handling and stop waiting when either ends.
- Make the extension's answers explicit and keep them current. It runs without your app, so write its inputs to the App Group at every launch.
- Bundle the one model that must work at first launch. Use packs for the rest.
- Pin your inputs and your tools. Record the Hugging Face commit in each pack's sources file, check hashes, and build with the release Xcode.
- Test the state you can't see. A fresh install, on the smallest device tier, with no packs available.
Built for ClamNotes
This pipeline ships the speech models ClamNotes uses to transcribe a class on the device, in 25 languages.
ClamNotes records a class, transcribes it on the device and writes a study note in the language that was spoken. For iPhone, iPad and Mac.
See ClamNotes