Skip to content

flashnext: opt-in shared-expert ANE column share for prompt passes (qwen4_exp) - #6467

Open
joshuaswarren wants to merge 5 commits into
ashhart:mainfrom
joshuaswarren:lead/train-w7Z-q4exp-ane
Open

joshuaswarren wants to merge 5 commits into
ashhart:mainfrom
joshuaswarren:lead/train-w7Z-q4exp-ane

Conversation

@joshuaswarren

@joshuaswarren joshuaswarren commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

TF_ANE_COLUMNS=N on qwen4_exp (Flash Next) moves the first N output columns of each layer's shared-expert gate+up prompt matmul onto the Neural Engine. The shared expert runs every token on all 48 layers on A3B-class checkpoints, so this is the largest prompt-side ANE surface after the qwen27/dense shares.

  • Weights: at load, the first N columns of shared_expert.gate_proj/up_proj are dequantized to fp16 (generic bits/group from xw, verified against qmmw_nax's s*q+b convention) and baked into one conv MIL program per layer (ane.gateUpSlice, byte-identical shape to the qwen27 generator).

  • Dispatch: in Prompt.moe's shared-expert phase the GPU tail runs through a width-resolved qmmSlice (offset weight Bufs, same prompt_w.qmm driver, no kernel changes); the ANE half is fenced with SharedEvent signal/wait around the silu·up stage, and a merge kernel overwrites sa[0..c) on the bf16 grid identical to stock pf_act.

  • Opt-in only: exact_output_qualified = false is logged at load; without TF_ANE_COLUMNS nothing changes (m.ane == null, the tail is byte-identical to today). Disabled under r.xpack/r.tp.

  • FSR path (--ssd-experts, the only way current qwen4_exp checkpoints fit): the lane's cb/enc are resynced from commands.active/r.enc around each fence op, and encoders reopen with the stream's own dispatch mode.

  • Issue: Refs Metal: Neural Engine prompt-MLP share beyond qwen27 (qwen3.5 row split, reusable ane_share) #6310 — shared-expert coverage for qwen4_exp; the reusable metal/ane_share.zig ring/fence/worker machinery is ported unchanged in shape from the qwen27 share.

  • Not stacked: branched off upstream/main.

  • atc overlap --json: {"complete": false, "limitations": ["pullFilesUnavailable", "timeLimit"], "overlaps": [{"pullRequest": 2273, "conflict": "clean"}, {"pullRequest": 2634, "conflict": "unknown"}, {"pullRequest": 2342, "conflict": "conflicts", "conflictFiles": 1}, {"pullRequest": 3480, "conflict": "conflicts", "conflictFiles": 5}, {"pullRequest": 3045, "conflict": "clean"}, {"pullRequest": 3380, "conflict": "unknown"}, {"pullRequest": 1635, "conflict": "unknown"}]} — every conflict hunk was inspected against both PR heads with git merge-tree: none contains a line this branch changes. The flash next pair: hand off through shared events and host-published epochs #3480 conflicts are its own staleness vs upstream (try on tp.send/waitWord/combine/argmax, copyPeer, l.enc write-backs it predates) and the qwen27 metal: qk projections, flat glue and Metal 4 verify passes, each bit-identical and switchable #2342 conflict is its stale end-of-file sources.zig append; this branch's flashnext_ane entry sits mid-file. The one intentionally adjacent hunk — share binding in Hooks.begin — was moved out of at() specifically to stay disjoint from flash next pair: hand off through shared events and host-published epochs #3480's pairSend/pairTake edits.

  • Head commit: 846e6a6 (on e60cafe).

Verification

  • macOS build (Zig 0.17.0, M-series): zig build and zig build native clean on macstudio.
  • Host tests: flashnext_recording_metal needed the ane/ane_share stub exports, now added; remaining suite failures (residency_recording_metal missing phase_trace, tfq5/inkling2/paged/rope) reproduce identically on the base commit — pre-existing upstream.
  • Live on jw-core-4b (qwen4_exp, 48L, shared_expert_intermediate=640, --ssd-experts 8 --ple-on-ssd): TF_ANE_COLUMNS=384 → loaded=true loaded_columns=384, warm-up and chat prompts pass through the share path; greedy 17*23? → 391.
  • Stock-vs-share greedy drift A/B (head 846e6a6bd build, TF_ANE_COLUMNS=384, 4 greedy prompts, 128 tok): output is NOT identical — common prefixes then divergence (prose 322/700, code 578/655, reasoning 178/378, logprobs 226/462 chars). An early argmax flip cascades; consistent with exact_output_qualified=false — the share at 384 cols is a semantic-changing fast path and stays opt-in.
  • zig fmt --check, git diff --check, zig ast-check on all touched files: clean.

Receipt

Live-verified engagement plus a measured drift A/B: share output diverges from stock on all 4 greedy prompts after a common prefix — expected and consistent with exact_output_qualified=false. Correctness of the stock path is unchanged (opt-in); merge rounding is pinned identical to pf_act — merge rounding is pinned identical to pf_act, input planes are bf16-lossless, and the ANE's fp16 in-chip accumulation residual is documented on #6334.

Checklist

@joshuaswarren
joshuaswarren marked this pull request as ready for review December 5, 2026 11:58
@ashhart ashhart added kind:feature Classified by Synthena as feature addition synthena:needs-changes Reviewed by Synthena; changes requested labels Dec 5, 2026
@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Needs changes (kind:feature)

Adds an opt-in TF_ANE_COLUMNS mode for qwen4_exp prompt passes. It moves the first N columns of each layer's shared-expert gate/up matmul onto the Neural Engine as fp16 conv programs, then merges the results back into the GPU's bf16 activation buffer with a new Metal kernel and SharedEvent fencing.

Findings:

  • [BLOCKER] zig/src/families/flashnext/ane_policy.zig: The opt-in path changes output bits. Weights are dequantized to fp16, bf16 activations are cast to fp16, and the gate/up projection is accumulated by an fp16 ANE conv instead of the GPU qmm. The PR itself marks the path as not exact, and project policy does not accept opt-in paths that change tokens or logits bits. Suggested fix: Only land the share if the ANE columns reproduce the GPU qmm's gate/up values bit for bit. Otherwise keep the reusable metal/ane_share.zig machinery out of the served flashnext path until an exact formulation exists.
  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Sequencing note from the #6334/#6435 column-share work: this PR and those both add zig/src/metal/ane_share.zig (plus the ane.zig runtime machinery). #6334's head is 0de8c79d1 on w7r/qwen35-ane-rows-v2; this branch is off upstream/main — whichever lands second will need the shared file reconciled (or this restacked on #6334 if that lands first).

Related finding from the same hardware probe (details: #6435 (comment)): on M1 Ultra the ANE conv emits fp16 only — bf16(fp16(acc)) diverges from bf16(acc) on ~6.3% of elements and fp32/bf16 MIL output types are rejected as InvalidMILProgram. If the flashnext share consumes ANE gate/up values the same way, it inherits the same bit-exactness floor, consistent with the token drift your A/B already shows.

@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. The sequencing note is clear, and the shared TensorFold ANE machinery can be reconciled according to landing order.

The exactness issue remains at this head. ane_policy.zig:5 records exact_output_qualified = false, while engine_load.zig:465 still enables the share. The fp16 gate/up results are merged into the served activation, and the four posted greedy comparisons diverge from stock.

Please make the shared gate/up values and served output bit-exact with the GPU path, or keep this nonexact share out of the served Flashnext route. An explicit opt-in does not satisfy the exactness requirement. The related fp16-output probe explains the limitation but does not resolve it.

  • Synthena

joshuaswarren and others added 5 commits December 5, 2026 17:52
Move columns [0, TF_ANE_COLUMNS) of each layer's shared-expert gate/up
projection to the Apple Neural Engine during prompt passes, leaving the
GPU the packed column tail, the silu*up merge and the down projection.

- metal/ane_share.zig: the generic Share — per-slice fp16 surfaces, a
  per-layer gate/up program, a worker thread driven by a SharedEvent
  counter, and the signal/wait handoff that splits a prompt lane's
  command stream behind a fence.
- families/flashnext: gate/up slice MIL (raw columns, no activation —
  the merge rounds to the bf16 grid before silu so both paths match
  stock pf_act), the pack/merge kernels, and the prompt-pass tail that
  slices columns [columns, 640) off the recorded (bits, group) weights.
- The lane's cb/enc are resynced from the run state before each
  handoff: the fsr stream's pause/overlap commits and replaces them
  mid-run, and encoders reopen in the stream's own dispatch mode.
- Off by default; exact_output_qualified=false. A load or build failure
  warns and falls back to the GPU path. Live-verified on jw-core-4b
  (8-bit/GS128 shared expert, --ssd-experts): loaded_columns=384,
  coherent greedy output.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Keeps Hooks.at's signature unchanged so the hunk stays disjoint from
the TP pair hand-off edits in ashhart#3480.
CI lean rule wants one-line comments within 120 columns and zig fmt
on replay_prompt; reword the folded doc comments to fit.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The coverage suite requires every kernel_sources export to appear in a
generated library; the share's fnext_ane merge text was compiled ad hoc
in replay_prompt but never inventoried.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@joshuaswarren
joshuaswarren force-pushed the lead/train-w7Z-q4exp-ane branch from 846e6a6 to b369d82 Compare December 6, 2026 00:08
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (b369d824b). One real conflict: upstream's shape threading replaced the hardcoded geometry literals this branch sliced against — the ANE share block now reads d/s.shared_width/topk/slots from r.shape instead of D/640/10/11, matching upstream's parameterization. TF_ANE_COLUMNS registration, runtime_sources entry, and the share plumbing carry over unchanged. Local zig build test test-golden green; no pinned serving files touched.

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

kind:feature Classified by Synthena as feature addition synthena:needs-changes Reviewed by Synthena; changes requested

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants