Core ML16 min read

My Core ML model crash-looped an iPhone 11: the Neural Engine's first-load memory spike

Planning a speech model for the Neural Engine took my app from 48 MB to its memory limit in ten seconds. Jetsam killed it, the next launch tried again, and no crash report ever said why.

On 13 October my iPhone 11, the oldest and smallest iPhone my app runs on, could not get past the app's introduction. The app opened, showed its first screen, and about ten seconds later it was gone. Open it again: same thing. With the console attached, the only last word was App terminated due to signal 9. No exception, no crash report, and nothing in my own log file, because the code that writes the log never got a chance to run.

The app is ClamNotes, which records a class and transcribes it on the device. The transcription runs on Core ML speech models of 0.6 to 1.9 GB, and the first one loads during the introduction so it is ready by the first recording. This post is about what that first load does to memory on an older iPhone, how I proved it, and the two small pieces of code that keep it from happening again.

A crash loop with no crash log

An app that dies at launch with no crash report is almost always one of two things: the watchdog (the app took too long to draw its first frame) or jetsam (the app used more memory than iOS allows it). Both end the process from the outside. The difference is in which report the system writes, and you have to go and collect it yourself.

Over USB, devicectl can copy the device's diagnostic reports to the Mac. That folder had what I needed: a series of JetsamEvent-2026-10-13-*.ips files, one per launch, each naming my app as largestProcess and giving it the reason per-process-limit, at about 2.4 GB of resident memory. The phone has 4 GB in total. The app already had the increased memory limit entitlement, so that was the raised limit, not the default one.

So it was memory, and it was big. The question was what took 2.4 GB in an app whose introduction is a few SwiftUI screens.

What the memory log showed

A process that is killed with SIGKILL cannot write a last log line, so I needed something that writes continuously and survives. I added a Debug-only sampler that appends the app's footprint and the memory iOS still allows it to a file every two seconds. The footprint is phys_footprint from task_info, the number iOS counts against the limit; the remaining allowance comes from os_proc_available_memory().

MemoryFootprint.swift
import Darwin
import os

public enum MemoryFootprint {
    /// What iOS counts against the app's memory limit.
    public static var bytes: UInt64 {
        var info = task_vm_info_data_t()
        var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
        let result = withUnsafeMutablePointer(to: &info) {
            $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
                task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
            }
        }
        return result == KERN_SUCCESS ? info.phys_footprint : 0
    }

    /// What iOS still lets the app take. Nil where there is no limit (a Mac).
    public static var available: UInt64? {
        #if os(iOS)
        UInt64(os_proc_available_memory())
        #else
        nil
        #endif
    }
}

The next launch left this in the file (the times are seconds after launch):

Diagnostics/memory.log
launch 14:52:22.035
14:52:24.037 footprint   48 MB, available 2299 MB
14:52:26.037 footprint  648 MB, available 1699 MB
14:52:28.036 footprint 1241 MB, available 1106 MB
14:52:30.036 footprint 1847 MB, available  500 MB
14:52:32.037 footprint 2287 MB, available   60 MB

About 600 MB every two seconds, in a straight line, until there was nothing left. The app's own log showed what started at the beginning of that line: the first load of Parakeet, the speech model that ships inside the app, about 0.6 GB on disk, with computeUnits = .cpuAndNeuralEngine.

0 500 1000 1500 2000 MB 0 s 2 4 6 8 10 12 limit ≈ 2347 MB guard marks “near” below 1/6 left killed Neural Engine, first load CPU only: 54 to 112 MB
Figure 1. The app's footprint after launch on an iPhone 11 (iOS 27), sampled every two seconds. Red: the first load of a 0.6 GB model with .cpuAndNeuralEngine; the limit is the footprint plus os_proc_available_memory() at launch. Grey band: the range the app's log reported for the same model with .cpuOnly, 54 to 112 MB, from separate runs.
~600 MB
growth every two seconds during the Neural Engine load
2322 MB
what os_proc_available_memory() allowed at the first load
54–112 MB
the app's footprint with the same model on the CPU alone

