Repository navigation
SM89 Qwen3-VL FP8 decode-path optimization (8B + 2B) - #139
LiangSu8899 merged 17 commits into
Conversation
… tests Complete the Qwen3-VL close-out cleanup: - Add get_latency_stats() to Qwen3TorchFrontendRtx (text LLM) and Qwen3VlTorchFrontendRtx (multimodal), with wall-clock timing in the VL generate() path. - Register qwen3_vl in _PIPELINE_MAP for SM120 and SM89 discoverability, matching the nexn2/cosmos3_video pattern. - Update qwen3_vl_rtx.py docstring to reflect the registration. - Expand test_qwen3_vl_rtx_bf16.py from 2 to 10 tests covering kernel-list validation, fail-fast on missing symbols, weight-loader exports, and constructor signature. - Update flash_rt/models/__init__.py docstring to list all current model directories.
Two decode optimizations for Qwen3-VL SM89 FP8 frontends: 1. Default use_fp8_lm_head=True: the lm_head GEMV reads 0.62GB FP8 weights instead of 1.24GB BF16, saving ~0.63ms per decode step (6.2% speedup, 10.19ms → 9.56ms at pos=63). Output quality is identical (same argmax token, cosine_sim≈1.0). 2. Remove decode graph cache clear from set_prompt(): the decode graphs are keyed by (cache_pos, rope_pos) and operate on pre-allocated KV cache buffers, so they remain valid across prompt changes. This fixes a 17x regression (178ms → 10.8ms/step) when replaying decode graphs after re-prompting with the same geometry. Also adds profiling scripts for A/B benchmarking and prefill breakdown.
Enable fuse_gate_up=True by default: merges gate and up projections into a single GEMV call, saving one kernel launch per layer. Reduces decode latency by ~0.05ms on 2B (1.8%) and ~0.05ms on 8B (0.5%). Also replace the redundant h.clone() + torch.add in the deepstack decode path with a single in-place h.add_(): the output buffer alternates between _layer_out_a/b so no aliasing hazard exists.
Port the residual_add_rms_norm fusion from SM120 to the SM89 FP8 text frontend. For both decode and prefill, the last transformer layer now fuses its residual-add with the final RMSNorm into a single kernel call (residual_add_rms_norm), eliminating the standalone torch.add, rms_norm, and copy_ that followed the loop. Also replace _import_fvk() with self._fvk in both _layer_forward and _layer_forward_prefill_fp8_blockscaled to avoid constructing a new _MergedKernels wrapper on every layer call.
The constructor defaults for fuse_gate_up and use_fp8_lm_head were changed to True, but the smoke script still used store_true (default False), silently disabling these optimizations unless the flags were passed explicitly. Switch to BooleanOptionalAction so the script defaults match and users can opt out with --no-fuse-gate-up or --no-fp8-lm-head.
Port the decode cross-layer norm fusion pattern to prefill: fuse each layer's residual-add epilogue with the next layer's input RMSNorm+FP8 quantization into a single residual_add_rms_norm_to_fp8_block128_bf16 kernel, eliminating ~32 standalone rms_norm_to_fp8 launches per forward pass. Deepstack layers correctly invalidate the prequant cache.
Add dict-based caching to avoid repeated hasattr+getattr on the underlying C extension modules during eager (non-graph) execution. Eliminates ~360 redundant module lookups per decode step and ~360 per prefill layer pass.
Add gemv_fp8_block128_m1_bf16in_{w8,w16} kernel that takes BF16
activations directly against FP8 weights with block-128 scale,
eliminating the standalone per-token FP8 quantization kernel before
O-proj and lm_head in decode.
8B decode: 9.510 → 9.473ms, 2B decode: 2.640 → 2.622ms.
Also improves numerical accuracy (cosine similarity 0.9995+).
Add rms_norm_bf16_out and residual_add_rms_norm_bf16_out kernels that skip the FP8 quantization pass, emitting BF16 activations. Route qkv and gate_up GEMV through the bf16in path (BF16 act x FP8 weight + block-128 scale), eliminating 56 per-step FP8 quant phases. Down-proj stays FP8 (silu_mul_to_fp8 unchanged — its output has wide dynamic range and the FP8 down-proj GEMV is already at roofline). Verified clean-GPU (idle cuda:0), 30-iter median: 2B decode: 2.622 → 2.552 ms (-5.3%) 8B decode: 9.473 → 9.213 ms (-2.7%) Cosine similarity maintained (0.9996+, slight improvement from BF16 activations). 39 tests pass. Cumulative since branch start: 2B: ~3.00 → 2.552 ms (~15%) 8B: ~10.75 → 9.213 ms (~14%)
ncu on residual_add_rms_norm_bf16_out_kernel (M=1, K=2048) showed: - 1 block x 128 threads, only 1/128 SMs used, 8% occupancy - 82% L1TEX scoreboard stall (per-element scalar reload in pass 2) - Duration 6.9us, Memory Throughput 0.4%, Compute 0.04% Rewrite to 256 threads + BF16x2 packed loads (matching the fvk2 residual_add_rms_norm_kernel shape), keeping the separate residual_out buffer (unlike fvk2 which is in-place). Adds block_reduce_sum_256. In-graph 28-chain bench (cold L2): hidden=2048: 3.95 -> 2.67 us/call (-1.28us, -32%) hidden=4096: 6.11 -> 3.91 us/call (-2.20us, -36%) ncu: Duration 6.9 -> 4.3us, L1/TEX throughput 9% -> 16%. End-to-end decode (30-iter median, idle card): 2B: 2.552 -> 2.427 ms (-4.9%) 8B: 9.213 -> 8.867 ms (-3.8%) Cosine 0.9994+, 39 tests pass. Also: add -lineinfo to flash_rt_qwen3_vl_kernels build for ncu source mapping. Cumulative since branch start: 2B: ~3.00 -> 2.427 ms (~19%) 8B: ~10.75 -> 8.867 ms (~18%)
ncu on residual_add_rms_norm_bf16_out_kernel at 8B (K=4096) showed a single-block M=1 grid using only 8 warps = 17% occupancy, Duration 6.56us, 74% L1TEX stall, Est. Speedup 83.73% (occupancy-limited). Templatize rms_norm_bf16_out_kernel and residual_add_rms_norm_bf16_out_kernel on kThreads: K>=4096 uses 512 threads (16 warps = 33% occupancy), K<4096 keeps 256. Adds block_reduce_sum_512 (16-warp reduce). rms_norm_bf16_out switches its scalar sync loop to BF16x2 packed loads, matching the residual variant. Verified (empty card): - ncu: 8B norm Duration 6.56->4.22us (-36%), occupancy 16.3%->27.4%, L1/TEX 9.6%->16.9%. - End-to-end 30-iter median: 8B 8.873->8.72ms (-1.7%); 2B path unchanged within noise. - Cosine: 8B 0.999396, 2B 0.999504, both matching baseline, no regression. - Tests: test_qwen3_vl_fp8_sm89_2b / _sm89 8 passed; rtx_bf16/smoke/ graph_cache 31 passed + 1 skipped.
For small-M prefill (M<256), the qkv/o/down linears (N<8192) under-fill
the grid with the 64x64/s1 tile (8B qkv M=128: 64x64_s1 = 192 blocks =
1.5/SM; 2B qkv = 128 blocks = 1/SM), so achieved occupancy is grid-limited
well below the theoretical cap. A 32x64 tile doubles grid_m (8B qkv ->
384 blocks = 3/SM; 2B qkv -> 256 = 2/SM) and nets a win despite the lower
per-block warp cap. gate_up (N>=8192) keeps the original s1 tile
(8B 128x128_w8_s1, 2B 64x64_s1), which is best at every M.
Verified (empty card):
- ncu (application replay, cold): 8B qkv M=128 32x64 51.6us vs 64x64_s1
61.9us (-17%).
- graph-captured e2e (launch noise removed, std<4%):
2B S=128: 4.676 -> 4.043ms (-13.5%)
2B S=192: 5.506 -> 5.203ms (-5.5%)
8B S=128: 15.852 -> 13.942ms (-12.0%)
8B S=192: 19.657 -> 19.264ms (-2.0%)
The gain shrinks as M approaches the 256 crossover (M>=256 keeps
64x64/s1, no new branch).
- nograph e2e (production, t-test): 2B S=128 -4.6% (t-stat 3.95, p<0.05,
significant).
- Correctness: 2B/8B S=128/S=512 cos+top all == baseline, decode flat,
no regression.
- Tests: test_qwen3_vl_fp8_sm89_2b/_sm89/rtx_bf16/smoke/graph_cache
39 passed.
Also:
- csrc/qwen3_vl_bindings.cpp: add bench-only tile-variant bindings for the
micro-bench sweep.
- scripts/bench_prefill_gemm.py: trusted prefill GEMM bench (warm/layer/cold
L2 regimes, peak=165 TFLOPS dense FP8 not 330 sparse), fixes 8B
gate_up/down shapes.
bench() used fn.__code__.co_argcount to decide whether to pass a stream, but the pybind11 bench bindings (bench_fp8_block128_gemm_bs_sm89_*) are builtins with no __code__ attribute, so the cold/warm regime raised AttributeError 'builtin_function_or_method' object has no attribute '__code__' and crashed the whole regime. The layer regime does not call bench() and was unaffected. All bench GEMM bindings share the fixed signature (A,B,D,M,N,K,asc,wsc,stream=0); the cold/warm callers already place the stream as the 9th positional arg inside the args tuple, so fn(*args) is enough — drop the __code__ branch and the duplicated stream-passing hazard.
Empty-card RTX 4090 cuda:1, iters=30 median, scripts/smoke_qwen3_vl_fp8_sm89.py: 8B multimodal (FlashRT.png, S=1581): prefill_graph 206.214 -> 193.183 ms (-6.3%) graph_decode 10.681 -> 9.284 ms (-13.1%) language_only 120.634 -> 106.863 ms (-11.4%) vision_only 88.990 -> 82.009 ms (-7.8%) 8B text (S=79): graph_decode 9.213 -> 8.715 ms (-5.4%) 2B text (S=79): graph_decode 2.653 -> 2.361 ms (377 -> 423 tok/s) 2B multimodal: prefill_graph 99.743 -> 81.129 ms (-18.6%) graph_decode 2.966 -> 2.669 ms (-10.0%) vision_only 69.670 -> 53.682 ms (-23%) language_only 29.827 -> 26.402 ms (-11.4%) The decode gain comes from the decode-path work on this branch (BF16-input GEMV skipping the FP8 activation quant, BF16-output RMSNorm, 8B norm widened to 512 threads, gate/up GEMV fusion, last-layer residual+RMSNorm fusion). The large-M prefill GEMM (M=1581) is L2-bandwidth-bound (~84% L2 / 42% compute / 33% occupancy) and was not further optimized on this branch; it is essentially flat vs the flashrt-project#111 end-state.
…-project#139 - CMakeLists.txt: remove `-lineinfo` from flash_rt_qwen3_vl_kernels — it was a dev-only ncu-source-mapping flag, not a repo convention (no other CUDA target uses it). Keep the build consistent with the rest of the kernel modules. - scripts/bench_prefill_gemm.py / bench_gemv_sm89.py: import the kernel extensions as submodules of `flash_rt` (`from flash_rt import flash_rt_qwen3_vl_kernels`), matching the CMake output location and the frontend/smoke import style. Drop the `REPO/flash_rt` sys.path insertion that only worked for top-level imports. - scripts/profile_qwen3_vl_fp8_sm89.py: `--use-graph` was a no-op (store_true with default=True); keep only `--no-graph` (default True), so the CLI has no dead option. Rebuilt flash_rt_qwen3_vl_kernels clean (sm_89). Tests: 39 passed, 1 skipped. bench_prefill_gemm.py and bench_gemv_sm89.py run end-to-end on the canonical imports.
There was a problem hiding this comment.
Pull request overview
Optimizes the SM89 (RTX 4090) Qwen3-VL FP8 implementation with a decode-dominated focus, reducing per-step overhead (activation quant, extra launches, host dispatch) and improving CUDA Graph replay behavior. Also adds micro-bench/profiling harnesses and refreshes the SM89 FP8 performance docs.
Changes:
- Decode-path optimizations: BF16-input GEMV for selected linears, BF16-output RMSNorm variants, multiple fusions (gate/up, last-layer residual+final norm), and kernel-symbol lookup caching.
- Prefill-path improvements: small-M GEMM tile selection and cross-layer norm/quant fusion to reduce standalone norm/quant launches.
- Tooling/docs updates: new benchmark/profiling scripts, CI-friendly BF16 frontend tests, and updated SM89 FP8 docs/numbers.
Reviewed changes
Copilot reviewed 23 out of 23 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_qwen3_vl_rtx_bf16.py | Expands CI-friendly BF16 frontend coverage (kernel wiring/completeness + API signature invariants). |
| scripts/smoke_qwen3_vl_fp8_sm89.py | Switches key perf toggles to boolean optional flags with defaults aligned to the new fast path. |
| scripts/profile_qwen3_vl_fp8_sm89.py | New nsys/ncu profiling harness with NVTX ranges for prefill vs decode. |
| scripts/profile_prefill_breakdown.py | New NVTX-separated vision vs LLM prefill timing harness for nsys analysis. |
| scripts/bench_prefill_gemm.py | New micro-benchmark to compare prefill GEMM tile variants across L2 regimes. |
| scripts/bench_graph_replay.py | New script to validate decode graph replay stability across re-prompts. |
| scripts/bench_gemv_sm89.py | New GEMV micro-bench across representative (N,K) decode shapes. |
| scripts/bench_fp8_lmhead.py | New A/B benchmark harness for BF16 vs FP8 lm_head in decode. |
| flash_rt/models/init.py | Updates package docstring to reflect current model-family directories. |
| flash_rt/hardware/init.py | Registers Qwen3-VL pipelines for RTX SM120 and SM89 for discoverability. |
| flash_rt/frontends/torch/qwen3_vl_rtx.py | Adds latency recording/stats utility to the SM120 Qwen3-VL frontend. |
| flash_rt/frontends/torch/qwen3_vl_fp8_sm89.py | Core SM89 FP8 frontend changes: bf16in GEMV path, bf16-out norms, fusions, cross-layer prefill fusion, kernel lookup caching. |
| flash_rt/frontends/torch/qwen3_vl_fp8_sm89_multimodal.py | Graph-cache behavior change: preserve decode graphs across set_prompt() calls. |
| flash_rt/frontends/torch/qwen3_rtx.py | Adds latency stats helper (consistent API for recorded latencies). |
| docs/qwen3_vl_fp8_sm89.md | Updates 8B SM89 FP8 performance numbers and deltas vs prior baselines. |
| docs/qwen3_vl_fp8_sm89_2b.md | Updates 2B SM89 FP8 performance numbers and deltas vs prior baselines. |
| csrc/qwen3_vl_bindings.cpp | Exposes new BF16-output norm bindings, BF16-input GEMV bindings, and bench-only GEMM tile entry points. |
| csrc/quantize/fp8_per_token_block_quant.cuh | Declares BF16-output RMSNorm / residual-add+RMSNorm APIs for decode. |
| csrc/quantize/fp8_per_token_block_quant.cu | Implements BF16-output norm kernels (256/512-thread variants) and supporting reductions. |
| csrc/gemm/fp8_gemv_m1_sm89.cuh | Declares BF16-input GEMV variants (no activation scale). |
| csrc/gemm/fp8_gemv_m1_sm89.cu | Implements BF16-input GEMV kernels (shared-memory BF16 activation). |
| csrc/gemm/fp8_block128_gemm_mma_sm89.cu | Adds small-M (M<256) tile selection for improved short-prefill occupancy. |
| CMakeLists.txt | Adds -lineinfo to the Qwen3-VL kernels target for profiler source mapping. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| p.add_argument("--model", choices=["2B", "8B", "both"], default="both") | ||
| args = p.parse_args() | ||
| torch.cuda.set_device(torch.device(args.device)) | ||
| import flash_rt_qwen3_vl_kernels as fvk |
There was a problem hiding this comment.
Fixed in 5d858dd: import via from flash_rt import flash_rt_qwen3_vl_kernels (matches the CMake output location and the frontend/smoke import style); dropped the REPO/flash_rt sys.path insertion that only worked for top-level imports.
| sys.path.insert(0, str(REPO_ROOT / "flash_rt")) | ||
| try: | ||
| import flash_rt_qwen3_vl_kernels as fvk | ||
| except ImportError: | ||
| import flash_rt_kernels as fvk |
There was a problem hiding this comment.
Fixed in 5d858dd: both branches now use from flash_rt import ... (qwen3_vl first, generic flash_rt_kernels fallback); removed the REPO_ROOT/flash_rt sys.path insertion.
| p.add_argument("--use-graph", action="store_true", default=True) | ||
| p.add_argument("--no-graph", dest="use_graph", action="store_false") |
There was a problem hiding this comment.
Fixed in 5d858dd: removed the no-op --use-graph (store_true with default=True); kept only --no-graph (default True) with an explicit help string, so the CLI has no dead option.
|
Pushed 5d858dd to address the Copilot review and a dev-only build flag:
Rebuilt flash_rt_qwen3_vl_kernels clean (sm_89). Tests: 39 passed, 1 skipped. Both bench scripts run end-to-end on the canonical imports. Also re-scoped the PR description to decode-only (prefill GEMM was not touched this round). |
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]>
Summary
SM89 (RTX 4090) Qwen3-VL FP8 decode-path optimization on top of the
merged SM89 FP8 path (#116). This round is decode-only; the prefill
GEMM was not touched (see Notes). All numbers below are CUDA Graph
replay, 30-iter median, empty single card, vs the #116 / #111 end-state.
Both
Qwen3-VL-8B-Instruct-FP8andQwen3-VL-2B-Instruct-FP8areimproved; no kernel-constraint or dtype-map change. Cosine vs the eager
BF16 reference is
1.000000on every captured graph; 39 tests pass(
test_qwen3_vl_fp8_sm89*/rtx_bf16/ smoke / graph_cache, 1 skipped).Performance (RTX 4090, sm_89, graph replay, iters=30 median)
Decode (
graph_decode):What changed
Decode path:
bf16inGEMV (BF16 act × FP8 weight, block-128 scale) reads the BF16 residual
state directly, skipping the per-step FP8 activation quant for these
linears. Down-proj stays FP8 (silu output dynamic range; already at
roofline). No cosine regression; marginally better numerics.
BF16 directly, removing a cast.
single-block grid; widening the block from 256→512 doubles active warps
on that one SM (17%→33% occupancy). 2B (K=2048) stays 256. BF16x2 packed
loads. ncu: 8B norm 6.56→4.22 µs (-36%).
already interleaved), removing a launch and a residual clone.
lm_headdefault (8B) — reads FP8 weights instead of BF16,~0.63 ms/step; same argmax, cosine ≈1.0. Opt out with
--no-fp8-lm-head._MergedKernels.__getattr__to cut hostdispatch overhead (~360 lookups/decode step).
set_prompt()— theyare keyed by
(cache_pos, rope_pos)on pre-allocated KV buffers and stayvalid across re-prompts (fixed a 17× replay regression).
Build / tooling:
scripts/bench_prefill_gemm.py: trusted prefill GEMM micro-bench(warm / layer / cold L2 regimes, peak=165 TFLOPS dense FP8). Two fixes
folded in: cold/warm crashed on pybind builtins (no
__code__), and therepo path uses
__file__(no hardcoded path).bench_gemv_sm89.py,bench_fp8_lmhead.py,bench_graph_replay.py,profile_prefill_breakdown.py,profile_qwen3_vl_fp8_sm89.py.Docs:
docs/qwen3_vl_fp8_sm89.md+docs/qwen3_vl_fp8_sm89_2b.mdupdated to the current SOTA numbers with the vs-#116/#111 comparison.
Build
cmake -S . -B build -DGPU_ARCH=89 -DFLASHRT_BUILD_QWEN3_VL=ON cmake --build build --target flash_rt_kernels flash_rt_fa2 flash_rt_qwen3_vl_kernels -jVerification
prefill_graph,graph_decode), 30-itermedian — not wall-clock
quickstartnumbers.1.000000on all captured graphs (prefill + decode,8B + 2B, text + multimodal).
8B mm graph_decode 9.283 ms, 2B mm graph_decode 2.668 ms — all within
noise of the docs numbers.
Notes (scope)
FlashRT.pngsingle-image workload, M=1581)is L2-bandwidth-bound (~84% L2 / 42% compute / 33% occupancy) and was
not further optimized on this branch; it is essentially flat vs Add SM89 Qwen3-VL FP8 path (8B + 2B) #111.
consumers, 2-stage named-barrier pipeline) was implemented and benched
but regressed ~84%: sm89 has no TMA, so each extra pipeline stage
costs a full smem buffer, doubling smem and halving occupancy (20.5%).
Reverted, not on this branch.
is latency/occupancy-bound, not roofline-bound, and persistent grid-stride
loops don't fix occupancy or sync — judged unlikely to help.
lm_headstays BF16 by default on the public path; FP8lm_headis anexplicit performance mode (validated against the BF16 head per-call).
scripts/*qwen3_vl_fp8_sm89*are local validation/ profiling, not CI.