One backbone for text, images, and audio

The backbone turns a sequence of text and media tokens into one 768-dimensional embedding. The first export could accept several sequence lengths, but Core ML ran it on the CPU. Giving each length its own function brought the work back to the GPU.

Join inputs

Text tokens and 512-value media vectors share a sequence. Placeholder positions tell the backbone where media belongs.

Look closer

Where the backbone fits

This port exports three Core ML models. For a text-only request, the pipeline calls the backbone directly. For images or audio, it runs the corresponding encoder first and inserts the resulting vectors into the text sequence.

Image / video frame Audio clip Text + placeholders Vision encoder 168M parameters Audio encoder 306M parameters (1, M, 512) Shared backbone 271M parameters input_ids (1, N) attention_mask (1, N) Embedding (1, 768), unit length
Inside the backbone

Follow the sequence from token lookup to a single embedding. The shapes show what each stage passes to the next.

in input_ids (1, N) · attention_mask (1, N) · media_features (1, M, 512)
1

Embed and fuse media

Look up 512-dim token embeddings, then drop vision/audio soft tokens into their placeholder slots.
Core ML changeNumber the media placeholders with cumsum, pick their vectors with gather, and insert them with where. Text-only calls provide a dummy zero row.
→ (1, N, 512)
2

Per-layer embeddings

Project to one 512-dim slice per layer, used later to gate each of the 24 layers.
Core ML changeUse a fixed reshape(1, -1, 24, 512) so tracing avoids an unsupported aten::Int operation.
→ (1, N, 24, 512)
3

Positions and masks

Positions 0…N−1 for RoPE, plus a full mask and a sliding-window mask (|q − k| ≤ 512).
Core ML changeCreate positions with a fixed arange and a runtime zero. Use −30000 to block attention in the masks.
→ pos (N) · two (N × N) masks
4

24 encoder layers

Attention, then MLP, then the per-layer gate. Five sliding-window layers, then one full-attention layer, four times over.
Sliding window · 2 KV heads · head_dim 256 Full attention · 1 KV head · head_dim 512
→ (1, N, 512)
5

Pool, project, normalize

Average over real tokens only, project 512 → 768, scale to unit length.
Core ML changeAverage the tokens before projecting. Because the projection is linear and has no bias, this gives the same result with one projection instead of one per token.
out (1, 768)
What the Core ML export revealed

Fixes 2 and 3 are linked: the fix for the counting limit caused the baked-in mask.

Flexible shapes pushed everything onto the CPU

Before · EnumeratedShapes
main · any of 128…8192
Runs on CPU. Plans 8192 × 8192 buffers at load.
After · iOS 18 multifunction
s128s512s2048s4096s8192
↓ one shared weight.bin · 521 MB
Static shapes run 100% on Metal GPU (2,812 / 2,812 ops via MLComputePlan).
s512 latency15,036 ms→15.2 ms
Peak RSS at load18.74 GiB→4.13 GiB
s2048segfault→57.3 ms
# backbone/export.py
desc = ct.utils.MultiFunctionDescriptor()
for tier, pkg in tier_paths:
    desc.add_function(str(pkg), src_function_name="main", target_function_name=f"s{tier}")
ct.utils.save_multifunction(desc, "models/backbone_fp16.mlpackage")

The position counter stalled at 2,048

Before

Positions came from cumsum(ones) − 1. The Neural Engine runs cumsum in FP16, where 2048 + 1 = 2048.

After

Each tier has a fixed length, so positions are a plain torch.arange(N). Exact up to 8191.

020484096 6144 020484096 61448192 arange FP16 cumsum
True position4096
FP16 cumsum gives2048
Off by2048 tokens
s4096 cosine0.9898→1.000000
s8192 cosine0.9774→1.000000
↓Using a plain arange made the mask a constant, which caused problem 3.

Core ML baked the 8K mask into the weights

  • With fixed positions, the sliding-window mask became a constant.
  • Core ML folded all 8192 × 8192 = 67M values into weight.bin.
  • Fix: add a zero that Core ML can only know at runtime. Positions stay exact; the mask is built at load instead.
Package size649 MB→521 MB
Compiled .mlmodelc1.1 GB→521 MB
Cold load11.7 s→3.5 s
Peak RSS5.00 GiB→4.15 GiB
# backbone/wrapper.py
pos = torch.arange(seq_len, dtype=torch.int32)
runtime_zero = (attention_mask[0] < 0).to(torch.int32)  # always 0, but only known at runtime
pos_runtime = pos + runtime_zero

A few more FP32 operations improved the PyTorch match

The first export kept RMSNorm in FP32, but its embeddings still drifted from PyTorch. Keeping the RoPE position calculations and sums in FP32 brought the outputs closer, especially for mixed text and media.

FP32
powreduce_meanrsqrtsqrteps add
RMSNorm. Squaring large activations overflows FP16’s 65,504 ceiling.
cast → mul → concatcossin
RoPE angles. FP16 loses angle precision at positions 4K–8K.
reduce_sumcumsum
Sums over thousands of tokens, and media slot indexing.
FP16
everything else
Weights, matmuls, MLPs and softmax. No measured speed cost from the FP32 ops.
Mixed media + text, s5120.997073→0.999984
Text, s20480.999677→1.000000
Benchmarks per tier

Compiled .mlmodelc, all compute units. Physical footprint is the isolated worker’s peak dirty and compressed memory (the metric iOS Jetsam enforces, excluding clean mapped weight files; includes ~290 MB of Python runtime). Cosine similarity compares Core ML and PyTorch outputs for the same input; closer to 1 means their directions match more closely.

Latency

452 MB–5.6 GBPhysical footprint scales with tier length (452 MB at s128, 5.6 GB at s8192).
3.5–3.9 sCold load per tier. 0.35 s once warm.
≤ 2.03e-04Max absolute error on text tiers.
TierReal tokensLoadLatencyPhysical footprintCosine similarityMax abs err
Terms used above
RMSNorm
x / sqrt(mean(x²) + ε). LayerNorm without the mean subtraction.
Masked mean pooling
sum(h · mask) / sum(mask). Padding never dilutes the vector.
L2 normalization
v / ‖v‖. Unit length, so dot product equals cosine similarity.
Multifunction package
iOS 18+. Several static entry points in one .mlpackage, sharing one copy of the weights.
Sliding-window attention
Each token attends only to tokens within 512 positions. Used in 20 of 24 layers.
RoPE
Rotary Position Embedding. Encodes each token’s position by rotating its query and key vectors before attention.
Constant folding
The compiler precomputes anything that doesn’t depend on inputs and stores the result.
Build and verify
# 1. Verify PyTorch wrapper parity
uv run python -m backbone.verify_pytorch

# 2. Export multifunction FP16 Core ML package (521 MB)
uv run python -m backbone.export

# 3. Compile to .mlmodelc
xcrun coremlcompiler compile models/backbone_fp16.mlpackage models/

# 4. Verify Core ML parity, latency, and peak memory
uv run python -m backbone.verify_coreml --model models/backbone_fp16.mlmodelc