Why the first Neural Engine load is special

A compiled Core ML model (.mlmodelc) is not yet something the Neural Engine can run. The first time you load it with the Neural Engine allowed, Core ML plans it for that specific chip and OS version, and caches the result so later loads are quick. For these speech models that step can take minutes and happens once per iOS version, which is why the app shows an "optimizing" state the first time and never again until the next OS update.

Apple's documentation for classic Core ML says little about this step. The newer Core AI framework documents the same idea plainly: its article on managing model specialization and caching describes specialization as producing code "tied to that device's hardware and OS version", cached after the first call, and always invalidated on an OS update. Two consequences matter for memory:

  • The expensive load is rare. You don't see it in day-to-day testing on your own phone, because your cache is warm. A fresh install, a new OS version or a cleared cache brings it back.
  • Its peak happens inside your process. The memory that grew in the log above was counted against my app's limit, not against some system daemon.

Why so much memory? I measured it rather than found it documented. The model's weights are INT8, and the app grew to about four times the size of its weight.bin files. My guess is that the weights are expanded to 32-bit floats while the plan is built, since INT8 to FP32 is exactly a factor of four, but Apple doesn't document it. Loaded on the CPU alone, the same model added only tens of megabytes; my reading is that Core ML maps the weight files there instead of copying them. Both are inferences from one model on one device. I treat "four times the weights" as a working estimate, not a law, and the code is written so a wrong estimate costs one launch, not every launch.

Telling a jetsam kill from a crash

Apple's article on identifying high-memory use with jetsam event reports has the details. In short:

  • A jetsam event report is a separate file, JetsamEvent-<date>.ips. It is JSON, it lists the memory of every process on the device, and it has no backtraces of your threads. In my case there was no crash report next to it at all.
  • Only the process that was killed has a reason key. per-process-limit means your app crossed its own limit. vm-pageshortage means the system needed memory for the foreground app and took it from a background one, which is a different problem.
  • Memory is in pages: multiply rpages by the header's pageSize.

This script prints the killed process from every report in a folder:

jetsam.py
# A minimal example: python3 jetsam.py device-logs/JetsamEvent-*.ips
import json, sys

for path in sys.argv[1:]:
    with open(path) as f:
        f.readline()                    # the first line is a small header of its own
        report = json.loads(f.read())
    page = report.get("pageSize", 16384)
    print(path, "largest:", report.get("largestProcess"))
    for process in report.get("processes", []):
        if "reason" in process:         # only the killed process has one
            mb = process["rpages"] * page / 1_048_576
            print(f"  {process['name']}: {process['reason']}, {mb:.0f} MB, {process.get('states')}")

In the field, without a cable, MetricKit counts the same thing: MXAppExitMetric reports cumulativeMemoryResourceLimitExitCount for foreground exits, once a day. It tells you that it happens and how often, not where. For where, you need the app to have written something down before it died, which is the second half of the fix.

The watchdog that followed the jetsam

Some launches after a kill died differently: a regular crash report with EXC_CRASH (SIGKILL) and the termination code 0x8BADF00D, "scene-create watchdog transgression", the app having used its 17.33 seconds of wall-clock time without drawing a first frame. Apple's guide to addressing watchdog terminations explains the two CPU lines in that report. Mine read 80% of the CPU for the whole system and 1% for my app. The app wasn't busy; the device was. The system's Neural Engine compiler service was still working on the plan the dead process had asked for, and the phone's thermal state was serious. So a memory problem can surface as a launch-time watchdog crash on the following launch, with a backtrace that points at whatever SwiftUI happened to be doing. If you see 0x8badf00d with low application CPU time right after jetsam events, look at the jetsam first.

The fallback that couldn't run

Here is the embarrassing part. The code already had a CPU fallback. Some chips refuse certain INT8 models on the Neural Engine (on an A15 the load fails with "ANE model load has failed"), so the load looked like this:

UltraTranscriber.swift
// simplified
do {
    loaded = try await models(.cpuAndNeuralEngine)
} catch {
    log.warning("Did not load on the Neural Engine, so on the CPU: \(error)")
    loaded = try await models(.cpuOnly)
    onCPU = true
}

That handles a load that fails. Jetsam doesn't make a load fail. It ends the process with SIGKILL, which cannot be caught: no catch block, no defer, no applicationWillTerminate. And the record that a model had been set up on this device was written only after a successful load. So every launch looked like the first one, started the same load in the introduction, and died at the same point.

The repair needed two things the old code didn't have: a way to avoid the load when it obviously won't fit, and a way to learn from a load that died without a word.

Check the budget before the load

The first half is a pre-flight check. Before the first load of a model, the app estimates what planning it for the Neural Engine will take, from the size of its weights on disk, and compares that with what iOS will still allow:

LocalTranscriber.swift
/// What planning a model for the Neural Engine may take at its first load:
/// about four times an INT8 model's weight files, plus a margin.
static func neuralEnginePeak(_ folder: URL) -> UInt64 {
    weightBytes(folder) * 4 + 200_000_000
}

/// Why a first load goes straight to the CPU; nil when the Neural Engine is tried.
private func neuralEngineRuledOut(_ engine: SpeechEngine, _ found: ModelFiles) -> String? {
    if endedOnNeuralEngine(engine) {
        return "iOS ended the app for its memory while it was planned for the Neural Engine."
    }
    guard let available = MemoryFootprint.available else { return nil }   // a Mac: no limit
    let peak = Self.neuralEnginePeak(found.folder)
    guard available < peak else { return nil }
    return "planning it takes about \(peak / 1_048_576) MB, and \(available / 1_048_576) MB is allowed."
}

weightBytes just adds up the sizes of the weight.bin files inside the model folders. On the iPhone 11 the log now says, before anything is loaded:

Console
[speech] ultra is loaded on the CPU alone: planning it for the Neural Engine takes about 2597 MB, and 2322 MB is allowed.
[speech] ultra loaded on the CPU alone; 89 MB in use.
[speech] ultra takes 2.69 s on the CPU alone.

A few details matter here.

  • Ask at the moment of the load, every time. os_proc_available_memory() returns the current limit minus the current footprint, and Apple's documentation says to treat it as advisory and not to cache it, since limits can change during the app's life. It also returns 0 once you're over the limit, which this check reads correctly as "doesn't fit".
  • Measure the model, don't list devices. I never compare device names. The same check sends the bigger Canary model to the CPU on 6 GB iPhones without a line of device-specific code, and it will keep working for devices that don't exist yet.
  • It only guards the first load. Once a plan is cached, later loads don't build it again. But the cache can disappear, and the app treats every OS update as a cleared cache, so the check runs again whenever a plan has to be built, not just on a fresh install.

A guard that survives SIGKILL

The pre-flight check is an estimate, and estimates are wrong sometimes: another model is already in memory, the system is under pressure, a new OS needs more. So the second half assumes the check can miss and makes sure a miss is paid for once.

The pattern is old: write a marker before the risky operation, clear it after. If the next launch finds the marker, the operation never finished. The interesting part is telling why it didn't finish. People swipe apps away during long loads, and a debugger stop looks the same from the outside. Losing the Neural Engine for good on this device because someone swiped the app away would be a bad trade. So while the load runs, a separate task watches the memory and adds "near" to the marker once the app gets close to its limit.

Launch N Launch N + 1 Write marker to disk ultra-loading = os/build|ane Load, Neural Engine allowed watch polls every 250 ms Near the limit marker += "|near" Jetsam: SIGKILL no catch, no defer: marker stays Read markers at start same OS and build, and "near"? Record the outcome ultra-ended-ane = os/build Load with .cpuOnly marker written and cleared again Ready retried after an OS or app update
Figure 2. The load guard. The marker lives in a small JSON file written atomically; the next launch turns a marker that was marked "near" into a permanent note for that OS version and app build, and a marker without "near" into nothing.

Here is the guard, trimmed a little. Every model load goes through it, on the Neural Engine and on the CPU:

LocalTranscriber.swift
// simplified
private func guarded<T>(_ engine: SpeechEngine, onCPU: Bool,
                        _ load: () async throws -> T) async throws -> T {
    let key = markerKey(engine) + "-loading"
    let value = "\(Self.systemAndBuild)|\(onCPU ? "cpu" : "ane")"
    Self.save { $0[key] = value }               // on disk before the load starts
    let watch = Task.detached(priority: .high) {
        while !Task.isCancelled {
            if Self.nearLimit {
                Self.save { $0[key] = value + "|near" }
                return
            }
            try? await Task.sleep(for: .milliseconds(250))
        }
    }
    defer {
        watch.cancel()
        Self.save { $0[key] = nil }             // runs for success and thrown errors, never for SIGKILL
    }
    return try await load()
}

/// Less than a sixth of what iOS lets the app take is left, or under 300 MB.
static var nearLimit: Bool {
    guard let available = MemoryFootprint.available else { return false }
    let limit = available + MemoryFootprint.bytes
    return available < max(300_000_000, limit / 6)
}

And this runs once per launch, before any model loads:

LocalTranscriber.swift
// simplified
static let endedLoads: Void = {
    save { saved in
        for (key, value) in saved where key.hasSuffix("-loading") {
            saved[key] = nil
            let parts = value.components(separatedBy: "|")
            // Only a load that died near the limit, on this OS and this build, counts.
            guard parts.count == 3, parts[0] == systemAndBuild, parts[2] == "near" else { continue }
            let model = String(key.dropLast("-loading".count))
            saved[model + "-ended-" + parts[1]] = systemAndBuild    // "-ended-ane" or "-ended-cpu"
        }
    }
}()

The choices behind those few lines:

  • A file I write myself, atomically. The markers live in a small JSON file saved with Data.write(to:options: .atomic) behind a lock, because the watch task writes it from outside the actor. I wanted a write that is on disk before the load starts, with nothing in between that I would have to reason about.
  • Poll faster than memory grows. At 600 MB per two seconds, the app goes from the "near" threshold (a sixth of about 2.35 GB, roughly 390 MB) to the limit in a little over a second. A 250 ms poll gets several chances in that window; a two-second one might get none.
  • Key the verdict to the OS version and the app build. A new iOS can change the Neural Engine compiler and always rebuilds the plan, and a new app build can bring a different model. Either one gets a fresh try.
  • Guard the CPU path too. If a model dies near the limit both ways, it is left out at once and the other models carry on, instead of the app trying again forever.

To test it, I added a Debug-only launch argument that skips the pre-flight check and goes to the Neural Engine regardless. On the iPhone 11 the forced launch's last memory sample read 2034 MB with 313 MB left, below the threshold, and then it was killed. The next launch logged "iOS ended ClamNotes for its memory while ultra loaded (ane); not loaded that way again on this OS and build". That launch then hit the watchdog described above, and the one after it was ready on the CPU without another attempt on the Neural Engine.

Choosing compute units per device

MLComputeUnits has four cases: .all, .cpuOnly, .cpuAndGPU and .cpuAndNeuralEngine. The app never uses the GPU: it transcribes while the iPhone is locked, and iOS doesn't let apps use the GPU in the background. Apple's own description of .cpuOnly mentions this case, an app that "might run in the background". That leaves two choices, and the app makes the choice per model, from evidence, in this order:

