Skip to content

Qwen3 prefill fast path default: 8.56 ms graph / 9.03 ms TTFT - #134

Merged
LiangSu8899 merged 21 commits into
mainfrom
qwen3-prefill-megakernel
Jul 7, 2026
Merged

LiangSu8899 merged 21 commits into
mainfrom
qwen3-prefill-megakernel

Conversation

@LiangSu8899

@LiangSu8899 LiangSu8899 commented Jul 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Additive NVFP4 prefill fast path for Qwen3-8B on SM120a (RTX 5090).
The fast profile is now the default path: SwiGLU epilogue fold, residual-fused
GEMM, and FP8 FMHA prefill are enabled unless explicitly disabled by env flags.
Fallback chains remain available for A/B checks and unsupported shapes.

The performance profile removes HBM round-trips between the prefill's NVFP4
GEMMs by fusing surrounding elementwise work (activation, norm, quant, RoPE,
residual add, attention) into producing/consuming kernels.

What's in here

  • SwiGLU epilogue fold - silu(gate)*up inside the interleaved gate|up
    NVFP4 GEMM's FP4-out epilogue plus even-column compaction. Default ON; set
    FLASH_RT_QWEN3_SWIGLU_FOLD=0 to restore the split GEMM + silu_mul path.
  • norm/quant kernels - one-block-per-row q/k norm+RoPE, register-prefetch
    norm-to-NVFP4 kernels, and rms_norm_to_nvfp4_swizzled_bf16_v3 with
    byte-identical fallback chains.
  • fp8 prefill attention - all-fp8 causal GQA is default ON
    (FLASH_RT_QWEN3_FP8_FMHA=1 by default); sage2 fp8-QK/fp16-PV remains
    available with FLASH_RT_QWEN3_FP8_ATTN=1. Unsupported shapes fall back to FA2.
  • residual fold - D = alpha*(A*B) + C NVFP4 GEMM variant folds the
    o_proj/down residual add into the GEMM epilogue. Default ON; set
    FLASH_RT_QWEN3_RESID_FUSE=0 or legacy FLASH_RT_QWEN3_NO_RESID_FUSE=1 to
    force the old separate-add path.
  • build-boundary cleanup - Qwen3 fp8 prefill attention now builds from the
    neutral qwen3_prefill_sm120_obj, independent of FLASHRT_ENABLE_MOTUS.
    SM120 tilesweep/normfold probe bindings are behind
    FLASHRT_ENABLE_SM120_DEV_KERNELS=ON and default OFF.

Measurements

Measured after the default-fast-path change in RTX 5090 / SM120a test environment on RTX 5090
/ SM120a, /path/to/qwen3-vl-8b-llm-nvfp4, prefill bucket S=512, 30
CUDA-event iterations:

  • Default fast profile (no Qwen3 prefill env flags after this PR): graph replay
    P50 8.56 ms, prefill_with_graph P50 9.03 ms. This meets the
    9.16 ms target with margin.
  • Legacy fallback profile remains available with
    FLASH_RT_QWEN3_SWIGLU_FOLD=0 FLASH_RT_QWEN3_RESID_FUSE=0 FLASH_RT_QWEN3_FP8_FMHA=0.

Compliance

  • Default behavior: Qwen3 prefill uses the fast profile by default; explicit
    env flags keep the legacy fallback path available for A/B checks.
  • Compilation ownership: Qwen3 fp8 attention is no longer compiled under Motus
    object/macro gates; Motus raw sage2 kernels remain under Motus gates.
  • Developer probes: tilesweep/normfold probe sources and pybind symbols require
    -DFLASHRT_ENABLE_SM120_DEV_KERNELS=ON.
  • Slim build layering: sources previously duplicated between the main target and
    gated target-source blocks were moved back to a single gated location.

Test

PYTHONPATH=. PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 pytest -q \
  tests/test_qwen3_prefill_maintenance.py \
  tests/test_build_inventory.py \
  tests/test_generic_kernel_bindings.py
# 4 passed, 10 skipped in this environment (no configured build dir)

python -m compileall -q \
  flash_rt/frontends/torch/qwen3_rtx.py \
  flash_rt/hardware/rtx/attn_backend_qwen3.py \
  scripts/build_inventory.py \
  tests/test_build_inventory.py \
  tests/test_qwen3_prefill_maintenance.py

git diff --check origin/main...HEAD

Additive new kernel cutlass_nvfp4_dual_gemm_silu_fp4out_sm120: the
dual-accumulator (gate+up share A) realization of the SwiGLU epilogue
fold, output N = intermediate so the blockscaled-FP4 store stays standard.

M0 lands the build/binding/instantiation scaffold and the epilogue half:
single projection silu(alpha*A@Wgate) -> NVFP4 packed + swizzled UE4M3 SF
(SiLu activation on the SM120 blockscaled fp4-out collective). Validated
end-to-end through the down GEMM vs (gate bf16 -> silu -> quant -> down):
cos 0.9956. The dual mainloop (Wup 2nd accumulator) + SwiGLU multiply land
incrementally on this stable interface.
…feasibility

Adds cutlass_nvfp4_w4a16_tilesweep_sm120: the production sm120 fp4 GEMM
family (arch::Sm120 + Cooperative + BF16 out) templated on TileShape, for
apples-to-apples per-tile efficiency measurement.

Finding: a 128x64 per-accumulator tile (which a dual-accumulator SwiGLU
mainloop would require to fit two accumulators in <=255 regs) does not
compile on the blockscaled path — the UE4M3 SF TMA atom requires
BLOCK_M,BLOCK_N >= 128. Baseline 128x128x256 compiles and reproduces the
~99% gate_up roofline. So the dual-accumulator realization is infeasible
without a from-scratch non-TMA SF mainloop; the SwiGLU fold proceeds via
the single-accumulator + epilogue route instead.
…-epilogue

Forks the SM120 blockscale-FP4 store visitor (Sm120BlockScaleFactorRowStore)
into a SwiGLU variant: visit() computes silu(alpha_gate*gate)*(alpha_up*up)
on the adjacent interleaved gate/up accumulator columns, reusing the stock
amax/quant/SF-store machinery verbatim. Added as a new FusionOperation
(SiluMulBlockScaleFactor) + callback specialization in an additive header;
the stock CUTLASS visitor is untouched. Mainloop stays the stock
128x128x256 collective so the gate_up GEMM keeps its ~99% roofline.

The dual-accumulator realization was empirically ruled out (a 128x64
per-accumulator tile does not compile on the blockscaled path), so the fold
runs as a single GEMM on an interleaved gate|up weight (gate@2i, up@2i+1).

M2a validates the in-epilogue silu_mul end-to-end through the down GEMM at
cos 0.9985 (full-width duplicated output). M2b will compact the output to
half width [M, intermediate] for the real down GEMM.
…king

The full-width [M,2*inter] dup'd output is compacted to the down-ready
[M,inter] NVFP4 without coordinate surgery or requant:

  * OutputSFVectorSize=32 on the interleaved gate|up GEMM output: the
    silu_mul 2->1 collapse makes 32 GEMM cols = 16 OUTPUT cols, so the SF
    is per-16-output. Its swizzled byte layout (rows M, n_blocks=inter/16)
    is byte-identical to the down GEMM's per-16 SFA, so SFD passes through
    unchanged. The blockscale visitor already supports SF32 (WarpsPerSF=2).
  * a trivial even-column nibble-gather kernel (fp4_swiglu_even_col_compact)
    packs the FP4 data [M,inter] dup'd bytes -> [M,inter/2] (~3us).

Validated through the REAL down GEMM (K=inter, normal weight) vs the shipped
gate/up->silu->quant->down path: cos 0.9988 (fp4 noise floor; the fold silu's
in fp32, the more accurate side). The SwiGLU epilogue fold is now functionally
complete: interleaved GEMM (silu in epilogue) -> compact -> down.
Integrates the fused SwiGLU GEMM into _layer_forward_full_nvfp4_prefill behind
FLASH_RT_QWEN3_SWIGLU_FOLD (default OFF). Replaces the [gate_up GEMM bf16 +
silu_mul_to_nvfp4] 2-launch chain with [dual_gemm_silu on the interleaved
gate|up weight + even-col compaction] — no bf16 activation round-trip.

Loader builds the interleaved gate|up weight (gate row i -> out col 2i, up ->
2i+1) by interleaving weight_packed + linear weight_scale on dim 0 then
swizzling; additive, the split and concat-fused weights remain as fallback.
M is padded to a 128-multiple for the blockscale SFD swizzle (down reads only
the real S rows).

Red line vs ORIGINAL HF bf16 (4 real prompts): argmax-vs-HF base 2/4 == fold
2/4 (same matches; misses are the existing fp4 quant), and cos(fold,HF) >=
cos(base,HF) on all 4 (the fold silu's in fp32). No quality regression. Perf:
eager -0.327 ms (standalone -0.66 ms). Additive + env-gated; default path
untouched.
… at identity (M-FULL-3a-i)

Norm-prologue-fold groundwork: a forked CUTLASS sm120 TMA warp-specialized
blockscaled CollectiveMma that will later fold RMSNorm into the consuming
GEMM's A-load. This commit lands the fork MACHINERY only, proven inert.

- MainloopSm120NormFold dispatch tag (distinct type -> selects the fork, no ODR
  conflict with the stock blockscaled collective).
- sm120_normfold_mma_tma.hpp: the forked CollectiveMma specialization (identity
  body, verbatim from stock; A-path transform comes in 3a-ii).
- sm120_normfold_builder.hpp: thin NormFoldBuilder that delegates to the stock
  CollectiveBuilder for all CuTe type derivation, swapping only the dispatch tag.
- cutlass_nvfp4_normfold_probe_sm120.cu: mirrors the production GEMM assembly,
  mainloop = NormFoldBuilder::CollectiveOp; binding fp4_normfold_probe_sm120_bf16out.

Verified bit-identical to fp4_w4a16_gemm_sm120_bf16out on real prefill scratch +
real weights (o_proj/qkv: max_abs=0). Additive only; no production path touched.
…r bf16-A fold

Adds ProbeVariant<TileShape> + fp4_normfold_probe_sm120_bf16out_v(variant) so the
forked collective can be exercised at <128,128,64> as well as the <128,128,256>
identity anchor.

Finding (drives the M-FULL-3a-ii design): bf16 A at BLK_K=256 is 64KB/stage and
cannot satisfy the collective's Stages>=2 in ~100KB smem, so the fold needs a
smaller K. The K=64 tile COMPILES + RUNS (rc=0) but cos vs production is ~0.997
(max_abs 2-3), not ~1.0 — an 8% L2 gap that pure fp32 K-reorder cannot explain, so
the SF-atom indexing is not self-consistent at BLK_K=64. => use sub-K bf16 staging
(keep BLK_K=256 fp4 smem + the bit-exact consumer; stage bf16 A in 64-K chunks and
quantize to the existing fp4/SFA smem). Full file-cited change surface + plan in
qwen3_prefill_dev/notes/MEGAKERNEL_RESEARCH.md S11j. Additive; identity gate green.
…bf16-direct

Adds ProbeVariant<128,128,128> (variant 2). K128 is bit-IDENTICAL to production
(max_abs=0, cos=1.0) on o_proj+qkv, vs K64's 0.997. So the SF-atom quirk is unique
to BLK_K=64 (one m16n8k64 K-tile, degenerate SF sub-tiling); K128 has 2 k_blocks
and is exact.

=> the bf16-A norm fold can use bf16-direct @BLK_K=128: smem holds only bf16 A
(32KB/stage) + fp4 B (8KB), ~40KB/stage so 2 stages fit <100KB; the consumer
quantizes bf16 smem -> e2m1+UE4M3 registers and feeds the (proven-exact) K128 MMA,
dropping the fp4-A smem + SFA TMA entirely. Much less plumbing than sub-K staging.
Design + crux (per-16-K-block amax locality) in MEGAKERNEL_RESEARCH.md S11j.
…CT (M-FULL-3a-ii)

The consuming GEMM now loads A as bf16 and quantizes it to NVFP4 (e2m1 + UE4M3
SFA) inside the consumer registers — folding the activation quantize into the
GEMM's A-load (toward folding RMSNorm; identity norm here). Output is bit-exact
(cos 1.0, relL2 0) vs the standalone quantize_bf16_to_nvfp4_swizzled + production
fp4 GEMM, across const / vary-M / vary-Kblk / within-block / randn / scale sweeps.

Mechanism:
- New tag MainloopSm120NormFoldBf16A + forked CollectiveMma (bf16 A smem via
  UMMA::Layout_K_SW128_Atom<bf16>; SFA TMA dropped); NormFoldBuilderBf16A delegates
  all other CuTe types to the stock fp4 builder.
- Consumer quantize: cooperative per-16-K-block amax in a small smem buffer
  (broadcast, no warp shuffle), then e2m1 (raw uint4 write) + UE4M3 into the MMA
  fragments via the production SFA copy-view coords.
- BLK_K=128 (proven bit-exact tile), StageCount<2>, amax buffer processed per
  k-block (2 KB) so mainloop+epilogue fit the 99 KB sm120 smem.

Three bugs found + fixed (full diagnostic trail in qwen3_prefill_dev/notes/
MEGAKERNEL_RESEARCH.md S11l-m): (1) e2m1 fragment write re-encoded by value —
write the raw nibble via recast<uint4_t>; (2) smem budget — drop dead smem_SFA +
per-k-block amax; (3) cross-K-tile corruption — the A quantize fills all k-blocks
at once, so it cannot be software-pipelined ahead of the current tile's last
gemm_kblock; de-pipelined the consumer loop.

Probe-only (fp4_normfold_bf16a_probe_sm120 binding); not yet wired into prefill,
not yet perf-tuned (raw smem copy, de-pipelined). Additive; identity fork stays
the bit-exact regression anchor.
Fork the identity normfold collective so the producer TMAs bf16 A into a
staging buffer and the consumer quantizes it in natural layout (per-row,
per-16-K-block thread-local amax, zero cross-thread shuffle) into fp4 sA +
ue4m3 SFA, which the stock roofline fp4 blockscaled MMA then reads unchanged.

Fit BLK_K=128 into the sm_120 ~100KB smem cap by single-buffering the bf16
staging (PIPE=1) behind a 1-deep handoff mbarrier: the consumer ARRIVEs after
quantizing bf16[0], the producer WAITs before refilling; "full" stays on the
existing tx-byte pipeline. The barrier is initialized exactly once on the
producer's first K-tile (smem_pipe_write.count()==0) and seen by the consumer
through the pipeline fence — no per-tile __syncthreads.

Additive: new collective file + NormFoldBuilderPQ + ProbeVariantPQ + probe
binding; the identity and bf16-direct forks are untouched. Probe result vs the
separate quantize(A)+production-GEMM path: K128 cos 1.000000 / relL2 0 on
o_proj/qkv/gate_up; K64 stays at the SF-atom-tile floor 0.985.
The fused gate_up GEMM with an in-epilogue silu(gate)*up (interleaved gate|up
weight, FP4 out, SF32) removes the separate silu_mul launch and its bf16
round-trip. Graph-validated -0.438 ms/prefill at S=512 (10.95 -> 10.52); the
HF argmax/cos red line holds (fold-vs-HF == base, cos(fold,HF) >= cos(base,HF)).
Still env-gated and only activates when the interleaved weight + fused-kernel
symbols are present; FLASH_RT_QWEN3_SWIGLU_FOLD=0 restores the old path.
…refill)

