perf(prims-ts): QToken NVFP4 prefill: gather4 scale copies, per-layout group policy and balanced CLC scheduling #9876
All Vouch review confidence checks passed
Residual risk 0.30 = Change Risk (0.75) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.75 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Sensitive Paths
sensitive_paths
0.075
Real PR Conversation Timeline
1 comments
"Review active on #9876"
general
weight: 0.35
qsang-nv
<!-- .github/pull_request_template.md -->
📌 Description
Changes for NVFP4 QToken-KvBlock-Sparse-Attention prefill with grouped routes (GB300, D256, block 4, top-k 512), one commit each:
1. Gather4 NVFP4 scale copies and causal route unions. With separate compact scale tensors, the Keeps raw ring gathers four page fragments' scale rows per TMA gather4 (8 instead of 32 scale copies per KV128 tile). The G latency model caps each route's expected union at the context its last query sees, so causal prefill from a short prefix no longer overestimates large groups (16/1 Q/KV heads, 4096 queries, empty prefix: G4 177 us -> G8 138 us).
2. Per-layout G latency model. The union-growth exponent is now the measured 0.48 (was 0.35, which overcharged TileQ128 at G2/G4 and picked groups up to 1.26x slower for 32 and 64 Q heads per KV head). Work items cost per TileQ and SM waves are fractional.
suggest_q_token_kv_block_sparse_group_size(nvfp4_interleaved_kv=...)selects constants fitted per NVFP4 layout (interleaved rows make TileQ64 ~7% slower than separate scales). Over 1848 swept cases the chosen group is within 1.002x (separate scales) and 1.004x (interleaved rows) of the best, vs 1.008x / 1.017x before.3. Balanced CLC scheduling. Persistent launches handed out routes in index order; route cost follows its K/V union, which varies 1.3-1.9x within one call, so long routes often started last (SMs busy 71% of the kernel in an all-CTA trace). The metadata kernel's last CTA now counting-sorts routes by KV128 tiles in shared memory and the CLC work queue takes them in that order. When the requests' K/V fits in half of L2 every route is ordered longest first; otherwise only the shortest two SM waves move to the end and the rest keep index order (L2 reuse). New plan option
QTokenKvBlockSparsePagedTSWrapper.plan(balanced_scheduler=None):Noneenables it for persistent launches whose routes exceed one SM wave,Truefor every persistent launch,Falsekeeps index order. Cost: ~0.9 us in the metadata kernel; attention starts at the same time under PDL.4. Interleaved-rows group constants refit under the balanced scheduler. Fewer, larger TileQ128 work items lose less to the last wave with balanced scheduling, so with interleaved rows G8 now beats G4 for 16 Q heads per KV head over long contexts (16/1, 4096 queries over 32K: 348 -> 311 us; 16/1 x 4 requests x 1024 queries: 1.15x). Refit on the same sweeps with every multi-wave case re-measured on this branch; separate-scale constants unchanged.
5. Balanced scheduler auto rule skips short routes. Routes that can read at most two KV128 tiles (
max_seq_len_kv <= 256) leave nothing to balance while the order costs ~1-2 us; the default now leaves them in index order.6. Review fixes. These cover the CodeRabbit and reviewer comments.
- The work queue never reads the route order at the undefined index of a failed CLC cancel: invalid tiles read entry 0, with no branch.
- The L2 estimate counts separate NVFP4 scale tensors.
- Bitmap metadata launches stay within the per-CTA shared-memory limit.
- The completion counter must be a nonempty 1-D tensor.
- Only persistent launches reserve the route-order workspace region.
- Gather4 scale launches skip the two unused 4-D scale-map encodes.
- The longest bucket (127+ KV128 tiles) is documented.
- The scheduler test uses full indexer prefixes and poisons the order before repeated runs.
This commit measured 1.000x geomean vs commit 5 on the full table below for both layouts.
7. Route-order workspace only for shared patterns. Per-head sparse patterns (even with one KV head) never take the route order, so they no longer reserve its workspace region; shared-pattern layouts are unchanged.
8. Balanced scheduler auto rule by SM waves. Commit 5's cut-off (routes of more than two KV128 tiles) also dropped two-tile routes over several SM waves, where the order pays: 16/1 Q/KV heads with 16 or 64 requests x 256 queries from an empty prefix now run 1.08-1.10x faster than main (64 requests with separate scales was 0.987x). Short routes over fewer waves lose to the order's cost instead. The default now enables it when routes span more than one wave and can read more than one KV128 tile; routes of up to four tiles (
max_seq_len_kv <= 512) also need three or more waves.GB300, real indexer top-k, auto G, A/B/A/B on one GPU per shape, both NVFP4 layouts (main/branch time, geomean (max)):
| Q/KV heads (top-k corpus) | cases | separate scales | interleaved rows |
|---------------------------|------:|-----------------|------------------|
| 4/1 (book) | 39 | 1.026x (1.16x) | 1.003x (1.08x) |
| 16/1 (book) | 39 | 1.042x (1.40x) | 1.021x (1.48x) |
| 16/1 (code) | 39 | 1.046x (1.44x) | 1.025x (1.50x) |
| 16/2 (book) | 39 | 1.039x (1.24x) | 1.013x (1.20x) |
| 32/1 (book) | 27 | 1.082x (1.45x) | 1.073x (1.52x) |
| 32/2 (book) | 27 | 1.063x (1.17x) | 1.034x (1.18x) |
| 64/2 (book) | 27 | 1.064x (1.44x) | 1.059x (1.49x) |
| 64/4 (book) | 27 | 1.075x (1.45x) | 1.051x (1.50x) |
| 128/8 (book) | 27 | 1.060x (1.17x) | 1.022x (1.08x) |
| 16/1, 4-64 requests (book)| 69 | 1.053x (1.22x) | 1.031x (1.19x) |
| all | 360 | 1.052x (1.45x) | 1.030x (1.52x) |
One request unless noted; 0/32K/64K-token prefixes, 1-4096 queries (batches: 0/32K prefix, 1-1024 queries per request); split-KV auto; base is main at a7ed35743, with all eight commits rebased onto it.
Cases flagged in this table (the branch's best run more than 1% slower than main's worst) were re-timed in three rotated rounds of 30 replays. All are within noise (0.995-1.007x) except the accepted 128/8 cases and two small separate-scale launches listed under Reviewer Notes.
🔍 Related Issues
Follow-up to #9375.
🚀 Pull Request Checklist
Thank you for contributing to FlashInfer! Before we review your pull request, please make sure the following items are complete.
✅ Pre-commit Checks
pre-commitby runningpip install pre-commit(or used your preferred method).pre-commit install.pre-commit run --all-filesand fixed any reported issues.🧪 Tests
unittest, etc.).Reason: <!-- e.g. cross-cutting change to shared infrastructure -->
Suggested CI test targets (optional; paths under
tests/, whitespace-separated — a startingpoint for
@flashinfer-bot run <targets>//bot run <targets>, reviewers may adjust):tests/attention/test_attention_ts_q_token_kv_block_sparse_metadata.py tests/attention/test_attention_ts_decode.py tests/attention/test_attention_ts_decode_mixed_precision.py🔬 Experimental Track
<!-- Only for PRs submitted under the experimental policy (CONTRIBUTING.md → "Experimental APIs and Backends").
Leave this section untouched for normal PRs. -->
flashinfer/experimental/and/or an@flashinfer_experimental_api. Tracking issue: #- [ ] The tracking issue names an owner, the reason for the experimental path, and a graduation plan with a target release.
- [ ] Core changes are limited to a thin entry point (signature, shared validation, feature-gate check, backend selection, handoff).
- [ ] Tests live in
tests/experimental/and were validated on the intended hardware; a runnable example is included.- [ ] Nothing is registered in
flashinfer/aot.py, and no experimental backend is reachable frombackend="auto"withoutFLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1. (Calling an@flashinfer_experimental_apior naming a backend explicitly is itself the opt-in and needs no environment variable.)- [ ] Test scope declared below. The experimental CI lane runs exactly these targets, so keep them as narrow as the change allows.
<!-- Required for experimental PRs. Replace the commented lines below with your targets.
Do not delete the fence or change its
experimental-teststag — the experimental-trackwatcher reads it verbatim to decide which targets to ask CI for. -->
``
experimental-tests
`One target per line: a directory or a file. (A pytest ::selector is not
supported -- the sharding runner cannot consume one.) Must be under
tests/experimental/ and must exist. Delete these comment lines and add yours, e.g.
# tests/experimental/test_my_backend.py
tests/experimental/my_backend/
# Declaring the whole tree (tests/experimental/) is allowed but means every
experimental PR pays for every other feature's tests, in every matrix cell.
Reviewer Notes
/ruff format --checkon the changed Python files,clang-format(repo.clang-format) on the changed C++/CUDA files, andgit diff --check.,test_attention_ts_decode.pyandtest_attention_ts_decode_mixed_precision.pypass on GB300 (SM103), CuTe DSL 4.8.1, CUDA 13.4, on this branch rebased onto main a7ed35743.adds an int32 [routes] region afterseq_lens` in the workspace of packed grouped persistent plans with shared sparse patterns, and the plan owns a one-int32 completion counter (zeroed at plan time, rearmed by the metadata kernel), so a workspace shared between plans cannot disturb it.🤖 Generated with Claude Code
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
Summary by CodeRabbit
New Features
Added optional balanced scheduling for packed, grouped sparse attention. Eligible plans can prioritize longer routes while retaining a configurable tail of shorter routes; scheduling can also be explicitly enabled or disabled.
Updated sparse-group size recommendations to account for route context and interleaved NVFP4 cache layouts.
Added an optimized scale-loading path for eligible NVFP4 configurations.
Tests
Added coverage for route scheduling across repeated runs, sparse-group recommendations, and NVFP4 layout options.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->