Repository navigation
fix: FA4 paged-KV zero-size page-table registers on SM90 - #35757
Conversation
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]>
|
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 Kernel-level, I called 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 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_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. |
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.
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.
…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.
evidence/upstream_fa4: the FA4 SM90 paged-KV checks behind the sgl-project/sglang#35757 comment
|
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 The vendored copy needs the same change on top of this PR's line (diff below). With both (I ran the 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): |
…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".
…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".
…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".
Motivation
Serving
Qwen/Qwen3.8-27B-FP8with--attention-backend fa4on a GH200 (Hopper, SM90) crashes in the scheduler during startup warmup, before the server ever accepts a request:Environment: GH200 480GB (SM90), CUDA 13.2,
nvidia-cutlass-dsl4.6.2, sglang built from source ateac91ac36(line numbers above are from that commit). Reproduced with:Root cause
PagedKVManager.create()sizes its per-thread page-table registers with a floor division:When
tile_n < 128this evaluates to0, andcute.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()returnstile_n = 80for that head dim (64 with a sliding window). sglang's defaultpage_size=1never equalstile_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 athead_dim=256hits this;head_dim=192is affected too (tile_n112 / 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_nto 64 ininterface.py; the division itself was left as-is. That doesn't cover SM90, wheretile_n = 80is 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: usecute.ceil_divinstead of floor division.Why
ceilis the right size rather than merely non-zero:load_KV()indexestPrXPtr[m // gmem_threads_per_row]forminrange(n_block_size * gmem_threads_per_row / num_threads), so the largest index used needs exactlyceil(n_block_size / num_threads)entries. The entries this over-allocates whenn_block_size < num_threadsare already predicated off by therow < n_block_sizecheck inload_page_table()(which writespage = 0), and are never consumed by theshuffle_syncinload_KV().Risk is limited to configurations that cannot currently run:
ceil == floorwhenevern_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_kvcacheon 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 onmainand passes with this change:(
ref_absmax≈ 1.3–4.1, so these are bf16 rounding.)End-to-end:
Qwen/Qwen3.8-27B-FP8on GH200 with--attention-backend fa4now completes startup warmup and serves. A 7044-token prompt with a needle placed mid-context returned the needle exactly, which exercises manyn_blockiterations of the cp.async page-table path rather than just compilation.Not covered: SM100.
ceil == floorfor 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_threadis 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-savingtile_n = 64for 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.pyrunsHEAD_DIM = 64only, which is why this went unnoticed — no FA4 test exercises atile_nthat 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 undertest/registered/kernels/ops/attention/) gated to SM90 if reviewers want one;1-gpu-largeis 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