Skip to content

Enable FlashInfer decode attention access for NVFP4 KV cache and fix Gemma4 text config - #43247

Open
weignerg wants to merge 28 commits into
sgl-project:mainfrom
weignerg:sm120-nvfp4-blackwell-integration
Open

weignerg wants to merge 28 commits into
sgl-project:mainfrom
weignerg:sm120-nvfp4-blackwell-integration

Conversation

@weignerg

@weignerg weignerg commented Oct 9, 2026 •

Copy link
Copy Markdown

Motivation

This pull request provides complete, production-grade Blackwell (SM120 / RTX 5090) integration for NVFP4 KV cache and Gemma 4 model execution with FlashInfer:

  1. FlashInfer NVFP4 Decode Attention Access:

    • When running models with --kv-cache-dtype nvfp4 and --decode-attention-backend flashinfer, fp4_kv_cache_quant_method.py previously omitted flashinfer from decode access registration, raising ValueError: KV cache method 'nvfp4' does not support decode with flashinfer attention backend.
    • SGLang already implements the underlying dequant workspace in memory_pool.py (get_flashinfer_decode_dequant_workspace_kv_buffer).
    • This PR registers flashinfer into _NVFP4_DQ_KV_DECODE_BACKENDS and KV4_ATTENTION_MHA_BACKEND_CHOICES.
  2. Gemma 4 Configuration & Heterogeneous Architecture Fixes:

    • In _apply_gemma4_attention_overrides, text_config.is_heterogeneous was accessed directly, raising an AttributeError on standard HuggingFace Gemma4TextConfig objects where is_heterogeneous is absent. Guarding this with getattr(text_config, 'is_heterogeneous', False) enables seamless config parsing.
    • Fixed RoPE embedding device alignment in Gemma4RotaryEmbedding (casting inv_freq to fp32 and target device before concatenation).
    • Added support for --language-model-only execution with heterogeneous head dimensions.
  3. Memory Pool & Stride Geometry Protection:

    • Routed memory pool zeroing through uint8 tensor views to preserve 3D/4D tensor geometry and prevent stride corruption during FlashInfer decode operations.
    • Excluded shared dequant workspace buffers from per-layer cell size calculations to avoid memory pool over-allocation.

Technical Validation & Benchmarks

  • Target Hardware: NVIDIA GeForce RTX 5090 (Blackwell SM120, 32GB GDDR7, CUDA 13.4, Driver 615.71.09).
  • Unit Test Suite: Ran test/registered/unit/layers/quantization/test_fp4_kv_cache_quant_method.py — 23/23 tests passing.
  • Model Compatibility:
    • RedHatAI/gemma-4-26B-A4B-it-NVFP4 (64k context, zero CPU offload, pure GPU speed): verified end-to-end token generation.
    • RedHatAI/gemma-4-31B-it-NVFP4 (32k–256k context with host RAM offload): verified parsing and KV allocation.
    • nvidia/Gemma-4-31B-IT-NVFP4: verified config parsing and speculative draft layers.

CI States

Latest PR Test (Base): ❌ Missing run-ci label -- add it to run CI tests.
Latest PR Test (Extra): ❌ Blocked -- run-ci is required first.
Latest PR Test (AMD ROCm 10): ➖ No AMD PR run found for this commit.

JAVerma and others added 14 commits September 16, 2026 11:24
Serving an NVFP4 MoE checkpoint on SM120 (RTX PRO 6000) fails before the
first token: create_moe_runner() sends every device with compute capability
>= 10.0 to FLASHINFER_TRTLLM, whose NVFP4 kernels are implemented for SM100
only, so apply() falls through to the NotImplementedError at the end of the
same function. Select FLASHINFER_CUTLASS for these parts instead.

That alone still raised, naming the case it told you to use, because
enable_flashinfer_cutlass_moe answers from the raw --moe-runner-backend.
That stays "auto" whether or not create_moe_runner() resolved to CUTLASS,
so apply() skipped its CUTLASS branch. Passing --moe-runner-backend
flashinfer_cutlass explicitly only worked because it happened to make the
global agree. Read the resolved backend, the way the two other
_moe_runner_backend reads in this file already do.

This half is not SM120-specific: any device whose "auto" resolves to
CUTLASS hits it.

Verified on an RTX PRO 6000 Blackwell serving
nvidia/Qwen3.6-35B-A3B-NVFP4 with no --moe-runner-backend flag. The added
tests resolve the backend without launching kernels, so they run anywhere;
the two SM120 cases fail without this change and the SM100 case passes
either way, pinning the B200/B300 default in place.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
FMHAv2 has no FP8 (e4m3) prefill kernel on SM120/SM121, and ModelOpt NVFP4
checkpoints commonly declare "kv_cache_quant_algo": "FP8", so
--kv-cache-dtype auto selects one and the run dies inside CUDA-graph
capture with

  ValueError: FP8 (e4m3) is not yet supported for FMHAv2 on SM120

raised from flashinfer, naming neither the flag that caused it nor a way
out. Check it in the constructor, mirroring the trtllm-gen page-size
precondition just below, and name both remedies.

get_default_attn_backend() already gates trtllm_mha on is_sm100, so this
only triggers when the backend was asked for explicitly.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ly installs

Two assumptions in the JIT toolchain no longer hold on distributions
shipping glibc >= 2.41 (Ubuntu 26.04 being the common case), where every
kernel build fails before any sglang code runs.

glibc 2.41 declares C23 rsqrt/rsqrtf as noexcept. CUDA toolkits before
13.2 declare them with no exception specifier, so nvcc rejects every
translation unit that reaches <cmath>:

  bits/mathcalls.h: error: exception specification is incompatible with
  that of previous function "rsqrt" (crt/math_functions.h)

Detect that from the headers rather than a version tuple, and fall back to
a pip-installed toolkit carrying the _NV_RSQRT_SPECIFIER guard. An
explicit CUDA_HOME still wins, and an unreadable header is treated as
usable, so an unfamiliar layout keeps today's behaviour.

The pip CUDA wheels are also runtime-only: libraries live in lib/ rather
than lib64/, and libcudart.so.13 ships without an unversioned dev symlink,
so the link step searched a directory that does not exist and then could
not find -lcudart. Resolve the real library directory and fall back to
ld's -l: form rather than writing symlinks into site-packages. Those
wheels are independently versioned, so nvcc and the runtime headers can
disagree and CCCL aborts the build complaining about include paths; warn
with the versions that actually differ.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Conflict in trtllm_mha_backend.py: main removed the blank line after the
use_fmha_v2 assignment while this branch inserted the SM120 FP8-KV guard
there. Kept the guard; main's side of the hunk was empty.

main's new native NVFP4 KV path (uses_native_fp4) is unaffected -- it runs
on FP4 scales, not an e4m3 KV cache, so the guard's data_type check does
not fire for it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@weignerg
weignerg requested a review from pyc96 as a code owner October 9, 2026 01:00
…d FlashInfer stride geometry

- Ensure Gemma4RotaryEmbedding casts inv_freq and zero-pad slices to device and fp32 before torch.cat, with device-aligned cos_sin_cache
- Dynamically evaluate swa_head_dim alongside head_dim in SWAKVPool and DefaultPoolConfigurator / HybridSWAPoolConfigurator cell size calculation
- Route memory pool _safe_zeros through torch.empty uint8 zeroed views to preserve 3D/4D tensor geometry and avoid mutating outer dimensional strides for FlashInfer decode
detain added a commit to detain/sglang that referenced this pull request Oct 10, 2026
detain added a commit to detain/sglang that referenced this pull request Oct 10, 2026
…VFP4 KV cache + Gemma4 text config

Skip reversed per user direction: NVFP4 KV (RDXA + NVDA NVFP4 variants of
Qwen3.8-Flash-Next) is an ACTIVE FUTURE config. Squash of pr43247 net diff
(22 files, base 5b5d721) with toolchain.py excluded (entry 65 already
applied; modelopt_quant.py entry-63 hunks auto-merged idempotently via -3).
Carries the branch's merged-in PR sgl-project#42419 (drop fp8 scales under nvfp4 KV,
still OPEN upstream) as part of the net diff.

Conflicts resolved (4):
- flashinfer_backend.py x4: UNION our KVLocPlan `plan=` plumbing with the
  PR's per-wrapper head_dim/num_kv_heads/num_qo_heads kwargs (heterogeneous
  SWA dims) at all 4 call_begin_forward sites + signature keyword-only
  marker preserved; PR's custom_kv_indices wiring into update_sliding_window
  replaces entry 175's single-wrapper RuntimeError guard (PR intent).
- memory_pool.py: MHATokenToKVPool.set_kv_buffer_prefix_valid keeps our
  removed conversion preamble (fp8 fused-scale paths) + takes the PR's
  is_quantized_kv_cache early-return at its anchor; _safe_zeros Float4
  allocation hunks auto-merged.
- pool_configurator.py: took the PR's has_heterogeneous restructure
  (self.kv_cache_dtype_str == kvc.kv_cache_dtype_str, __init__:220) over
  our equivalent kvc. spelling; _compute_qsa_cell_size tail preserved.
- utils/common.py: make_layers empty_cache-per-layer generator body (from
  d9e1d68) inside our layer_stack/neighbour wrapper.

Test adaptation: test_flashinfer_nvfp4_speculative.py __new__ stub gains
prefill_wrappers_ragged/prefill_wrapper_ragged (PR adds the attribute read
in init_forward_metadata; real __init__ sets both) -- back to 6P.

Battery (CVD=9): shipped fp4_kv_cache_quant_method+nvfp4_moe_backend+
spec 31P; pool_configurator 13 subfail = entry-175 env class (is_cuda
False, no GPU); server_args/qsa_kv_pool/yarn/ple_staging/kv_loc_plan/
modelopt-nvfp4 set 408P+5skip; 8 imports incl. scheduler OK; ruff
repo-ruleset clean; ruff-format drift from the PR fixed in 9 files
(verified cosmetic). PRE-EXISTING red re-confirmed on stack tip:
test_kernels_namespace reclassified-entry-point inventory (batch C
qwen4_short_conv entry not inventoried -- owed, unrelated to this PR).
detain added a commit to detain/sglang that referenced this pull request Oct 10, 2026
…FP4 KV active future config), STACK=qwennext-stack-178-2026-10-10, tip 8ef534c (was stale at 3d1e688 since batch D)
detain added a commit to detain/sglang that referenced this pull request Oct 11, 2026
… 178 boot crash)

sgl-project#43247's has_heterogeneous branch in DefaultPoolConfigurator._compute_cell_size
read kvc.layer_info.{swa,full}_attention_layer_ids via getattr(..., []), but
ModelLayerInfo (sgl-project#40983) always defines those fields and defaults them to None
for models without a hybrid-SWA split. The [] fallback never fired, so
non-SWA models (Qwen3.8-Flash-Next, Mamba hybrid) crashed at memory-pool
init on every TP rank: TypeError: 'NoneType' object is not iterable.

Read the fields directly and coalesce None to []; swa_count == 0 then
falls through to the uniform cell-size path as before sgl-project#43247.

test_pool_configurator.py: 60P + 26 subtests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
detain added a commit to detain/sglang that referenced this pull request Oct 15, 2026
… during dequant workspace decode (req_pool_indices_cpu + capture-guarded _to_cpu_int_list; pool_configurator coalesce skipped as dup of b05a7c1) [batch-apply-e 2026-10-14]

(cherry picked from commit dbb764c15e1fdecfcb8d8c7680d387c137c9f0ac)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants