Skip to content

Add SM89 Qwen3-VL FP8 path (8B + 2B) - #111

Closed
heiheiha798 wants to merge 18 commits into
flashrt-project:mainfrom
heiheiha798:feature/qwen3-vl-sm89-fp8-2b
Closed

heiheiha798 wants to merge 18 commits into
flashrt-project:mainfrom
heiheiha798:feature/qwen3-vl-sm89-fp8-2b

Conversation

@heiheiha798

Copy link
Copy Markdown
Contributor

Summary

Brings up Qwen3-VL on Ada RTX 4090 (sm_89) with the official block-scaled
FP8 language weights, for both the 8B and the 2B variants. This is
the SM89 counterpart to the SM120/NVFP4 path (#107/#109), but it intentionally
uses the checkpoint's native FP8 weights instead of NVFP4 (NVFP4 is a
Blackwell-only path). The vision tower, geometry, scatter, DeepStack and
interleaved-MRoPE are reused from the SM120 Qwen3-VL work; this branch adds the
Ada FP8 language stack, a native sm_89 block-128 GEMM, and the config-driven
generalization + offline quantizer that bring up the 2B.

The core lever is a native Ada FP8 e4m3 block-128 scaled GEMM that reads
the FP8 weight directly (no dequant-to-bf16 scratch), cutting per-linear weight
traffic ~5x while keeping the per-token activation scale. This is the fix for
the SM89 prefill bottleneck (weight-dequant memory bandwidth); the CUTLASS Ada
blockwise route was a dead end at these shapes.

What's in it

  • Native sm_89 block-128 FP8 GEMM (fp8_block128_gemm_mma_sm89.cu):
    plain Ada mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 (no
    .kind::f8f6f4, which is sm_120a-only), DeepSeek block-128 scaling folded
    in the mainloop (BLOCK_K pinned to 128). Adapted from the SM120
    fp8_smallM_handtuned cp.async pipeline + m16n8k32 tiling. The dispatcher is
    shape-agnostic (any N%128==0, K%128==0), tuned over the Qwen3-VL linear
    shapes.
  • Text frontend (qwen3_vl_fp8_sm89.py): block-scaled M=1 FP8 GEMV decode
    • native block-128 FP8 GEMM prefill; BF16 attention (FA2), BF16
      residual/norms, per-token/per-128 FP8 activation quant fused into RMSNorm /
      residual-add-RMSNorm / SiLU-mul; CUDA-graph decode (per cache position).
      Now config-driven: instead of a hard 8B dim guard it enforces the kernel
      constraints (head_dim==128, GEMM dims %128, GQA divisibility) and derives all
      scratch shapes from config.json, so the 28-layer/16-head 2B stack runs the
      same kernels with no 8B behavior change.
  • Multimodal wrapper (qwen3_vl_fp8_sm89_multimodal.py): single-image
    prefill as a captured CUDA-graph replay (vision + S>1 FP8 blockscaled
    language + final norm), lm_head eager after replay; multi-image / video use
    the eager prefill. Decode graphs keyed by (cache_pos, rope_pos) so MRoPE
    continuation never reuses a stale rotary position across prompts.
  • 2B offline quantizer (scripts/quantize_qwen3_vl_to_fp8_block128.py):
    the 2B ships BF16 only, so this writes the official FP8 layout (e4m3
    weight + 128x128 weight_scale_inv = amax/448, multiply-to-dequant),
    keeping norms / embed_tokens / the BF16 vision tower unchanged and not
    materializing the tied lm_head.
  • FP8 weight loader (_qwen3_vl_fp8_weights.py): keeps the official
    weight + weight_scale_inv layout, fuses q/k/v and gate/up, optional
    host-side lm_head FP8 quant; now also handles single-file checkpoints
    (no index.json) and tied embeddings (synthesizes lm_head from
    embed_tokens) for the 2B.
  • Attention backend (attn_backend_qwen3.py): takes optional
    num_layers/num_q_heads/num_kv_heads/head_dim (default to 8B 36/32/8/128)
    and an explicit device (was hardcoded 'cuda' / current_device(), wrong
    KV-cache placement under multi-GPU). Additive — the SM120 Qwen3 / Higgs
    callers use the defaults unchanged.
  • Fail-fast & shape guards: capability == (8,9) check, required-symbol
    presence check (rebuild hint), kernel-constraint config check, runtime
    K%128/N%128 guards on the new GEMM + block-128 quant entries, and a
    quantizer guard that the number of quantized linears == num_layers * 7.
  • Docs / scripts / tests: docs/qwen3_vl_fp8_sm89.md (8B) +
    docs/qwen3_vl_fp8_sm89_2b.md (2B), the smoke benchmark
    (scripts/smoke_qwen3_vl_fp8_sm89.py), prefill-GEMM micro-benchmarks, and
    CPU-friendly import/invariant/geometry/quantizer tests.

