Skip to content

qwen3_5 Metal: opt-in ANE share of prompt MLP columns (TF_ANE_COLUMNS) - #6334

Draft
joshuaswarren wants to merge 10 commits into
ashhart:mainfrom
joshuaswarren:w7r/qwen35-ane-rows-v2
Draft

joshuaswarren wants to merge 10 commits into
ashhart:mainfrom
joshuaswarren:w7r/qwen35-ane-rows-v2

Conversation

@joshuaswarren

Copy link
Copy Markdown
Contributor

What this changes

Adds an opt-in TF_ANE_COLUMNS=C share of the qwen3_5 prompt MLP: the first C columns of every gate/up
projection in a prompt pass run on the Neural Engine through a new generic metal/ane_share.zig (program pool +
worker + fence-ordered handoff), while the GPU keeps the tail columns, the fp32 SiLU·up merge and the down
projection. Unset, the binary takes the stock path.

Checks on this head

  • Head commit: 733310fee
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: base 514 findings, head 514 —
    0 new.
  • Tests run, with the command and pass, fail and skip counts: zig build test test-golden at a3c994d47,
    Apple M1 Ultra — 22456 passed / 6 failed / 201 skipped (22663 total). All 6 failures are in files this
    change does not touch (retained_taps_host/phase_trace, lfm3, inkling2, rope, tfq5, deepseek chat) and
    reproduce at the merge-base: pre-existing upstream breakage.
  • CI: pending on the draft.
  • Not run, and why: M3/M4/M5/M6 chips — no access; the share is opt-in and only verified on M1 Ultra.

Receipt

  • Main against branch: docs/receipts/qwen35-ane-share-m1-ultra/ — raw ABBA JSON plus
    bench_concurrent/bench_cache/bench_openai transcripts for both arms.
  • Boxes it reaches: Apple M1 Ultra only.
  • New switch? TF_ANE_COLUMNS (already registered in platform/environment.zig for qwen27): a whole column
    count, 0/unset disables the share (the default). Values above the shared width lose outright
    (C=5632 measured +75% TTFT); C=2048 is the measured M1 Ultra point.
  • Environment: TensorFold 733310fee, Zig 0.17.0, Metal4/MTL4 on Apple M1 Ultra, macOS arm64;
    mlx-community/Qwen3.5-2B-MLX-4bit@93760be4f1f69842a46bc13dbdc0f19e291392a3.
  • Paths and platforms the change reaches, which I ran and which I could not: qwen3_5 Metal prompt path when the
    env is set — ran. Every other family/backend and the default path — unchanged; host suite above.
  • Exactness, from tools/bench_concurrent.py --alone --serial: head alone.equal 12/12 on all four rows,
    serial.equal clean with drafts accepted (196/135 on the code rows) — identical to base. Bits: the share
    evaluates fp16 where the GPU path uses bf16, so prompt logits can differ by that rounding and greedy decode
    amplifies it — 2 of 4 greedy receipt-pack prompts emit different tokens vs the GPU path. Same-build
    consistency (solo vs concurrent, drafted vs undrafted) is unaffected; no perf_receipt.py receipt can verify
    a token-drift change by construction, so decode-abba-51fa1a34.json is committed as raw evidence instead.
  • Main against this branch, same machine and checkpoint: committed under the receipt dir.
  • Decode speed before and after, from tools/bench_openai.py: base 118.0–119.2, head 119.0–120.7 tok/s —
    parity; the row floor keeps every decode round on the stock path.
  • Speed claims: no verified-receipt claim (token drift, above). Measured for calibration: cold 2571-token TTFT
    base 1.506 s vs head 1.535 s median (bench_cache --require-cold, qualified); 9013-token ABBA base
    6.349/6.320 s vs head 6.288/6.200 s. The share sits at the GPU/ANE crossover on M1 Ultra — the value is the
    verified path plus a knob for chips where the ANE is relatively faster (M5/M6 verification next).
  • Prompt speed before and after: see bench_cache line above.
  • Licence of any new weights or drafter, or "n/a": n/a.
