Skip to content

[w2] Fold the Q attention rotation (FWHT) into the rms_norm_mul_rope kernel - #171

Merged
rafasmour merged 1 commit into
masterfrom
opt/w2-rotation-fold
Dec 4, 2026
Merged

rafasmour merged 1 commit into
masterfrom
opt/w2-rotation-fold

Conversation

@rafasmour

Copy link
Copy Markdown
Owner

What

The Q attention rotation (Hadamard / FWHT) after rope is a separate fwht_cuda launch per attention layer (PR #152 already fused the K and V rotations into the q8_0/q4_0 store). This folds it into the existing fused norm+rope kernel:

RMS_NORM, MUL, ROPE, RESHAPE, MUL_MAT(Hadamard hint) -> one rms_norm_mul_rope_f32 launch (FWHT_N = 128 / 256 / 512 template epilogue).

  • The row's rope result stays in shared memory; the epilogue runs the same butterfly as fwht_cuda (same stage order h = 1, 2, 4, ..., the scale 1/sqrtf(n) applied first, x+y / x-y pairs), so the values are meant to be bit-identical to the separate kernels. One block of D/2 threads per row (64 / 128 / 256 threads), 2 values per thread.
  • Output is F32, as the Hadamard MUL_MAT output already is (ggml_cuda_op_mul_mat_use_fwht requires F32), which the FA reads as before. The "f16 as the consumer expects" option in the plan does not apply: the MUL_MAT result is F32.
  • The matcher (ggml_cuda_try_fuse_rms_norm_mul_rope_fwht, self-contained function plus one dispatch call in ggml_cuda_try_fuse) needs rotation size == head size (128/256/512), contiguous rope output and MUL_MAT result, wave32, ggml_can_fuse_subgraph + ggml_check_edges + memory-range check. It leaves the K chain alone (MUL_MAT -> RESHAPE -> VIEW ... -> SET_ROWS), which keeps its quantizing store fusion.
  • Not done: plain ROPE -> MUL_MAT(hadamard) without a norm (step 3, the plain rope kernel is a different, per-element kernel, so it is not cheap with this epilogue) and the output inverse rotation fold (step 5 stretch: the V rotation is 64-value rows spanning two q8_1 blocks, so it needs a new quantize kernel or an FA epilogue).

Rotation sites and remaining fwht launches per token (after #152)

Same chain shape (RMS_NORM, MUL, ROPE, RESHAPE, MUL_MAT) in all three attention builders: build_attn (Gemma 4 / Qwen 3.x, llama-graph.cpp ~l.3489), the iswa variants (~l.3779, l.3902) and build_attn_qsa in qwen4exp.cpp (l.962, so Qwen 4 gets the same fold). K and V rotation are fused into the cache store (fusion.cu fwht_set_rows_q, rms_norm_fwht_set_rows_q). What remains is one Q rotation and one output inverse rotation (V rot, 64-wide) per attention layer. Counts below are estimates from the earlier kern/prof traces (pre-#152 totals minus the K/V launches), not new measurements:

model Q rot (removed here) output inverse rot (remains)
Gemma 4 31B ~60 (256: SWA, 512: full) ~60
Qwen3.8 27B ~16 ~16
Qwen4 (q8_0 KV; dense and QSA layers) one per attention layer one per attention layer

Expected gain (estimate, not measured)

Scout bound with Q and output folds: Qwen3.8 +1.0-1.4%, Gemma +2-3%. The Q fold alone is about half of that. Fewer launches (about 2 us idle per dependent launch).

Env switch

GGML_CUDA_NO_ROPE_FWHT_FUSION=1 turns the fusion off (bit-identical, default on). No other switch renamed.

Files

  • ggml/src/ggml-cuda/rope.cu, rope.cuh: FWHT_N epilogue in rms_norm_mul_rope_f32, launcher, fwht_mm argument (default nullptr).
  • ggml/src/ggml-cuda/fusion.cu: matcher + kill switch.
  • tests/test-backend-ops.cpp: test_rope_fwht (op_desc ROPE_FWHT), own commented block; eval: D 128/256/512 x nb 1/3/512 x neox/normal/imrope, freq factors, partial rope, K chain with set_rows (must not be folded); perf: D 128/256/512 x nb 1/3/512, neox + normal.

CPU checks done

  • HIP compile (gfx1100, object files only): fusion.cu.o, rope.cu.o, fwht.cu.o OK. No new warnings (one existing fwht.cu:420 loop-not-unrolled warning).
  • llvm-readelf --notes of the FWHT kernel instances (D 128/256/512, with/without freq factors): private_segment_fixed_size 0, no spills, 55-61 VGPRs, LDS 1/2/4 KB. The non-FWHT instances are unchanged (0 LDS, 43-48 VGPRs).
  • ISA of the D=128 epilogue: scale multiply is a separate v_mul_f32 (no FMA contraction into the first stage), stages are ds_bpermute + sign-select + v_add_f32, same as fwht_cuda<128> in the baseline object.
  • CPU build: test-backend-ops test -b CPU -o ROPE_FWHT 33/33 OK, perf -b CPU -o ROPE_FWHT runs; test-llama-archs -a gemma4 -b CPU and -a qwen4exp -b CPU pass. Build tree deleted.

The CUDA fusion path itself was NOT run (no GPU).

Risks

  • Bit-identity depends on matching the butterfly order; checked by ISA reading and CPU tests only, the GPU KLD gate is the real check. If KLD is not exactly 0, flip nothing and report: the cause would be FMA contraction in the rope part of the fused kernel (pre-existing for the unfused-in-this-PR fusion) or my epilogue.
  • Q rotation sizes other than the head size (e.g. n_rot 64 for a 192 head) and heads outside 128/256/512 are not fused (unfused path as before).
  • fusion.cu conflicts with the other w2 fusion branches: kept to one new function plus one 3-line dispatch addition in the RMS_NORM block of ggml_cuda_try_fuse.

GPU validation tonight (NOT YET RUN)

Use preamble (P) of the wave plan.

Eval:

./gpusmall.sh ./test2.sh w2-rotf $BA - ROPE_FWHT '.'

Launch count (trace):

./gpublock.sh ./tr.sh g-rot-on $BA $G 32 -- $GA -p 0 -n 32 -r 1
GPURUN_OPTS='-e GGML_CUDA_NO_ROPE_FWHT_FUSION=1' ./gpublock.sh ./tr.sh g-rot-off $BA $G 32 -- $GA -p 0 -n 32 -r 1

tg (each on and off, off = GPURUN_OPTS='-e GGML_CUDA_NO_ROPE_FWHT_FUSION=1'):

./gpublock.sh ./lb.sh g-rot-on $BA $G $GA -p 0 -n 128 -d 0,32768 -r 5
./gpublock.sh ./lb.sh q38-rot-on $BA $Q38 $Q38A -p 0 -n 128 -r 5
./gpublock.sh ./lb.sh q4-rot-on $BA $Q4 $Q4A -p 0 -n 128 -r 5

KLD (exactly 0):

./gpublock.sh env KL_ENV=GGML_CUDA_NO_ROPE_FWHT_FUSION=1 ./kl.sh g-rot-off $BA $G base $GA
./gpublock.sh ./kl.sh g-rot-on $BA $G test $GA

Qwen4 QSA only becomes sparse above 2048 KV: for Qwen4 KLD add -c 16384 --chunks 3.

Hard rules followed

No GPU used or locked, no production/homelab/router/docker-compose touched, nothing sent to ggml-org/llama.cpp, build under the build lock at nice 19 / -j6 and deleted afterwards. Do not merge before the GPU gates.

Assisted-by: Claude Sonnet 5.5

…ernel

RMS_NORM, MUL, ROPE, RESHAPE, MUL_MAT (Hadamard hint) of the Q of a rotated KV cache
run as one kernel: the rope result of the row stays in shared memory and is transformed
by the butterfly of fwht_cuda (same stage order, scale applied first). Heads of 128, 256
and 512 values. One launch less per attention layer (Gemma 4, Qwen 3.x, Qwen 4 q8_0 KV).
The K chain (rotation stored into a quantized cache) is left to the K store fusions.

GGML_CUDA_NO_ROPE_FWHT_FUSION=1 turns the fusion off. Adds ROPE_FWHT eval and perf cases.

Assisted-by: Claude Sonnet 5.5
@rafasmour
rafasmour merged commit 9699c0f into master Dec 4, 2026
8 of 27 checks passed
@rafasmour

Copy link
Copy Markdown
Owner Author

Reverted from master on 2026-12-04 (w2 build crashed Qwen4-single at >20k ctx; no measured gain). Commit preserved on branch archive/w2-25f0def; will be re-landed individually after GPU validation.

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.

1 participant