Additive on the shared-module front: the new GEMM is gated behind
ENABLE_SM89_BLOCK_FP8_GEMM (only compiled for GPU_ARCH=89); the block-128
quant helpers are added to the existing quant TU; the SM120 paths are
untouched.

Performance & correctness (RTX 4090, sm_89)

8B — official Qwen3-VL-8B-Instruct-FP8, workload FlashRT.png + prompt
"Describe this image in one sentence." (6256 vision patches, 1581 language
tokens — same workload as the SM120 report):

S=1581 pixel_shape=(6256, 1536) spans=[(4, 1568)]
prefill_graph  median=206.2 ms  cos_vs_eager=0.998522  top=785  finite=True
graph_decode   (cache_pos=1581) median=10.681 ms  cos_vs_eager=1.000000  (~94 tok/s)
top_eager=2168  top_graph=2168

2B — quantized Qwen3-VL-2B-Instruct-FP8 (FP8 lm_head):

text  S=79  decode 2.653 ms = 377 tok/s  logit_cos=0.999426
mm    FlashRT.png S=1581  prefill_graph 99.7 ms  cos_vs_eager=0.9975  top=32
      graph_decode (cache_pos=1581) 2.966 ms = 337 tok/s  cos_vs_eager=1.000000
      generate -> coherent caption of the logo

The 2B is ~3.8x faster at decode than the 8B on the same card, as expected
from the ~4x smaller language weights. FP8 lm_head is what carries 2B decode
past 350 tok/s (BF16 lm_head: 287 tok/s; same top token at every step). The
same workloads are faster on the SM120/NVFP4 path (Blackwell NVFP4 kernels);
this branch targets the best Ada-compatible dtype path.

Build & usage

cmake -S . -B build -DGPU_ARCH=89 -DFLASHRT_BUILD_QWEN3_VL=ON
cmake --build build -j --target flash_rt_kernels flash_rt_fa2 flash_rt_qwen3_vl_kernels

# 8B
python examples/qwen3_vl_quickstart.py --arch sm89 \
  --checkpoint /path/to/Qwen3-VL-8B-Instruct-FP8 \
  --image FlashRT.png --prompt "Describe this image in one sentence."

# 2B: first quantize BF16 -> FP8, then run with --fp8-lm-head
python scripts/quantize_qwen3_vl_to_fp8_block128.py \
  --src /path/to/Qwen3-VL-2B-Instruct --dst /path/to/Qwen3-VL-2B-Instruct-FP8
python examples/qwen3_vl_quickstart.py --arch sm89 --fp8-lm-head \
  --checkpoint /path/to/Qwen3-VL-2B-Instruct-FP8 --image FlashRT.png \
  --prompt "Describe this image in one sentence."

CPU-friendly tests: pytest tests/test_qwen3_vl_fp8_sm89.py tests/test_qwen3_vl_fp8_sm89_2b.py.
See docs/qwen3_vl_fp8_sm89.md / docs/qwen3_vl_fp8_sm89_2b.md for the full
architecture / dtype map / limits.

Notes (scope)

  • Not an NVFP4 implementation — sm_89 uses official FP8 weights by design.
  • 8B lm_head stays BF16 by default; for 2B, use_fp8_lm_head=True is
    recommended (it carries decode past 350 tok/s and matches the top token).
  • There is no official 2B FP8 release; the 2B FP8 checkpoint is produced
    offline by the repo quantizer.
  • Single-image prefill has a CUDA-graph replay path; multi-image / video use
    the eager path. Decode graphs are captured per cache position.
  • The official FP8 weights are too large for CI, so end-to-end numerical
    validation lives in the local smoke script (numbers above); CI covers
    import / loader-invariant / geometry / quantizer tests.

Supersedes #110 (8B-only); this PR is 8B + 2B.

Make the SM89 code config-driven so the 28-layer/16-head 2B language stack runs
the same kernels as 8B: the 8B dim guard becomes kernel-constraint checks,
_fp8_shapes / qkv scratch derive from config, and the attention backend takes
layer/head counts + an explicit device. The 2B ships BF16 only, so add
scripts/quantize_qwen3_vl_to_fp8_block128.py to write the official FP8 layout
and teach the loader the single-file ckpt + tied lm_head. 8B behavior unchanged.

RTX 4090, 2B FP8 lm_head: text decode 377 tok/s (cos 0.9994), multimodal
S=1581 decode 337 tok/s (cos 1.0). 8B unchanged (prefill_graph 206.5 ms,
decode 10.70 ms, argmax 785/2168).
@heiheiha798
heiheiha798 requested a review from LiangSu8899 as a code owner June 25, 2026 06:19
Copilot AI review requested due to automatic review settings June 25, 2026 06:19

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@heiheiha798

heiheiha798 commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor Author

llama.cpp reference comparison

I also checked this PR against a fresh llama.cpp SM89 CUDA build as a reference point. This is intentionally kept as a PR note rather than repo documentation, because it is a cross-framework sanity check, not a long-term FlashRT benchmark claim.

Important caveat: llama.cpp does not run these HF FP8 safetensors directly. The checkpoints were converted with the current llama.cpp FP8 conversion path:

python convert_hf_to_gguf.py <Qwen3-VL-*-Instruct-FP8> \
  --outtype q8_0 --fp8-as-q8 \
  --outfile <qwen3-vl-*-fp8-as-q8_0.gguf>

So the llama.cpp rows below are GGUF Q8_0 converted from FP8, while FlashRT is running this PR's native official/block-128 FP8 path. This is not a strict native-FP8 apples-to-apples comparison.

Setup summary:

  • GPU: single RTX 4090
  • FlashRT: this PR, native Qwen3-VL SM89 FP8 path
  • llama.cpp: ggml-org/llama.cpp@683b04cc4, CUDA build targeting sm_89
  • Workload: text-only, prefill S=512, decode 128 tokens
  • llama.cpp command shape: llama-bench -p 512 -n 128 -ngl 99 -fa on -r 10 -o json
  • FlashRT decode measurement: 128 increasing-position CUDA graph replays after a 512-token prefill; graph capture excluded
Model Runtime Weight format Prefill 512 Decode 128
Qwen3-VL-2B FlashRT native block-128 FP8 10.964 ms median, 46.7k tok/s 350.422 ms median, 365.3 tok/s
Qwen3-VL-2B llama.cpp GGUF Q8_0 from FP8 16.701 ms warm median, 30.7k tok/s 368.219 ms median, 347.6 tok/s
Qwen3-VL-8B FlashRT native block-128 FP8 41.015 ms median, 12.5k tok/s 1247.299 ms median, 102.6 tok/s
Qwen3-VL-8B llama.cpp GGUF Q8_0 from FP8 43.171 ms warm median, 11.9k tok/s 1352.758 ms median, 94.6 tok/s

Notes:

  • The first llama.cpp prefill sample was a cold outlier, so the table uses warm medians from the JSON samples.
  • The 8B llama.cpp decode result had some rerun variance; it was in roughly the 95-103 tok/s bucket. FlashRT's 8B decode replay was stable around 102.6 tok/s.
  • This is a reference validation only. I would not treat it as a permanent cross-framework benchmark unless model format, sampling loop, cache setup, and warmup methodology are standardized.

@LiangSu8899

Copy link
Copy Markdown
Member

Thank you very much for this reference comparison!! Overall, the results look as expected, especially the decode phase, which is quite close to my previous comparisons with other adaptations.

PS: Based on past comparison experience, these numbers suggest there's still some room for improvement in the prefill phase.(I would say its like ~1.5-2x more faster) If ultra-low latency is a critical requirement, it might be worth exploring further. I'll also run some profiles on my side to see where we can optimize prefill.

@heiheiha798

Copy link
Copy Markdown
Contributor Author

Thanks for pointing this out. The PR is still in progress: I am running another independent agent review on the full diff, and I will also take another look at the prefill path to see what can be optimized further.

