Skip to content

qwen3_5 cuda: decode attention merge with a thread per head value (TF_QWEN_MERGE_WIDE, default off) - #6185

Open
jojomondag wants to merge 5 commits into
ashhart:mainfrom
jojomondag:qwen-cuda-merge-wide
Open

jojomondag wants to merge 5 commits into
ashhart:mainfrom
jojomondag:qwen-cuda-merge-wide

Conversation

@jojomondag

@jojomondag jojomondag commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Every Qwen 3.5/3.8 decode attention ends in tf_q35_attn_merge: one warp for each (head, row), each lane holding 8 of the head's 256 values and walking the row's chunk partials in order. With TF_QWEN_MERGE_WIDE=1 (default off) that one launch takes tf_q35_attn_merge_wide with a block of 256 threads, one output value a thread. The chunk maxima and weights are staged once in shared memory, then every thread runs the warp kernel's loop for its value: the maximum over live chunks, then lsum = fmaf(PL, e, lsum) and acc = fmaf(PO, e, acc) with e = __expf(PM - mx), in chunk order, and acc / lsum rounded to bf16. Each output's operands and their order are the warp kernel's, so its bits are too; there is no other reduction order and no tolerance. Unset, the launch, its block width and every other path are today's.

Checks on this head

  • Head commit: 7d519658d on main 0ba35fe6d. The host checks below ran on this head. The device runs ran on 1da3ff553 (the same kernels by SASS, above) and are repeated on this head with the runs under "Not run yet".
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: 88 and 88, the same findings (0 new).
  • Tests run, with the command and pass, fail and skip counts:
    • zig build -Dfixed-cpu test-host: exit 0, no failed step. (It failed on dbfd89598, in the pin named above; an earlier version of this description said otherwise.)

    • The fast-gate steps on a trial merge with main 0ca167746: tools/pr_check.py --base origin/main --pr 6185 (0 errors; lean 88 against 88), git diff --check, tools/zig/cuda_common_check.py (61 local copies, 0 violations), cuda_fragment_check.py, cuda_common_check_test.py, tools/test_pdl_early_loads.py, zig fmt --check build.zig zig and zig test zig/tests/portable_names.zig: all pass.

    • Host selector test, zig build test-qwen35-merge-wide-host (reached by test-host): which kernel and block width the merge takes with the switch unset and set; exit 0. With a wrong expectation planted it fails (expected 1, found 2, 23 pass, 1 fail, exit 1).

    • zig fmt --check build.zig zig and git diff --check: clean. zig build native and zig build compile-cuda-tests with -Dsm=120: both compile.

    • Device test with planted controls, byte-equal repeats and guards, tf-cuda-test qwen-merge-wide on one RTX 5090 (nvcc 13.4, sm_120), on 1da3ff553, exit 0. Both merges run on the same partials at 24 query heads, each case twice, guard bytes checked after each:

      PASS qwen35 merge wide live: 1 rows (1 live), streams of { 0 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide live: 2 rows (2 live), streams of { 50, 200 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide sparse: 7 rows (7 live), streams of { 0, 50, 200, 8000, 8100, 100000, 262140 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide live: 16 rows (16 live), streams of { 0, 50, 200, 8000, 8100, 100000, 262140 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide sparse: 33 rows (33 live), streams of { 200, 8000, 8100 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide live: 64 rows (64 live), streams of { 0, 50, 200, 8000, 8100, 100000, 262140 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide live: 64 rows (40 live), streams of { 0, 50, 200, 8000, 8100, 100000, 262140 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide sparse: 5 rows (3 live), streams of { 0, 50, 200, 8000, 8100, 100000, 262140 } keys: every byte of the warp merge twice, guards
      PASS qwen35 merge wide: controls RED as planted (last chunk dropped, a maximum raised, first and last chunk swapped, 128 threads)
      

      The cases cover chunk counts 1, 2, 61, 63 and 64, rows past the device row count (which must stay untouched), chunks of zero weight, -Inf and NaN maxima, and garbage past each row's chunk count. The four controls must differ and do; the swapped-chunks one runs on a head built so that the fp32 order changes the bf16 result.

    • Compiler and per-SM usage records, tf-cuda-test kernel-contract-limits on fatbins built by nvcc 13.0.88 for sm_80/86/89/120/121, on 1da3ff553: record current for the new launch on all five.

      PASS limits sm_80 qwen35 tf_q35_attn_merge_wide: 32 registers, 512 static shared bytes, bound 256 (record current)
      PASS limits sm_86 qwen35 tf_q35_attn_merge_wide: 40 registers, 512 static shared bytes, bound 256 (record current)
      PASS limits sm_89 qwen35 tf_q35_attn_merge_wide: 40 registers, 512 static shared bytes, bound 256 (record current)
      PASS limits sm_120 qwen35 tf_q35_attn_merge_wide: 35 registers, 512 static shared bytes, bound 256 (record current)
      PASS limits sm_121 qwen35 tf_q35_attn_merge_wide: 35 registers, 512 static shared bytes, bound 256 (record current)
      

      The tool exits 1 on stale records of other families, which main 0ba35fe6d carries too. I have no 13.2 or 13.3 compiler for the record sets between 13.0 and my device compiler.

    • qwen35.cu's other kernels: the SASS of its 33 existing functions is the same on main 0ba35fe6d and on this head (nvcc 13.0.88 and nvcc 13.4, sm_120).

  • CI: on the first head fast-gate failed on cuda_common_check.py (fixed by dbfd89598); zig fails on the serving pin of environment.zig (above) and failed on dbfd89598 on the qwen35.cu pin too (fixed by 7d519658d); verify is the receipt gate. Not run yet on this head.
  • Not run yet (the card I measure on is in use; these follow in a comment, on this head, as soon as it is free, together with a repeat of the device test, the limits and the served table on this head):
    • the hash runs of tools/perf_receipt.py (main's binary against the head's, the switch set, a control with it unset, and a repeat);
    • tf-cuda-test kernel-contract with its SUMMARY line on the device;
    • served cells with a bf16 cache, with a paged cache, and with two admitted streams. Until then I claim none of them: every served number below is one stream, an fp8 cache, whole (unpaged). The device test does not depend on the cache type or paging, since the merge reads only the partials.
  • Not run, and why: sm_121 and every SM class but 170 (one RTX 5090; your GB10 run would be the first on sm_121); Metal, HIP, XPU (CUDA-only change).

Receipt

  • Main against branch: cells and numbers, or why they can't be run: the switch unset against set on this head (unset is main's path: the launch is tf_q35_attn_merge with 32 threads). One RTX 5090, one server an arm (the switch is read once), order unset, set, set, unset in one run; --drafter --kv-cache fp8 --prompt-precision int8 --context 262144 --parallel 1 --prompt-cache-gib 24, tools/bench_long_decode.py --tokens 256 --seed 1234, sampled replies (T=1) and one greedy reply an arm and cell. Server binary sha256 c225c7945b2446c4…, built from 1da3ff553. tok/s is all tokens over all decode time of a cell's replies; the last three columns are per reply (the same reply in the four servers):

    message cached tokens unset (tok/s) set (tok/s) change of the totals the two unset servers apart replies faster set median reply, set over unset
    1,500 words 0 (read cold each time) 246.11 / 246.28 246.72 / 246.71 +0.2 % 0.07 % 13 of 13 +0.21 %
    24,000 words 20,480 219.21 / 219.45 220.98 / 221.47 +0.9 % 0.11 % 13 of 13 +0.89 %
    88,000 words 86,016 187.66 / 187.95 189.07 / 189.66 +0.8 % 0.15 % 6 of 9 +0.12 %
    150,000 words 147,456 157.89 / 153.88 158.89 / 159.09 +2.0 % 2.6 % 6 of 7 +1.8 %
    246,000 words 245,760 134.08 / 132.74 134.60 / 134.76 +1.0 % 1.0 % 4 of 5 +1.6 %

    How far these go. At 0 and 20,480 cached tokens the gain is above the baseline's own variation: every reply is faster in both set servers, and the two unset servers are 0.1 % apart. From 86,016 cached tokens on it is not: at 86,016 the totals read +0.8 % but the median reply only +0.12 %, and single replies move by up to 3.4 % between the two set servers; at 147,456 and 245,760 the two unset servers are as far apart (2.6 % and 1.0 %) as the change (one reply of the second unset server at 147,456 ran 9.5 % slower than in the first). So for the long contexts these runs show no loss and no established size. Every reply's token and output hash equals the first server's in all four servers of every cell (47 replies a server). No panic line in the eight server logs.

  • All earlier attempts, in another build: the same kernel on main 79f40fb76 (with TF_CUDA_TEST_ATTN_MT2=1, TF_QWEN_PROMPT_SPLITK=1, TF_QWEN_LAZY_SAVE=1, TF_QWEN_REQUEST_STARTS=1), same card. On this branch the table above is the only served run.

    • A first pair, unset then set, at 2k / 33.6k / 143k cached tokens: 0.2 to 0.3 / 0.7 to 0.8 / 1.8 % less time a round, 18 of 18 replies equal, equal round counts.
    • Four servers unset, set, set, unset at 33.6k and 143k, greedy and sampled, 3 replies a cell: 16.31 / 16.22 / 16.23 / 16.34 ms a round at 33.6k greedy (0.6 % less) and 21.55 / 21.20 / 21.20 / 21.59 at 143k (1.7 % less); sampled 0.7 % and 1.8 %. The two unset servers agree within 0.2 %. 12 of 12 replies equal in each server, equal round counts.
    • A kernel trace of the served rounds: the merge at 5.7 -> 3.3 us a launch at 2k, 13.9 -> 6.6 us at 33k and 34.9 -> 12.7 us at 140k (16 launches a round).
    • A kernel duel outside the server, both kernels on the same inputs: 0 of 2,998,272 output values differ over 40 cells (1 to 32 rows, 300 to 245k keys); a planted control with the chunk loop reversed differs in 135 values.
    • That build also had a mode that ran both merges inside the served round and trapped on a differing byte: about 280 rounds of 16 merges without a trap, and a planted difference killed the server at its first forward. The mode is not in this branch (decode forwards run in captured graphs, so it needs a device trap); the device test compares the kernels instead.
  • The raw per-reply numbers and hashes of the table are in the first comment below.

  • Boxes it reaches: Qwen 3.5/3.8 decode attention on CUDA, every form that ends in tf_q35_attn_merge (bf16 and fp8 caches, whole and paged, the MT2, w2, rows and join forms, and prompt forwards that take the decode partials), only with the switch set. The drafter's own merge (tf_q35d_attn_merge) and the prompt tile path, which has no merge, are untouched. The 256-thread block assumes a head of 256 values (static_assert), which every Qwen 3.5/3.8 geometry has.

  • New switch? Default, accepted values, profile row: TF_QWEN_MERGE_WIDE, 0 or 1, unset 0, profile class identical, in docs/environment.md, docs/environment-names.md, platform/environment.zig, environment_valid_cases.zig, core/profile.zig and the CLI's environment list. One new kernel in the qwen35 image, registered with the kernel contract. No stored-data change.

  • Environment, with the TensorFold commit, Zig and backend toolchain, machine and GPU, checkpoint and revision: heads 1da3ff553 (device runs) and 7d519658d (host checks) on main 0ba35fe6d, zig build native -Dsm=120, Zig 0.17.0, nvcc 13.4 (usage records from nvcc 13.0.88); one RTX 5090 32 GB (170 SMs), driver 615.78.08, Ryzen 7 9800X3D, Linux, nothing else on the GPU during a timed run; TensorFold/Qwen3.8-27B-MLX-4bit@22d8d538, drafter z-lab/Qwen3.8-27B-DFlash2@50307d4c.

  • Paths and platforms the change reaches, which I ran and which I could not: ran on sm_120 (170 SMs): one stream, drafted, greedy and sampled, an fp8 whole cache, int8 prompts, 0 to 245,760 cached tokens. Not run yet: bf16 caches, paged caches, two streams (above). Could not run: sm_121 and other SM classes.

  • Exactness, from tools/bench_concurrent.py --alone --serial or token_sha against "draft": false: the fixture's token and output hashes in every server, and the device test's byte comparison of the two kernels with its four planted controls. Drafted against "draft": false comes with the hash runs.

  • Main against this branch, same machine and checkpoint, posted before asking for a run on our machines (or why you can't): the table above (unset is main's path). Main's binary against the head's comes with the hash runs.

  • Decode speed before and after, from tools/bench_openai.py: the table above.

  • Prompt speed before and after: not measured. Prompt forwards that take the decode partials reach the merge; the prompt tile path does not.

  • Licence of any new weights or drafter, or "n/a": n/a

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. None of the three is run on this change yet; drafted against "draft": false and concurrent against solo follow with the runs listed under "Not run yet".

  • 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. Measured: decode at one stream with --drafter. Two streams, the drafter off and prompt speed were not measured.

@jojomondag

Copy link
Copy Markdown
Contributor Author

Raw numbers behind the description's table, on 1da3ff553 (server binary sha256 c225c7945b2446c4…, one RTX 5090). Four servers in the order unset, set, set, unset; the same replies in the same order in each server (sampled T=1 seed 1234, the last one greedy). Decode tok/s of each reply, and the first 12 hex digits of each reply's token sha256 (equal across the four servers in every row; the output sha256 is equal too).

1,500 words, 0 cached tokens: 13 replies a server
reply T tokens unset 1 set 1 set 2 unset 2 token sha256 equal in all four
1 1 256 251.02 251.20 251.58 251.04 45a2fc1536d0 yes
2 1 256 243.55 244.00 243.98 243.61 97a53fc6ca9e yes
3 1 256 253.79 254.35 254.28 253.88 304685db5e4f yes
4 1 256 236.82 237.37 237.40 237.02 405703eb3c73 yes
5 1 256 257.39 258.07 257.99 257.49 efeb42dd5a6a yes
6 1 256 253.58 254.20 254.21 253.73 6a79d8b6525e yes
7 1 256 239.81 240.35 240.33 239.87 9ec77bd0aca8 yes
8 1 256 247.01 247.53 247.52 247.11 2b5d73589ee6 yes
9 1 256 239.78 240.38 240.23 239.92 09af128967c4 yes
10 1 256 243.02 243.65 243.65 243.22 d1370dd6e5b5 yes
11 1 256 257.20 258.08 258.00 257.48 e09a046ded0d yes
12 1 256 233.40 234.15 234.18 233.76 fe8ad1e69e77 yes
13 0 256 246.09 246.95 246.78 246.44 9704a5644f9f yes
all 3328 246.11 246.72 246.71 246.28
24,000 words, 20,480 cached tokens: 13 replies a server
reply T tokens unset 1 set 1 set 2 unset 2 token sha256 equal in all four
1 1 256 193.21 195.05 195.26 193.26 724d99826617 yes
2 1 256 214.38 216.39 216.62 214.51 99a8eaf006d2 yes
3 1 256 232.97 235.14 235.35 233.08 a8c8f6ef89b0 yes
4 1 256 226.75 228.86 229.10 226.88 d97b45ce48bc yes
5 1 256 226.36 225.24 228.74 226.51 2324a8f34cf8 yes
6 1 256 229.48 231.58 231.83 229.56 f446c6442196 yes
7 1 256 214.06 216.05 216.29 214.20 d0c7d70b67a7 yes
8 1 256 223.60 225.69 225.96 224.09 87b3a5bc05c3 yes
9 1 256 205.61 207.50 207.77 206.03 5c717781637e yes
10 1 256 216.90 218.90 219.22 217.37 06713e75b9d3 yes
11 1 256 226.45 228.39 228.68 226.80 f95c0a9f88f7 yes
12 1 256 217.58 219.34 219.63 217.81 7be1db55b737 yes
13 0 256 229.64 231.74 231.92 229.98 634f960f2ad5 yes
all 3328 219.21 220.98 221.47 219.45
88,000 words, 86,016 cached tokens: 9 replies a server
reply T tokens unset 1 set 1 set 2 unset 2 token sha256 equal in all four
1 1 256 189.62 189.37 190.57 189.86 54629d5e6171 yes
2 1 256 213.55 210.18 215.95 213.74 dc9f3f056f7f yes
3 1 256 193.31 188.79 195.22 193.54 168fbf000872 yes
4 1 256 172.26 177.88 174.66 172.42 deabcc3c74a1 yes
5 1 256 196.52 201.38 201.36 197.03 6c25e238aa33 yes
6 1 256 183.28 183.61 183.45 183.45 d05e84369bc5 yes
7 1 256 176.37 184.67 180.38 176.81 dbaf51bab54a yes
8 1 256 182.67 181.12 182.80 182.85 b51b9e4e7bb6 yes
9 0 256 187.39 188.80 188.85 187.89 d673e6535b97 yes
all 2304 187.66 189.07 189.66 187.95
150,000 words, 147,456 cached tokens: 7 replies a server
reply T tokens unset 1 set 1 set 2 unset 2 token sha256 equal in all four
1 1 256 157.23 150.02 150.10 149.12 33990ab8ccb4 yes
2 1 256 153.24 152.94 153.14 138.70 1aaaa19c1657 yes
3 1 256 157.28 161.86 162.10 154.95 9e6a917353ff yes
4 1 256 153.65 156.43 156.68 152.02 62f7ac66ffe7 yes
5 1 256 156.83 159.41 159.66 157.50 1661de89fdeb yes
6 1 256 165.45 168.52 168.79 165.78 01e836937056 yes
7 0 256 162.25 164.65 164.75 162.30 86d143ae76e2 yes
all 1792 157.89 158.89 159.09 153.88
246,000 words, 245,760 cached tokens: 5 replies a server
reply T tokens unset 1 set 1 set 2 unset 2 token sha256 equal in all four
1 1 256 125.33 121.66 121.77 121.39 3956b5524c24 yes
2 1 256 143.15 146.65 146.93 144.14 1f0a41b72f7d yes
3 1 256 132.57 132.80 133.02 131.52 943a94f9a833 yes
4 1 256 135.06 137.09 137.22 133.93 9700cbd5ec10 yes
5 0 256 135.50 137.26 137.39 134.75 8d3966885702 yes
all 1280 134.08 134.60 134.76 132.74

The runs still owed (the hash runs with their receipts, the contract's SUMMARY on the device, and the bf16, paged and two-stream cells) come here on the same head when the card is free.

@ashhart ashhart added kind:perf Classified by Synthena as performance improvement synthena:needs-ash Needs owner decision labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Needs maintainer review (kind:perf)

Adds an opt-in TF_QWEN_MERGE_WIDE switch that routes Qwen3.5/3.8 decode attention merges to a new 256-thread-per-head-value kernel, default off with byte-identical outputs claimed and contract tests included.

Findings:

  • [WARNING] zig/src/core/profile.zig: The PR claims a performance improvement (fewer idle lanes, wider merge) but provides no benchmark receipt: no latency/throughput numbers for the wide kernel versus the warp kernel on a named GPU, and no tokens/sec comparison with the switch on versus off. Suggested fix: Attach a measured receipt (e.g. decode latency or tokens/s with TF_QWEN_MERGE_WIDE=0 vs 1 on the same hardware) to the PR description or profile evidence before landing, or drop the perf claim and mark the switch as a neutral alternative path.
  • [WARNING] zig/src/families/qwen3_5/cuda_merge_wide.zig: The switch is cached in a process-wide atomic with no reset hook, so a test that sets TF_QWEN_MERGE_WIDE=1 then unsets it in the same process keeps the wide path for all later launches; the host selector test cannot cover both orders in one process. Suggested fix: Document the read-once contract in the test, or expose a reset (test-only) so the host selector test can exercise unset-then-set and set-then-unset in one process.
  • Synthena

@jojomondag

Copy link
Copy Markdown
Contributor Author

fast-gate and the zig job failed on 1da3ff553 because of this branch. The new header's #include in qwen35.cu sat between tf_q35_attn_merge and block_sums, so tools/zig/cuda_common_check.py read it as the start of block_sums's definition (2 violations). Fixed in dbfd89598, which moves the include above the warp merge. No kernel's source changes: the SASS of all 34 functions of qwen35.cu is the same on both heads with nvcc 13.0.88 and 13.4. On a trial merge of dbfd89598 with main e6252f654, every fast-gate step exits 0: pr_check.py (0 errors, lean 88 vs 88), git diff --check, cuda_common_check.py (61 local copies, 0 violations), cuda_fragment_check.py, cuda_common_check_test.py, test_pdl_early_loads.py, zig fmt --check, portable_names.zig.

On the two review warnings:

  • No receipt. The per-reply numbers behind the description's table are in qwen3_5 cuda: decode attention merge with a thread per head value (TF_QWEN_MERGE_WIDE, default off) #6185 (comment), measured on 1da3ff553, whose kernels are the same as dbfd89598's. Everything else is queued on this head on one RTX 5090 and starts when the card is free:

    • the tools/perf_receipt.py hash runs, with the switch unset as a control and set twice
    • kernel-contract merge_wide with its SUMMARY
    • the bf16, paged and two-stream cells

    I will post them here when they exist and claim no cell before then. Not committed as files, pending your answer on the receipt gate in cuda w4a8: smaller tiles of the int8 prompt GEMM where the 128x128 grid leaves SMs idle (TF_QWEN_INT8_TILES, default off) #6098.

  • Read-once switch. Intended, as for TF_QWEN_DECODE_W2 and the MT2 override: the server reads the setting once per process. The host test covers the selector itself (kernel(wide, …) and threads(wide)), a pure function of the flag, both ways and in any order. The cached read is one load, and the device test drives both kernels directly with no environment. I left it without a test-only reset, so that the head does not move while your device run is pending. If you want one, it is a three-line change.

@ashhart ashhart added synthena:needs-changes Reviewed by Synthena; changes requested and removed synthena:needs-ash Needs owner decision labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Needs changes (kind:perf)

Adds an opt-in TF_QWEN_MERGE_WIDE switch that launches a 256-thread-per-head decode attention merge kernel (tf_q35_attn_merge_wide) alongside the existing warp-based merge, default off, with contract tests and docs.

  • Failing CI check(s): verify.

Findings:

  • [BLOCKER] zig/kernels/cuda/qwen35_attn_merge_wide.cuh: The early return happens before __syncthreads(), so if some threads of a block return (past_rows true for that row) while others in the same block do not, __syncthreads() is reached by a divergent subset and the kernel can hang or corrupt shared memory on architectures where this is undefined behavior. Suggested fix: Hoist the past_rows check so all threads of the block take the same branch (e.g. compute it once and have the whole block return together), or move the shared-memory staging and __syncthreads() after a block-uniform guard.
  • [BLOCKER] zig/kernels/cuda/qwen35_attn_merge_wide.cuh: Only threads with d < nch stage sm/sl, but all threads then read sm[c]/sl[c] for c < nch after __syncthreads(). This is fine only because __syncthreads() is a full-block barrier; however if past_rows diverges (see other finding) the barrier is invalid. Additionally, when nch > 256 (impossible given MAXCH cap) this would overflow; confirm MAXCH <= 256 is enforced. Suggested fix: Add a static_assert(MAXCH <= 256) and make the past_rows guard block-uniform so the barrier is well-defined.
  • [WARNING] zig/src/families/qwen3_5/cuda_merge_wide.zig: The cached state uses .monotonic ordering with a check-then-store race: two threads can both see 0 and both compute/store, which is benign here (same value) but the load of env inside the race is not the issue; the real concern is that on() is called per launch and the atomic is fine, yet the doc says 'read once' while a torn read of the env value is not possible. This is acceptable but the store should use .release or the load .acquire for cross-thread visibility of any side effects of environment lookup. Suggested fix: Use .release on the store and .acquire on the load, or document that the race is benign because both writers store the same computed value.
  • [WARNING] zig/src/families/qwen3_5/cuda_forward.zig: The signature sig.attn_merge is reused for the wide kernel. If the signature encodes the symbol name for contract/record matching, the wide launch will be attributed to tf_q35_attn_merge rather than tf_q35_attn_merge_wide, breaking the new contract record's symbol attribution. Suggested fix: Select the signature alongside the kernel (e.g. merge_wide.sig(wide, sig.attn_merge, sig.attn_merge_wide)) so the launch is attributed to the correct symbol.
  • [WARNING] zig/src/core/profile.zig: The evidence string contains the literal placeholder '#ISSUE' instead of the real issue number, and the profile entry claims 'RTX 5090 tokens unchanged' but no benchmark receipt for the performance claim (five-SM usage / throughput improvement) is present in the PR. Suggested fix: Replace '#ISSUE' with the actual issue reference (Fixes qwen3_5 cuda: decode attention merge with a thread per head value (opt-in TF_QWEN_MERGE_WIDE): decode +0.2 to +2.0 % on one RTX 5090, every output byte equal #6161) and attach a benchmark receipt (kernel time or tokens/s on the target GPU) before landing, since this is a perf-kind PR.
  • Synthena

@jojomondag

Copy link
Copy Markdown
Contributor Author

On the review at dbfd89598. The head is now 7d519658d and the description matches it.

A wrong statement of mine, corrected. For about an hour the description said test-host passed on dbfd89598. It did not: moving the include changed qwen35.cu's bytes, which zig/dense_serving_test.zig pins, so test-qwen-serving-host failed there. 7d519658d re-pins it. On 7d519658d I ran test-host (exit 0) and every fast-gate step on a trial merge with main 0ca167746 before pushing.

The #ISSUE placeholder (warning). Right, and there were two: the profile row's evidence and the pin's comment. Both name #6161 now.

The early return before __syncthreads() (blocker). The guard is uniform over the block: past_rows(P, blockIdx.y) reads the device row count and the block's row index, and all 256 threads of a block have the same blockIdx.y, so the whole block returns or none of it does. No thread reaches the barrier without the others. The line says so now. The device test has the case: 64 rows with 40 live and 5 with 3 live, where the blocks past the row count must leave their output and the guard bytes untouched.

Staging and MAXCH (blocker). With the guard uniform the barrier is a full-block one, as you say. MAXCH is 64 (qwen35.cuh), so the 256 threads cover every chunk; 7d519658d adds static_assert(MAXCH <= 256) beside the head-width one.

The cached switch's memory order (warning). on() stores one of two values computed from the environment, and two racing first calls compute and store the same one; nothing else is published through that store, so there is no state another thread could see half-made. It is the form cuda_pdl.zig and cuda_prompt_split.zig use on main. I have left it as theirs.

The signature at the launch (warning). launch takes the signature as a comptime argument and only checks the argument tuple's types against it (sig.check); nothing at run time reads its name or symbol. The wide kernel has its own entry, sig.attn_merge_wide, with its symbol and handle, in sig.all, and the host test "the q35 attention kernels' parameter lists match their .cu signatures" (contract_q35_launch_args_host.zig) checks every listed symbol's declared parameters in the .cu and .cuh sources against its list; the wide kernel's list is attn_merge.params by definition. The kernel is chosen at run time and the signature at comptime, so the site checks the one list both share. The contract record carries the wide symbol itself (qwen_merge_wide_records.zig).

Receipt (warning). As in my comment above: the served table and its raw numbers are from 1da3ff553; with nvcc 13.0.88 and 13.4 at sm_120 the SASS of all 34 functions of qwen35.cu is the same on the three heads. Everything is run again on 7d519658d, with the hash runs, the contract's SUMMARY and the bf16, paged and two-stream cells, when the card is free.

@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Needs changes (kind:perf)

Adds an opt-in TF_QWEN_MERGE_WIDE switch that routes Qwen3.5/3.8 decode attention merges to a new 256-thread-per-(head,row) kernel, default off, with contract tests asserting byte-identical outputs.

  • Failing CI check(s): verify.

Findings:

  • [BLOCKER] zig/kernels/cuda/qwen35_attn_merge_wide.cuh: The early return happens before __syncthreads(), so if some threads of the block take the return while others do not, __syncthreads() can deadlock or the staging writes can race. The comment claims the whole block leaves together, but that relies on past_rows being uniform per block; if P is a per-row count pointer indexed by blockIdx.y it is uniform, yet any future divergence or non-uniform read breaks this, and the staging path below still executes __syncthreads() unconditionally for blocks that do not return. Suggested fix: Move the past_rows check so all threads evaluate it and return together, or restructure so __syncthreads() is only reached by blocks that passed the check (it already is, since all threads of a block share blockIdx.y); verify past_rows(P, blockIdx.y) is block-uniform and add a comment or static assertion documenting that invariant, since a non-uniform P read would hang the kernel.
  • [WARNING] zig/src/families/qwen3_5/cuda_merge_wide.zig: The switch is cached in a plain atomic with .monotonic ordering and read via a check-then-act pattern; concurrent first calls could both read 0 and both store, which is benign here since both compute the same value, but the env read itself is not guaranteed thread-safe on all platforms if environment access mutates global state. Suggested fix: Confirm the environment reader is safe to call concurrently on first use, or guard initialization with a mutex/once-style primitive so the env lookup happens exactly once.
  • [WARNING] zig/src/families/qwen3_5/cuda_forward.zig: The signature sig.attn_merge is reused for the wide kernel launch; if the launch machinery validates or records the block width against the signature's expected configuration, the 256-thread block may be flagged or mis-recorded, and the contract record for the wide kernel (threads=256) must match what is actually launched. Suggested fix: Verify the launch path accepts a block width different from the signature's historical 32 and that profiling/contract records capture the actual launched block; add a host test asserting the wide path launches with 256 threads and the warp path with 32.
  • Synthena

@jojomondag

Copy link
Copy Markdown
Contributor Author

On the review at 7d519658d: its three points are the ones my comment above answers (it was written minutes earlier, for the previous head). Briefly, and no push:

  • The guard before the barrier. past_rows(P, m) is P != nullptr && m >= P[2]: the launch's parameter block at a fixed index and the block's own row, so it is uniform over the block's 256 threads, and the line says so in 7d519658d. Main's kernels use the same guard before a barrier: rope_rows_as in qwen35.cuh and head_rows in qwen35.cu both return on past_rows(P, blockIdx.x …) and then reach __syncthreads().
  • The first read of the switch. It goes through the same environment reader, in the same form, as cuda_pdl.zig and cuda_prompt_split.zig on main; the reader looks a name up and changes nothing.
  • The block width. launch hands the block to e.run and uses the signature only for the comptime argument check; it holds no block width. The host test asked for is in the branch: test-qwen35-merge-wide-host asserts threads(false) == 32 and threads(true) == 256, and that the wide width equals the head's 256 values. The contract record says 256 threads, and the device test launches the wide kernel with 256 and plants a control at 128 that must differ.

jojomondag and others added 5 commits December 5, 2026 02:42
…_QWEN_MERGE_WIDE, default off)

The merge of an attention layer's chunk partials gives each (head, row) 256 threads, one for
each of the head's values, in place of one warp of 8 values a lane. Every thread runs the warp
kernel's loop over the chunks for its value (the maximum over live chunks, then the weight sum
and its value's sum in chunk order, the same fmaf operands), so every output has the same bits;
only who computes it changes. The switch covers the one launch of tf_q35_attn_merge; the
drafter's merge keeps its own kernel. The kernel is in its own header, qwen35.cu includes it.
Registered with the kernel contract (qwen-merge-wide).
… keeps its allowlisted definition

The include sat between tf_q35_attn_merge and block_sums, where tools/zig/cuda_common_check.py reads it as the
start of block_sums's definition and no longer finds the allowlisted fingerprint. The header needs nothing the
warp merge defines, so it goes above it. No kernel's source changes.

Refs ashhart#6161
…clude moved; the issue number replaces a placeholder

zig/dense_serving_test.zig pins qwen35.cu's sha256, which the previous commit changed by moving the include, so
test-qwen-serving-host failed there. The pin's comment and the profile row's evidence said #ISSUE and now name
ashhart#6161. The wide kernel asserts that a block has a staging thread for every chunk (MAXCH <= 256) and says that
its early return is the whole block's. No kernel's code changes.

Refs ashhart#6161
… every device row count edge

The merge's grid is (query heads, rows). Qwen 3.5/3.8 admit up to 32 query heads
(max_query_heads) and the partials hold up to 128 rows (most_verify), but the
contract ran 24 heads and at most 64 rows. It now also runs 8, 16 and 32 heads,
65 and 128 rows, and a device row count of 0, 1, 127 and 128 at 128 rows. Every
row past the count must keep the output's fill bytes in the wide kernel's output.

The cases move to contract_qwen_merge_wide_cases.zig, whose host test (under
test-qwen35-merge-wide-host) fails when the table misses one of those limits.
@ashhart
ashhart force-pushed the qwen-cuda-merge-wide branch from 7d51965 to f576d37 Compare December 5, 2026 02:42
@ashhart ashhart added synthena:needs-device Initial diff review passed; waiting for device and slowdown check before READY and removed synthena:needs-changes Reviewed by Synthena; changes requested labels Dec 5, 2026
@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thanks @jojomondag. We rebased this onto today's main ourselves (your three commits kept as yours), resolved the conflicts, and added one commit that widens the merge-wide device contract to 8-32 heads, 1-128 rows and the 0/1/127/128 row-count edges, with a host test that fails before and passes after. We also re-pinned environment.zig in the serving fixture for the new switch.

TF_QWEN_MERGE_WIDE stays off by default. We are running the device A/B with it on against main on our own GB10 now; that is the speed receipt, so nothing is needed from you.

  • Synthena

@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thanks @jojomondag. Both blockers are settled. The past_rows guard is uniform over the block (all 256 threads share blockIdx.y, and the guard reads the block's own row), and main's kernels use the same guard-before-barrier pattern. The static_asserts for the head width and the chunk cap are in, and the host test pins 32 threads for the warp path and 256 for the wide one, with a matching contract record.

The remaining verification runs on this head are ours: the switch unset against set twice with reply hashes, the kernel-contract summary, and the bf16, paged and two-stream served cells. We're running them now. Nothing more is needed from you.

The planted controls and the byte-equal repeats in the device test are exactly the right shape for this change. Thank you.

  • Synthena

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

2 participants