Skip to content

cuda: fuse SwiGLU + sign flip + Hadamard (and the PTQ1_0 MMQ q8_1 quantization) for prompt batches - #445

Open
sb32445 wants to merge 1 commit into
PrismML-Eng:prismfrom
sb32445:pr/swiglu-hadamard-prefill
Open

sb32445 wants to merge 1 commit into
PrismML-Eng:prismfrom
sb32445:pr/swiglu-hadamard-prefill

Conversation

@sb32445

@sb32445 sb32445 commented Nov 16, 2026 •

Copy link
Copy Markdown

Overview

The FFN down input of a Hadamard-folded model (Bonsai) is SWIGLU(gate, up) -> MUL(signs) -> RESHAPE -> MUL_MAT(Hadamard hint). For prompt batches (more than 8 tokens; decode and verify batches keep ggml_cuda_try_fwht_q8) the CUDA backend ran the GLU kernel, then the transform, then (for a PTQ1_0 weight) the q8_1 MMQ quantization: three launches and three passes over the activation.

  • fwht_cuda_block_swiglu forms silu(gate) * up with the expression of the GLU kernel, applies the scale, the signs and the same butterfly, and writes the transformed rows: one launch and one pass less. The output may sit exactly on top of the gate buffer (the allocator reuses it); the kernel reads a whole transform before it writes it, any other overlap refuses the fusion. GGML_CUDA_GLU_FWHT_FUSION=0 disables it.
  • When the only reader of the transformed rows is a PTQ1_0 mul_mat_q, the same launch also quantizes the rows to block_q8_1_mmq (D4) and the F32 rows are never written (swiglu_fwht_quantize_mmq reproduces the GLU kernel, the signed transform and quantize_mmq_q8_1 in order, including the 127/amax form, so the rows are bit-identical to the three-launch version). The rows go into a pool block held for the graph and are registered in ctx.fwht_q8() with a new mmq flag; ggml_cuda_mul_mat hands them to ggml_cuda_mul_mat_q as external_q8. The fusion is refused if the transform output has another reader, is a graph output, or the consumer would not take the MMQ path. GGML_CUDA_GLU_FWHT_Q8=0 keeps only the F32-output version.

Layout check (review). Both launches read gate, up and the signs as flat float arrays of the shape of the GLU output. The predicate only checked the layout of the GLU output; the stride checks of the inputs were inside the F32 launch and did not cover the direct MMQ launch, so a strided gate or up view could enter it and be read wrongly. The predicate now requires, before either launch, F32 type, contiguous layout and the shape of the GLU output for gate and up, and F32 and contiguous for the signs; anything else keeps the unfused nodes.

RTX 4070, Bonsai 2 27B PTQ1_0, q4_0 K/V, llama-bench pp2048 against plain prism d12ca13bb (mean of 3 interleaved rounds): -ub 512 1374.3 -> 1432.0 tok/s (+4.2 %), -ub 2048 1295.7 -> 1360.3 (+5.0 %); at depth 32768 +3.1 % and +3.5 % (measured on prism 6447906bf, not repeated). Decode is unchanged (MTP, 8 pairs: +0.01 %, CI [-0.10, +0.10] %). Results are bit-identical: perplexity 14.5423 in both, KL divergence 0.000000, same top token 100 %.

Additional information

  • One commit, 7 files. Tests: MUL_MAT_HADAMARD cases with swiglu for 9, 33, 64 and 17 tokens, with a PTQ1_0 ffn_down consumer for 9, 33, 512, 64 and 17 tokens, and (review) three cases with strided gate and up views (row stride twice the width, without and with the PTQ1_0 consumer).
  • Correction to the earlier test cases. While adding the strided cases I found that the PTQ1_0 weight of the cases with a consumer was never initialized (initialize_tensors only filled F32/F16 tensors). Both backends computed zeros, the NMSE was NaN, and NaN > max is false, so those cases passed without comparing anything. They now initialize every tensor. With real data: the strided MMQ cases fail without the predicate fix (NMSE 0.86), all PTQ1_0 cases fail if the fused quantization is skipped (NMSE inf), and with the fix all 63 MUL_MAT_HADAMARD cases pass. The earlier claim that these cases verify the MMQ path was therefore not true for the previous revision; the bit-identity result below (perplexity and KL against the unfused build) was measured separately and is not affected.
  • The three-launch path stays and is used whenever the fusion is refused or switched off; both switches turn the new code off completely.
  • test-backend-ops test -b CUDA0 (full suite) on this branch: 21118/21118 passed (CPU as reference).
  • Interaction with other open PRs: the branches of cuda: gate (SwiGLU) fused PTQ1_0 mat-vec for 2-4 columns #310, cuda: prefetch the next PTQ1_0 mat-vec's weights into L2 from the last CTAs #314, cuda: use ncols2 = 2 in the MMA flash attention for prompt batches at GQA ratio 6 #410, cuda: scale PTQ1_0 MMQ results once per 128-weight block #411 and the C2 and sampler PRs merge pairwise without conflict into this one; I have not built and run them all together.
  • Earlier numbers on an older base (ktrain 4c0c11d7e) were +2.8 % for the F32-output version alone and +5.8 / +6.3 % with the quantization; those were measured against a different reference, the numbers above are against prism.
  • Tuned and measured on one GPU (RTX 4070, Ada, cc 8.9). Only PTQ1_0 consumers get the MMQ quantization; the F32-output SwiGLU + transform fusion applies to any model with the Hadamard hint pattern. Not tested: other GPUs, HIP, other models.

Test results

  • Hardware / software: RTX 4070 12 GB (AD104, cc 8.9), Linux 6.18, NVIDIA driver 620.70, CUDA 13.4, GCC 16.2; Release build, -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=89.
  • Base: prism at d12ca13bb (separate builds of base and patch).
  • Model: Ternary-Bonsai-2-27B (PTQ1_0) with a community MTP draft head (Q8_0), q4_0 K/V cache.
  • Prefill, re-measured on d12ca13bb (llama-bench -p 2048 -n 0 -b 2048 -fa 1 -ctk q4_0 -ctv q4_0 -r 3, 3 interleaved rounds, tok/s ↑):
-ub base patch change rounds
512 1374.3 1432.0 +4.20 % +4.17 / +4.20 / +4.23
2048 1295.7 1360.3 +4.99 % +4.90 / +4.95 / +5.13

Earlier numbers on 6447906bf (-p 2048 -n 128 -d 0,32768 -r 2): at depth 32768 +3.1 % (-ub 512: 969.2 -> 998.8) and +3.5 % (-ub 2048: 934.8 -> 967.9); tg128 unchanged (65.8 -> 65.7 tok/s at depth 0, 59.1 -> 59.1 at 32768).

  • Decode with MTP (--spec-draft-n-max 2, 4 greedy prompts x 256 tokens, 8 interleaved A/B pairs, on 6447906bf): 115.25 -> 115.24 tok/s, +0.01 %, outputs identical. Not repeated for the layout check, which only affects graphs where the fusion is refused.
  • Quality (on 6447906bf, not repeated): llama-perplexity (German text, 16 x 512, -b 2048 -ub 512): PPL 14.5423 against 14.5423, mean KLD 0.000000, same top token 100 %.
  • Not tested: other GPUs, multi-GPU, other PTQ1_0 models, several slots.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: The patches were developed with Claude Code (Anthropic's coding agent): it wrote the code, the measurement scripts and the first drafts of the commit messages and PR texts. I decided what to work on (which kernels and host paths to optimise, based on profiles of my own decode setup). The measurements and checks listed in the PR texts were run in the Claude Code sessions; I did not re-run them independently. I will maintain the changes. Commits where Claude Code was used carry a Co-Authored-By trailer.

🤖 Generated with Claude Code

@bri-prism bri-prism left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The fused MMQ branch passes gate, up, and signs directly to ggml_cuda_swiglu_fwht_quantize_mmq as flat float arrays. Its predicate checks the GLU output layout, but the stride checks on the inputs are inside the separate F32 helper. A strided gate or up view can enter the direct MMQ branch and read the wrong values. Please validate input type and layout before launching either fused branch, and add a noncontiguous input case that exercises the fallback.

…batches, and quantize in the same launch for the MMQ

The FFN down input of a Hadamard-folded model is SWIGLU(gate, up) -> MUL(signs) -> RESHAPE -> MUL_MAT(Hadamard hint).
For more than 8 tokens (decode and verify batches keep ggml_cuda_try_fwht_q8) the CUDA backend ran this as the GLU
kernel, then fwht_cuda_block. fwht_cuda_block_swiglu reads gate and up, forms silu(gate)*up with the expression of the
GLU kernel, applies scale, signs and the same butterfly, and writes the transformed rows: one launch less and one
full pass over the activation less. The output may sit exactly on top of the gate buffer (the allocator reuses it);
the kernel reads a whole transform before it writes it, any other overlap refuses the fusion.
GGML_CUDA_GLU_FWHT_FUSION=0 disables it.

When the only reader of the transformed rows is a PTQ1_0 mul_mat_q (prompt batches), the same launch also quantizes
the rows to block_q8_1_mmq (D4) and the F32 rows are never written (swiglu_fwht_quantize_mmq reproduces
unary_gated_op_kernel<op_silu>, the signed fwht_cuda_block and quantize_mmq_q8_1 in order, including its 127/amax form,
so the rows are bit-identical to the three-launch version). The rows go into a pool block held for the graph and are
registered in ctx.fwht_q8() with the new mmq flag; ggml_cuda_mul_mat hands them to ggml_cuda_mul_mat_q as external_q8
without quantizing. The fusion is refused if the transform output has any other reader, is a graph output, or the
consumer would not take the MMQ path. GGML_CUDA_GLU_FWHT_Q8=0 keeps only the F32-output version.

Ternary-Bonsai-2-27B PTQ1_0, RTX 4070, llama-bench pp2048, q4_0 K/V, against prism 6447906 (mean of two runs):
-ub 512 1354.8 -> 1411.6 tok/s (+4.2 %), -ub 2048 1279.2 -> 1343.0 (+5.0 %); at depth 32768 +3.1 % and +3.5 %.
Decode (MTP, 8 interleaved pairs) is unchanged (+0.01 %, outputs identical). Perplexity and the KL against the
unfused build are unchanged (mean KLD 0.000000, same top token 100 %).
tests: MUL_MAT_HADAMARD cases with swiglu (9, 33, 64 and 17 tokens) and with a PTQ1_0 ffn_down consumer (9, 33, 512,
64 and 17 tokens).

Review fix: both fused launches read gate, up and the signs as flat float arrays, but the predicate only checked the
GLU output layout (the stride checks of the F32 launch did not cover the direct MMQ launch). The predicate now requires F32,
contiguous gate, up and signs of the shape of the GLU output before either launch; anything else keeps the unfused nodes.
tests: MUL_MAT_HADAMARD cases with strided gate and up views (with and without the PTQ1_0 consumer); without the check
the MMQ case fails (NMSE 0.86). The PTQ1_0 weight of these cases was never initialized, so both backends computed zeros and
the comparison was empty; it is now filled, and skipping the fused quantization makes the cases fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@sb32445

sb32445 commented Nov 21, 2026

Copy link
Copy Markdown
Author

Thanks, you are right: the stride checks of the inputs were only in the F32 launch, so the direct MMQ launch could take a strided gate or up view and read it as a flat array.

Changed (one commit, rebased on current prism d12ca13bb, was 6447906bf):

  • The fusion predicate now checks, before either launch, that gate and up are F32, contiguous and have the shape of the GLU output, and that the signs are F32 and contiguous. Anything else keeps the unfused nodes.
  • New MUL_MAT_HADAMARD cases with strided gate and up views (row stride twice the width), without and with the PTQ1_0 ffn_down consumer (the MMQ branch). Without the predicate change the two MMQ cases fail (NMSE 0.86 against 0.0005); with it they pass.

While building these cases I found a problem in the test cases I had added earlier, which also means my claim that they verify the MMQ path was not true: the PTQ1_0 weight (w_down) was never initialized (initialize_tensors only filled F32/F16 tensors), so both backends computed zeros, the NMSE was NaN, and NaN > max is false: those cases passed without comparing anything. They now initialize all tensors. With real data, skipping the fused quantization makes all the PTQ1_0 cases fail (NMSE inf), so they are sensitive now. The bit-identity numbers in the description (perplexity and KL against the unfused build) were measured separately and are not affected, but they were not repeated on the new base.

Results on d12ca13bb: MUL_MAT_HADAMARD 63/63; full test-backend-ops test -b CUDA0 21118/21118. llama-bench pp2048 (q4_0 K/V, Bonsai 2 27B PTQ1_0, 3 interleaved rounds) against plain prism: -ub 512 1374.3 -> 1432.0 tok/s (+4.2 %), -ub 2048 1295.7 -> 1360.3 (+5.0 %), as before; so the stricter predicate costs nothing. Decode, perplexity/KL and the depth-32768 numbers were not repeated (measured on 6447906bf).

The description has the new text and numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants