Skip to content

fix: FA4 paged-KV zero-size page-table registers on SM90 - #35757

Merged
BBuf merged 3 commits into
sgl-project:mainfrom
razorback16:fix/fa4-paged-kv-page-entry-ceil-div
Oct 14, 2026
Merged

BBuf merged 3 commits into
sgl-project:mainfrom
razorback16:fix/fa4-paged-kv-page-entry-ceil-div

Conversation

@razorback16

@razorback16 razorback16 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Serving Qwen/Qwen3.8-27B-FP8 with --attention-backend fa4 on a GH200 (Hopper, SM90) crashes in the scheduler during startup warmup, before the server ever accepts a request:

Generate warm up request for compiling DeepGEMM...
[2026-08-20 14:09:01] Scheduler hit an exception: Traceback (most recent call last):
  File "sglang/srt/managers/scheduler.py", line 5174, in run_scheduler_process
    scheduler.run_event_loop()
  [...]
  File "sglang/srt/models/qwen3_5.py", line 1212, in self_attention
    attn_output = self.attn(q, k, v, forward_batch)
  File "sglang/srt/layers/attention/hybrid_linear_attn_backend.py", line 1134, in forward_extend
    return self.full_attn_backend.forward_extend(
  File "sglang/srt/layers/attention/flashattention_backend.py", line 1496, in forward_extend
    result = flash_attn_with_kvcache(
  File "sglang/kernels/ops/attention/flash_attention_v4.py", line 276, in flash_attn_with_kvcache
    result = flash_attn_varlen_func(
  File "sglang/kernels/ops/attention/flash_attn/cute/interface.py", line 1628, in _flash_attn_fwd
    _flash_attn_fwd.compile_cache[compile_key] = cute.compile(
  [... CUTLASS DSL trace-building frames elided ...]
  File "sglang/kernels/ops/attention/flash_attn/cute/flash_fwd_sm90.py", line 806, in then_block_9
    self.load(
  File "sglang/kernels/ops/attention/flash_attn/cute/flash_fwd_sm90.py", line 983, in while_after_block_2
    paged_kv_manager = PagedKVManager.create(
  File "sglang/kernels/ops/attention/flash_attn/cute/paged_kv.py", line 119, in create
    tPrPage = cute.make_rmem_tensor((page_entry_per_thread,), Int32)
  [...]
  File "nvidia_cutlass_dsl/dsl_packages/cutlass/cute/core.py", line 339, in _check_shape
    raise ValueError(
        f"Expected size in shape to be strictly positive, but got {shape}"
    )
ValueError: Expected size in shape to be strictly positive, but got 0

Environment: GH200 480GB (SM90), CUDA 13.2, nvidia-cutlass-dsl 4.6.2, sglang built from source at eac91ac36 (line numbers above are from that commit). Reproduced with:

python -m sglang.launch_server --model-path Qwen/Qwen3.8-27B-FP8 \
  --attention-backend fa4 --kv-cache-dtype auto \
  --speculative-algorithm DFLASH \
  --speculative-draft-model-path z-lab/Qwen3.8-27B-DFlash2 \
  --speculative-num-draft-tokens 8

Root cause

PagedKVManager.create() sizes its per-thread page-table registers with a floor division:

page_entry_per_thread = n_block_size // num_threads   # num_threads = 128

When tile_n < 128 this evaluates to 0, and cute.make_rmem_tensor((0,), Int32) fails the shape check above.

Qwen3.8-27B's full-attention layers have head_dim=256, and _tile_size_fwd_sm90() returns tile_n = 80 for that head dim (64 with a sliding window). sglang's default page_size=1 never equals tile_n, so the non-TMA cp.async path — the one that stages the page table in registers — is always the one selected. So every paged-KV FA4 run on SM90 at head_dim=256 hits this; head_dim=192 is affected too (tile_n 112 / 96).

This is the same assertion seen in #32118 (merged) and #31903, but those addressed the SM100 diff-headdim split-KV case by not shrinking tile_n to 64 in interface.py; the division itself was left as-is. That doesn't cover SM90, where tile_n = 80 is not a conditional shrink but the tile the heuristic picks unconditionally — there is no configuration that steers around it.

Upstream FA4 (Dao-AILab/flash-attention, flash_attn/cute/paged_kv.py) already uses ceiling division here, with a comment about counting the final partially populated wave of rows. sglang's vendored copy diverged.

Modifications

One line in python/sglang/kernels/ops/attention/flash_attn/cute/paged_kv.py: use cute.ceil_div instead of floor division.

Why ceil is the right size rather than merely non-zero: load_KV() indexes tPrXPtr[m // gmem_threads_per_row] for m in range(n_block_size * gmem_threads_per_row / num_threads), so the largest index used needs exactly ceil(n_block_size / num_threads) entries. The entries this over-allocates when n_block_size < num_threads are already predicated off by the row < n_block_size check in load_page_table() (which writes page = 0), and are never consumed by the shuffle_sync in load_KV().

Risk is limited to configurations that cannot currently run: ceil == floor whenever n_block_size % num_threads == 0, which is true of every tile that compiles today, so those kernels are bit-identical.

Accuracy Tests

Standalone script calling flash_attn_with_kvcache on the paged path, checked against an fp32 SDPA reference, on GH200 (SM90). Deliberately shuffled page tables so page-index/offset mix-ups can't hide. Every case fails to compile on main and passes with this change:

case page_size causal window max abs err
b1, s_q=s_k=512 1 yes – 0.0156
b3 ragged, s_q=[300,17,128], s_k=[300,1000,128] 1 yes – 0.0156
b4 spec-decode, s_q=8, s_k=[513,80,81,1024] 1 yes – 0.0039
b2, non-causal 1 no – 0.0039
b2, multi-token pages 64 yes – 0.0156
b2, sliding window (tile_n=64) 1 yes (256, 0) 0.0078

(ref_absmax ≈ 1.3–4.1, so these are bf16 rounding.)

End-to-end: Qwen/Qwen3.8-27B-FP8 on GH200 with --attention-backend fa4 now completes startup warmup and serves. A 7044-token prompt with a needle placed mid-context returned the needle exactly, which exercises many n_block iterations of the cp.async page-table path rather than just compilation.

Not covered: SM100. ceil == floor for the tiles that arch uses, so no behavior change is expected there, but I don't have Blackwell hardware to confirm.

Speed Tests and Profiling

No impact. page_entry_per_thread is a compile-time constant and the generated kernel is unchanged for every configuration that compiles today.

Follow-up (deliberately not in this PR)

With the root cause fixed, the not (page_table is not None and q_stage == 1) guard added by #32118 could likely be relaxed to restore its SMEM-saving tile_n = 64 for SM100 diff-headdim decode. I can't validate that without Blackwell, so I've left it alone.

Note on test coverage

test/registered/attention/unittests/dense/test_fa4.py runs HEAD_DIM = 64 only, which is why this went unnoticed — no FA4 test exercises a tile_n that isn't a multiple of 128. Precedent: #32118 fixed the same assertion in this subsystem and validated it with a standalone repro rather than a committed test. Happy to add a regression case (here or under test/registered/kernels/ops/attention/) gated to SM90 if reviewers want one; 1-gpu-large is an H100 runner, so it would genuinely guard this.

Checklist


CI States

Latest PR Test (Base): ⏳ Run #38529399118
Latest PR Test (Extra): ❌ Run #38529398680
Latest PR Test (AMD ROCm 10): ⏳ Run #38529398873

PagedKVManager stages the page table in per-thread registers sized
`n_block_size // num_threads`. When tile_n is smaller than the 128-thread
load warp group that division floors to 0 and the kernel fails to compile
with "Expected size in shape to be strictly positive, but got 0". This
blocks serving any head_dim 192/256 model with --attention-backend fa4 on
Hopper, e.g. Qwen3.8-27B on a GH200, which crashes during startup warmup.

Use ceil_div, matching upstream FA4. The tail entries this allocates are
already predicated off by the `row < n_block_size` check in
load_page_table(), and ceil == floor for every tile that works today, so
no currently-supported configuration changes behavior.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@SamMausberg

SamMausberg commented Oct 2, 2026 •

Copy link
Copy Markdown

I hit the same failure independently on a GH200 and can confirm this fix on main at f6fcda8 (the line is unchanged on main today).

With --attention-backend fa4, Qwen/Qwen3.5-4B (head_dim 256 in its full-attention layers) fails on main during CUDA graph capture with the same ValueError: Expected size in shape to be strictly positive, but got 0 from paged_kv.py. With the ceil-divide (Dao-AILab/flash-attention#2745's hunk) it starts and serves. On GSM8K (first 200 test questions, 5-shot, sglang.test.few_shot_gsm8k), the fa4 server scores 0.870 and the triton server 0.875, with otherwise identical flags. With 200 questions that only shows the fa4 server answers sensibly; it cannot resolve a difference of a few points.

Kernel-level, I called flash_attn_with_kvcache(ver=4) with a shuffled page table and checked against an FP32 reference. With the (n + t - 1) // t form, these configurations, which failed to compile on main, now run correctly: head_dim 256 (tile_n 80: page size 1 causal and non-causal, page size 16 causal), head_dim 256 with a window (tile_n 64) and head_dim 192 (tile_n 112). The largest error is 0.0022-0.0029, against 0.006-0.010 for a BF16 PyTorch reference. Your exact cute.ceil_div line and the max(1, n // t) in #42019 give the same results at head_dim 256, causal, page size 1; for tile_n of 128 or less, all three forms give 1.

head_dim 160 (tile_n 112) and 224 (tile_n 80) also fail on main with the ValueError. The ceil-divide gets them past it, but not to correct output, so they need a separate fix. Their tile_n is at most 128, so your cute.ceil_div line computes the same count (1) as the (n + t - 1) // t form I ran. With that form, the same flash_attn_with_kvcache check at page size 1 (causal and non-causal) returns finite but wrong output (largest error 1.03-1.43, against 0.005-0.008 for the BF16 reference), and a single flash_attn_varlen_func call with an identity page table (seqlen_k 300) fails with an illegal memory access.

The FA4 tests don't cover the head_dim 256 case on SM90 yet, so here is the regression test I used, in case you want to add it. It goes in test/registered/kernels/ops/attention/test_flash_attention_4.py, which is already registered on 1-gpu-large (H100). It needs is_sm90_supported added to the file's sglang.srt.utils import. On the GH200 it fails on main with the ValueError and passes with your exact line (both page sizes).

test_flash_attn_paged_non_tma_partial_loader_tile_sm90
@pytest.mark.skipif(
    not is_sm90_supported(),
    reason="Covers the SM90 head_dim 256 tile (128 x 80).",
)
@pytest.mark.parametrize("page_size", [1, 16])
def test_flash_attn_paged_non_tma_partial_loader_tile_sm90(page_size):
    """The SM90 head_dim 256 tile has 80 KV rows, fewer than the 128 threads of
    the cp.async paged-KV loader; a page size other than 80 must still work."""
    device = "cuda"
    dtype = torch.bfloat16
    batch_size, seqlen_q, seqlen_k = 3, 16, 600
    nheads, nheads_k, d = 16, 4, 256
    torch.random.manual_seed(0)

    q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype)
    k_cache, v_cache, page_table, k_cache_paged, v_cache_paged, _ = (
        _generate_block_kvcache(
            seqlen_k, page_size, batch_size, nheads_k, d, d, device, dtype, dtype
        )
    )
    # Lengths that end inside a KV tile, so the last tile is partially loaded.
    cache_seqlens = torch.tensor([seqlen_k, 97, 333], dtype=torch.int32, device=device)
    cu_seqlens_q = (
        torch.arange(batch_size + 1, dtype=torch.int32, device=device) * seqlen_q
    )

    out = flash_attn_with_kvcache(
        q=rearrange(q, "b s h d -> (b s) h d"),
        k_cache=k_cache_paged,
        v_cache=v_cache_paged,
        page_table=page_table,
        cache_seqlens=cache_seqlens,
        cu_seqlens_q=cu_seqlens_q,
        max_seqlen_q=seqlen_q,
        causal=True,
        ver=4,
    )
    out = rearrange(out, "(b s) h d -> b s h d", b=batch_size)

    key_padding_mask = rearrange(
        torch.arange(seqlen_k, device=device), "s -> 1 s"
    ) < rearrange(cache_seqlens, "b -> b 1")
    out_ref, _ = attention_ref(q, k_cache, v_cache, None, key_padding_mask, causal=True)
    out_pt, _ = attention_ref(
        q,
        k_cache,
        v_cache,
        None,
        key_padding_mask,
        causal=True,
        upcast=False,
        reorder_ops=True,
    )
    assert (out - out_ref).abs().max().item() <= 2 * (
        out_pt - out_ref
    ).abs().max().item() + 1e-5
    assert (out - out_ref).abs().mean().item() <= 1.5 * (
        out_pt - out_ref
    ).abs().mean().item()

Edit: added head_dim 160 and 224.

SamMausberg added a commit to SamMausberg/verified-progress that referenced this pull request Oct 2, 2026
Row 0002 now says that common_ops in the inspected aarch64 wheel
(sglang-kernel 0.4.8) lacks sm_90a, as the posted
sgl-project/sglang#42263 body does, instead of saying all aarch64 wheels
carry none. Row 0001 names Qwen3.5-4B, lists the head dims checked, and
says sgl-project/sglang#35757 writes the ceil-divide as cute.ceil_div.
SamMausberg added a commit to SamMausberg/verified-progress that referenced this pull request Oct 2, 2026
Row 0001 now says, as the edited sgl-project/sglang#35757 comment does,
that at head_dim 160 and 224 the ceil-divide gets past the compile error
but not to correct output.
SamMausberg added a commit to SamMausberg/verified-progress that referenced this pull request Oct 3, 2026
…es and the upstream patches

BF16 (#222, evidence/bf16_paths): the served benchmark read both gross
positions as ill-conditioned in BF16. #222 supports that for a4db11ff/333
only. At 579ae7ce/439, the paper's 8.9-nat position, transformers in BF16
keeps FP32's top token in all 16 readings, FP32 under one-rounding noise
moves 1756 by at most 0.52 nats, and no single SGLang kernel swap removes
the miss: an SGLang outlier at a selected position, whose frequency the
unselected positions cannot compare with transformers'. The abstract and
§4.5 add "unlike transformers'"; App E.5, the served README (two places)
and a new notes subsection give the reading; register entry bf16-paths in
both registers.

Low-concurrency probes (#220, evidence/speed_lowc): one notes paragraph
(split-KV verify dropped by its rule; FA4's head-dim-256 compile failure
and backport; one-session served FA4 probes, exactness not classified;
fused GDN chain passed its rule but not built), H6, "What did not work",
register entry speed-lowc, and the missing index rows.

Upstream (#226): one notes paragraph and register entry upstream-patches
(the FA4 test as a comment on sgl-project/sglang#35757; the sgl-kernel
sm_90a build fix open as sgl-project/sglang#42263). The two FP8 lines say
the CUTLASS GEMM "fails" rather than "aborts", consistent with the engine
README.

Reviewer's optional item from #227: "calls of up to 30-64 positions" in
the abstract and §4.5 (largest certified calls at each point).

Paid for in §4.5's paragraph with no claim dropped; the main text still
ends at the foot of p10.
SamMausberg added a commit to SamMausberg/verified-progress that referenced this pull request Oct 3, 2026
evidence/upstream_fa4: the FA4 SM90 paged-KV checks behind the sgl-project/sglang#35757 comment
@SamMausberg

SamMausberg commented Oct 3, 2026 •

Copy link
Copy Markdown

Follow-up to my comment above on head_dim 160 and 224: I found the cause, and it also affects head_dim 80 and 96, which compile on main and are silently wrong.

It is in PagedKVManager.load_KV, not in the page-entry count this PR fixes. The loader copies a K/V tile in passes of 32 rows (64 at head_dim 80). When tile_n is not a multiple of that (144 at head_dim 80/96 non-causal, 112 at 160, 80 at 224), the threads of the last pass whose row is past the tile still issue a cp.async, and a predicated-off cp.async zero-fills, so they write over the first rows of the tile's next head-dim block, of the other stage, or (head_dim 160/224) past the end of shared memory. I filed it upstream as Dao-AILab/flash-attention#2957, with a fix in Dao-AILab/flash-attention#2958.

The vendored copy needs the same change on top of this PR's line (diff below). With both (I ran the (n + t - 1) // t form of your line, which gives the same count at every tile here), on a GH200 with SGLang main at 65f7591, the flash_attn_with_kvcache check from my comment is correct at head_dim 80 and 96 (non-causal, page size 1; 96 also at page size 16) and at 160 and 224 (causal and non-causal, page size 1), and so is a single flash_attn_varlen_func call (head_dim 96 at seqlen_k 100, 144, 145 and 300; 80, 160 and 224 at 300). Head dims 96 (causal), 128, 192 and 256 and the regression test above still pass. With the ceil-divide alone (run at f6fcda8; the vendored flash_attn directory is identical at both commits), every affected case above is wrong or faults, except the varlen call whose seqlen_k is exactly one tile (144).

The vendored-copy change (on top of this PR)
--- a/python/sglang/kernels/ops/attention/flash_attn/cute/paged_kv.py
+++ b/python/sglang/kernels/ops/attention/flash_attn/cute/paged_kv.py
@@ -300,6 +300,7 @@
             if n_block >= 0
             else 0
         )
+        rows_per_pass = self.num_threads // self.gmem_threads_per_row
         for m in cutlass.range_constexpr(cute.size(tXsX, mode=[1])):
             row_valid = tXc0X[0, m, 0][0] < seqlenk_row_limit
             should_load = cute.make_fragment_like(tXsX[(0, None), m, 0], cute.Boolean)
@@ -320,7 +321,14 @@
             mX_paged_cur_copy = cute.tiled_divide(
                 mX_paged_cur, (self.async_copy_elems,)
             )
-            self._copy_row_async(tXsX, tXcX, mX_paged_cur_copy, m, should_load)
+            if const_expr(tXc0X[0, m, 0][0] + rows_per_pass <= self.n_block_size):
+                self._copy_row_async(tXsX, tXcX, mX_paged_cur_copy, m, should_load)
+            else:
+                # Last pass when n_block_size is not a multiple of rows_per_pass: rows past the
+                # tile alias other rows of sX (next head-dim block or stage), and a predicated-off
+                # cp.async still zero-fills its destination, so those threads must not copy.
+                if tXcX[0, m, 0][0] < self.n_block_size:
+                    self._copy_row_async(tXsX, tXcX, mX_paged_cur_copy, m, should_load)
 
     @cute.jit
     def load_sf_KV(self, n_block: Int32, sSFX: cute.Tensor, K_or_V: str):

SamMausberg added a commit to SamMausberg/verified-progress that referenced this pull request Oct 3, 2026
…concurrency cost; prefills one or two at a time

- Notes "Changes offered upstream" and README's upstream bullet link Dao-AILab/flash-attention#2957
  and #2958 and the follow-up comment on sgl-project/sglang#35757 (README also links the first
  comment and #42263).
- Notes admission paragraph: at c = 1 and 8 the setting passes its declared no-harm rule but the
  time to first token is longer in all six session pairs and throughput lower in five of six
  (confirm_points.csv), replacing "changes nothing measurable".
- Section 4.5 and README: speculative requests are prefilled one or two at a time, and the
  33 ms / 9 ms figure is a lone plain-decoding prefill (admission README), not "each prefilled alone".
SamMausberg added a commit to SamMausberg/verified-progress that referenced this pull request Oct 3, 2026
…concurrency cost; prefills one or two at a time

- Notes "Changes offered upstream" and README's upstream bullet link Dao-AILab/flash-attention#2957
  and #2958 and the follow-up comment on sgl-project/sglang#35757 (README also links the first
  comment and #42263).
- Notes admission paragraph: at c = 1 and 8 the setting passes its declared no-harm rule but the
  time to first token is longer in all six session pairs and throughput lower in five of six
  (confirm_points.csv), replacing "changes nothing measurable".
- Section 4.5 and README: speculative requests are prefilled one or two at a time, and the
  33 ms / 9 ms figure is a lone plain-decoding prefill (admission README), not "each prefilled alone".
SamMausberg added a commit to SamMausberg/verified-progress that referenced this pull request Oct 3, 2026
…concurrency cost; prefills one or two at a time

- Notes "Changes offered upstream" and README's upstream bullet link Dao-AILab/flash-attention#2957
  and #2958 and the follow-up comment on sgl-project/sglang#35757 (README also links the first
  comment and #42263).
- Notes admission paragraph: at c = 1 and 8 the setting passes its declared no-harm rule but the
  time to first token is longer in all six session pairs and throughput lower in five of six
  (confirm_points.csv), replacing "changes nothing measurable".
- Section 4.5 and README: speculative requests are prefilled one or two at a time, and the
  33 ms / 9 ms figure is a lone plain-decoding prefill (admission README), not "each prefilled alone".
@BBuf BBuf added the run-ci CI: run the baseline test suite on this PR label Oct 12, 2026
@BBuf
BBuf merged commit bab9c81 into sgl-project:main Oct 14, 2026
141 of 173 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jit-kernel run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants