Skip to content

perf(ggml-cuda): bit-identical qwen4exp prefill fusions on gfx1151 (stacked on #860) - #862

Merged
davide221 merged 9 commits into
Luce-Org:mainfrom
dusterbloom:pr/qwen38-prefill-fusions
Oct 23, 2026
Merged

davide221 merged 9 commits into
Luce-Org:mainfrom
dusterbloom:pr/qwen38-prefill-fusions

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #860 (row-split gated-delta-net prefill recurrence). Merge order: #860, this. Review only this PR's commits (five fusions plus two review fixes): dusterbloom/lucebox-hub@dc50b1d...243994d

What

Five changes to the qwen4exp prefill graph on gfx1151, one commit each. Every commit has its own kill switch and its own test, and all five are bit-identical to the code they replace.

  1. 16-byte vector path for strided same-type copies (LUCE_CPY_VEC_LEGACY). The K/V cache append (a permuted F16 CPY into a cache view) ran cpy_scalar<half, half>, one element per thread, at about 36 GB/s. The copy now moves one uint4 per thread when three conditions hold:

    • source and destination have the same type;
    • the contiguous inner dimension is a multiple of 16 bytes;
    • the outer strides and bases are 16-byte aligned.

    Every other shape keeps the scalar kernel.

  2. QSA3 union bitmap kernel and per-forward M-RoPE table (LUCE_ATTN_PREFILL_LEGACY).

    • Union. QSA3 prefill built the union of each query group's selected blocks by rank-sorting every id row and merging pairwise. The rows hold -1 holes, so the sortedness check failed for every query before the indexer top-k position, and the O(ns^2) sort ran on half the rows. One bitmap kernel now marks the selected blocks per group.
    • M-RoPE table. M-RoPE recomputed an FP64 angle for every layer and head. A cos/sin table is now built once per positions tensor and forward, and Q, K and the indexer query of all layers share it. Entries are keyed by node, data pointer and a generation that is bumped per graph compute, so a recycled pool address cannot serve a stale table.
  3. Wave-per-row gated norm, and q/k norm folded into the GDN conv epilogue (LUCE_GDN_NORM_LEGACY). Both reproduce the reduction order of the kernels they replace.

    • q/k norm. The SSM_CONV epilogue applies the q/k L2 norm itself. The graph passes the channel count, epsilon and scale in the node's op_params. The generic kernel asserts if the fusion did not match, so an unnormalised q/k cannot reach the recurrence.
    • Gated norm. A 32-lane wave owns each 128-column gated-norm row. The 256-wide gamma-free gate stays on the block kernel, where the wave version measured slower.
  4. Attention norm sites (LUCE_ATTN_FUSE_LEGACY).

    • RMS_NORM, MUL and ROPE (and the PERMUTE and CONT after it) run in one launch for the attention Q and K and the indexer q. This fires only where rope takes its per-token path (qwen4exp on HIP RDNA3.5); other q/k-norm M-RoPE graphs, such as Qwen3.5, and CUDA builds keep the separate kernels.
    • The gated store is a HIP-only dispatch, like the other QSA calls.
    • The QSA3 prefill attention store folds in the sigmoid output gate and writes the F16 operand of the output projection directly.
    • The hc grouped norm expands its gamma view first, so RMS_NORM and MUL are adjacent and the backend fuses them.
  5. PLE conv and norm (LUCE_PLE_FUSE_LEGACY).

    • Conv. The PLE conv matcher took its shape from the 3-D view root, so it never matched. It now reads the logical shape from the reshape and the contiguity from the root, so concat, tap copies, mul, add and silu run as one launch, and the graph drops the CONT after silu. The fused kernel keeps main's lifetime contract: it reads the transposed input that the first tap holds alive through src[1], and it reads the state from the concat head.
    • Norm. The PLE grouped norm expands its gamma view first, so RMS_NORM and MUL fuse.

Changes 2 to 5 run only on qwen4exp graph paths. The copy path (1) applies to every same-type copy with the aligned shape on the CUDA/HIP backend, decode's cache append included; it moves bytes, so no result changes. Other backends are untouched. There are no new flags apart from the five kill switches.

Exactness

Against the #860 head (main + #860):

  • Teacher-forced. Over the same 2,392 positions (2 code and 2 prose slices, 599 forced tokens each, no draft), KL is exactly 0 and the dumped logits files are byte-identical.
  • Greedy. Outputs are hash-identical on every generation: 10 of 10 p4096, 8 of 8 p16384 and 46 of 46 no-draft decode requests.
  • All five kill switches set. The tip is identical to main + perf(ggml-cuda): row-split gated-delta-net prefill recurrence on gfx1151 #860: the logits are byte-identical, and the greedy outputs are hash-identical on 10 of 10 p4096, 8 of 8 p16384 and 23 of 23 decode requests.

So this PR's quality against main is #860's quality (mean KL 0.0096, top-1 96.36%, NLL 1.0970 vs 1.1006, 72.78% accuracy on the forced text on both).

Tests (gfx1151, at this head)

New unit tests, registered with the unit-test targets, all pass:

  • test_cpy_vec_parity. Compares the whole destination buffer with a host reference, for vector shapes (F16 [256, 2, 4136] into a cache view, T = 1, F32 [128, 48, 128]) and for fallback shapes (inner dimension 24 and 6, misaligned base).
  • test_qsa3_union_parity. Compares every kernel variant with a CPU set union.
  • test_rope_table_parity. The table rotation and the inline rotation are hash-equal.
  • test_gated_norm_wave_parity and test_gdn_conv_qknorm_parity. Byte comparisons against the block-per-row kernel and against the RMS_NORM + SCALE chain, at T in {1, 7, 333, 4096} and {256, 333, 4096}.
  • test_norm_rope_fusion. The fusion fires on all 9 expected sites, and the output hash equals the separate kernels. With the qwen4exp profile off (a Qwen3.5-style graph), nothing fuses and the output equals the separate kernels.
  • test_qsa3_gate_parity. 0 F16 mismatches against the store + gate kernels.
  • test_hc_norm_mul_fusion and test_ple_norm_mul_fusion. With the gamma view expanded first, RMS_NORM and MUL are adjacent, and the hash equals the legacy order.
  • test_ple_conv_fusion. Rebuilds the qwen4exp PLE subgraph. It requires zero matcher give-ups, and the output hash must equal the unfused nodes.

test_gdn_rowsplit_parity from #860 still passes.

Speed (gfx1151, UD-Q4_K_XL)

Measured at 5240b3a. The two fix commits on top (CUDA link guard and norm+rope gate; the LUCE_ATTN_PREFILL_LEGACY mapping) do not change the gfx1151 qwen4exp default path: the fused norm+rope still fires on all 9 test sites with the same hash, and all 11 unit tests pass at 243994d.

Setup.

Prefill, server tok/s, median / mean / best / min:

prompt main main + #860 main + #860 + this PR
p4096 1139.1 / 1137.9 / 1178.8 / 1044.6 1201.5 / 1195.0 / 1215.2 / 1136.6 1247.1 / 1241.2 / 1269.2 / 1154.3
p16384 1264.9 / 1245.0 / 1299.6 / 1110.6 1337.4 / 1329.8 / 1366.8 / 1225.7 1379.5 / 1359.1 / 1418.8 / 1017.3
step p4096 median (mean) p16384 median (mean)
this PR over #860 +3.79% (+3.86%) +3.15% (+2.20%)
#860 over main +5.48% (+5.02%) +5.73% (+6.81%)
#860 + this PR over main +9.48% (+9.07%) +9.06% (+9.16%)

Block medians:

prompt main #860 this PR
p4096 1148, 1153, 1134, 1129 1202, 1206, 1202, 1183 1245, 1252, 1265, 1219
p16384 1289, 1270, 1267, 1255 1347, 1333, 1359, 1332 1366, 1405, 1406, 1376

Client-side prefill (time to first token), median tok/s:

prompt main #860 this PR
p4096 1110.8 1164.4 1211.4
p16384 1255.1 1326.5 1367.9

Wall for 8 new tokens, seconds, median / mean / lowest / highest:

prompt main #860 this PR
p4096 3.74 / 3.77 / 3.67 / 4.14 3.60 / 3.60 / 3.52 / 3.82 3.47 / 3.47 / 3.38 / 3.77
p16384 13.13 / 13.38 / 12.82 / 15.06 12.43 / 12.53 / 12.13 / 13.66 12.09 / 12.31 / 11.68 / 16.42

Decode without the draft (256 new tokens, ABBA with 2 blocks per arm, n = 40 per arm):

  • Client tok/s, median / mean / best / min: main 24.0 / 24.1 / 24.9 / 23.6; this PR 24.0 / 23.9 / 24.5 / 23.4.
  • Server median: 23.7 and 23.6.

Decode is unchanged: these changes touch prefill graph nodes only, and the outputs are bit-identical.

Per commit

The five are one PR because no single one shows a gain that clearly survives the spread between blocks; together they add +3% to +4% to prefill (table above). The leave-one-out rows (tip against tip with one switch set, ABBA, 2 blocks per arm, n = 16 at p4096 and n = 12 at p16384) were measured on a longer stack. That stack also carried a single-launch F16 routed GLU kernel, which is not in this PR:

switch p4096, tip over switch-on p16384, tip over switch-on
LUCE_CPY_VEC_LEGACY -0.49% -0.40%
LUCE_ATTN_PREFILL_LEGACY -0.06% +2.05%
LUCE_GDN_NORM_LEGACY +1.21% -0.60%
LUCE_ATTN_FUSE_LEGACY -0.59% +0.16%
LUCE_PLE_FUSE_LEGACY +1.40% +3.46%

The spread between blocks of one arm in those runs was 1.5% to 3%. Only the QSA3 and PLE rows at p16384 are above it. The combined step above is the measurement that counts.

Kill switches

All five are unset by default. Setting one to 1 restores the previous code for its commit:

  • LUCE_CPY_VEC_LEGACY
  • LUCE_ATTN_PREFILL_LEGACY
  • LUCE_GDN_NORM_LEGACY
  • LUCE_ATTN_FUSE_LEGACY
  • LUCE_PLE_FUSE_LEGACY

All five set together restore main + #860 exactly (see Exactness). They are documented in server/docs/ENVIRONMENT.md.

Replace the tiled S_v=128 chain-mode prefill kernel with a row-split
recurrence on RDNA3.5: four lanes own one state row, each lane carries two
rows, the decay is folded into a scaled state so the per-token update is one
in-place FMA per element, and token windows are staged through
double-buffered LDS. The scaled-state factor is floored at 1e-24 so gates
with expf(g) == 0 do not produce NaN.

The route is unchanged: qwen4exp graphs, chain path, one sequence,
S_v=128, H=48, T>=2. LUCE_GDN_LEGACY=1 restores the tiled kernel. The output
differs from the tiled kernel by float32 reassociation noise, so greedy
decoding can diverge between the two kernels; test_gdn_rowsplit_parity
compares both at T in {1, 5, 33, 512, 4096}. Layout adapted from gufo's
GdnRowSplitKernelT (MIT); the notice is in gated_delta_net.cu.
The K/V cache append of the qwen4exp graphs (a permuted F16 CPY into a cache
view) ran cpy_scalar<half, half> with one element per thread at about 36 GB/s.
When source and destination have the same type, a contiguous inner dimension
that is a multiple of 16 bytes, and 16-byte aligned outer strides and bases,
the copy now moves one uint4 per thread with the same index decomposition.
The bytes are moved, not converted, so the result is identical; every other
shape takes the scalar kernel as before. LUCE_CPY_VEC_LEGACY=1 keeps the
scalar kernel.

test_cpy_vec_parity compares the whole destination buffer against a host
reference for vector-eligible shapes (F16 [256, 2, 4136] into a cache view,
T=1, F32 [128, 48, 128]) and for the fallback shapes (inner dimension 24 and
6, misaligned base).
…rward M-RoPE table

QSA3 prefill built the union of the selected blocks of each query group with
a rank sort of every id row followed by a pairwise merge. The rows hold -1
holes between the selected blocks and the tail, so the sortedness check failed
for every query before the indexer top-k position and the O(ns^2) sort ran on
half the rows. One bitmap kernel now marks the selected blocks per group
directly.

M-RoPE recomputed the FP64 angle for every layer and head. The angle depends
only on the token and the pair, so a table of cos/sin is built once per
positions tensor and forward and shared by Q, K and the indexer query of all
layers. Entries are keyed by node, data pointer and a generation bumped per
graph compute, so a recycled pool address cannot serve a stale table.

Both changes are bit-identical. LUCE_ATTN_PREFILL_LEGACY=1 restores the
previous kernels and the inline angles. test_qsa3_union_parity compares every
kernel variant with a CPU set union, test_rope_table_parity compares table and
inline rotations byte for byte.
…GDN conv epilogue

Gated-delta-net layers normalised q and k with a separate RMS_NORM and SCALE
after the conv, and the gated output norm ran one 128-thread block per row
with an LDS reduction. On gfx1151 the SSM_CONV epilogue now applies the q/k
L2 norm itself (the graph passes the channel count, epsilon and scale in the
node's op_params, and the generic kernel asserts if the fusion did not match so
an unnormalised q/k can never reach the recurrence), and a 32-lane wave owns
each 128-column gated-norm row. Both reproduce the reduction order of the
kernels they replace, so the results are bit-identical.

LUCE_GDN_NORM_LEGACY=1 restores the previous kernels and graph. The 256-wide
gamma-free gate stays on the block kernel, where the wave version measured
slower.

test_gated_norm_wave_parity and test_gdn_conv_qknorm_parity compare against the
block-per-row and the RMS_NORM + SCALE chains, byte for byte.
Three bit-identical changes behind one kill switch, LUCE_ATTN_FUSE_LEGACY=1:

- rope.cu: RMS_NORM -> MUL -> ROPE [-> PERMUTE -> CONT] in one launch for the
  attention Q/K and the indexer q (one block per token looping the heads, the
  same reduction as rms_norm_f32<256,true> and the same rotation as the
  per-forward table kernel).
- qsa.cu: the QSA3 prefill attention store folds in the sigmoid output gate
  and writes the F16 operand of the output projection directly.
- qwen4exp_graph.cpp: the hc grouped norm applies gamma on the 3-D norm
  output and expands the gamma view first, so RMS_NORM and MUL are adjacent
  and the backend fuses them.

Unit tests: test_norm_rope_fusion, test_qsa3_gate_parity, test_hc_norm_mul_fusion.
Two bit-identical changes behind one kill switch, LUCE_PLE_FUSE_LEGACY=1:

- ple-conv.cu: the PLE conv matcher took its shape from the 3-D view root and
  never matched. It now reads the logical shape from the reshape and the
  contiguity from the root, so concat, tap copies, mul, add and silu run as one
  launch. The graph drops the CONT after silu.
- qwen4exp_graph.cpp: the PLE grouped norm expands its gamma view first so
  RMS_NORM and MUL are adjacent and the backend fuses them.

Unit tests: test_ple_conv_fusion and test_ple_norm_mul_fusion.

@davide221 davide221 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review

Found 2 issues.

Copy to agent

Use the copy button in the top-right corner of the block, then paste into your agent.

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.

Repository: Luce-Org/lucebox
Reviewed commit: 5240b3a62b87ceb7e501efe79bac8cd6ebd1c6ae
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.

<file name="server/deps/llama.cpp/ggml/src/ggml-cuda/qsa.cu">

<violation number="1" line="704" end_line="707">
LUCE_ATTN_PREFILL_LEGACY=1 selects the new compacting rows kernel, not the legacy kernels it promises to restore

The kill switch's contract, stated both in the kernel comment at line 57 ("LUCE_ATTN_PREFILL_LEGACY=1 restores the previous kernels") and in the PR description (with all five kill switches set the tip is identical to main + #860), is that setting the env var returns to the pre-PR code path. But `rows_variant` is computed as `u &amp;&amp; atoi(u) ? 1 : 2`: variant 1 is `qsa3_rows_compact_kernel` + `qsa3_merge_kernel` — a kernel added by this PR — while the actual legacy path, `qsa3_rows_kernel` (the O(ns^2) rank sort) + merge, is variant 0 and is now unreachable from the graph path (only the unit test passes variant 0 explicitly to `ggml_cuda_qsa3_union_launch`). The union result is still numerically identical, but anyone setting the kill switch to diagnose a regression or to A/B against main + #860 (the PR's own exactness protocol) is silently still running new code on the rows phase, at ~5 ms/layer different performance characteristics from true legacy. Fix: map the env var to variant 0 (`return u &amp;&amp; atoi(u) ? 0 : 2;`), or add a separate env var if the compacting variant is intended to be selectable.

<suggestion>
    static const int rows_variant = [] {
        const char * u = getenv("LUCE_ATTN_PREFILL_LEGACY");
        return u &amp;&amp; atoi(u) ? 0 : 2;
    }();
</suggestion>
</violation>

</file>

<file name="server/deps/llama.cpp/ggml/src/ggml-cuda/rope.cu">

<violation number="1" line="1212" end_line="1219">
Fused norm+rope fires for any RMS_NORM-&gt;MUL-&gt;ROPE chain but only implements the RDNA3.5 mrope F32 case; other modes abor

**Contract.** `ggml_cuda_op_norm_rope` is dispatched from `ggml-cuda.cu:6604-6614` for *any* adjacent `GGML_OP_RMS_NORM -&gt; GGML_OP_MUL -&gt; GGML_OP_ROPE [-&gt; PERMUTE -&gt; CONT]` chain whenever `LUCE_ATTN_FUSE_LEGACY` is unset — there is no architecture, rope-mode, or dtype check at the dispatch site (unlike the neighbouring `qwen4exp_rdna35`-gated fusion at line 6628). Once it runs, the caller skips the RMS_NORM and MUL nodes (`i += 2`/`i += 4`), so the fused path must reproduce all three ops bit-identically for whatever rope the graph actually contains.

**How it breaks.**
1. Non-mrope rope modes: `ggml_cuda_op_rope_impl` switches `src0` to the norm's raw input (`rope.cu:1023`, `norm != nullptr ? norm-&gt;src[0] : dst-&gt;src[0]`), but only passes `norm_args` to `rope_multi_cuda` (the `is_mrope &amp;&amp; !is_vision` branch, lines 1149-1158). For `ROPE_TYPE_NEOX`/normal rope — the standard qk-norm pattern (`rms_norm -&gt; mul(norm_weight) -&gt; rope`) used by ordinary models — the rope kernel therefore rotates the **unnormalised, unscaled projection**, and the RMS_NORM and MUL are never computed at all. Silently wrong logits on any backend, including plain NVIDIA CUDA builds this repo supports.
2. mrope on any non-RDNA3.5 build: on NVIDIA CUDA (and non-RDNA3.5 HIP) `per_token` is `false` (the `#else` at lines 916-918), so the norm branch hits `GGML_ASSERT(per_token &amp;&amp; ne00 &lt;= 256)` at line 920 and aborts the process on the first attention layer.

Both paths are reachable because `ggml_cuda_can_fuse` only matches the op sequence/connectivity, and RMS_NORM-&gt;MUL-&gt;ROPE is the generic q/k-norm subgraph, not a qwen4exp-only shape. The unit test only exercises the gfx1151 mrope case, so neither failure is caught.

**Fix.** Make the fused entry honor only what it implements: in `ggml_cuda_op_norm_rope` (or the matcher in `ggml-cuda.cu`), require mrope (`!is_vision`), F32 input, `ne00 &lt;= 256`, and the RDNA3.5 per-token path (the same condition that sets `per_token` in `rope_multi_cuda`); otherwise execute the three ops via the existing separate kernels instead of skipping them.
</violation>

</file>
Issue overview
  1. LUCE_ATTN_PREFILL_LEGACY=1 selects the new compacting rows kernel, not the legacy kernels it promises to restore · confirmed (server/deps/llama.cpp/ggml/src/ggml-cuda/qsa.cu:704-707)

  2. Fused norm+rope fires for any RMS_NORM->MUL->ROPE chain but only implements the RDNA3.5 mrope F32 case; other modes abor · likely (server/deps/llama.cpp/ggml/src/ggml-cuda/rope.cu:1212-1219)

Reviewed 5240b3a6 · 4 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again

Comment on lines +704 to +707
static const int rows_variant = [] {
const char * u = getenv("LUCE_ATTN_PREFILL_LEGACY");
return u && atoi(u) ? 1 : 2;
}();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LUCE_ATTN_PREFILL_LEGACY=1 selects the new compacting rows kernel, not the legacy kernels it promises to restore · confirmed

The kill switch's contract, stated both in the kernel comment at line 57 ("LUCE_ATTN_PREFILL_LEGACY=1 restores the previous kernels") and in the PR description (with all five kill switches set the tip is identical to main + #860), is that setting the env var returns to the pre-PR code path. But rows_variant is computed as u && atoi(u) ? 1 : 2: variant 1 is qsa3_rows_compact_kernel + qsa3_merge_kernel — a kernel added by this PR — while the actual legacy path, qsa3_rows_kernel (the O(ns^2) rank sort) + merge, is variant 0 and is now unreachable from the graph path (only the unit test passes variant 0 explicitly to ggml_cuda_qsa3_union_launch). The union result is still numerically identical, but anyone setting the kill switch to diagnose a regression or to A/B against main + #860 (the PR's own exactness protocol) is silently still running new code on the rows phase, at ~5 ms/layer different performance characteristics from true legacy. Fix: map the env var to variant 0 (return u && atoi(u) ? 0 : 2;), or add a separate env var if the compacting variant is intended to be selectable.

Checked (95%): In qsa.cu:704-707 the kill switch computes rows_variant as u && atoi(u) ? 1 : 2, and the launcher (lines 607-623) maps variant 1 to qsa3_rows_compact_kernel — a kernel added by this PR — while variant 0, the legacy qsa3_rows_kernel rank-sort path (line 617), is unreachable from qsa_prefill_run. The kernel comment at line 57 and the PR's exactness protocol state that LUCE_ATTN_PREFILL_LEGACY=1 restores the previous kernels, so the switch does not deliver its promised legacy behavior.

Suggested change
static const int rows_variant = [] {
const char * u = getenv("LUCE_ATTN_PREFILL_LEGACY");
return u && atoi(u) ? 1 : 2;
}();
static const int rows_variant = [] {
const char * u = getenv("LUCE_ATTN_PREFILL_LEGACY");
return u && atoi(u) ? 0 : 2;
}();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid, fixed in 243994d: LUCE_ATTN_PREFILL_LEGACY=1 now selects variant 0, the rows kernel + merge that main runs. The union was the same either way (test_qsa3_union_parity covers every variant).

Comment on lines +1212 to +1219
void ggml_cuda_op_norm_rope(ggml_backend_cuda_context & ctx, ggml_tensor * norm, ggml_tensor * mul, ggml_tensor * rope,
ggml_tensor * cont) {
static const bool debug = getenv("LUCE_NORM_ROPE_DEBUG") != nullptr; // the unit test counts these lines
if (debug) {
fprintf(stderr, "[norm-rope] fused ne=[%lld,%lld,%lld] cont=%d\n", (long long) rope->ne[0], (long long) rope->ne[1],
(long long) rope->ne[2], cont != nullptr);
}
ggml_cuda_op_rope_impl<true>(ctx, rope, nullptr, cont, norm, mul);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fused norm+rope fires for any RMS_NORM->MUL->ROPE chain but only implements the RDNA3.5 mrope F32 case; other modes abor · likely

Contract. ggml_cuda_op_norm_rope is dispatched from ggml-cuda.cu:6604-6614 for any adjacent GGML_OP_RMS_NORM -> GGML_OP_MUL -> GGML_OP_ROPE [-> PERMUTE -> CONT] chain whenever LUCE_ATTN_FUSE_LEGACY is unset — there is no architecture, rope-mode, or dtype check at the dispatch site (unlike the neighbouring qwen4exp_rdna35-gated fusion at line 6628). Once it runs, the caller skips the RMS_NORM and MUL nodes (i += 2/i += 4), so the fused path must reproduce all three ops bit-identically for whatever rope the graph actually contains.

How it breaks.

  1. Non-mrope rope modes: ggml_cuda_op_rope_impl switches src0 to the norm's raw input (rope.cu:1023, norm != nullptr ? norm->src[0] : dst->src[0]), but only passes norm_args to rope_multi_cuda (the is_mrope && !is_vision branch, lines 1149-1158). For ROPE_TYPE_NEOX/normal rope — the standard qk-norm pattern (rms_norm -> mul(norm_weight) -> rope) used by ordinary models — the rope kernel therefore rotates the unnormalised, unscaled projection, and the RMS_NORM and MUL are never computed at all. Silently wrong logits on any backend, including plain NVIDIA CUDA builds this repo supports.
  2. mrope on any non-RDNA3.5 build: on NVIDIA CUDA (and non-RDNA3.5 HIP) per_token is false (the #else at lines 916-918), so the norm branch hits GGML_ASSERT(per_token && ne00 <= 256) at line 920 and aborts the process on the first attention layer.

Both paths are reachable because ggml_cuda_can_fuse only matches the op sequence/connectivity, and RMS_NORM->MUL->ROPE is the generic q/k-norm subgraph, not a qwen4exp-only shape. The unit test only exercises the gfx1151 mrope case, so neither failure is caught.

Fix. Make the fused entry honor only what it implements: in ggml_cuda_op_norm_rope (or the matcher in ggml-cuda.cu), require mrope (!is_vision), F32 input, ne00 <= 256, and the RDNA3.5 per-token path (the same condition that sets per_token in rope_multi_cuda); otherwise execute the three ops via the existing separate kernels instead of skipping them.

Checked (75%): The matcher for the fused norm+rope (ggml-cuda.cu:5269-5299) does check mrope mode, F32 dtype, ne0<=256 and ne2>=64, so the reviewer's claim 1 (non-mrope NEOX chains silently fusing with wrong results) is wrong. However, the matcher has no device/architecture gate (unlike the neighbouring ROPE->PERMUTE->CONT matcher at 5259 which requires ggml_cuda_qwen4exp_graph()), while rope_multi_cuda's per_token path is compile-time gated (rope.cu:916-918, #else const bool per_token = false;). On a non-RDNA3.5 build (plain CUDA) the fused entry hits GGML_ASSERT(per_token && ne00 <= 256) at rope.cu:920 and aborts, and any mrope F32 qk-norm model with ne2>=64 on such a build matches the fusion, so the abort is reachable in normal use.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 50af186. Claim 1 does not hold: the matcher already requires M-RoPE, F32, rows <= 256 and T >= 64. Claim 2 holds, and it also reaches Qwen3.5 graphs on HIP, where per_token is false too. ggml_cuda_norm_rope_enabled() now requires the per-token path (HIP, qwen4exp on RDNA3.5). test_norm_rope_fusion gained a profile-off arm: on 5240b3a it aborted, now nothing fuses and the output equals the separate kernels. The same commit puts the gated QSA3 store dispatch under GGML_USE_HIP, which fixes the CUDA link failures.

@davide221

Copy link
Copy Markdown
Contributor

CI failed on 5240b3a6

New qsa3 gate fusion calls HIP-only functions; NVIDIA CUDA builds fail to link

One of the fusion commits makes the shared CUDA dispatch file call three helper functions that only exist in qsa.cu, a file that is compiled only for AMD/HIP builds. Every NVIDIA CUDA job (Windows MSVC+CUDA, Linux CUDA, and the GB10 sm_121 runner) therefore fails at link time with unresolved symbols. The change under test is at fault; the kernels themselves are fine, the call site just needs to be skipped on non-HIP builds.

How to fix: Guard the new qsa3 gate fusion dispatch in ggml-cuda.cu with #if defined(GGML_USE_HIP)

  1. Edit server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu: wrap the GGML_OP_FLASH_ATTN_EXT + ggml_cuda_qsa_gate_enabled() dispatch block (the one calling ggml_cuda_flash_attn_ext_qsa_gated) in #if defined(GGML_USE_HIP) / #endif.
  2. Rebuild an NVIDIA target to confirm the link: cmake --build build --target test_dflash (Linux) or build backend_ipc_daemon on the Windows CUDA job.
  3. Push and let CI rerun; the HIP/gfx1151 job is unaffected and keeps the fusion.

link error: unresolved symbols (HIP-only code called from sh · high confidence · run

Details and evidence

Failed: Build Windows (MSVC + CUDA, library + server targets) › Build Windows targets; Build (cmake + uv sync --extra megakernel) › Build luce (smoke + server); GPU tests (self-hosted DGX GB10, sm_121 verifier) › Build focused NVIDIA verifier tests (sm_121)

All three failed jobs die at link, not compile. Windows: ggml-cuda.lib(ggml-cuda.cu.obj) : error LNK2019: unresolved external symbol "bool __cdecl ggml_cuda_qsa_gate_enabled(void)" plus ggml_cuda_flash_attn_ext_qsa_gate_supported and ggml_cuda_flash_attn_ext_qsa_gated, then fatal error LNK1120: 3 unresolved externals. Linux and the GB10 runner show the same three undefined references in libggml-cuda.so when linking test_dflash / test_server_unit.

Root cause: commit 9fe54e3 added a dispatch block in server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu:6617-6624 that calls ggml_cuda_qsa_gate_enabled(), ggml_cuda_flash_attn_ext_qsa_gate_supported() and ggml_cuda_flash_attn_ext_qsa_gated(). Those are defined only in server/deps/llama.cpp/ggml/src/ggml-cuda/qsa.cu:665-687, and qsa.cu is deliberately excluded from the NVIDIA CUDA build because it uses AMD intrinsics: server/deps/llama.cpp/ggml/src/ggml-cuda/CMakeLists.txt:124-129 (list(REMOVE_ITEM GGML_SOURCES_CUDA ... qsa.cu)). The HIP backend globs all *.cu, so HIP builds link; NVIDIA builds don't. The pre-existing qsa call in fattn.cu:4767 links on CUDA, so it must already sit behind a HIP-only guard; the new block in ggml-cuda.cu has no such guard. The ggml_cuda_can_fuse addition (ggml-cuda.cu:5303-5310) references no qsa symbols and is harmless.

Other things to try

  • Alternative: provide non-HIP stub definitions (e.g. #if !defined(GGML_USE_HIP) inline functions returning false) in qsa.cuh so the dispatch site needs no guard; keep whichever matches house style (fattn.cu already guards its qsa call).
  • After the fix, re-run the gfx1151 job and check test_qsa3_gate_parity still passes so the fusion itself is confirmed intact on HIP.
  • Reproduce locally with any NVIDIA CUDA configure: cmake --build build --target test_dflash fails to link before the patch and succeeds after.
Patch (1 file)

Not applied anywhere. To try it, save the diff as fix.patch and run git apply fix.patch.

diff --git a/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu b/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu
index 47312b8c..ccc493e4 100644
--- a/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu
+++ b/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu
@@ -6614,7 +6614,10 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud
                         }
                     }
 
+#if defined(GGML_USE_HIP)
                     // qsa3 prefill attention with the sigmoid output gate applied in its store (F16 out for wo).
+                    // HIP-only: these helpers live in qsa.cu, which the NVIDIA CUDA build excludes
+                    // (ggml-cuda/CMakeLists.txt REMOVE_ITEM), so referencing them there breaks the link.
                     if (node->op == GGML_OP_FLASH_ATTN_EXT && ggml_cuda_qsa_gate_enabled() && i + 1 < cgraph->n_nodes &&
                         ggml_cuda_flash_attn_ext_qsa_gate_supported(*cuda_ctx, node, cgraph->nodes[i+1]) &&
                         ggml_cuda_can_fuse(cgraph, i, { GGML_OP_FLASH_ATTN_EXT, GGML_OP_GATED_RMS_NORM_F16 }, {})) {
@@ -6622,6 +6625,7 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud
                         i++;
                         continue;
                     }
+#endif // defined(GGML_USE_HIP)
 
                     // Bit-exact replacement for the two-kernel GDN normalization.
                     // Qualified for qwen4exp on RDNA3.5 and 128-wide rows.
Prompt for a coding agent
A GitHub Actions run failed in Luce-Org/lucebox. Please fix it.

- Pull request #862 (branch `pr/qwen38-prefill-fusions`), commit 5240b3a62b87ceb7e501efe79bac8cd6ebd1c6ae
- Workflow: CI (https://github.com/Luce-Org/lucebox/actions/runs/39402254095)
- Failed: Build Windows (MSVC + CUDA, library + server targets) › Build Windows targets; Build (cmake + uv sync --extra megakernel) › Build luce (smoke + server); GPU tests (self-hosted DGX GB10, sm_121 verifier) › Build focused NVIDIA verifier tests (sm_121)

Diagnosis:
All three failed jobs die at link, not compile. Windows: `ggml-cuda.lib(ggml-cuda.cu.obj) : error LNK2019: unresolved external symbol "bool __cdecl ggml_cuda_qsa_gate_enabled(void)"` plus `ggml_cuda_flash_attn_ext_qsa_gate_supported` and `ggml_cuda_flash_attn_ext_qsa_gated`, then `fatal error LNK1120: 3 unresolved externals`. Linux and the GB10 runner show the same three undefined references in `libggml-cuda.so` when linking `test_dflash` / `test_server_unit`.

Root cause: commit 9fe54e3c added a dispatch block in `server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu:6617-6624` that calls `ggml_cuda_qsa_gate_enabled()`, `ggml_cuda_flash_attn_ext_qsa_gate_supported()` and `ggml_cuda_flash_attn_ext_qsa_gated()`. Those are defined only in `server/deps/llama.cpp/ggml/src/ggml-cuda/qsa.cu:665-687`, and `qsa.cu` is deliberately excluded from the NVIDIA CUDA build because it uses AMD intrinsics: `server/deps/llama.cpp/ggml/src/ggml-cuda/CMakeLists.txt:124-129` (`list(REMOVE_ITEM GGML_SOURCES_CUDA ... qsa.cu)`). The HIP backend globs all `*.cu`, so HIP builds link; NVIDIA builds don't. The pre-existing qsa call in `fattn.cu:4767` links on CUDA, so it must already sit behind a HIP-only guard; the new block in `ggml-cuda.cu` has no such guard. The `ggml_cuda_can_fuse` addition (ggml-cuda.cu:5303-5310) references no qsa symbols and is harmless.

Proposed fix: Guard the new qsa3 gate fusion dispatch in ggml-cuda.cu with #if defined(GGML_USE_HIP)
1. Edit `server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu`: wrap the `GGML_OP_FLASH_ATTN_EXT` + `ggml_cuda_qsa_gate_enabled()` dispatch block (the one calling `ggml_cuda_flash_attn_ext_qsa_gated`) in `#if defined(GGML_USE_HIP)` / `#endif`.
2. Rebuild an NVIDIA target to confirm the link: `cmake --build build --target test_dflash` (Linux) or build `backend_ipc_daemon` on the Windows CUDA job.
3. Push and let CI rerun; the HIP/gfx1151 job is unaffected and keeps the fusion.

Suggested patch (a starting point):
```diff
diff --git a/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu b/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu
index 47312b8c..ccc493e4 100644
--- a/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu
+++ b/server/deps/llama.cpp/ggml/src/ggml-cuda/ggml-cuda.cu
@@ -6614,7 +6614,10 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud
                         }
                     }
 
+#if defined(GGML_USE_HIP)
                     // qsa3 prefill attention with the sigmoid output gate applied in its store (F16 out for wo).
+                    // HIP-only: these helpers live in qsa.cu, which the NVIDIA CUDA build excludes
+                    // (ggml-cuda/CMakeLists.txt REMOVE_ITEM), so referencing them there breaks the link.
                     if (node->op == GGML_OP_FLASH_ATTN_EXT && ggml_cuda_qsa_gate_enabled() && i + 1 < cgraph->n_nodes &&
                         ggml_cuda_flash_attn_ext_qsa_gate_supported(*cuda_ctx, node, cgraph->nodes[i+1]) &&
                         ggml_cuda_can_fuse(cgraph, i, { GGML_OP_FLASH_ATTN_EXT, GGML_OP_GATED_RMS_NORM_F16 }, {})) {
@@ -6622,6 +6625,7 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud
                         i++;
                         continue;
                     }
+#endif // defined(GGML_USE_HIP)
 
                     // Bit-exact replacement for the two-kernel GDN normalization.
                     // Qualified for qwen4exp on RDNA3.5 and 128-wide rows.
```

Check out that commit, confirm the diagnosis, make the fix (adjust it if the diagnosis is wrong), and re-run the failing step locally before pushing.

Reply with /ci-fix and what to change to get a revised diagnosis.

dusterbloom and others added 3 commits October 20, 2026 13:55
… the HIP qwen4exp path

qsa.cu is built for HIP only, so the gated-store dispatch in ggml-cuda.cu
left three undefined symbols on every CUDA build (the Linux, Windows and
GB10 jobs failed to link). It is now under GGML_USE_HIP, like the qsa calls
in fattn.cu.

The RMS_NORM -> MUL -> ROPE matcher fired for any F32 M-RoPE q/k-norm chain,
but the fused kernel is rope_multi_cuda's per-token path, which runs only for
qwen4exp on HIP RDNA3.5. Anywhere else (Qwen3.5 graphs, CUDA builds) it hit
GGML_ASSERT(per_token) on the first prefill of 64 or more tokens.
ggml_cuda_norm_rope_enabled() now requires that path.

test_norm_rope_fusion gains a profile-off arm: nothing fuses and the output
equals the separate kernels. Before this change that arm aborted.
…kernel of the QSA3 union

The kill switch selected variant 1, the compacting rows kernel this PR adds.
Variant 0 is the rows kernel and merge that main runs. The union was the same
either way (test_qsa3_union_parity covers every variant); now the switch runs
main's kernels.
ENVIRONMENT.md: keep Luce-Org#860's LUCE_GDN_LEGACY row (now on main) and this PR's five kill-switch rows. The tree equals 183b7c3 + this branch, the build verified on lucebox2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@davide221
davide221 merged commit 9a6c85c into Luce-Org:main Oct 23, 2026
5 checks passed
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
CMakeLists.txt and ENVIRONMENT.md: keep this PR's test target and LUCE_MMVQ_INVARIANT_* rows next to the ones Luce-Org#860 and Luce-Org#862 added on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…er branch

kvflash_pager.h reset(): keep Luce-Org#854's sync_page_stream_() (checked wait that
clears page_work_queued_) and this branch's free_host_buffer_() helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…led snapshot branch

Via the Luce-Org#848 branch merge. server/CMakeLists.txt keeps both new unit tests
(test_kvflash_restore_plan.cpp and main's test_dflash_window.cpp).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…led grid branch

Via the Luce-Org#849 branch merge; no new conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…sion restore branch

Via the Luce-Org#850 branch merge. server/CMakeLists.txt keeps this branch's live
restore and resume tests plus main's test_dflash_window.cpp.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

2 participants