Standalone harness to pick the best FA2 forward tile for the Qwen3-VL
vision tower (non-causal full attention over S=6256 patches) without the
~9-minute full FA2 rebuild. Links only the forward template (no split-KV
/ causal) so one head-dim bucket compiles in a few minutes. Documents the
layout-faithfulness caveat: faithful only when real head_dim == bucket
(hd64/2B yes; hd96/8B no -> trust end-to-end for hd96 tile).
Qwen3-VL 2B vision runs non-causal full attention with head_dim=64. PR111
padded it into the hd96 bucket, wasting ~33% of the attention work. Add the
hd64 sm80 forward instantiations (no split-KV: 2B vision never splits, and
split-KV is the expensive ptxas object), a <=64 no-split dispatch bucket,
and a 128x64 sm8x non-causal tile chosen by the standalone vision-attn
micro-bench (128x64=1.185ms < 128x128=1.216 < 128x32=1.241 at S=6256).

End-to-end (RTX 4090, FlashRT.png, nsys): 2B vision attention 43.5->28.6ms
(-34%), 2B total prefill 103.9->89.1ms (-14.3%); cos_vs_eager=1.0, top token
unchanged (32). 8B unchanged (uses hd96, untouched: 208.7->208.6ms). hd96
left at PR111's 128x64 (GPT's 128x32 was a measured regression).
@heiheiha798

Copy link
Copy Markdown
Contributor Author

Prefill optimization (1/2): 2B vision attention head_dim=64 path

Following up on the prefill headroom noted in review. Profiling the official
FlashRT.png workload
(S=1581, 6256 vision patches) with nsys shows the full
prefill is dominated by two costs, not one — and a language-only profile hides
the second:

2B (--fp8-lm-head) 8B
FP8 block-128 GEMM (language) 39.5% 60.0%
Vision-tower attention (FA2) 41.8% 23.6%

The vision tower runs non-causal full attention over all 6256 patches per
block. The 2B vision tower uses head_dim=64, but it was being padded into the
FA2 hd96 bucket, wasting ~33% of the attention work.

This change adds a native FA2 hd64 path:

  • hd64 sm80 forward instantiations (no split-KV — 2B vision never splits, and
    split-KV is the expensive ptxas object).
  • A head_dim<=64 no-split dispatch bucket.
  • A 128x64 sm8x non-causal tile, chosen by a new standalone vision-attention
    micro-bench (benchmarks/sm89_vision_attn): at S=6256, 128x64 = 1.185 ms <
    128x128 = 1.216 < 128x32 = 1.241.

Results (RTX 4090, nsys, FlashRT.png):

before after
2B vision attention 43.5 ms 28.6 ms (-34%)
2B total prefill 103.9 ms 89.1 ms (-14.3%)
8B total prefill 208.7 ms 208.6 ms (unchanged)

8B is intentionally untouched (its vision head_dim=72 already maps to hd96,
which keeps its existing 128x64 tile). Correctness preserved:
cos_vs_eager=1.000000, top token unchanged (32), coherent caption.

GEMM-side prefill optimization will follow as a separate change.

Standalone harness for the SM89 block-128 FP8 prefill GEMM (clean PR111
baseline kernel + a CANDIDATE template for structural experiments, cold-L2
timing, sampled correctness, NCU wrapper).

Baseline NCU on gate (M=1581,N=12288,K=4096): the top bottleneck (~51% est.
speedup) is the row-strided scalar act_scale load (32-byte sector, 4 used
bytes). C1 stages SCALE_KTILE=8 scale columns in smem with a coalesced load,
re-staged per k-tile so the smem footprint is K-independent (~2KB) and
occupancy does not regress on large-K shapes.

Cold-L2: gate -9.7%, down -7.3%, qkv -9.1%. NCU gate: 813->731us, executed
instructions 254M->200M (-21%), occupancy held 33.3%. Correctness unchanged.
Port the validated micro-bench candidate C1 to the production kernel: stage
the per-CTA activation/weight scales in shared memory with a coalesced load
(SCALE_KTILE=8 columns at a time, re-staged per k-tile so the smem footprint
is K-independent ~2KB and occupancy holds). Replaces the row-strided scalar
act_scale loads that were NCU's top global-load bottleneck.

End-to-end (RTX 4090, FlashRT.png, nsys/smoke):
- 8B FP8 GEMM 125.3->114.6ms (-8.5%); 8B total prefill 208.7->197.8ms (-5.2%)
- 2B total prefill 89.1->82.0ms (-8.0%)
- cos_vs_eager=1.0, top token unchanged (8B 785 / 2B 32), decode unchanged.
After C1, NCU's top bottleneck is the scalar 16-bit BF16 epilogue stores (8/32
bytes per sector). The m16n8 layout holds two adjacent output columns per lane
per row, so emit one 32-bit bfloat162 store per row instead of two scalar
stores (tail columns keep scalar). NCU gate: store sector utilization 8->16
bytes, duration 731->696us.

End-to-end (RTX 4090, FlashRT.png, cumulative with C1):
- 8B total prefill 192.96->187.85ms; vs PR111 baseline 204.4ms -> -8.1%
- 2B total prefill 81.97->79.33ms
- cos_vs_eager=1.0, top token unchanged (8B 785 / 2B 32).
Raw-page NCU on C1+C2 shows the LSU pipe is the real top bottleneck (67.7%,
54.7M shared-load instructions = 27% of all insts) - the scalar 32-bit LDS
reads of A/B fragments. C4 ports the sm120 ldmatrix structure: 128B-swizzle
smem (no pad) + ldmatrix.x4.m8n8.b16 reads (sm89 e4m3 MMA, not the sm120a-only
kind::f8f6f4), keeping C1 scale staging + C2 pair-store. Build -DUSE_LDMATRIX.

Cold-L2 vs baseline: gate -15.7%, down -12.2%, qkv -15.7%. NCU gate: LSU
67.7%->29.8%, shared-load instructions 54.7M->5.5M (-10x). Correctness exact.
@heiheiha798

Copy link
Copy Markdown
Contributor Author

Prefill optimization (2/2): FP8 block-128 GEMM access-pattern coalescing

The FP8 block-128 GEMM is the largest single prefill cost (8B 60% / 2B 46% of
GPU kernel time). Using a standalone micro-bench (benchmarks/sm89_fp8_block128_gemm,
cold-L2 timing + sampled correctness + NCU wrapper) I iterated NCU-first: profile
the clean baseline kernel, fix the top-ranked bottleneck, re-profile, repeat.

NCU on the baseline (gate, M=1581,N=12288,K=4096) ranked the bottlenecks as
memory access pattern, not compute or bandwidth (Tensor pipe 35%, DRAM 9%):

C1 — scale-load coalescing (NCU top, ~51% est. speedup). The row-strided
scalar act_scale[row*K128+kb] loads delivered only 4 of 32 bytes per sector.
Stage the scales in shared memory with a coalesced load, SCALE_KTILE=8 columns
at a time so the smem footprint is K-independent (~2 KB) and occupancy holds.
(A first attempt staging the whole [BLOCK_M,K128] slice regressed down +17%
on its 24 KB scale smem — the tiled version is the fix.) NCU: executed
instructions 254M→200M, load sector utilization 4→31.5 of 32 bytes.

C2 — store-pattern coalescing (next NCU top, ~47%). The scalar 16-bit BF16
epilogue stores delivered 8 of 32 bytes per sector. The m16n8 layout holds two
adjacent output columns per lane per row, so emit one 32-bit bfloat162 store
per row. NCU: store sector utilization 8→16 bytes.

Rejected — occupancy tuning. NCU still lists occupancy (124 regs → 4 CTAs/SM).
Forcing 5 CTAs/SM drops to 96 regs but spills and runs +4.8% slower: the kernel
is latency-bound (warp-cycles/inst ~14.7, DRAM ~10%), not occupancy-bound.

Results (RTX 4090, FlashRT.png, nsys, cumulative C1+C2):

before after
8B FP8 GEMM kernel 125.3 ms 108.7 ms (-13.2%)
8B total prefill 204.4 ms 187.9 ms
2B total prefill 89.1 ms 79.3 ms

cos_vs_eager=1.000000, top token unchanged (8B 785 / 2B 32), decode unchanged.

Cumulative with the hd64 vision change, vs the pre-optimization baseline:
2B prefill 103.9 → 79.3 ms (-23.7%), 8B prefill 208.7 → 187.9 ms (-10.0%).

Fold the C4 ldmatrix.x4 + 128B-swizzle kernel into production and extract the
device kernel body into a shared header (fp8_bs_gemm_device.cuh) that both the
production launcher and the micro-bench include. The bench's --mode baseline now
runs the exact production kernel, so it can no longer drift behind it -- the bug
that made the C1-C4 cold-L2 deltas read ~10x larger than their true marginal
value (the old frozen baseline was the pre-C1 kernel, ~19% slower than shipped).

The bench candidate defaults to aliasing production (--mode both -> ~0%, a
built-in honesty check); build --experiment to compile the editable
fp8_bs_gemm_kernel_cand for a structural experiment. profile_ncu.sh builds
--experiment for candidate mode so the two profiles are not identical.

Verified end-to-end (2B multimodal prefill): cos_vs_eager=1.0, top=32,
prefill 79.9 ms (matches prior C4).
The SM120a reference GEMM defaults to a 2-stage (up to 5) cp.async pipeline to
hide load latency. Since the SM89 block-128 kernel is latency-bound, multi-stage
looked like the natural next step, so the bench candidate gains a CAND_STAGES
knob (./build.sh --experiment --stages N) that overrides the production S=1.

Result: STAGES>=2 regresses on SM89 (64x64 gate +12.4%, down +10.1%, qkv +12.0%
at S=2; +60-73% at S=3), all bit-exact. NCU shows why and why it differs from
SM120a: the second smem stage grows dynamic smem 18.5->34.9 KB, dropping the
shared-mem block limit 5->2 and halving occupancy (33.3%->16.7%). Per-warp
latency hiding does improve (Warp-Cycles/Inst 11.74->6.17) but eligible warps
still fall (0.46->0.37) -- losing half the resident CTAs costs more than
double-buffering gains. The kernel is register-limited to 4 CTA/SM at 128 regs
with no smem headroom (4 x 34.9 KB > 100 KB/SM). SM120a affords S>=2 only because
its per-tensor-alpha motus kernel has no block-128 scale staging and thus the
occupancy headroom this kernel lacks. S=1 stays correct for production.
…enue

Add --bm/--bn/--warps candidate tile knobs so multi-stage can be tested at
smaller tiles that hold occupancy at S>=2. Result closes the cp.async pipeline
avenue on SM89 from both sides:
  - 64x64 S=2: occupancy halves (4->2 CTA/SM) -> +12%.
  - 32x64 S=1 already +36% (arithmetic-intensity loss); S=2 over S=1 there is a
    wash (+0.7%); 32x128 S=2 is +23.6%. No tile wins.
The SM120 Qwen3-VL GEMM wins via TMA + warp-specialization (KernelTmaWarp
SpecializedBlockwisePingpongSm120); Ada has no TMA and no warp-specialized
CUTLASS collective (Sm90+/Sm120 only), and CUTLASS's Ada blockwise example is
the same cp.async class already benched slower. A TMA-style win on sm89 needs a
hand-written warp-specialized producer/consumer kernel (deferred). All bit-exact;
candidate still defaults to production (honesty check ~0%).
@heiheiha798

Copy link
Copy Markdown
Contributor Author

Superseded by #116, which reorganizes the SM89 Qwen3-VL FP8 work into clean, scoped commits aligned with the SM120a path. #116 has been merged. Closing this one.

@heiheiha798
heiheiha798 deleted the feature/qwen3-vl-sm89-fp8-2b branch June 28, 2026 12:38
LiangSu8899 added a commit that referenced this pull request Jul 7, 2026
* cleanup(qwen3_vl): add latency stats, pipeline registration, and BF16 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.

* perf(qwen3_vl_sm89): FP8 lm_head default + fix graph replay regression

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.

* perf(qwen3_vl_sm89): fuse gate/up GEMV + remove deepstack clone

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.

* sm89: fuse last-layer residual + final RMSNorm into one kernel

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.

* fix smoke script: match fuse_gate_up/fp8_lm_head defaults to constructor

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.

* prefill cross-layer norm fusion for SM89 FP8

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.

* cache kernel lookups in _MergedKernels __getattr__

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.

* sm89: BF16-input GEMV kernel — skip FP8 quant for O-proj and lm_head

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+).

* sm89: BF16-out norm + bf16in GEMV for qkv and gate_up decode

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%)

* sm89: 256-thread packed BF16x2 norm kernel for decode residual+RMSNorm

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%)

* sm89: widen 8B decode norm to 512 threads for occupancy

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.

* sm89: use 32x64 GEMM tile for small-M prefill to fill the grid

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.

* fix(bench): prefill GEMM cold/warm regime crashed on pybind bindings

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.

* docs(qwen3-vl-sm89): update 8B/2B numbers to current SOTA (iters=30)

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 #111 end-state.

* fixup: drop dev-only -lineinfo + address Copilot review on PR #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.

* Tighten Qwen3-VL SM89 PR surfaces

* Fix Qwen3-VL SM89 lm_head docs

---------

Co-authored-by: LiangSu8899 <[email protected]>
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.

3 participants