Kernel contract, only when a GPU kernel is new or changed
  • Kernels registered with the contract, and the kernel each one replaces: qwen35_ane_pack (bf16→fp16 row
    gather into share planes) and qwen35_ane_merge (fp32 silu(gate)·up over the shared columns) — new, no
    predecessors.
  • A planted control for each new kernel, and each one fails as planted: pack_zero (zeroed plane) and
    merge_no_sigmoid (missing SiLU) both go red at the shapes gate as planted.
  • Each backend's SUMMARY line and exit status: metal — pack and merge pass nonfinite/repeat/shapes; sums N/A
    (.accum = .none); limits pass (128/256 threads vs pipeline maximum 1024); offline compiles confirm
    M1 = 1024 and M2 = 1024 recorded limits, records exact.
  • Chips I could not run: M3, M4, M5, M6.

Checklist

  • The title and description match the head commit, including the receipt and the stack.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.
  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo.
  • No precision traded for speed. If the bits change, the description says which sums change and why.
  • Decode and prompt processing are no slower than main at one stream and the widest admitted; with --drafter, no slower than without it, greedy and sampled — for the default path the flag is off; with the flag on, decode is parity (-0.01%) and prompt is the disclosed crossover (loses ~2% at 2.5k tokens, wins ~1.4% at 9k on M1 Ultra).

joshuaswarren and others added 9 commits December 4, 2026 13:21
qwen27 is the only family that uses the Neural Engine today. This lifts
its Share into zig/src/metal/ane_share.zig — parameterized on a shape
and a per-layer program maker so a family supplies checkpoint dequant
and a MIL choice and reuses the worker, surfaces and SharedEvent dance —
and wires the same prompt overlap into qwen3.5.

qwen3.5's projection kernels are generated per shape and cannot take a
column range, so it splits prompt rows instead: the Neural Engine runs
rows [0, TF_ANE_COLUMNS) of each prompt MLP end to end through the
existing mlpSlice MIL over 128-row fp16 planes, the GPU runs the
remaining rows on its existing kernels with buffer offsets, and two
small kernels copy s.x into the input plane and the output plane into
s.r. Signal and wait encode in-order inside the single forward command
buffer.

Opt-in only: TF_ANE_COLUMNS stays 0 by default, every default path is
unchanged, and admission gates on ane.available() alone so M1 through
M5 qualify. Not exact-output qualified. The kernel source is embedded
from the family's kernels.zig and the share reuses the existing
TF_ANE_COLUMNS extent, so no shared registration files change; a
dedicated per-family rule can follow. Refs ashhart#6310.

Generated with [Devin](https://devin.ai)
Row-split put the whole MLP (including the 6144-wide output reduction)
on the ANE in fp16: measured live on M1 Ultra it was 2.5x slower than
the GPU baseline and >=64-row shares collapsed to immediate EOS. Match
qwen27's model instead: the ANE owns gate/up columns [0, columns) and
returns silu(gate)*up activations; the GPU keeps the remaining columns
via contiguous affine-row suffix views on the existing qmm pipelines
and runs the full-width down projection, so fp16 never holds a long
reduction. TF_ANE_COLUMNS now names real intermediate columns; valid
values are 2048/4096/5632 (GPU rest lands on qmm_4096/2048/512_2048).
Wire the loaded share's out-of-footprint price into qwen35 admission.

Generated with [Devin](https://devin.ai)
A fp16 silu(gate)*up computed on the Neural Engine overflows far below
the fp16 range of its factors; live A/B showed corrupted logits
(repetition, echo) at C=2048. Match qwen27's proven shape: the program
emits gu raw into a [2C][128] plane and the merge computes the product
in fp32. The output surface doubles; the weight blob is unchanged.

Generated with [Devin](https://devin.ai)
The column share corrupted prompt output non-deterministically. Metal 4
defers command-buffer events to the queue at commit and lets a buffer's
encoders overlap, so ending and reopening the encoder around an in-order
signal raced the tail projections against the pack and attention work.

Take the share's own signal/wait handoff instead: fence the encoder,
commit the buffer so the queued signal releases the worker, then reopen
behind the fence. The share carries the MTLFence; forward's mlp keeps a
lane whose buffer the handoff swaps.
Registers both ane_share.metal kernels: the fp16 plane pack and the
fp32 silu merge, each with a planted control, launch records against
M1/M2 (1024 both, offline-compiled), and the launchOf mapping.

SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings;
2 controls: 2 red as planted, 0 missed; 0 limit problems.
The qualify check compares a wide forward against solo rows bit-for-bit;
run it on the GPU pipeline the contract actually covers, then reattach
the share. And bound the share to passes a merged decode round cannot
reach, so co-batched rows never change a stream's tokens.
Decode parity in the mirrored ABBA, bench_concurrent alone/serial clean
on both arms, and the fp16-vs-bf16 prompt-logit drift named instead of a
verified receipt.
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Follow-up measurement on the exact-output ask — tested whether the fp16-vs-bf16 drift is a merge-kernel artifact or inherent.

Hypothesis tested. The merge kernel reads the ANE's fp16 gate/up plane as float while GPU columns arrive on the bf16 grid, so silu inputs sit on different grids. Patch: round both plane reads to bfloat16_t before the silu, putting ANE columns on the same lattice. The merge's silu expression is textually identical to stock mlp_act either way, so inputs were the only lever.

Method. qwen35-2b-4bit on an M1 Ultra, TF_ANE_COLUMNS=2048, tf-receipt-v1 greedy pack, three arms: stock (env unset), share+patch, share unpatched. Share engagement confirmed — the unpatched arm reproduces the 2/4 drift.

Result. Patched arm still drifts on the same 2/4 prompts (code_greedy, reasoning_greedy). First-divergence positions vs stock: reasoning_greedy identical at char 447/474 in both builds; code_greedy 254/548 patched vs 409/548 unpatched — changed but not converged. prose_greedy and logprobs_long (256-token cap) match exactly under both builds.

Conclusion. The residual isn't a grid misalignment the merge can fix — it's the ANE's in-chip fp16 conv accumulation vs the GPU's fp32-accumulate→bf16 GEMV. Plane inputs are already lossless (bf16→fp16 is exact in-range), so the divergence lives inside the ANE's dot product and no downstream rounding can recover it. Greedy bit-equality is not achievable at this decomposition — consistent with the design's own exact_output_qualified=false and env-only opt-in.

Suggestion: land the share as the documented non-exact opt-in it is, with this quantified drift (2/4 greedy prompts on the receipt pack, divergence typically late in generation) stated in the receipt, unless the exact-output gate is meant to block the mechanism entirely.

@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. Same finding as on #6435, which carries these commits: with TF_ANE_COLUMNS set, the ANE hands fp16 gate and up values to SiLU where the default path rounds them to bf16, so tokens change (your receipt shows 2 of 4 greedy prompts differ). TensorFold only takes paths that match the default output bit for bit, opt-in ones included. test-qwen35-metal-schedule-host also stops compiling on this head. Details and what would make it landable are on #6435.

  • Synthena

…e the default path's gate and up tensors; the host Metal facade gains the share stand-ins the schedule test needs
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Cross-posting from the #6435 review follow-up since the same commits live in this stack — full detail there: #6435 (comment)

Head 0de8c79d1 on this branch:

  • The merge now rounds the fp16 plane inputs to bf16 before SiLU — the default path's rounding point on its bf16 gate/up tensors.
  • The merge keeps g/(1+exp(-g)) deliberately: mlp_act on the default path uses that single-round naive form, so the formula and its −0 overflow behavior now match exactly.
  • test-qwen35-metal-schedule-host compiles and passes again (schedule_fake_metal gained the ane/ane_share/event/fence stand-ins; the test's model literal sets .ane = null).

The bit-exactness blocker stands, measured on the M1 Ultra receipt host: the ANE conv accumulates at fp32+ grade but only emits fp16; bf16(fp16(acc)) diverges from bf16(acc) on ~6.3% of elements, and fp32/bf16 MIL output types are rejected as InvalidMILProgram. The column share can't reproduce the default path's bf16 gate/up bit-for-bit, so exact_output_qualified stays false — this stays open as reference per your call.

Also flagging for merge sequencing: #6467 adds its own zig/src/metal/ane_share.zig off upstream/main — whichever lands second needs the shared file reconciled.

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.

Metal: Neural Engine prompt-MLP share beyond qwen27 (qwen3.5 row split, reusable ane_share)

2 participants