Skip to content

feat: add FlashInfer attention backend for SM120 decode - #112

Open
yanbao1217 wants to merge 11 commits into
InferMatrixLab:mainfrom
yanbao1217:flashinfer-sm120
Open

yanbao1217 wants to merge 11 commits into
InferMatrixLab:mainfrom
yanbao1217:flashinfer-sm120

Conversation

@yanbao1217

@yanbao1217 yanbao1217 commented Oct 10, 2026 •

Copy link
Copy Markdown

Adds FlashInfer XQA as a selectable paged attention backend for Ouro. Refs #69.

Backend selection and KV cache

  • On SM120, auto considers XQA for supported BF16 configurations. It checks the installed FlashInfer JIT target and CUDA toolkit. When head_dim > 256 and the Q/KV head ratio is unknown, selection continues to the next backend.
  • SM90 and SM100 retain explicit --attention-backend flashinfer opt-in. Hardware validation in this PR covers the RTX 5090 (SM120).
  • Decode and per-query prefill use the existing paged KV cache, including CUDA Graph replay and asynchronous scheduling. The adapter handles non-contiguous queries. Packed prefill is outside this backend’s scope.
  • On SM120, --kv-cache-dtype fp8_e4m3 uses startup-calibrated scalar K/V scales. Q and output stay BF16. The accuracy and throughput measurements below use BF16 KV.

Validation on RTX 5090

Ouro-1.4B BF16, page size 16, four fixed loops, per-query prefill, FlashInfer 0.7.5.post1.

Accuracy. On frozen GSM8K-87, using the same greedy configuration and strict scorer, Triton scored 62/87 and XQA 58/87. XQA missed the 59/87 acceptance threshold by one question. The backends generated identical token sequences on 61 of 87 questions. Four questions scored only for Triton. XQA gave the wrong numerical answer on #203 (27 vs 31). On #426, #745 and #819 it produced the correct amount with a currency sign that the strict scorer did not parse.

Throughput. Median output tokens/s across three paired trials per concurrency, alternating backend order. Each request used 512 input tokens and 128 output tokens in eager execution.

Concurrent requests Triton FlashInfer XQA Change
1 15.9 16.9 +6.2%
8 108.2 115.7 +6.9%
32 317.3 334.0 +5.3%

Regression checks. All three repository pre-commit hooks passed (Ruff lint, Ruff format, CPU regression suite). The focused XQA/backend run passed all 44 selected cases on the RTX 5090 host, including GPU attention and CUDA Graph cases.

RTX 5090 reproduction recipe · Backend requirements and accuracy analysis

Register FlashInfer (flashinfer-python >= 0.7.0, XQA kernels) as a
paged decode backend through the attention contract layer:

- explicit "flashinfer" selection plus an auto slot between
  FlashAttention-2 and Triton; the SM gate keeps auto away from it on
  SM8/9/10, so it is only reached where every FlashAttention generation
  is rejected (SM 12.x)
- capabilities declare CUDA graphs and async scheduling; packed prefill
  stays FA4-only because the adapter leaves the kernel without a
  prefill entry point
- validation rejects unsupported setups explicitly (float16 unvalidated
  on SM120, page sizes outside the compiled XQA variants, head_dim not
  divisible by 16); the workspace allocates lazily on first execution so
  backend selection performs no device allocations
- empty batches return early because the kernel host-dispatch SIGFPEs on
  batch 0; padded block-table columns are clamped non-negative and the
  kernel bounds reads by seq_lens, so -1/zero/stale padding stays
  invisible
- requires CUDA_HOME with nvcc >= 12.9 and that toolkit's lib directory
  on LD_LIBRARY_PATH for the just-in-time compiled modules
The run subcommand accepts --attention-backend (torch/triton/flashinfer,
default triton), records it in the run metadata, and passes it through
Generator to the engine instead of the hardcoded Triton selection.
Document installation and the two runtime requirements (CUDA_HOME with
nvcc >= 12.9 for JIT kernels, the toolkit lib directory on
LD_LIBRARY_PATH), scope and explicit rejections, backend selection
guidance, and the GSM8K-87 greedy variation measured on RTX 5090.
@yanbao1217

Copy link
Copy Markdown
Author

Matched throughput results for the FlashInfer vs Triton decode path (RTX 5090, Ouro-1.4B BF16, block_size=16, fixed four-loop depth).

