Repository navigation
metal : faster qwen4exp decode (short-row Q8_0 / Q5_K mat-vec, fused hyper-connection ops) - #499
danielhanchen wants to merge 38 commits into
Conversation
…SKIP, GGML_METAL_CHUNK_NODES)
…nnection down projection
…and the hc down fusion
…to the next norm, split short Q5_K rows (A/B switches GGML_METAL_FUSION_OFF, GGML_METAL_Q5K_SPLIT_OFF)
…expert, residual add) into hc_post + norm, fuse the gated norm and the linear-attention gates (A/B switch GGML_METAL_FUSION_OFF)
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…apped back to token ids by the backend top-k; the target verify is unchanged
…eject hc_post norm weights aliasing the fused outputs
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…s (Q4_K / Q5_K), rows per simdgroup A/B knobs for the K-quant expert mat-vecs
…gate + up kernel verbatim
…wen4exp linear-attention token - GDN_CONV_STEP (18): CONCAT + CPY (new conv window into the cache) + SSM_CONV + SILU + RMS_NORM + SCALE of the q and k heads, one threadgroup per head of 128 channels - GDN_DELTA_STEP (19): the gates + GATED_DELTA_NET (state written into the cache) + RMS_NORM * w * sigmoid(z), one threadgroup per head (GGML_METAL_GDN_DELTA_NR=4|8|16|32 picks the state rows per simdgroup, A/B only) - both keep the per-element expressions and reductions of the kernels they replace; one token of one sequence only, everything else keeps the existing kernels (GGML_METAL_FUSION_OFF=18,19 for A/B) - qwen4exp gathers the recurrent state before the conv window, so the conv state store is the node right before the conv in the graph - the optimizer packs fusion spans longer than 16 raw nodes (the delta step spans 18) - test-backend-ops: GDN_CONV_STEP / GDN_DELTA_STEP / GDN_DECODE_LAYER (eval + perf)
…he k / v cache writes, the attention output gate in the vec reduce, the indexer top-k + mask in one kernel (A/B switch GGML_METAL_FUSION_OFF=18,19,20)
- every value that one original op writes and another reads now crosses a threadgroup_barrier in threadgroup memory, so the fast-math compiler cannot contract, reassociate or rewrite arithmetic across ops - each op keeps the code of its original kernel: the delta step follows the unfused add / softplus / mul / sigmoid, kernel_gated_delta_net_impl (S_v as the same function constant, the token loop over a runtime ne22) and the unfused rms_norm_mul / sigmoid / mul; the conv step follows ssm_conv (silu) and the norm + scale - the norms keep the reduction of kernel_rms_norm_fuse_impl: 32 threads, runtime ne00 / ne00_t / nth, simd_sum, the shmem_f32 round and the second simd_sum
…ows in the lightning indexer, write the indexer raw keys with their zero half in one kernel (A/B switch GGML_METAL_FUSION_OFF=20,21)
…sed kernels do (an opaque identity on a zero kernel argument), move the subset top-k selection to its own fusion id (22)
QSA fusion ids follow the linear-attention step fusions: 20 NORM_ROPE, 21 FA_GATE, 22 QSA_TOPK, 23 CAT_SET_ROWS. The QSA top-k selection uses the keys of the radix TOP_K and keeps its ties (lowest pick index), and selects a subset only where TOP_K takes its radix path; the separate subset id is gone.
…OCAB), mapped back to token ids by the backend top-k; the target verify is unchanged" This reverts commit 3e14063.
The folded shared-expert gate and residual add did not reproduce the unfused results bit for bit. Drop the fusion, the gated path of kernel_dsv4_hc_post_rms_norm_mul_f32 and its kernel arguments, and the ffn variants of the HC_TAIL test. HC_TAIL_ATTN is unchanged.
It was speed neutral on its own and the delta step fusion already folds the gates. The gate checks stay as a helper of the delta step check.
The qwen4exp decode fusions (MUL_MV_SCALE_SILU, HC_POST_NORM_MUL, HC_TAIL_ATTN, NORM_MUL_SIGMUL, GDN_CONV_STEP, GDN_DELTA_STEP, NORM_ROPE, FA_GATE, QSA_TOPK, CAT_SET_ROWS) match op chains that other models build too (the qwen3next / qwen35 conv step and gated attention, generic q/k norm + rope). They now apply only to graphs with a gated DSV4_HC_PRE and a GATED_DELTA_NET, which only qwen4exp has; the other hyper-connection models use the plain hc_pre. The check runs in both the structural and the full mode and also guards their alloc deps. The scan is cached per graph and thread. test-backend-ops: the tests of these fusions add a tiny signature to the graph, independent of the compared outputs, and each family has variants that must not fuse: no signature, the hc op only, the delta net only, and the plain hc_pre with the delta net. eval_perf creates the graph before build_graph, as eval does, so the perf cases get the signature too.
…s and a C enum tag in the device header
…e fusions NORM_ROPE, FA_GATE and CAT_SET_ROWS did not speed up the qwen4exp decode. Remove their checks, encoders, pipelines, kernel arguments, function constants and kernels (kernel_rms_norm_mul_rope_f32, kernel_flash_attn_ext_vec_reduce_gate, kernel_fa_gate_f32, kernel_cat_fill_set_rows), the rounding barrier only they used, and the QSA_NORM_ROPE, QSA_FA_GATE and QSA_KRAW tests. The flash attention encoder and the rope and common kernel sources are back to their state before the QSA fusions. QSA_TOPK (now id 17) is kept with the indexer key gather and constant head weight, still gated on the qwen4exp graph signature.
Shorten or drop the comments this series added, keeping the ones on bit-exactness, the qwen4exp signature gate, reduction order and in-place hazards, and restore the upstream comments it had reworded. Drop the test cases that repeat a path with a near-identical shape; every signature variant that must not fuse is kept. No functional change.
Remove GGML_METAL_FUSION_OFF and GGML_METAL_GDN_DELTA_NR. The delta step keeps its default of 4 state rows per simdgroup, doubled only while the pipeline cannot hold 128/nr simdgroups. GGML_METAL_FUSION_DISABLE is unchanged.
danielhanchen
left a comment
There was a problem hiding this comment.
Other-model check on Metal (M5 Max, AC power), base 0c8a972 vs this PR (50af5eb), built on the same machine.
test-backend-ops -b MTL0, all ops: base 21652/21652, head 21718/21718 (the 66 new cases included), no head-only failures. MUL_MV_SCALE_SILU 8/8, HC_POST_NORM_MUL 4/4, MUL_MV_HC_PRE 6/6.
Per model: greedy decode on 3 prompts x 128 tokens, llama-perplexity --kl-divergence -ub 1 on 10 WikiText-2 chunks against the base build's logits (an A/A base run is the reference row), and llama-bench tg128 run base, head, head, base.
| Model | Greedy (3 x 128) | Mean KLD, base A/A | Mean KLD, head | Same top, base / head | PPL base / head | tg128 base | tg128 head |
|---|---|---|---|---|---|---|---|
| Qwen3-0.6B Q8_0 | identical 3/3 | 0.000000 | 0.000000 | 100% / 100% | 23.7721 / 23.7721 | 414.1, 413.9 | 411.5, 409.6 |
| Qwen3-0.6B Q5_K_M | identical 3/3 | 0.000000 | 0.000000 | 100% / 100% | 24.0428 / 24.0428 | 459.9, 456.1 | 458.7, 459.9 |
| Llama-3.2-1B-Instruct Q5_K_M | identical 3/3 | 0.000000 | 0.000000 | 100% / 100% | 16.1589 / 16.1589 | 382.3, 388.0 | 383.0, 379.9 |
| gemma-3-1b-it Q8_0 | identical 3/3 | 0.000000 | 0.000000 | 100% / 100% | 33.0429 / 33.0429 | 287.4, 287.3 | 287.5, 287.5 |
| Qwen3.5-0.8B Q8_0 (hybrid) | identical 3/3 | 0.000001 | 0.000001 | 100% / 100% | 20.2498 / 20.2498 | 332.7, 333.1 | 331.9, 332.8 |
| gpt-oss-20b Q5_K_M (MoE) | identical 3/3 | 0.000000 | 0.000000 | 99.961% / 99.961% | 304.4252 / 304.4252 | 160.7, 160.7 | 160.9, 160.7 |
| Qwen4-35B-A3B UD-Q4_K_XL (target) | identical 3/3 | 0.000000 | 0.000000 | 100% / 100% | 8.0358 / 8.0358 | 89.7, 91.1 | 98.0, 97.9 |
On every model the head's KLD, top-token agreement, PPL and max KLD lines match the base A/A run in every printed digit, and greedy decode output is byte-identical. tg128 on the other models stays within the base runs' spread (the 0.6B / 1B rows have run-to-run spread of up to 20 tok/s), and the target model goes from 89.7-91.1 to 97.9-98.0 tok/s.
Why other models keep their kernels:
- The two fusions match only exact op sequences: a single-row contiguous Q8_0 MUL_MAT with no weight scale, read only by a SCALE, then a VIEW at offset 0, then SILU; and a DSV4_HC_POST without comb and with 4 streams, read only by an RMS_NORM (on the same shape), then a MUL with an F32 weight of 1 or 4 rows. Overlapping inputs and outputs are rejected. The only other model calling hc_post without comb (hy-v4-flash) reshapes before its norm, so it does not match.
- The short-row Q8_0 launch and the Q5_K split apply to any model with those row lengths, but both keep every lane's partial sums and the reduction order unchanged, so the results are bit-identical (as the rows above show).
Since this run, e925017 only adds the review fixes (the profiler respects the abort callback and no longer reports truncated timelines, and the hc_post + norm fusion rejects a norm weight that overlaps its outputs, with a new test case). CUDA (B200) on that head: MUL_MAT 2901/2901, MUL_MAT_ID 1128/1128, MUL_MV_SCALE_SILU 8/8, HC_POST_NORM_MUL 5/5, MUL_MV_HC_PRE 6/6.
Metal on e925017 (same M5 Max): HC_POST_NORM_MUL 5/5 (including the new aliasing case), MUL_MV_SCALE_SILU 8/8, MUL_MV_HC_PRE 6/6, MUL_MAT 2808/2808, MUL_MAT_ID 1233/1233. Greedy output is byte-identical to the 50af5eb build, and llama-bench runs cleanly with GGML_METAL_PROF=1 and with GGML_METAL_PROF=2 (GGML_METAL_CHUNK_NODES=1).
… tail has other readers or the gathered rows are not the keys
danielhanchen
left a comment
There was a problem hiding this comment.
Other-model check on Metal for the current head 267cbb7 (M5 Max, AC power), against base 0c8a972, built on the same machine. The model A/B ran on fc42936 plus the comment-only commit 33b99ca (the tree hash was checked on the Mac). 267cbb7 was then checked as the exact tree.
test-backend-ops -b MTL0, all ops: base 21652/21652, fc42936 + 33b99ca 21765/21765, 267cbb7 21766/21766. No case fails only on the PR builds. The new conv-step case (GDN_CONV_STEP tail_use=1) fails with the 267cbb7 check reverted (ERR 2.0) and passes with it.
Per model: greedy decode on 3 prompts x 128 tokens, llama-perplexity --kl-divergence -ub 1 on 10 WikiText-2 chunks against the base build's logits (with an A/A base run as the reference), llama-bench tg128 run base, head, head, base, and the fusions that fired (GGML_METAL_FUSION_DEBUG=1).
| Model | Greedy (3 x 128) | Mean KLD base A/A / head | Same top base / head | PPL base / head | tg128 base | tg128 head | Fusions fired on head |
|---|---|---|---|---|---|---|---|
| Qwen3-0.6B Q8_0 | identical 3/3 | 0.000000 / 0.000000 | 100% / 100% | 23.7721 / 23.7721 | 414.3, 409.8 | 413.1, 413.5 | RMS_NORM+MUL, MUL_MAT+ADD |
| Qwen3-0.6B Q5_K_M | identical 3/3 | 0.000000 / 0.000000 | 100% / 100% | 24.0428 / 24.0428 | 454.7, 457.5 | 459.4, 457.7 | RMS_NORM+MUL, MUL_MAT+ADD |
| Llama-3.2-1B-Instruct Q5_K_M | identical 3/3 | 0.000000 / 0.000000 | 100% / 100% | 16.1589 / 16.1589 | 384.3, 383.5 | 385.4, 378.9 | RMS_NORM+MUL, MUL_MAT+ADD |
| gemma-3-1b-it Q8_0 | identical 3/3 | 0.000000 / 0.000000 | 100% / 100% | 33.0429 / 33.0429 | 284.9, 287.7 | 287.5, 287.4 | RMS_NORM+MUL, RMS_NORM+MUL+ADD |
| Qwen3.5-0.8B Q8_0 (hybrid, gated delta net) | identical 3/3 | 0.000001 / 0.000001 | 100% / 100% | 20.2498 / 20.2498 | 332.8, 333.1 | 332.6, 332.2 | RMS_NORM+MUL, RMS_NORM+SCALE, GATED_DELTA_NET+CPY, SSM_CONV+UNARY, MUL_MAT+ADD |
| gpt-oss-20b Q5_K_M (MoE) | identical 3/3 | 0.000000 / 0.000000 | 99.961% / 99.961% | 304.4252 / 304.4252 | 160.5, 158.6 | 158.3, 158.8 | RMS_NORM+MUL, MUL+ADD+ADD+ADD |
| Qwen4-35B-A3B UD-Q4_K_XL (target) | identical 3/3 | 0.000000 / 0.000000 | 100% / 100% | 8.0358 / 8.0358 | 90.2, 90.4 | 105.2, 104.9 | (the qwen4exp fusions) |
On every model the head's KLD, top-token agreement, PPL and max KLD lines equal the base A/A run in every printed digit, and greedy output is byte-identical. On the six other models only fusions that already existed before this PR fire, Qwen3.5 included (it has a gated delta net but a plain hc_pre). Their tg128 stays within the base runs' own spread. Greedy output of 267cbb7 is identical to fc42936 + 33b99ca on Qwen4-35B-A3B and Qwen3.5-0.8B.
CUDA (B200) on 33b99ca: MUL_MAT 2901/2901, MUL_MAT_ID 1128/1128, LIGHTNING_INDEXER 240/240, TOP_K 534/534, and all the new cases pass. On 267cbb7: GDN_CONV_STEP 7/7 and QSA_SELECT 12/12. No CUDA code changes.
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
Faster Metal decode for
qwen4exp(Qwen4-35B-A3B) on Apple Silicon, with identical outputs. On an M5 Max with UD-Q4_K_XL, tg128 goes from 91.14 to 106.56 tok/s (+16.9%).unslothai/llama.cpp prebuilt = upstream ggml-org aged
b####+scripts/unsloth/pr-set.jsonpins, merged in order. This PR is a pin: upstream0c8a972(b13019 + 2) plus this one change, based onbase/upstream-0c8a9726c. It cannot sit on the b12966 pin base, becauseqwen4expitself arrived upstream after b12966; the current aged base b13024 contains0c8a972. Once upstream has an equivalent change, the pin is dropped.Changes
Metal backend and tests, plus one graph-order change in
src/models/qwen4exp.cpp.First round (all models, launch parameters only):
hc_up(256 columns) goes from 8.3 to 4.6 us per call.Fusions, all gated to
qwen4expgraphs (see Scope below):MUL_MV_SCALE_SILUHC_POST_NORM_MULhc_postfolded into the next RMS_NORM + MUL, same reduction order as the norm kernelHC_TAIL_ATTNhc_post+ normNORM_MUL_SIGMULGDN_CONV_STEPGDN_DELTA_STEPQSA_TOPKAlso:
test-backend-opscases for every fusion. Kill switches:GGML_METAL_QWEN4EXP_FUSION_DISABLE=1turns off only fusions 11-17 (it makes the qwen4exp graph check return false, so the optimizer, the encoders and the alloc deps all skip them) and leaves the base's Metal fusions on; the existingGGML_METAL_FUSION_DISABLE=1turns off every Metal fusion, including the ones the base already has (about 16% below the base on the Mac). The short-row launch changes 1-2 are not covered by either switch; they are bit-identical by construction (below). The decode profiler of earlier heads (GGML_METAL_PROF*,GGML_METAL_CHUNK_NODES) is removed from the pin.src/models/qwen4exp.cpp: thecache_sgather moves beforebuild_conv_state_at, so the conv step chain is contiguous in the graph. Order only, no change to the math.Tried and left out: an
hc_up+HC_PREfusion (0.6% slower), a FFN sublayer tail fusion (not bit-exact under fast math), a routed-expert gate + up + swiglu kernel (bit-exact but slower in the real decode stream), and three more attention-core fusions (bit-exact but no measurable gain).Scope: other models
DSV4_HC_PRE(ggml_dsv4_hc_pre_gated) and aGATED_DELTA_NETnode. Onlyqwen4expbuilds that pair. glm5-next, kimi-k3/k31, raon1-mini and zonos3 (plainhc_prewith GDN) and DeepSeek V4 (HC without GDN) are rejected.qwen35), Qwen3.5-35B-A3B Q2 (qwen35moe) and Qwen3-0.6B (qwen3) give identical greedy tokens,-ub 1KLD identical to their own A/A run, and identical fusion statistics with zero engagements of the new fusions.Results (M5 Max, UD-Q4_K_XL, AC power)
0c8a972Dispatches per decoded token drop from about 1980 to about 1465. The linear-attention step kernels (15, 16) give most of the second-round gain (about +4 to +8 tok/s).
Correctness
Measured on the PR branch at
267cbb7, whose kernels and fusions are identical to this head (the head only drops the profiler and comments): all 21,766 Metaltest-backend-opscases pass, and six other models give unchanged output and speed, with a negative control.llama-perplexity --kl-divergence,-ub 1so the fused kernels run, 10 WikiText-2 chunks): identical to the A/A run in every printed line (mean 0, same top token 100%).test-backend-opson Metal, this exact commit: MUL_MAT 2808/2808, MUL_MAT_ID 1233/1233, RMS_NORM 61/61, GATED_DELTA_NET 89/89, SSM_CONV 75/75, LIGHTNING_INDEXER 240/240, TOP_K 534/534, TOP_K_MASK 38/38, and every new fusion test including the must-not-fuse and aliasing cases.Pin set
llama_pinset.py simat b13024 with the current 67-pin round plus this pinpin_contractall intact,merge_checksclean. The only overlap is an add/add hunk intests/test-backend-ops.cppnext to the Inkling perf cases, resolved additivelytest-backend-ops -b MTL0full run: A 23239/23248, B 23357/23362; the only failures on both sides are a fewHC_MIX_FUSEDandFLASH_ATTN_EXT_BANDED(bf16)cases marginally over the 5e-4 NMSE limit (0.00051 to 0.0007), and A fails more of them than B. Touched ops all pass on both (MUL_MAT 3027/3027, MUL_MAT_ID 1418/1418, GATED_DELTA_NET, SSM_CONV, RMS_NORM, TOP_K, CONCAT, GET_ROWS, CPY, LIGHTNING_INDEXER, DSV4_HC_PRE / POST / COMB)The
HC_MIX_FUSED/FLASH_ATTN_EXT_BANDED(bf16)failures above are tolerance noise, not this pin:HC_MIX_FUSEDbuilds an HC graph without aGATED_DELTA_NET, so none of fusions 11-17 run in it;FLASH_ATTN_EXT_BANDEDuses no kernel this pin touches.HC_MIX_FUSEDreaches is the short-row Q8_0 launch on its 256-columnw_upmat-vec (8 blocks per row). With 4 simdgroups the extra 3 only held 0.0 partials, and the cross-simdgroup sum adds the same nonzero partial to the same zeros, so the output is bit-identical for the same input. The 5e-4 NMSE margin is set by Q8_0 activation rounding in the CPU reference.test-backend-opsdraws inputs fromstd::random_deviceon each run, so which borderline cases cross 5e-4 changes from run to run. That is why B newly failsn_tokens=1, post=0while A fails 7 cases and B 3. (A seed sweep, 20 runs per side, is in the Mac rerun below.)On the pin-set tree (A = 67-pin set, B = A + this pin), Qwen4-35B-A3B UD-Q4_K_XL, A/B/A/B rotated:
MTP 2 acceptance is 149 of 212 drafts in every A and B run, and the generated text is identical across all runs.
Greedy text on the pin-set tree, A vs B: identical on Qwen4-35B-A3B UD-Q4_K_XL, Qwen3.8-27B UD-IQ2_XXS, Inkling-2-Mini UD-IQ1_S and Qwen3.8-Flash-Next UD-IQ1_S (
--cpu-moe), and on an NVFP4 Qwen3.8-27B.GGML_METAL_FUSION_DISABLE=1also turns off the Metal fusions the base already has, so with it B matches A run with the same switch (same text), not A's default.Rerun of this head (
ab80aa9) on the Mac, same pin-set tree (A = 67-pin set, B = A + this pin, Bk = B withGGML_METAL_QWEN4EXP_FUSION_DISABLE=1), Qwen4-35B-A3B UD-Q4_K_XL,llama-bench -r 3, 3 rotated rounds with a second base arm A2:4367bd6c), and A and Bk on Inkling-2-Mini (c6719213).HC_MIX_FUSEDover 5 runs per side: A passes 3 to 7 of 10 per run (9 distinct borderline IDs fail at least once, none in every run), B passes 4 to 6 (10 distinct IDs, one in every run). Every failure is an NMSE between 5.0e-4 and 1.06e-3 against the 5e-4 limit, on both sides.FLASH_ATTN_EXT_BANDED: A 325/327 in all 5 runs, B 325/327 in 4 runs and 326/327 in one.Not tested
pr-set.json,feature-checks.json) is a follow-up once this is reviewed.