The scalar even_col_compact ran one thread per output byte (byte-granular
loads, ~45% BW) and cost 0.42 ms/prefill at S=512. Add a vectorized variant
fp4_swiglu_even_col_compact_v2 (16B uint4 load / 8B uint2 store, one thread per
8 output bytes) that is bit-identical to the scalar kernel and 2.5x faster
standalone; in the pipeline it drops 11.66 -> 2.69 us (the fold output is
L2-resident). Wired into prefill behind a hasattr guard with scalar fallback.
Full prefill graph S=512: 10.49 -> 10.21 ms. Additive: new kernel + binding;
the scalar kernel is untouched.
… ms prefill)

The block-per-row rms_norm / residual_add_rms_norm / quantize -> nvfp4 kernels
were at only ~28% HBM BW: latency-bound, because the grid-stride load loop ate
one memory latency PER iteration. Add bit-identical _v2 kernels that prefetch the
whole row into a register array (independent loads issue back-to-back = one
latency), reuse it so the input is read once (no second-pass re-read), fuse the
per-16-block amax -> UE4M3 SF -> FP4 pack into one atomic-free, sync-free pass,
and encode e2m1 branchless (the 8-way if-else diverged across the warp).

Standalone, bit-identical (packed/SF/h_post all match v1): rms_norm 10.25->6.15us
(1.67x), residual_add_rms_norm 12.29->8.20us (1.50x), quantize 8.19->4.12us
(1.99x). Wired into the prefill via init helpers (self._resnorm_q/_rmsnorm_q/
_quant_q) with the v1 kernels as fallback for cols>4096. Full prefill graph
S=512: 10.21 -> 9.86 ms. Additive: new _v2 kernels + bindings; v1 untouched.
The batched q/k_norm_rope prefill kernels launched ONE BLOCK PER (head, row) =
n_heads*S = 16384 tiny 128-element blocks, leaving them at 2.5x their memory-copy
floor (10.25us vs a 4.10us strided-copy of the same 8MB). The cost was the block
COUNT, not memory/sync/compute: a sync-free warp-per-row variant, vectorized 256B
transactions, and vectorized bf162 conversions each moved it 0.