Protocol follows the PR #30 methodology scaled to a 32 GB device: 512-token random-token inputs, 128 output tokens, 2x concurrency requests with closed-loop replacement, three trials per condition (medians below); timing covers prefill and drain and excludes loading, warmup, and tokenization; both backends run identical feature stacks (eager, and graphs = async scheduling + multi-stream + static buffers + pad-to-power-of-two + CUDA graphs).

stack concurrency Triton out-tok/s FlashInfer out-tok/s delta
eager 1 22.1 21.7 -2%
eager 8 151.6 151.4 ~0%
eager 32 441.0 429.8 -2.5%
graphs 1 49.7 65.9 +33%
graphs 8 220.7 246.6 +12%
graphs 32 392.5 384.0 -2%

Notes:

  • The FlashInfer advantage concentrates exactly where the XQA split-KV parallelism matters: the performance-oriented graphs stack at low concurrency (+33% for a single request), the typical single-user RTX 5090 configuration. At concurrency 32 both kernels saturate the GPU and the difference is within noise (-2%).
  • Under the eager stack the two backends are equal within noise: per-step host work dominates there, not attention.
  • Greedy paired runs: per-request output token counts matched 540/540 across all conditions and trials.
  • Raw per-trial data (including KV plans and selection info) is recorded locally; the benchmark driver stays out of the tree in line with keeping benchmark artifacts in PRs rather than in main (as with [FEAT] Capture fixed-depth speculative decode with CUDA Graphs #48).

🤖 Generated with Claude Code

Document the --attention-backend flag on the native run command, the
RTX 5090 Triton/FlashInfer scores on the frozen 87-question case, and
the expected single-pass greedy variation between BF16 kernels.

@0z5a 0z5a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for adding FlashInfer through the existing attention backend contract and for the C1/C8/C32 measurements on RTX 5090. Reviewed 1a24e52; I have one selection concern before merging and several follow-up suggestions.

1. [P2] Restrict automatic selection to validated architectures.

auto places FlashInfer before Triton, and the constructor accepts SM90/SM100 with only a warning. A CPU selection probe using the original constructors with hardware/import boundaries mocked reproduces this on SM90: BF16, head dimension 128, page size 16, FA4/FA3 unavailable and FA2 rejecting the page size selects Triton at the base revision and FlashInfer at this head. SM100 has an analogous fallback change.

Could we gate automatic FlashInfer selection to the validated SM120 target for now, retain explicit opt-in on H100, and add fallback regression tests? The PR description's automatic-selection restriction is currently stronger than the code implements.

2. Backend capability reuse.

The kernel's self.capabilities duplicates the wrapper's _FLASHINFER_CAPABILITIES. Please use the existing backend contract as the single source of truth and exercise that contract in selection tests.

3. Metadata and workspace validation.

Please profile the per-invocation block_tables.clamp_min(0) and context_lengths.to(torch.uint32) overhead at larger batches before considering preparation once per KV batch. Preserve padding and graph-buffer update semantics if these tensors are reused.

The instance-owned 128 MiB workspace is a useful ownership choice. The runner currently serializes attention on its core stream; I have not established a workspace race. Please reuse the existing CUDA Graph test matrix for FlashInfer and cover replay, eager fallback, cancellation and request reuse to verify the workspace lifetime and ordering contract.

4. High-concurrency E2E coverage.

For follow-up validation, C64/C128 with dynamic arrivals, mixed prompt lengths and recurrence depths, cancellation/reuse, and both supported KV layouts would be useful. Please report latency percentiles, graph replay/fallback counts, KV reclamation and output/exit-depth correctness alongside output tok/s. Account for the reported BF16/GSM8K divergence explicitly; matching token counts alone does not establish generation equivalence.

I can help run the H100 side of this validation. Please ping me @0z5a if useful.

}
_AUTO_PRIORITY = ("flash_attn_4", "flash_attn_3", "flash_attn_2", "triton", "torch")
_FLASHINFER_CAPABILITIES = BackendCapabilities(cuda_graphs=True, async_scheduling=True)
_AUTO_PRIORITY = ("flash_attn_4", "flash_attn_3", "flash_attn_2", "flashinfer", "triton", "torch")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Gate the automatic FlashInfer candidate to validated architectures. Putting FlashInfer before Triton changes the fallback on SM90/SM100 because its constructor accepts those architectures with only a warning. Using the pinned original selection/constructor functions with mocked hardware/import boundaries, SM90 BF16, head dimension 128 and page size 16 selects Triton at the base revision when FA4/FA3 are unavailable and FA2 rejects the page size, but selects FlashInfer here. This exceeds the stated SM120 validation scope. Please keep explicit SM90/SM100 opt-in available while restricting the auto candidate to validated targets, and add fallback tests for missing FlashAttention candidates.