EvidenceChoice
A load on the Neural Engine ended the app near its limit on this OS and build.cpuOnly, no new attempt
Four times the weights plus 200 MB exceeds os_proc_available_memory().cpuOnly from the first load
The Neural Engine load or the first run throws (as INT8 encoders can on an A15).cpuOnly
It loads, but 15 s of test audio takes more than 3 stimed on the CPU too, the faster kept
Otherwise.cpuAndNeuralEngine

The timing rule exists because "it loaded" is not the same as "it runs on the Neural Engine". Core ML can quietly place parts of a model on the CPU, and a model that takes far longer than the Neural Engine would is better off on the CPU in a mode I control. The choice and the time are saved with the OS version, so a second launch doesn't repeat any of this.

On the iPhone 11 the CPU turned out to be a perfectly good place for this model: 2.02 to 2.69 seconds for 15 seconds of audio in my logs, set up 22 to 33 seconds after its first load began, and a footprint around 100 MB instead of a dead app. It also changed a background rule: the app now unloads its models in the background only when it takes more than 500 MB, so a model on the CPU, which costs little, stays loaded and doesn't have to load again when the person comes back.

Testing on old hardware

None of this showed up in the Simulator or on my newer iPhones, where the cache was warm and the memory limit far away. You need a cold first load on the smallest device you support. What made it quick to repeat:

  1. Keep a minimum-spec device and reset its state from a launch argument. A Debug-only argument deletes the app's record of which models were set up, so every launch is a first launch without reinstalling a 1 GB app. A second argument forces the Neural Engine, to watch the guard work.
  2. Pull the system's reports over USB. devicectl copies jetsam reports and crash reports from the device, and files from the app's container, without Xcode's UI.
  3. Log memory to a file, not just the console. The sampler writes every two seconds with the file opened, appended and closed each time, so a SIGKILL loses two seconds at most.
  4. Launch from the terminal with the console attached. You see your os_log lines live, and the line before the kill tells you which load was running.
Terminal
# The device's identifier comes from: xcrun devicectl list devices
DEVICE=<device id>
APP=<your bundle id>

# Jetsam and crash reports
xcrun devicectl device copy from --device "$DEVICE" \
  --domain-type systemCrashLogs --source / --destination ./device-logs

# The app's own memory log
xcrun devicectl device copy from --device "$DEVICE" \
  --domain-type appDataContainer --domain-identifier "$APP" \
  --source "Library/Application Support/MyApp/Diagnostics" --destination ./app-logs

# Launch as a first launch, console attached, with Debug-only arguments
xcrun devicectl device process launch --device "$DEVICE" --terminate-existing --console \
  -- "$APP" -MyAppDebugFreshSetup YES     # your own Debug-only argument

One more lesson from the old phone: an iPhone 11 that was just killed is not a neutral test device. The compiler service from the dead process can keep the CPU busy and the phone warm for a minute or more, which is exactly how I got the watchdog crash above. Wait for it to settle between runs, or you'll chase a second bug that only exists in your test loop.

Takeaways

  • The first Core ML load with the Neural Engine allowed is a different operation from every later load. Test it cold, on your smallest device, after an OS update.
  • A launch-time death with no crash report is jetsam or the watchdog until proven otherwise. JetsamEvent reports with per-process-limit next to your app's name settle it.
  • catch can't handle what SIGKILL does. For any load that might be killed, write a marker before and clear it after, and decide at the next launch.
  • Check os_proc_available_memory() against the load's likely peak at the moment you choose MLComputeUnits, and don't trust the device's RAM or the increased memory limit entitlement to make that call for you.

Built for ClamNotes

The speech models in ClamNotes now pick the Neural Engine or the CPU on each device, down to a 4 GB iPhone 11.

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

Artur BerkovicsI build ClamNotes, a note-taking app for students, on my own: the iPhone, iPad and Mac apps, the relay behind them and the website. I write about what broke and how I fixed it.