New v3 kernels run ONE BLOCK PER ROW (grid=(S,), 256 threads = 8 warps); each warp
loops over its heads via a warp-per-row helper: lane owns the contiguous 4 elements
{4t..4t+3} (one 8-byte vectorized load), the RMS sum is a warp shuffle, and the
RoPE partner (i +/- 64, owned by lane^16) is fetched with one __shfl_xor — no smem,
no __syncthreads. Block count 16384 -> 512 (matching the fast row-grid kernels):
10.25 -> 4.09 us (2.5x, exactly the copy floor), cos 1.0 vs the old kernel (~1 ULP
from the fp32 sum regrouping). Wired with a v1 fallback; full prefill graph S=512
9.86 -> 9.60 ms. HF red line unchanged (argmax 2/4, cos 0.97-0.99 vs the bf16 ref).
Additive: new kernels + bindings; the per-(head,row) and decode kernels untouched.
Prefill attention was the bf16 FA2 vendor kernel at 28.3us/layer in-graph, with
the S=512 shape leaving the tensor pipes latency-bound (0.75-wave occupancy).
An e4m3 path halves every operand: same softmax/masking numerics, fp8 QK^T and
P*V MMAs with fp32 accumulate.

Two attention kernels, both env-gated OFF and falling back to FA2 for any
unsupported shape (q_seq not a multiple of 128, decode, cross-attn ranges):

* sage2-based fp8-QK / fp16-PV causal GQA kernel (FLASH_RT_QWEN3_FP8_ATTN=1),
  per-token e4m3 Q/K scales, fp16 V.
* all-fp8 causal GQA kernel (FLASH_RT_QWEN3_FP8_FMHA=1, takes precedence):
  raw e4m3 Q/K/V with no scales - post-norm Q/K magnitudes sit inside e4m3's
  dynamic range (max ~228 vs the 448 format max), so a scale adds no relative
  precision. 8 MMA warps per (q-tile, head), cp.async double-buffered K/V with
  a one-tile prefetch, XOR-swizzled smem tiles, and a padded V-transpose row
  stride (128 -> 136) that removes the 8-way bank conflict of the scatter
  store. 24.1us/layer in-graph vs FA2's 28.3.

The e4m3 operands are produced for free: new norm_rope prefill variants fold
the cast into the existing RMS-norm+RoPE row pass (the row is already in
registers), also skipping the now-redundant bf16 Q_buf write. The direct
variant drops the per-token amax reduce and emits V as e4m3 too.

Full prefill graph S=512: 9.560 -> 9.471 ms. Red line: argmax matches the
bf16 path at S=128/256/512 on real prompts (logits cos 0.991+); per-layer
attention cos >= 0.988 vs fp32 reference. Additive: new kernels + bindings +
an env-gated branch in the backend/frontend; FA2 and decode paths untouched.
The v2 rms_norm_to_nvfp4_swizzled kernel loads its input one bf16 at a time:
each warp transaction moves 64B = half a 128B line, capping the kernel at
~50% of HBM peak. Standalone with an L2-hot input that costs nothing (v2 ==
v3 at S=512), but inside the prefill graph the input arrives L2-cold from the
preceding GEMM and the half-width transactions dominate: 7.7us/call in-graph.

The v3 kernel keeps v2's exact math and fused amax->SF->pack phase, but moves
data full-width: uint4 (8 x bf16) loads for the row and the norm weight,
uint4 staging stores, and one uint2 store for each 16-element block's packed
FP4 bytes. Bit-identical output (packed and SF byte-equal to v2 across random
inputs); the fp32 ssq regrouping is also unchanged in practice. Falls back to
v2 outside the vector envelope (cols % 16 != 0 or cols > 4096).

In-graph 7.7 -> 5.0us/call across the 72 prefill norm sites; S=1024/2048
buckets gain 1.25-1.56x standalone. Full prefill graph S=512: 9.47 -> 9.30 ms.
Argmax red line unchanged (bit-exact kernel swap). Additive: new kernel +
binding; the frontend getattr chain now prefers v3 -> v2 -> v1.
… (-0.11 ms)

The prefill layer ran o_proj and down as plain GEMMs and added their
residuals in the following norm kernel, which therefore read two tensors.
A residual variant of the NVFP4 W4A16 GEMM (D = alpha*(A*B) + C, C the bf16
residual, added in FP32 by the epilogue's linear combination) folds that
add into the GEMM: o_proj takes C = h_in and emits h_post directly; a
non-final layer's down GEMM takes C = h_post and emits h_out, so both
following norms are plain rms_norm+quant over ONE tensor.

The FP32 epilogue add is slightly more accurate than the previous separate
bf16 add — a small behavioural change (S=512 argmax unchanged; logits cos
~0.992 vs the unfused path). Default ON; FLASH_RT_QWEN3_NO_RESID_FUSE=1
restores the separate-add path. The final layer keeps the separate residual
+ final-norm chain. Additive: new GEMM entry point + binding.
…14 ms)

On the all-fp8 prefill attention path the O tile lives in registers at the
end of the mainloop, gets written out as bf16 (4 MB/layer), and is then
immediately re-read by the standalone quantize kernel to produce the o_proj
GEMM's NVFP4 A-operand. Both halves of that round-trip are avoidable.

The fp4-out kernel variant quantises in the epilogue instead: each
16-element group's amax reduces across its owning lane quad with two
shuffles, the ue4m3 group scale and packed e2m1 bytes assemble in registers
(values round through bf16 first, so packed and SF bytes are identical to
the bf16-write + quantize-kernel chain — verified byte-equal), and the
tt==0 lane stores the 8-byte block plus its swizzled SF byte straight into
the o_proj scratch. The bf16 O write and the 36 quantize launches disappear.

Wiring: the frontend hands the o_proj packed/SF scratch pointers to the
attention backend before run(); the backend prefers the fp4-out kernel when
they are set and the frontend skips the quantize call under the same gate.
FA2 and the bf16-out fp8 kernel are untouched (decode and non-128-multiple
prefills fall back as before).

Full prefill graph S=512: 9.30 -> 9.16 ms. Argmax red line unchanged at
S=128/256/512 (byte-identical operands into o_proj).
# Conflicts:
#	CMakeLists.txt
#	csrc/bindings.cpp
@LiangSu8899 LiangSu8899 changed the title perf(qwen3-8b): NVFP4 prefill kernel fusion — SwiGLU / norm / fp8 attention (graph S=512 → 9.16 ms) Qwen3 prefill fast path default: 8.56 ms graph / 9.03 ms TTFT Jul 5, 2026
@LiangSu8899

Copy link
Copy Markdown
Member Author

TODO: Gradually move the build system from hardware-driven broad compilation toward model-family-level governance, so kernels, bindings, runtime paths, and tests can be traced and trimmed by model family rather than implicitly pulled in by hardware support alone.

@LiangSu8899

Copy link
Copy Markdown
Member Author

Pre-merge validation completed on an RTX 5090 / SM120a test environment.

Summary:

  • PR head: a8d3aa7f0d0ccda2d2cbcd2de72cb30fde31e692
  • GitHub mergeability: MERGEABLE
  • CUDA extension imports: flash_rt_kernels and flash_rt_fa2 import successfully

Build / compile-boundary checks:

  • cmake --build <sm120-motus-off-build> -j --target flash_rt_kernels: passed
  • cmake --build <sm120-motus-on-build> -j --target flash_rt_kernels: passed
  • Motus OFF symbol gate matches expectations:
    • fmha_fp8_causal_gqa_nhd_d128: present
    • fmha_fp8_causal_gqa_nhd_d128_fp4out: present
    • sage2_qk_f8_sv_f16_bf16_gqa_nhd_d128_causal: present
    • fp4_normfold_probe_sm120_bf16out: absent
    • fp4_w4a16_tilesweep_sm120_bf16out: absent
    • Motus raw sage2 binding: absent
  • Dev-kernel configure gate matches expectations:
    • dev OFF: qwen3_prefill_sm120_obj present, sm120_nvfp4_dev_obj absent
    • dev ON: qwen3_prefill_sm120_obj present, sm120_nvfp4_dev_obj present
  • Motus OFF compile flags include ENABLE_QWEN3_FP8_PREFILL_ATTN=1 and ENABLE_SAGE2_F8_RAW=1, and do not include ENABLE_MOTUS_SAGE2_RAW.

Static / smoke checks:

  • git diff --check over the PR cleanup commits: passed
  • compileall over changed Python/test files: passed
  • pytest with the SM120 build inventory dir: 11 passed, 3 skipped
  • Import smoke passed for the main kernel module and representative frontends: Qwen3, Qwen3.6, Qwen3-VL BF16, Pi0.5 RTX, Pi0.5 RTX FP16, and GROOT N1.7 Thor.

Qwen3 prefill correctness smoke:

  • Default fast profile, S=128/256/512, graph prefill vs eager prefill:
    • argmax match: true for all three lengths
    • finite outputs: true for all three lengths
    • cosine range: 0.999976 to 0.999991
  • Fallback profile with FLASH_RT_QWEN3_SWIGLU_FOLD=0 FLASH_RT_QWEN3_RESID_FUSE=0 FLASH_RT_QWEN3_FP8_FMHA=0, S=128/256/512, graph prefill vs eager prefill:
    • argmax match: true for all three lengths
    • finite outputs: true for all three lengths
    • cosine approximately 0.99998

Default performance smoke, no Qwen3 prefill env flags set:

  • Default fast features are active: SwiGLU fold, residual fuse, FP8 direct attention, and FP4-out attention epilogue.
  • S=512 graph replay P50: 8.38 ms
  • S=512 prefill_with_graph P50: 8.94 ms

This confirms the intended default fast path, fallback path, Motus-independent Qwen3 FP8 attention build, and dev-only probe gating.

@LiangSu8899
LiangSu8899 merged commit 5b21aa8 into main Jul 7, 2026
hypertseng added a commit to hypertseng/FlashRT that referenced this pull request Jul 10, 2026
Include:
- Qwen3 prefill fast path optimization (flashrt-project#134)
- SM89 Qwen3-VL FP8 decode-path optimization (flashrt-project#139)
- VLASH async runner (flashrt-project#138)
- RTC temporal fusion runtime (flashrt-project#137)
- GRoot N17 latency stats and fixes (flashrt-project#132)
- Thor fp16 routing through Thor producer (flashrt-project#133)
- Qwen3-VL improvements and fixes

Co-Authored-By: Claude Fable 5 <[email protected]>
heiheiha798 added a commit to heiheiha798/FlashRT that referenced this pull request Jul 17, 2026
Fuse gate_up GEMM + silu_mul + per-token block-128 FP8 quant into one launch,
eliminating the [S, 2*inter] BF16 transient the baseline two-launch path
(gate_up GEMM -> silu_mul_merged_to_fp8) materializes. Mirrors flashrt-project#134's SwiGLU
epilogue fold (sm120) and sm100 flashrt_megakernel_geglu's gate-in-smem
pattern, ported to sm89's hand-written cp.async + ldmatrix.x4 + mma.m16n8k32
idiom (no TMA/tcgen05).

Two kernel variants in fp8_bs_gemm_device.cuh (additive; fp8_bs_gemm_kernel
untouched):
  - fp8_bs_geglu_silu_fold_kernel: two-pass (gate -> smem -> up), the shipped
    tile (32x128_w4_s1). Single B smem region reused across passes; only one
    accumulator live at a time (~70 regs).
  - fp8_bs_geglu_silu_fold_apersist_kernel: A-persistent interleaved
    experiment (both gate+up acc in regs, B reloaded per k-iter). Kept as a
    bench-only tile; the two-pass s1 won the e2e sweep.

ncu diagnosis (issue #1 Phase 2) isolated why naive two-pass lost: s2 occupancy
collapse (gate_smem + 2 cp.async stages -> 49.7KB -> 1 CTA/SM, 8.33% occupancy)
+ 2x pipeline drain. s1 (29.7KB, 3 CTA/SM) recovers and wins in the
launch-bound regime. The gate_up GEMM is compute-bound above the S crossover,
so the fused path is shape-gated per-inter (2B S in [96,192], 8B S=128 only);
outside the band the baseline two-launch path runs unchanged (default
byte-identical, env FLASH_RT_SM89_SILU_FOLD_PREFILL=1 opt-in).

Correctness: e2e prefill cosine 0.9992-1.0 vs baseline, argmax preserved
across S (saturating-FP8 real activations). One fewer bf16(acc) rounding than
baseline (documented). Fixed an out_scale write bug (single-thread guard left
rows 1..BM-1 unwritten -> garbage scale, correct fp8).

E2E prefill (4090, 30-iter median, fold on vs off):
  2B S=128: 6.10 -> 5.64 ms  +7.5%
  2B S=192: 6.10 -> 5.54 ms  +9.2%
  8B S=128: 13.97 -> 13.45 ms +3.7%  (stable across 3 runs)
Above the band: no regression (falls back to baseline).

Bench script scripts/test_geglu_silu_fold_correctness.py included.
LiangSu8899 pushed a commit that referenced this pull request Jul 24, 2026
…151)

* feat(sm89): residual-fold GEMM epilogue (idiom validation, not wired)

Add RESID template param to fp8_bs_gemm_device.cuh: D = bf16(acc) + resid,
folding the residual add into the GEMM epilogue (no separate residual_add
launch, no D HBM round-trip). if constexpr (RESID) dead-strips the residual
branch, so RESID=false stays byte-identical to the baseline kernel.

Adds 4 residual-fold tile variants (32x64 / 64x64 / 64x64_s1 / 128x128_s1)
for the prefill down-proj shapes, bound bench-only under
ENABLE_QWEN3_VL_DEV_KERNELS (additive; production dispatcher untouched).

Phase 1 finding: prefill's residual add is ALREADY fused by
residual_add_rms_norm_to_fp8 on every non-last layer, so residual-fold only
saves ~1 [S,hidden] bf16 transfer (0 launches). Validated as the
epilogue-fold idiom proof (cos 1.0 vs fp32 ref, 1-ULP reassociation diff) but
NOT wired — real prize is silu-fold (Phase 2). Bench script included.

* feat(sm89): GeGLU silu-fold megakernel for prefill gate_up (opt-in)

Fuse gate_up GEMM + silu_mul + per-token block-128 FP8 quant into one launch,
eliminating the [S, 2*inter] BF16 transient the baseline two-launch path
(gate_up GEMM -> silu_mul_merged_to_fp8) materializes. Mirrors #134's SwiGLU
epilogue fold (sm120) and sm100 flashrt_megakernel_geglu's gate-in-smem
pattern, ported to sm89's hand-written cp.async + ldmatrix.x4 + mma.m16n8k32
idiom (no TMA/tcgen05).

Two kernel variants in fp8_bs_gemm_device.cuh (additive; fp8_bs_gemm_kernel
untouched):
  - fp8_bs_geglu_silu_fold_kernel: two-pass (gate -> smem -> up), the shipped
    tile (32x128_w4_s1). Single B smem region reused across passes; only one
    accumulator live at a time (~70 regs).
  - fp8_bs_geglu_silu_fold_apersist_kernel: A-persistent interleaved
    experiment (both gate+up acc in regs, B reloaded per k-iter). Kept as a
    bench-only tile; the two-pass s1 won the e2e sweep.

ncu diagnosis (issue #1 Phase 2) isolated why naive two-pass lost: s2 occupancy
collapse (gate_smem + 2 cp.async stages -> 49.7KB -> 1 CTA/SM, 8.33% occupancy)
+ 2x pipeline drain. s1 (29.7KB, 3 CTA/SM) recovers and wins in the
launch-bound regime. The gate_up GEMM is compute-bound above the S crossover,
so the fused path is shape-gated per-inter (2B S in [96,192], 8B S=128 only);
outside the band the baseline two-launch path runs unchanged (default
byte-identical, env FLASH_RT_SM89_SILU_FOLD_PREFILL=1 opt-in).

Correctness: e2e prefill cosine 0.9992-1.0 vs baseline, argmax preserved
across S (saturating-FP8 real activations). One fewer bf16(acc) rounding than
baseline (documented). Fixed an out_scale write bug (single-thread guard left
rows 1..BM-1 unwritten -> garbage scale, correct fp8).

E2E prefill (4090, 30-iter median, fold on vs off):
  2B S=128: 6.10 -> 5.64 ms  +7.5%
  2B S=192: 6.10 -> 5.54 ms  +9.2%
  8B S=128: 13.97 -> 13.45 ms +3.7%  (stable across 3 runs)
Above the band: no regression (falls back to baseline).

Bench script scripts/test_geglu_silu_fold_correctness.py included.
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