@yanbao1217

Copy link
Copy Markdown
Author

Thanks @0z5a — acknowledged. Plan: gate the automatic candidate to SM120 while keeping explicit opt-in elsewhere, make the contract layer the single source for the capability declaration, profile the per-call clamp/cast conversions, and extend the graph-matrix coverage (replay, eager fallback, cancellation, request reuse) for FlashInfer. The C64/C128 dynamic-arrival validation sounds right as a separate follow-up; I'd gladly take you up on the H100 half once these land.

…ties

Address review feedback on InferMatrixLab#112:

- auto only considers the flashinfer candidate on SM 12.x, so SM90/SM100
  keep their pre-FlashInfer fallback when every FlashAttention generation
  is unavailable; explicit --attention-backend flashinfer still opts in
  on other accepted architectures with the unvalidated-architecture warning
- the capability declaration now lives only in the attention registration
  layer; the kernel adapter no longer carries a duplicate
- regression rows for the SM90/SM100 fallbacks, an explicit-opt-in test,
  and the CUDA Graph matrix (replay, eager fallback, abort/cancellation,
  request reuse) now cover FlashInfer
@bjf-frz

bjf-frz commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator

Please prioritize investigating the accuracy regression before merging. Under the same configuration, Triton scored 61/87 and FlashInfer 58/87, with three correct-to-incorrect flips and no improvements. FlashInfer also falls below the existing 59/87 acceptance threshold.

Different BF16 accumulation orders may explain the divergence, but this alone does not rule out an integration bug. Please:

  1. Check implementation correctness on SM120: KV layout and strides, sequence lengths, padding, and graph replay behavior. Address the zero-length-row issue observed on B300 separately; it is not yet established as the cause of the SM120 accuracy loss.
  2. Locate the first divergence in the three regressed cases: use identical token prefixes and compare attention outputs, final logits, and the top-1/top-2 logit gap against an FP32 attention reference. Avoid comparing later steps after the generated prefixes have already diverged.
  3. Rerun the same accuracy evaluation after fixing the issues: keep the model, dataset, prompts, and generation settings fixed, and report correct counts and per-question losses/gains against Triton. Then verify that the performance gains remain.

Bitwise-identical generation across kernels is not required, but the current accuracy failure needs to be investigated and resolved rather than dismissed as expected BF16 variation.

@bjf-frz

bjf-frz commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator

Any updates?

@yanbao1217

Copy link
Copy Markdown
Author

I have completed first-divergence analysis for the three regressed questions. The evidence supports the following mechanism: numerical differences between attention backends affect candidate logits through either the current decoding step or historical KV contents; BF16 rounding then creates ties in some states, leaving the final choice to argmax tie-breaking. These ties do not always occur on the FlashInfer side.

No adapter defect was identified within the integration checks and controlled replays performed. However, the frozen-protocol result remains 58/87 for FlashInfer, below the 59/87 threshold. The findings below explain the divergence mechanism; they do not establish task-level accuracy equivalence or justify dismissing the regression.

Scope and experimental controls

  • Seven questions were instrumented, covering 288–384 attention calls per question. The swap grid below focuses on the three regressed questions.
  • Both histories were reconstructed using the same prompt and forced generated-token prefix. Prefix checksums, zero-based divergence positions, and position IDs were recorded.
  • Each experimental branch reconstructed its state in a separate engine, with independently saved snapshots. Repeated control replays were bit-identical for Q/K/V, attention outputs, hidden states, and logits.
  • Page tables and effective sequence lengths were bit-identical across backends. In the instrumented replays, the first tensor difference appeared at the layer-0 attention output.
  • On the tested frozen Q/K/V inputs, Triton matched the specified FP32 attention reference rounded to BF16 bit-for-bit. XQA exhibited reproducible deviations of approximately ±1 ULP. This observation alone neither establishes a violation of the upstream numerical contract nor implies unbiased task-level effects.

Swap experiments for the three regressions

"Current-step kernel replacement" below covers all 96 attention calls in the final decoding step, not an individual call.

Question and first divergence T history + T / X / reference kernel X history + T / X kernel T engine + X-KV + T kernel
360@24 6757 / 650 / 6757 6757 / 650 6757
819@90 216 / 216 / 216 1885 / 1885 1885
881@106 357 / 392 / 357 392 / 392 392

For this model, execution path, and these checkpoints, KV transplantation reproduced all call outputs and logits of the corresponding X-history cells bit-for-bit. Together with the implementation check confirming that decode does not carry hidden states across steps, this supports attributing the historical-path effect to KV contents.

Within the tested intervention scope:

  • q360: Replacing the current-step kernel alone is sufficient to flip the selection; replacing KV alone is not.
  • q819: Replacing KV alone is sufficient to flip the selection; replacing the current-step kernel is not.
  • q881: Either replacement is individually sufficient to flip the selection.

Output-head precision and tie-breaking

Using the same frozen hidden state and weights, we compared the production BF16 output head, an FP32 recomputation, and that FP32 result rounded back to BF16.

Let A denote the original Triton choice, B the original FlashInfer choice, and Δ = z_A − z_B. The three relevant tied states are:

Question Original path containing the tie FP32 recomputed Δ FP32 ranking favors Selection after the BF16 tie
q360 FlashInfer approximately +0.047 A: 6757 B: 650
q819 Triton approximately −0.023 B: 1885 A: 216
q881 Triton approximately −0.021 B: 392 A: 357

In these states, the candidate scores become equal after rounding, and argmax selects the lower token ID under its first-occurrence tie-breaking rule. This conclusion is based on the observed rounded values, not an assumption that a gap below a particular ULP threshold must produce a tie.

Across the six tested states, FP32 recomputation followed by rounding reproduced the production path's fixed-candidate scores and decisions. However, full-vocabulary logits have not been shown to match everywhere: full-vocabulary comparisons for the three T-history states found small differences in 2/2/4 elements, respectively. Full-vocabulary comparisons for X-history states have not yet been checked.

The FP32 ranking here refers only to output-head recomputation for a given frozen state, not an end-to-end FP32 model reference. For q819/q881, it favors FlashInfer's choice. This demonstrates that closer agreement with the local FP32 ranking does not guarantee a correct final answer; the task-level correct-to-incorrect flips remain valid observations.

Frozen-protocol rerun and current status

No fix was applied for this rerun:

  • Triton: 61/87.
  • FlashInfer: 58/87.
  • Each backend reproduced its own original generated token sequences exactly for all 87 questions.
  • Correct-to-incorrect flips remain 360, 819, and 881, with zero incorrect-to-correct flips.
  • The CUDA Graph, concurrency-1 performance recheck measured 64.4 versus 49.0 tok/s, retaining approximately 31% higher throughput.

We now have controlled causal evidence for the first divergence in all three questions, but task-level accuracy equivalence remains unproven, and the original acceptance threshold is still unmet.

I will continue investigating ways to improve numerical behavior while checking whether the performance benefit is retained. Experiments that change output-head precision or other computation paths will be reported separately, without question-specific decoding adjustments. Candidate changes will include explicit protocol differences, per-question gains and losses, and performance results. Please also review the current findings and let me know if there is a preferred optimization direction.

The diagnostic scripts, logs, and snapshots have been saved and are available for reproducing these experiments.

@yanbao1217

Copy link
Copy Markdown
Author

FlashInfer XQA scored 58/87 on frozen GSM8K-87, one answer short of the 59/87 acceptance threshold. Triton scored 62/87 under the same settings. Three of the four questions that only Triton passed were formatting losses: on questions 426, 745, and 819, XQA returned the correct amounts, but the strict scorer could not parse them with a leading dollar sign.

BF16 rounding in XQA attention contributed to the numerical loss on question 203. At the first differing attention row, rounding the unnormalized softmax weights to BF16 reproduced all 2,048 XQA output components. Substituting that row into Triton erased the 0.125-logit lead for 7 at token 15. Greedy decoding selected 5 on the tie, and the final answer changed from 31 to 27. The reverse swap left XQA’s answer at 27, so correcting that row alone was insufficient to recover the point.

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