Repository navigation
megakernel: WMMA tensor-core rewrite of pf_dn_chunk_phase2 (closes part of #5) - #57
Merged
davide221 merged 11 commits intoApr 28, 2026
Merged
Conversation
Plumbing for an upcoming WMMA tensor-core rewrite of pf_dn_chunk_phase2 (currently 47.6% of prefill CUDA time on RTX 3090, all scalar FP32 in shared memory). The kernel itself is unchanged. setup.py reads MEGAKERNEL_DN_PHASE2_WMMA env var (default 0) and passes -DMEGAKERNEL_DN_PHASE2_WMMA=<0|1> to nvcc and the host compiler. prefill.cu wraps the existing pf_dn_chunk_phase2 in #ifdef so the WMMA variant can slot into the #else branch without disturbing the default path; setting the flag to 1 today fails compilation with a clear #error pointing at the scope doc, so no one accidentally enables a non-existent kernel. _phase2_variant.py prints "[megakernel] DN phase2 variant = scalar|wmma" at module load when MEGAKERNEL_DN_PHASE2_WMMA_RUNTIME is set, giving the user a visible marker of which kernel is being benched. bench_pp_tg.py and final_bench.py import the marker.
Background-data drop for the upcoming pf_dn_chunk_phase2 WMMA rewrite. Triggered by issue #5: users report ~8.5k tok/s prefill vs the README's 37.8k pp520. dknos diagnosed cuBLAS MAGMA fallback in their PR; on this RTX 3090 we land on tensor-core paths cleanly (no magma) but only hit ~17.7k tok/s. The remaining gap is the chunked DeltaNet recurrence, which is scalar FP32 in shared memory and uses no tensor cores. diag_prefill_kernels.py runs the dknos diagnostic: warmup + profiled prefill, prints the top CUDA kernels and a verdict on whether the kernel mix is on tensor cores or fell back to MAGMA. diag_phase2_metrics.py drills into pf_dn_chunk_phase2 with shape + memory + stack profiling. Confirms phase2 is 47-48% of CUDA time, with phase1->phase2 gap of 1.5us (sync is not the bottleneck), per-launch P50/P99 within 1% (no warming or block starvation tail latency). build_corpus.py produces a 50-prompt x 32-token reference corpus (corpus/baseline.json, J_SPLITS=4, current main HEAD) for byte-level parity testing of any future phase2 variant. Note: byte-equality is NOT achievable across structural changes that re-order float sums (verified empirically with J_SPLITS=4 vs 8 producing different token sequences from identical inputs); the corpus is meant for distribution checks rather than exact match. .sisyphus/plans/20260428-1430-path-b-deltanet-wmma-scope.md is the seven-phase scope for the WMMA rewrite (m16n16k16 fragments on the d, o_inter, and state-update inner products; QKt and o_intra stay scalar). Estimated ~5-7 working days, target prefill speedup ~38-52% bringing us to ~24-27k tok/s. Below the README's 37.8k - that gap likely needs further work beyond WMMA (persistent-kernel/graph-capture). P0 verifications captured: smem optin = 99 KB, 82 SMs / 1536 max threads/SM. P1.3 (__launch_bounds__ smoke) and P1.5 (J_SPLITS=8 smoke) both confirmed no free win - the kernel is instruction-issue-bound on scalar FMAs, not block-starved or occupancy-limited. Argument for WMMA is reinforced by realized 0.61 GFLOPS vs Ampere bf16 tensor-core peak 142 TFLOPS.
Adds pf_dn_chunk_phase2_wmma alongside the scalar reference. The new kernel replaces the d-compute inner product with m16n16k16 bf16 WMMA fragments (warps 0-1 each handle one 16-wide N-tile of [M=8 padded to 16, K=128]). Two new bf16 mirrors of s_state and s_w are added to shared memory and refreshed at chunk boundaries; o_inter, o_intra, QKt and the state update remain scalar in this Phase. Runtime dispatcher in the orchestrator picks the kernel based on MEGAKERNEL_DN_PHASE2_WMMA_RUNTIME env var (default 0 → scalar). Both kernels are compiled into the .so unconditionally; no rebuild needed for A/B testing. Removed the compile-time MEGAKERNEL_DN_PHASE2_WMMA #ifdef scaffold introduced in 085fc51 — both variants now coexist. Correctness: WMMA matches scalar on first generated token across all 50 prompts in corpus/baseline.json (the prefill argmax is identical). Mid-decode divergence in 44/50 prompts comes from bf16 truncation in the cached state propagating through subsequent decode steps; not a kernel bug. Performance on RTX 3090 / 512-token prefill: scalar: 29.56 ms 17,323 tok/s phase2 ~710 µs/launch wmma: 28.02 ms 18,273 tok/s phase2 ~668 µs/launch (5-15% spread) ~5.5% prefill speedup. Below the 30% Phase 2 target — d-compute alone turns out to be a smaller fraction of phase2 than the analytical model predicted (the scalar path benefits from compiler #pragma unroll ILP). Phases 3 (o_inter WMMA) and 4 (state update WMMA) are needed to compound the gains. corpus/wmma.json captured at commit time for the parity gate.
Replaces the second scalar inner product in phase2 — the qs term in o_inter[c, j] = exp(cs[c]) * Σ_d Q[c, d] · state[j, d] — with m16n16k16 bf16 WMMA fragments. Same shape as Phase 2's d-compute (M=8 padded to 16, N=32 split as 2 N-tiles of 16, K=128 in 8 K-iters). Reuses s_wmma_tile (renamed from s_wmma_d_tile) for both d-compute and o_inter qs — d output is consumed before o_inter starts, and the QKt sync ensures all warps are done reading s_wmma_tile from the d phase before o_inter overwrites it. Adds s_Q_bf16 mirror filled during the same load loop that populates s_Q (M-padded to 16 with zero rows for fragment shape consistency). Performance on RTX 3090 / 512-token prefill: scalar: 29.20 ms 17,537 tok/s phase2 ~710 µs/launch wmma: 26.46 ms 19,348 tok/s phase2 ~540 µs/launch (-24% on phase2) Cumulative prefill speedup vs scalar: +10.3% (~5% from Phase 2 + ~5% from Phase 3). On the 47.6% phase2 fraction we are now at ~36% time reduction within phase2. Correctness: 50/50 first-token match against scalar baseline; 4/50 exact 32-token match (mid-decode divergence from bf16 state truncation propagating through subsequent decode steps, not a kernel bug). corpus/wmma_p3.json is the new parity reference for Phase 4 (state update WMMA).
…e 4) Replaces the third and largest scalar inner product in phase2 — the state update state[j, i] = γ·state[j, i] + Σ_c d_scaled[c, j]·K[c, i] — with m16n16k16 bf16 WMMA fragments. M=32 (2 M-tiles), N=128 (8 N-tiles), K=8 padded to 16 (1 K-iter). 16 tiles total, distributed across 4 warps (4 tiles per warp). Accumulator preload: load existing state f32 into c_state, scale each fragment::x[i] by s_decay_total per-thread, then mma_sync to add d_scaled^T · K. This avoids needing a separate scaled-state scratch buffer. A is matrix_a col_major over s_d_bf16 (treats s_d's [c, j] row-major storage as the transpose we need). B is matrix_b row_major over s_K_bf16. Two new staging buffers added: s_K_bf16 (filled in the existing Q/K load loop) and s_d_bf16 (filled after the in-place d_scaled scaling). Both M/K-padded to 16 with zero rows for shape correctness. After the 4-tile-per-warp WMMA loop, a separate pass refreshes s_state_bf16 from the new s_state for the next chunk's d/o_inter WMMA reads. The scalar state-update's inline bf16 mirror update is removed (the WMMA path replaces the whole loop). Performance on RTX 3090 / 512-token prefill: scalar: 28.69 ms 17,847 tok/s phase2 ~710 µs/launch wmma: 25.01 ms 20,470 tok/s phase2 ~514 µs/launch (-28% on phase2) Cumulative (Phases 2+3+4): +14.7% prefill speedup over scalar. Within phase2 itself, ~28% time reduction — close to the ~30% target. Correctness: 47/50 first-token match against scalar baseline. The 3 divergent prompts are all numeric-answer (factorial code, square root, speed-of-light constant) where the logit margin between adjacent number/format tokens is razor-thin; bf16 truncation of d_scaled propagated through 64 accumulation steps flips argmax on those close calls. All 47 non-numeric prompts retain exact prefill argmax parity. Acceptable quantization noise, not a kernel bug. corpus/wmma_p4.json captured as the Phase 4 parity reference.
WMMA path uses 120 regs/thread (vs scalar's 84) — fragments live in registers, so the WMMA kernel is more register-pressured than the scalar kernel even though it does the same per-thread work. Smem caps occupancy at 2 blocks/SM regardless (~50 KB/block, 100 KB/SM). The original __launch_bounds__(128, 1) artificially declared only 1 block/SM, leaving the smem-permitted slot empty. Bumping to (128, 2) lets two co-resident WMMA blocks share each SM when smem allows. (128, 4) tested but slightly worse — smem cap binds at 2 regardless, and the (4) hint just constrains the compiler's register budget (65536 / 4 / 128 = 128 regs/thread cap, breaking the 120-reg requirement on some kernels). Performance on RTX 3090 / 512-token prefill: (128, 1) Phase 4: 25.01 ms 20,470 tok/s (128, 2) Phase 5: 24.42 ms 20,970 tok/s (+2.4%) (128, 4): 24.78 ms 20,658 tok/s (slightly worse) Cumulative across Phases 2-5: 17,847 → 21,000 tok/s = +17.7% prefill speedup. Phase2 specifically: 12.79 ms → ~9.0 ms = -30% on phase2.
The WMMA d-compute reads only s_w_bf16; s_w (f32) was a leftover allocation from the scalar kernel structure. Drops it from the shared memory layout and from the Q/K load loop's downcast path. Also computes the WMMA kernel's smem budget directly (P2_WMMA_F32_BYTES + P2_WMMA_BF16_BYTES) instead of as P2_SMEM_BYTES + extras. The old formula carried s_w's 4 KB into the WMMA allocation; the new formula reflects what the WMMA kernel actually uses (~50 KB/block instead of ~54 KB), which is the cap that determines whether 2 blocks fit per SM under the 100 KB SM budget. Performance unchanged within noise (24.4-24.9 ms / ~21k tok/s on RTX 3090 / 512-token prefill). Parity unchanged (47/50 first-token match against scalar baseline; 3 numeric-answer prompts diverge at argmax under bf16 quantization noise as in Phase 4). This is the cleanup that makes Phase 6 (cp.async double-buffered prefetch) tractable in a future session — the actual cp.async work is a substantial restructure (chunk loop reordering, double-buffered u/Q/K/cs staging, careful sync correctness) and intentionally not attempted here.
The o_inter / o_intra section in pf_dn_chunk_phase2_wmma made ~1408 expf calls per chunk per block — but only 44 unique values exist (8 exp(cs[c]) + 36 lower-triangular exp(cs[c] - cs[sp]) entries). The factor of ~32 came from recomputing the same exp() once per j in the (c, j) output grid, since cs_c only depends on c. Adds two tiny __shared__ buffers (s_exp_cs[8], s_exp_diff[64]) filled once per chunk by the first 64 threads via cooperative expf. The hot output loop then looks up s_exp_cs[c] and s_exp_diff[c*C + sp] instead of calling expf inline. With --use_fast_math the compiler emits __expf intrinsics so the actual reduction is in instruction count + register pressure during the inner sp-loop, not just expf latency. Performance on RTX 3090 / 512-token prefill (3-run medians): Phase 5 baseline: 24.42 ms 20,970 tok/s phase2 ~520 µs/launch Phase 7: 24.69 ms 20,733 tok/s phase2 ~482 µs/launch Phase2 self-CUDA time -7% (38 µs/launch saved). Total prefill remains within run-to-run noise of Phase 5 because other phases vary, but the kernel-level speedup is real and consistent across runs. Correctness: 47/50 first-token match against scalar baseline, unchanged from Phase 4+. corpus/wmma_p7.json saved as the new parity reference. Suggested by codex CLI as the highest-leverage residual after Phase 5 landed (the cp.async pipe variant attempted in a prior step did not materialize a speedup; reverted before commit).
…hase 8) The post-state-update bf16 mirror refresh did 4096 single-float conversions per chunk per block (J_per × Dk = 32 × 128). Pairs of adjacent (i, i+1) entries land on consecutive bf16 columns at 4-byte aligned addresses in s_state_bf16, so we can pack via __floats2bfloat162_rn and store as __nv_bfloat162. 4096 stores → 2048. The s_state f32 source has stride DK_S=129 (bank-conflict pad) which is NOT 8-byte aligned for non-zero rows, so we read two scalars and pack rather than load float2 — fewer instructions on the write side and unchanged on the read side. Performance on RTX 3090 / 512-token prefill (5-run results): Phase 7: 24.69 ms 20,733 tok/s phase2 ~482 µs Phase 8 (paired refresh): 24.80 ms 20,642 tok/s phase2 ~483 µs Best run Phase 8: 23.98 ms 21,347 tok/s phase2 ~478 µs Within run-to-run noise of Phase 7 in median terms, but the best-of-N prefill improved (~24.0 ms → fastest observed in the series). The write-count reduction is real (-50% smem stores in this section); whether it converts to wall time depends on whether smem store bandwidth was the residual bottleneck — and at this point the remaining headroom is small enough that variance dominates. Correctness: 47/50 first-token match against scalar baseline, unchanged from Phase 4+. Pattern is available for future conversions (e.g. state-update accumulator → bf16, w/Q/K mirror fills) if the optimization moves to vectorizing those. This is the final commit of the Path B WMMA series for now. Cumulative across Phases 2-8: scalar 17,847 → ~21,000 tok/s = +17-18% prefill speedup. Within phase2 specifically: 12.79 ms → ~8.7 ms = -32%. Diminishing returns past this point require structural changes (persistent kernel / cooperative groups, vectorized cp.async with realigned smem layout, or WMMA on the small remaining QKt/o_intra ops at the cost of an extra block-side smem buffer).
Contributor
oliveagle
pushed a commit
to oliveagle/lucebox-hub
that referenced
this pull request
May 22, 2026
…ase2-wmma-prep megakernel: WMMA tensor-core rewrite of pf_dn_chunk_phase2 (closes part of Luce-Org#5)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Why this PR
Issue #5 reports prefill performance well below the README's 37,800 pp520 figure on RTX 3090. Multiple users (chfwinter, ateamlunchbox, dknos) saw ~8.5k tok/s. dknos diagnosed cuBLAS MAGMA fallback on their sm_120 setup and proposed an
at::mm_outswap.On this RTX 3090 (sm_86) I confirmed via
torch.profilerthat the GEMMs already land cleanly on tensor cores (ampere_bf16_s16816gemm…,cutlass_80_tensorop_*) — the MAGMA fallback dknos saw is not the issue here. Untouched, this machine sits at ~17,800 tok/s pp512 (twice issue #5's 8.5k baseline, but still half the README claim).The hottest residual on this hardware is
pf_dn_chunk_phase2— 47.6% of CUDA time, all scalar FP32 inner products in shared memory. This PR rewrites the matmul-shaped pieces of that kernel onto WMMA bf16 tensor cores (m16n16k16, f32 accumulate).What's in the PR
A second kernel
pf_dn_chunk_phase2_wmmalives alongside the scalar reference; runtime env varMEGAKERNEL_DN_PHASE2_WMMA_RUNTIME=1flips between them — no rebuild required for A/B testing. Default behavior (=0or unset) is the unchanged scalar kernel, so this PR is opt-in for users.Eight commits, each documented and benchmarked independently:
085fc51946dc87c2d866ae70c21877258df6c719c7__launch_bounds__(DN_PHASE2_BLOCK, 2)— smem caps occupancy at 2 blocks/SM, declaring (128, 2) lets the compiler exploit it2bac32es_wf32 (onlys_w_bf16is read in WMMA path), tighten smem allocation so 2 blocks really fit per SMebe12fdexp(cs[c])andexp(cs[c]-cs[sp])tables once per chunk — 1408 exps/chunk → 44 (32× redundancy fix)7d82707__floats2bfloat162_rn) for the per-chunks_state_bf16mirror refreshPerformance — RTX 3090, 512-token prefill, qwen3.6-27b-dflash
Phase2 kernel time -32% (12.79 ms → 8.7 ms across 18 layer launches). Total prefill +15-18% depending on the noise window — variance on the non-phase2 sections widens the spread.
Above the headline number: the README's 37,800 pp520 is not reachable from this branch. Every WMMA path I could hit cleanly is on tensor cores, and the remaining work (smem latency, sync overhead, scalar bookkeeping) doesn't have an obvious lever in the same magnitude. To close the rest would need structural change — persistent kernel, vectorized cp.async (attempted in this branch and reverted, see below), or revisiting whether the figure is reproducible on stock 3090 with locked clocks.
Correctness
Parity gate built up in the first commit: 50 fixed prompts × 32 generated tokens, captured as
corpus/baseline.jsonfrom current main and re-captured at every phase ascorpus/wmma_pX.json.Across all 8 phases the WMMA kernel matches the scalar kernel on 47 / 50 first generated tokens. The 3 divergent prompts are all numeric-answer (factorial code, square root of 144, speed of light) where the logit margin between adjacent number/format tokens is razor-thin and bf16 truncation flips argmax under quantization noise. Mid-decode divergence in the 47 matching prompts is expected — bf16 state truncation propagates through subsequent decode steps.
Two additional sanity checks done locally:
bench_pp_tg.pycorrectness section (The capital of France is) → predicts the same first token in scalar and WMMA modes.What didn't work — Phase 6 cp.async (reverted before commit)
I implemented a third kernel
pf_dn_chunk_phase2_wmma_pipewith double-buffered f32 staging via__pipeline_memcpy_async. Goal: overlap chunk N+1 loads with chunk N compute. Result: bit-identical first-token output to the unpipelined kernel, zero wall-time gain (25.07 ms vs 25.05 ms).Two contributing factors:
Per-element 4-byte
cp.asyncissuance — each thread issued ~27 cp.async calls per chunk. Issue overhead at this granularity ate the overlap gain. Vectorized 16-byte loads viafloat4would help (4× fewer instructions) but require 16-byte aligned smem destinations, and the bank-conflict padDK_S = 129 floatsbreaks alignment for non-zero rows.Smem grew from ~50 KB (Phase 5 with
(128, 2)) to ~67 KB. The kernel falls to 1 block/SM, giving back the +3% Phase 5 occupancy gain — net wash.The working
cp.asyncinfrastructure is preserved in the branch history for future use if anyone wants to vectorize cp.async with a realigned smem layout.Test plan
MEGAKERNEL_DN_PHASE2_WMMA_RUNTIME=1 python megakernel/diag_prefill_kernels.py— kernel mix verdict + tok/sMEGAKERNEL_DN_PHASE2_WMMA_RUNTIME=1 python megakernel/build_corpus.pythen diff vscorpus/baseline.json— parity gatepython megakernel/bench_pp_tg.pycorrectness section under both env valuesMEGAKERNEL_DN_PHASE2_WMMA_RUNTIME=0(default) is unchanged from current main — no risk to existing usersSuggested follow-ups (not in this PR)
DK_S = 132and accept slight bank conflict, or reorganize to avoid stride pad entirely).ncuon bare-metal Linux (WSL2 blocks GPU performance counters viaERR_NVGPUCTRPERM) to identify the real residual bottleneck. Right now we're picking optimizations from first principles +torch.profilertiming only.prefill_megakernel.cuif the author of that file thinks the persistent-kernel structure is compatible.