Skip to content

feat(coreml): SmolLM2 example from the Hugging Face checkpoint to iOS and watchOS - #384

Draft
matthargett wants to merge 11 commits into
rustnn:mainfrom
rebeckerspecialties:feat/smollm2-coreml-example
Draft

matthargett wants to merge 11 commits into
rustnn:mainfrom
rebeckerspecialties:feat/smollm2-coreml-example

Conversation

@matthargett

@matthargett matthargett commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #383 (SmolLM2 float16 needs the compressed constants to load on a phone). Only the last commit belongs to this PR; draft until #383 lands.

Summary

The SmolLM2 numbers in #382 and #383 came from a model bundle and a harness that were never published, so nobody else could repeat them. This PR puts the whole path in the repository: from the Hugging Face checkpoint to a receipt on a Mac, an iPhone and an Apple Watch.

  • examples/smollm2_coreml reads HuggingFaceTB/SmolLM2-135M-Instruct's model.safetensors, quantizes the weights and authors the single-token decode graph with MLGraphBuilder. No Python, no ONNX export, no prebuilt model. It saves the graph as .webnn, compiles it through MLContext, carries the key/value window as an MLState or as tensors, and prints a receipt: build time, decode rate, peak resident memory, token hash.
  • examples/smollm2_coreml_device is the same program as a static library. scripts/apple_device_app.py links it with a small SwiftUI host (scripts/apple_device_host.swift), signs the app, installs it with devicectl, launches it and fetches the receipt. An app has to run the system's application loop; a bare Rust binary gets as far as loading weights on watchOS and is then killed.
  • The CoreML runtime now links for watchOS, tvOS and visionOS with the published crates. The shim defines objc_msg_lookup and objc_msg_lookup_super, which objc 0.2 calls outside macOS and iOS, and build.rs provides the empty BlocksRuntime library block 0.1 asks for there. docs/integration/coreml.md used to tell users to patch objc; that is no longer needed.
  • docs/user-guide/smollm2-on-apple-devices.md has the commands, the checkpoint revision and hash, and the reference runs.

Does it reproduce the earlier numbers?

Yes, for the Mac and the A13.

  • Quantizing the checkpoint with the recipe in author.rs gives the earlier bundle's embedding, projection and norm tensors bit for bit (checked with numpy against the old graph.safetensors).
  • With the earlier prompt tokens and 64 greedy tokens, the token hash equals the earlier receipts: 2db53a2d95685f0b through a compiled bundle and e2b450fbb2d994c6 through the in-memory load.

2026-11-17, CPU, one run per row unless a range is given:

Device Carry, route Build Rate Peak resident Token hash
MacBook Pro M4 Max, macOS 27.3 state, auto 1.1 s 374 tok/s 890 MiB 2db53a2d95685f0b
state, export 0.8 s 348 tok/s 883 MiB 2db53a2d95685f0b
tensors, export 0.8 s 287 tok/s 880 MiB 2db53a2d95685f0b
tensors, auto 5.8 s 55 tok/s 994 MiB e2b450fbb2d994c6
iPhone SE 2nd gen (A13), iOS 26.7.1 state, auto 4.6 to 5.0 s 41 to 52 tok/s (2 runs) 672 to 819 MiB 2db53a2d95685f0b
state, export 4.3 s 43 tok/s 730 MiB 2db53a2d95685f0b
tensors, export 4.2 s 43 tok/s 745 MiB 2db53a2d95685f0b
tensors, auto 8.7 s 23 tok/s 843 MiB e2b450fbb2d994c6
iPhone XS Max (A12), iOS 18.7.10 tensors, export 3.4 s 23 tok/s 724 MiB 2db53a2d95685f0b
tensors, auto 9.9 s 19 tok/s 841 MiB 2db53a2d95685f0b
Apple Watch Series 10, watchOS 27.2 state, auto, two-layer cut, 16 tokens 0.7 s not timed 215 MiB deb9a7079c2fa62e, as on the Mac

The Mac builds faster than in #383 (1.1 s against 2.6 s) because the authored graph has no redundant casts; the rates are the same within run-to-run spread.

What does not work yet

  • The full model does not fit an Apple Watch. On the Series 10 the process is killed while the model loads. An app there was granted 299 MiB when I measured it on 2026-10-30; I did not pull a jetsam report. On the M4 the physical footprint is 304 MiB after the graph load, 626 MiB at the peak of the build and 319 MiB while decoding, for 142 MB of weights. While decoding, 9 MB of the heap is in use; the rest is freed memory the allocator has not returned, and Core ML's weights are a clean mapped file. So the limit is rustnn's transient copies: the loader holds the file and the per-tensor constants at once, and the build adds a clone of the graph and the weights blob. That needs constants that stay file-backed through load, conversion and export, which I will propose as a separate PR after this one; it touches ConstantData, the loader and WeightFileBuilder, not the example. A two-layer cut (--layers 2, 157 MiB peak on the M4) does run on the watch end to end with the Mac's tokens, which is what validates the link fixes, the export route and the state carry there. The watch suspended the app while its screen slept, so that run is not timed.
  • --carry state fails to load on iOS 18.7.10 (A12) with Core ML error -14, also for the two-layer cut. --carry tensors works there. feat(coreml): carry recurrent state in Core ML MLState #382 was validated on iOS 26.7.1 and macOS 27.3 only. I have not found the cause.
  • psm does not assemble for watchOS without CFLAGS_aarch64_apple_watchos=-DCFG_TARGET_OS_ios. It comes in through pest 2.9.4 and the .webnn parser. The page documents the define. The fix is proposed upstream in psm: select Mach-O assembly for watchOS and visionOS rust-lang/stacker#162.
  • With the default chat prompt and repetition penalty 1.1 the Mac and the A13 give different replies after the first tokens (2a52fbf63c0ee2a3 and 043aec35f9f94560). Both are coherent. The fixed prompt above agrees on every device.
  • arm64_32 watches (Apple Watch SE 2nd gen), GPU and Neural Engine requests were not tried.

Notes for review

  • libc is a new dev-dependency (for getrusage); it was already in the lock file.
  • The receipt records the physical footprint per phase as well as peak resident size, since resident size counts Core ML's mapped weights and the system does not.
  • Both examples need native-examples and coreml-runtime, so the default build and the Linux checks do not compile them.
  • The objc_msg_lookup definitions are compiled only when the target is neither macOS nor iOS. class_getMethodImplementation returns the runtime's forwarding entry for an unimplemented selector, so doesNotRecognizeSelector: still fires; objc checks nil receivers before the lookup.

Validation

  • cargo test --no-default-features --features native-examples,coreml-runtime,coreml-export,dynamic-inputs: 3342 passed, 0 failed.
  • CoreML WPT on the M4: 2590 passed, 0 failed, 104 ignored.
  • cargo fmt --check and clippy with -D warnings clean; cargo check with default features and with coreml-converter alone pass.
  • Device builds: aarch64-apple-ios and aarch64-apple-watchos with Rust 1.98.
  • MkDocs was not built locally.

matthargett and others added 11 commits November 17, 2026 00:07
Problem: a decode step of a recurrent or attention model returns its state
(KV cache, recurrent state, convolution history) as graph outputs and takes
it back as graph inputs, so every dispatch crosses the host boundary with
those arrays. Core ML can keep such state inside the model as an MLState
(`read_state` / `write_state`, iOS 18), and there was no way to emit it. The
MIL function also still used the CoreML7 opset although every model already
declares specification version 9.

Change:
- `CoremlOptions::carried_state_pairs` lists `(input, output)` names and
  `CoremlOptions::carry_state_automatically` pairs by naming convention
  (`X`/`next_X`, `past_X`/`present_X`, `X_in`/`X_out`). Both default to off.
  `converters::coreml_state` validates and detects pairs: same float16 or
  float32 type, same static shape.
- `CoremlMlProgramConverter::convert_with_carried_state` declares each paired
  input as a `state<tensor<fp16, ...>>` function input, feeds its consumers
  from `read_state`, stores the paired output with `write_state` and lists
  the pair under `ModelDescription.state`. Core ML accepts only float16
  state storage, so float32 pairs are cast on the way in and out. A graph
  whose float16 lowering needs Pipeline children cannot carry state and is a
  conversion error.
- Every emitted function uses the CoreML8 opset (`MIL_OPSET`). The
  deployment floor is unchanged: specification version 9 already means
  iOS 18 / macOS 15 / watchOS 11.
- The backend creates one MLState per graph, predicts with
  `predictionFromFeatures:usingState:`, removes the paired names from the
  dispatch bindings, reports them in
  `CoremlLoadDiagnostics::carried_state_pairs` and resets with
  `MLGraph::rustnn_reset_state`. A stateful program skips the in-memory
  asset, which refuses to plan one (error -14 on macOS 27.3), and compiles
  from a URL.
- The compiled-bundle cache key includes the pairs and, for exported
  bundles, `mlmodelc_export::VERSION`. `mlmodelc-export` moves to 0.2, which
  writes state inputs, `write_state` and `stateSchema`.
- `MLBackendGraph::CoremlModel` is boxed (clippy large_enum_variant).
- `examples/coreml_kv_benchmark` gains a `state` mode checked against the
  same oracle.

Validation (M4 Max, macOS 27.3 26C5035r, rustc 1.97.0):
- fmt; clippy -D warnings with `coreml-runtime,dynamic-inputs` and with
  `coreml-export` added (plus -A clippy::useless_conversion, which fires on
  main in src/operation_type_support.rs); rustdoc -D warnings; operator
  report check.
- `cargo test --no-default-features --features
  coreml-runtime,coreml-export,dynamic-inputs`: 3346 passed, 0 failed
  (488 library tests); without `coreml-export`: 3339 passed.
- CoreML WPT, 2590 passed / 0 failed / 104 skipped in each of: default
  route with native float16, default route with exact float16, Rust export
  route with exact float16.
- New tests: pair detection and rejection; the stateful protobuf (state
  input, read_state, write_state, state feature) for float16 and float32;
  equal decoded models without pairs; the Pipeline rejection; a three-step
  recurrence on the Core ML runtime equal to the host round trip through
  the byte and native tensor paths, the Rust export route and a cache miss
  then hit; reset; a tensor bound under a carried name is rejected.
- TinyStories-8M float16 (16 float16 KV pairs, 4.2 MB per step), CPU, 128
  greedy tokens, both modes loaded through the Rust export route: iPhone SE
  2nd gen (A13, iOS 26.7.1 23H30) 172.6-173.6 tok/s with tensors bound and
  442.6-452.0 tok/s with state, three runs each; M4 Max 1154 and 1583
  tok/s, one run each. All runs produce the same tokens on both devices.

Not run locally: `make ci-docs` (no MkDocs here), the default-feature build
and the non-Apple feature checks (disk).
Problem: the C and C++ API check failed on rustnn#382 because the generated
rustnn.h declared rustnn_coreml_new_state and rustnn_coreml_predict_stateful,
whose Objective-C Object parameters are not a C type. The other CoreML shim
functions are listed in the cbindgen exclude list; the two new ones were not.

Change: add both to the exclude list, and gate their non-Apple stand-ins on
target_vendor like the existing ones.

Validation: cbindgen --config cbindgen.toml --crate rustnn produces a header
with no Object or shim declarations (the previous config reproduces the
failing declarations); cargo fmt --check and cargo check with
coreml-runtime,dynamic-inputs pass.
Problem

Quantized language-model graphs author each weight matrix as a constant
dequantization chain: an int8 or uint8 constant [n, k], cast to float16 or
float32, an optional sub of a scalar zero point, reshape to [n, g, w], mul
by a [n, g, 1] scale, reshape back to [n, k]. The CoreML converter lowered
each of these operations literally, so Core ML evaluated the chain into a
float copy of every weight while compiling or loading the model. A
SmolLM2-135M float16 graph (210 uint8 matrices and one int8 table) took
26 s and a 5.8 GB peak to build through the URL compiler on an M4 Max,
and does not load under a 2 GiB process limit.

Change

- New prepass src/converters/coreml_blockwise.rs, run after the constant
  fold on the same copy of the graph. It recognizes the chain in the
  GraphInfo (operand names and architecture do not participate), replaces
  it by one dequantizeLinear over constants (stored data, a [n', g'] scale
  in the chain's float type, an offset of that shape in the stored type
  for a nonzero zero point) and marks its output. Every intermediate must
  be read by the chain alone and must not be a graph output, the zero
  point must be an integer in the range of the stored type, the scale
  must be finite and constant inside a block; anything else keeps the
  literal lowering. An authored dequantizeLinear keeps its own lowering.
- The lowering emits a marked dequantizeLinear as MIL
  constexpr_blockwise_shift_scale with its parameters bound to const
  operations, so the weights blob keeps the int8/uint8 bytes.
- Readers. Core ML evaluates a matmul over a constant weight with another
  kernel than a matmul over a weight computed at run time. Through the
  URL compiler both return the same bits; on the in-memory route, which
  evaluates the literal chain and its transpose on every dispatch,
  float16 results differ in rounding (measured: the logits of the model
  above, and a near-tied greedy choice that flips at the seventh
  generated token). So a program that carries state, which always
  compiles from a URL, reads the constant in matmul with
  transpose_y = true and omits the transpose when only such matmuls read
  it; a stateless program keeps the transpose over the constant. A table
  shared by a gather and an output projection is one stored constant in
  both cases.
- The exact float16 lowering of a graph with float16 operands is
  excluded: in its Pipeline the compressed constant returned +0 where the
  literal chain returns -0 (zero difference or zero scale with a negative
  sign; macOS 27.3, CPU). Without a float16 operand the exact lowering is
  the native one and takes the rewrite.
- New constants are appended to the operand table in chain order, so the
  weights blob stays the same bytes on every conversion. The new source
  file is part of the compiled-bundle cache key (build.rs).
- Docs: converters.md (CoreML lowering rules), integration/coreml.md
  (Quantized constant weights), CHANGELOG.

The constant is fl((q - zero) * scale), rounded once in the chain's float
type, as in the literal chain; the module documentation has the argument.

Validation (M4 Max, macOS 27.3, --no-default-features
--features coreml-runtime,dynamic-inputs)

- cargo fmt --check; cargo clippy --all-targets -- -D warnings
  -A clippy::useless_conversion: clean.
- cargo test: 36 targets, 0 failed; lib 511 passed (25 new in
  coreml_blockwise).
- tests/test_coreml_blockwise_constants.rs runs the rewritten and the
  literal graph on the Core ML runtime and compares the bits of the
  constant with fl((q - zero) * scale) for float16 and float32, uint8
  with zero points 128 and 255, int8 with zero points 0, -5 and none,
  every byte value against 16 scales (both signs, subnormal products, a
  zero scale), as a stateless program in memory and through the URL
  compiler and as a program that carries state; the exact float16
  lowering is checked to keep the literal chain.
- CoreML WPT: 2590 passed, 104 skipped, 0 failed (unchanged).
- RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --lib: clean; operator
  support report: no drift.
- SmolLM2-135M float16, 64 greedy steps, CPU. Carried state (URL route):
  build 26 s -> 1.2 s, peak RSS 5.76 GB -> 0.92 GB, 366 -> 346 tok/s.
  Stateless (in-memory route): build 1.0 s -> 6.6 s, peak RSS 2.52 GB ->
  2.01 GB, 2.2 -> 2.8 tok/s. Same tokens in both, and the logits of the
  first and the seventh generated step are bit-identical to the literal
  lowering on each route. GPU and Neural Engine requests with carried
  state return the same tokens.
- A float16 graph without integer constants (TinyStories) returns the
  same tokens.
…use unusable pairs

Problem (review of rustnn#382):
- A float32 pair whose new state is also a model output returned zeros when
  the state was produced by add (next_s = add(s, x), h = identity(next_s),
  and gruCell with out = identity(h_out)). The emitted MIL is correct; the
  same bundle run from Swift returns zeros too, on CPU, GPU and all units
  (macOS 27.3; reported on 26.7.1). sub, maximum and tanh are unaffected,
  and so is a value with another consumer before the output.
- A pair whose output is a plain copy of a graph input, and pairs that
  cover every graph output, passed validation and failed in the build with
  an internal error ("invalid proven output", "Models must have one or more
  outputs").

Change:
- When the stored float32 value is also a block output, after proven copies
  are coalesced, write_state narrows mul(value, 1.0) instead of the value.
  The multiplication is exact and keeps the two uses apart.
- converters::coreml_state refuses a pair whose output is a proven copy of a
  graph input and the pair that would leave the graph without an output.
  Explicit pairs are errors that name the pair; the automatic mode skips
  them, so the last candidate in graph input order stays an output. The
  converter entry point checks the output coverage as well.
- Docs: the CoreML integration page and the converter guide describe both.

Validation (M4 Max, macOS 27.3): fmt; clippy -D warnings with and without
coreml-export; cargo test with coreml-runtime,coreml-export,dynamic-inputs
3350 passed, 0 failed (492 library tests); CoreML WPT 2590 passed, 0 failed,
104 skipped; rustdoc -D warnings. New runtime test compares a returned state
with the host round trip for add, sub and gruCell and fails for add with the
copy disabled; new tests for the emitted copy, the copy pair and the
all-outputs pair, explicit and automatic.
Problem (review of rustnn#383):
- The transposed matmul reader used transpose_y only in a program that
  carries state, as a proxy for the URL route, on the claim that outputs
  stay bit-identical to the literal lowering there. They do not on every
  system (reported: macOS 26.7.1, CPU, float16, a [8192, 576] table and one
  token), and gemm and matmul without a transpose already read the
  constant directly in a stateless program.
- The runtime test fed matmul the identity matrix, so every product was
  one weight times 1.0 and exact under any kernel.
- The docs said the chain was evaluated at compile or load time. That is
  the URL route; in memory it was evaluated on every dispatch, and the
  compressed constant moves that cost into the load.

Change:
- apply() takes no flag: matmul(x, transpose(W)) reads the constant with
  transpose_y in every program, and the transpose is omitted when only
  such matmuls read it.
- The bit-identity statement now covers the constant only. Docs, module
  documentation and changelog say that float16 matmul and gemm results
  over it can differ from the literal lowering in rounding, and describe
  the cost per load route.
- The runtime test reads the constant back through gather for the bit
  comparison and gives matmul a dense input, checked against an f64
  reference within 4 unit roundoffs of the sum of term magnitudes (largest
  seen 0.7), with a guard that the bound can tell the result from zeros.

Validation (M4 Max, macOS 27.3): fmt; clippy -D warnings; cargo test with
coreml-runtime,coreml-export,dynamic-inputs 3381 passed, 0 failed; CoreML
WPT 2590 passed, 0 failed, 104 skipped; rustdoc -D warnings. SmolLM2-135M
float16, CPU, 64 greedy tokens, stateless on the in-memory route: M4 Max
2.9 -> 48.7 tok/s, iPhone SE 2nd gen (A13, iOS 26.7.1) 0.68 -> 22.8 tok/s,
with one different token from the URL route's stream on both devices.
Carried state and the Rust export route keep their tokens.
… and watchOS

The SmolLM2 numbers reported for the state carry and the blockwise constants
came from a model bundle and a harness that are not published, so nobody else
could repeat them. This adds the whole path to the repository.

examples/smollm2_coreml reads SmolLM2-135M-Instruct's model.safetensors,
quantizes the weights (8-bit per block of 32 with float16 scales for the
projections, per block of 64 for the shared embedding and head), and authors
the single-token decode graph with MLGraphBuilder: float16 projections,
attention and key/value window, float32 residual stream and RMSNorm. It saves
the graph as .webnn, compiles it through MLContext, carries the window as an
MLState or as tensors, and prints a receipt with build time, decode rate, peak
resident memory and a token hash.

An app needs the system's application loop, so smollm2_coreml_device builds
the same program as a static library, and scripts/apple_device_app.py links it
with a SwiftUI host, signs the app, installs it with devicectl and fetches the
receipt.

The CoreML runtime did not link for watchOS with the published crates. The
shim now defines objc_msg_lookup and objc_msg_lookup_super, which objc 0.2
calls outside macOS and iOS, and build.rs provides the empty BlocksRuntime
library that block 0.1 asks for there. psm still needs a CFLAGS define to
assemble for watchOS; the page documents it.

Validation, 2026-11-17, CPU, fixed prompt, 64 greedy tokens:
- The weights quantized here equal the earlier bundle's tensors bit for bit,
  and the token hash equals the earlier receipts (2db53a2d95685f0b through a
  compiled bundle, e2b450fbb2d994c6 through the in-memory load) on the M4 Max
  (macOS 27.3) and the iPhone SE 2nd gen (A13, iOS 26.7.1).
- iPhone XS Max (A12, iOS 18.7.10): same hash with --carry tensors. With
  --carry state the model fails to load there with Core ML error -14, also for
  a two-layer cut. Not investigated.
- Apple Watch Series 10 (watchOS 27.2): a two-layer cut runs end to end with
  the Mac's tokens. The full model is killed while loading; the watch grants
  an app about 300 MiB and the run peaks near 640 MB of footprint on the Mac.
- cargo test with native-examples, coreml-runtime, coreml-export and
  dynamic-inputs: 3342 passed, 0 failed. CoreML WPT: 2590 passed, 0 failed,
  104 ignored. Format and clippy clean. MkDocs was not built locally.
…ceipt

Peak resident size counts Core ML's mapped weights file, which the system does
not charge to an app. The receipt now also records the physical footprint
after the graph load, after the build and at the end, with its lifetime peak.

On the M4 Max the full model reads 304 MiB after the graph load, peaks at
626 MiB during the build and decodes at 319 MiB, of which 9 MB is heap in
use. A two-layer cut peaks at 157 MiB. The page's Apple Watch section now
gives these figures and names the cause: transient copies of the weights in
the loader and the converter, not Core ML and not the model.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants