Skip to content

qwen27 metal: qk projections, flat glue and Metal 4 verify passes, each bit-identical and switchable - #2342

Open
ashhart wants to merge 10 commits into
mainfrom
lead/qwen27-qk-glue-metal4
Open

ashhart wants to merge 10 commits into
mainfrom
lead/qwen27-qk-glue-metal4

Conversation

@ashhart

@ashhart ashhart commented Nov 6, 2026 •

Copy link
Copy Markdown
Owner

Qwen3.8-27B on Metal: three changes, each with its own switch and each bit-identical to what it replaces. Four commits; the commit messages carry the details.

  1. qk projections (zig/kernels/metal/core/qk.metal, core/qk_projection.zig):
    • A tensor-op projection for 4-bit group-64 matrices, reading projection.weight_layout in place: load skips the reorder for tf_lane_reg, so no extra memory is needed.
    • Every output word equals tf_lane_reg's on the same K split.
    • It's used only on chips with tensor units (M5), and TF_Q27_QK=0 restores tf_lane_reg.
  2. Flat glue: a column tree scan, a vector GDN prepare, a row-side activation and a chunked argmax.
    • Each is bit-identical to the kernel it replaces, with ours kept wherever a round doesn't fit.
    • On by default on every chip; TF_Q27_FLAT_GLUE=0 turns it off.
  3. Metal 4 submission for verify and decode passes of up to 64 rows (zig/src/metal/metal4.zig):
    • The model gets its own MTL4 queue, allocator, argument table, a ring for setBytes and a residency set.
    • Each commit gets fresh commit options with a feedback handler for errors and GPU time.
    • Prompt chunks, keeps, the drafter and snapshots stay on Metal 3.
    • On by default only with tensor units; TF_Q27_METAL4=0 turns it off.

For review:

  • Buffer.deinit now calls metal4.released().
  • command.zig's Queue, CommandBuffer and ComputeEncoder gain an optional m4 field.
  • core/fence.zig guards its Metal 4 branch with @hasField, so the recording fakes still compile.

A/B tools: tf-qwen27-qk-ab, tf-qwen27-glue-ab, tf-qwen27-metal4-ab and tf-qwen27-stack-ab.

Checked on an Apple M5 Max (at main 7040192, before this rebase onto 691fb43):

  • public golden: 1024 of 1024;
  • stack-ab (stock on Metal 3 against all three in one process): every logit and pick equal over 68 rounds cool and 244 hot;
  • served replies: 128 of 128 equal to stock; streams, marks and lanes equal;
  • zig build test exits 0.

Speed:

  • a 16-row verify is 4.2% faster cool and 5.5% hot;
  • served streams are about 5% faster (93.1 against 98.3 tok/s, rests between, order off on on off);
  • one-row decode is about 2.5% faster;
  • prompts run at stock speed.

On this rebase, zig build native (ReleaseFast) builds on an Apple M3 Ultra, lean matches main (252), and the commits are unchanged apart from the base.

Not checked yet, so this stays out of the queue:

  • M1 to M4: qk and Metal 4 stay off there, but the flat glue is on by default and has only been measured on an M5 Max. If it costs anything there, it can default to tensor-unit chips only (set from device.tensorUnits() in Runner.initReady, with TF_Q27_FLAT_GLUE still overriding), as Metal 4 already does;
  • M5 Pro and M5 Ultra.

Before landing, we'll run main against this branch on an Apple M3 Ultra and an Apple M5 Ultra: replies equal, and prefill and decode level or faster.

@ashhart

ashhart commented Nov 6, 2026

Copy link
Copy Markdown
Owner Author

Apple M3 Ultra (Qwen3.8-27B MLX 4-bit, main against this branch, base new new base): GREEN. On this chip only the flat glue is new, since qk and Metal 4 stay off without tensor units. Replies are equal, and decode is level to slightly faster:

Cell Main This branch Change
1 stream, code, greedy 34.9 / 35.0 35.7 / 35.8 +2.3%
4 streams, code, greedy 103.3 / 103.8 105.0 / 105.2 +1.5%
1 stream, code, T=1 35.7 / 35.7 35.9 / 35.9 +0.6%
4 streams, code, T=1 103.6 / 103.6 103.7 / 103.6 +0.0%

Each pair is that arm's two runs, aggregate tok/s, and every run lands on the same side. This run checked decode only; prefill on pre-M5 isn't covered. The M5 Ultra cells, which run qk and Metal 4 too, come next. This lands when they're level.

@ashhart
ashhart force-pushed the lead/qwen27-qk-glue-metal4 branch from fa3b147 to f9429aa Compare November 11, 2026 18:45
@ashhart

ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner Author

Apple M5 Ultra (Qwen3.8-27B MLX 4-bit, main against this head 49412a3d9, warm then base new new base): GREEN, tokens unchanged.

Cell Main This PR Change
Decode, 1 stream (chat, greedy) 48.5 tok/s 50.7 tok/s +4.5%
Decode, 4 streams (chat, greedy) 170.9 tok/s 176.2 tok/s +3.1%
Prompt 2,048 tokens 1,889 tok/s 1,901 tok/s +0.6%
Prompt 8,192 tokens 1,880 tok/s 1,889 tok/s +0.5%
Decode after an 8,192-token prompt 46.8 tok/s 48.7 tok/s +4.1%

Prompt tokens match across every run (0 of 20 rows differ), and both chat cells (thinking on and off) qualify on both builds. With the M3 Ultra run from 6 Nov, both chips are covered: on the M5 the qk projections and Metal 4 verify passes add a few percent to decode, and nothing is slower.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 14, 2026

Copy link
Copy Markdown
Owner Author

Rebased onto main (now 174645f). It conflicted with #2818's whole-prompt row blocks in quant_gpu.zig; the resolution keeps both:

  • 8-bit matrices keep main's rule: past 16 prompt rows they take the long key as independent row blocks.
  • Plain 4-bit matrices keep this PR's paths: qk when it applies, tf_lane_reg on a reg copy (long key past 128 rows), else the cooperative kernel at reg_rows, never long.

test-qwen27-quant-host and test-qwen27-shared-allocation-host pass on the rebased tree. Because the dispatch code changed in the merge, the M5 A/B runs again with the landing train before this lands. #2936 is restacked on top (9dd124b, the same patch).

  • Synthena (Ash's Agent)

…and argmax

Four glue kernels for Qwen27 rounds, each bit-identical to the kernel it
replaces, with TensorFold's own kept wherever a round does not fit them.

- tf_delta_gdn_columns_1/2/4 replace tf_delta_gdn_tree_slots_* for lone
  trees of up to 4 live states, reading the slot schedule as flow words
  (tree_slots.flows, a new frame field).
- tf_delta_gdn_pre_vectors replaces tf_delta_gdn_pre for four taps over
  128-wide heads with bf16 conv, A_log and dt.
- q27_mlp_rows replaces custom_kernel_q27_mlp_xs where 256 threads run.
- tf_round_pick_chunks/rows replace tf_round_bf16_argmax for Qwen27's two
  callers through Ops.argmaxChunks; other families keep Ops.argmax.
- TF_Q27_FLAT_GLUE=0 at load, or decode_round.setFlatGlue, keeps every
  round on TensorFold's kernels.
- tf-qwen27-glue-ab: the general glue against the flat kernels.

Checked on an M5 Max, alone on 1.2.2: glue-ab equal over 1,204 rounds;
golden, streams, marks, reuse, lanes and served replies equal; a 16-row
verify 3.2% to 4.2% faster. Rebased here with one conflict (main's routed
block fields in gpu_frame.zig) and checked stacked on qk: golden 1024 of
1024.

On main d2b3722 (#2913: XS sums compile out before tensor units),
q27_mlp_rows writes XS only under Q27_XS and its key carries main's .xs,
so M1-M4 keep the flat activation without sums; main's norm and MLP test
now runs with the flat glue off and on.
Main's 9f23d0d keeps Metal 4 out of the 27B's binary after a balanced rerun showed small losses, so #2342 lands
without its Metal 4 commits (Metal 4 submission for Qwen27 verify passes, tf-qwen27-stack-ab and the unfair-lock
follow-ups). Its CHANGELOG line now names only the qk projections and flat glue.
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
@ashhart
ashhart force-pushed the lead/qwen27-qk-glue-metal4 branch from 0402836 to 5439065 Compare November 23, 2026 19:55
ashhart added a commit that referenced this pull request Nov 23, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 23, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 23, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 28, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 28, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 28, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 28, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 28, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 28, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
ashhart added a commit that referenced this pull request Nov 28, 2026
…the dropped Metal 4 commits

Main's 739ed5d left zig/src/families/qwen27/decode_round.zig at 596 lines, and #2342's flat glue adds seven,
which its Metal 4 commit (no longer part of this PR) had offset. Three blank lines between top-level declarations
go; nothing else changes.
@ashhart ashhart added kind:perf Classified by Synthena as performance improvement synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner Author

Synthena Initial Review — Performance receipt required (kind:perf)

Adds three switchable Qwen27 Metal optimizations (tensor-op qk projections, flat glue kernels, Metal 4 verify/decode submission) claimed bit-identical to the kernels they replace, plus A/B tooling and contract tests. The PR reports speedups but no verifiable benchmark receipt is attached.

  • Performance claim detected without a verified tf-receipt-v1 receipt.

Performance PRs require a verifiable benchmark receipt before running project CI hardware. See CONTRIBUTING.md (Performance PRs: verifiable benchmark receipt) and attach the output of:

python3 tools/perf_receipt.py run --base-bin /path/to/base-tf --head-bin /path/to/head-tf --model /path/to/model.tfold --out receipt.json

Findings:

  • [BLOCKER] zig/src/core/tree_round_gpu.zig: argmaxChunks computes the logits byte length from (rows-1)stride + vocab, but the legacy argmax path (and the contract's checkArgmax) sizes the buffer as rowsstride, so a caller whose last row's stride extends past vocab (padded logits) will now fail the bounds check with BufferTooSmall on a buffer that argmax accepted. Suggested fix: Size the logits check as rows * stride * 2 bytes (matching argmax/contract.checkArgmax) or document and enforce that callers pass unpadded strides; add a regression test with padded logits.
  • [BLOCKER] zig/src/core/tree_round_gpu.zig: The fallback threshold means small vocabularies (chunks < 8, i.e. vocab <= 7168) silently take the old kernel while large ones take the chunked path, but the PR claims every output word is bit-identical; the two paths are different kernels with different reduction orders, so the A/B coverage must prove equality across the threshold boundary, not just on the vocabularies exercised. Suggested fix: Add an A/B test at the chunks == 7/8 boundary and for vocabularies just above/below 8192 tokens, or gate the chunked path behind the same TF_Q27-style switch as the other changes so it can be disabled independently.
  • [WARNING] zig/src/core/tree_slots.zig: flows() scans forward from every step to find the next consumer of the written slot, making plan building O(rows^2) in the worst case (e.g. long chains where every step writes the same slot); on 2048-row prompt passes this adds up to ~2M comparisons per window group on the host. Suggested fix: Track the next consumer index per slot in a small array while iterating once backwards, or precompute it in the existing planner pass, to keep plan building linear.
  • [WARNING] zig/src/families/qwen27/gpu_weights.zig: markPlain flips matrices to weight_layout based on qk availability at load time, but the qk pipeline is only selected per-launch via TF_Q27_QK; if the runtime compiler fails later (or TF_Q27_QK is toggled after load), plain matrices have no reg copy and tf_lane_reg cannot consume weight_layout, so the model cannot fall back at runtime. Suggested fix: Either keep a reg_layout copy alongside plain words (as the A/B tools do via reg_copy) so TF_Q27_QK=0 works after load, or resolve the layout once at load and make TF_Q27_QK a load-time-only switch documented as requiring a reload.
  • [WARNING] zig/src/platform/environment.zig: TF_Q27_FLAT_GLUE and TF_Q27_QK are registered as metal-scope flags but TF_Q27_METAL4 (mentioned in the PR description as the third switch) is absent from the rules table, so the environment reader will reject or ignore it depending on strictness, and users cannot disable Metal 4 via the documented env var. Suggested fix: Add a TF_Q27_METAL4 rule entry matching the other two, and extend environment_test.zig's valid-case table with 0/1 cases for it.
  • Synthena

@ashhart ashhart added synthena:needs-device Initial diff review passed; waiting for device and slowdown check before READY and removed synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 5, 2026

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:perf Classified by Synthena as performance improvement synthena:needs-device Initial diff review passed; waiting for device and slowdown check before READY

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant