← Back to Pull requests

feat: add FlashInfer attention backend for SM120 decode #112

Open
yanbao1217 opened this pull request with 569 lines diff across 14 files
View on GitHub
yanbao1217 yanbao1217 commented on Oct 10, 2026 08:14 UTC
Author

Adds flashinfer as a selectable paged-decode attention backend (FlashInfer XQA kernels, flashinfer-python >= 0.7.0), giving RTX 50-series (SM120) a second attention path alongside Triton. FlashAttention 2/3/4 reject SM120 for paged KV, so Triton is currently the only option there. Refs #69.

Rebased onto the merged attention contract layer (2534e24 + 3defab4): FlashInfer registers through vllm_rlt.attention with explicit selection and an auto slot between FlashAttention-2 and Triton, declaring BackendCapabilities(cuda_graphs, async_scheduling). The SM gate keeps auto away from FlashInfer on SM8/9/10, so auto only reaches it where every FlashAttention generation is rejected.

Scope

  • Decode and per-token prefill with Triton-equivalent semantics, including CUDA Graph capture and asynchronous scheduling.

  • No packed prefill: the FA4-only path stays closed because the adapter provides no prefill entry point. No prefill/decode disaggregation.

  • float16 rejected at startup: kernels compute correctly, but the 0.7.0.post1 f16 JIT module crashes the process (host SIGFPE) on first in-process use on SM120.

  • Explicit startup validation: page sizes {16, 32, 64, 128} (compiled XQA variants), head_dim divisible by 16 within [16, 512], SM major {9, 10, 12} — validated on 120 only.
  • Design notes

  • Thin translator over the existing five-argument attention contract: empty-batch early return (a zero-size batch host-crashes the kernel dispatch), block_tables clamped non-negative so -1/zero/stale graph-replay padding stays invisible, seq_lens cast to uint32, explicit kv_layout="NHD".

  • The 128 MiB kernel workspace allocates lazily on first execution, so backend selection itself performs no device allocations; engines profile before any graph capture, so the workspace exists by then.

  • Auto-selection tests cover the SM120 matrix (FlashInfer selected when installed, Triton when the package is missing) and explicit no-fallback behavior.
  • Validation (RTX 5090, Ouro-1.4B BF16, block_size=16, four-loop decode)

  • CPU suite: 501 passed, 125 skipped (excluding six pre-existing test_scheduler_selection.py failures on current main: OuroConfig.tiny is missing); ruff clean.

  • GPU suite: oracle parity on non-contiguous layer slices; padding tri-state bitwise-invisible (-1 / zero / stale replay ids); zero-length rows exact zeros; batch-composition determinism (rtol=0, atol=0); CUDA-graph capture with rewritten buffers; token/exit-depth equality against Triton across sync/async/multi-stream x last_exited/shared x static buffers.

  • Real-model greedy generation smoke: coherent output with fixed-depth exits.

  • GSM8K-87 (single greedy pass, frozen protocol, HF baseline 59): Triton 61, FlashInfer 58. 64/87 generations are token-identical between the two backends; the 23 divergent ones flip near-tied greedy argmax decisions at scattered positions with unchanged exit depths. Kernel-level deviation vs a float32 oracle is 1e-3..4e-3 — exactly one BF16 ulp (the Triton kernel is near-exact by comparison because it shares the oracle's serial order). Documented in docs/flashinfer.md; Triton remains the default backend.
  • Environment requirements (docs/flashinfer.md)

    pip install -e ".[flashinfer]", plus a CUDA toolkit with nvcc >= 12.9 reachable via CUDA_HOME (the kernels JIT-compile for compute_120f) and that toolkit's lib directory on LD_LIBRARY_PATH.

    Follow-ups

  • Packed prefill support: generalize the remaining generation == 4 gate sites now that capabilities are declared.

  • Greedy-parity numerics (investigated, negative so far): the XQA path rejects float32 outputs (xqa.py asserts output dtype matches query), and 0.7.0.post1 → 0.7.1rc2 contains zero XQA changes, so no reduction-precision knob exists today; the 1-ulp difference is inherent to the different accumulation order. Remaining option: logit-gap forensics on the three flipped GSM8K answers.

  • Matched low/high-concurrency throughput report against Triton as a separate results PR.
  • 🤖 Generated with Claude Code

    Diff: 569 lines (+547 / -22) across 14 files Reviewer: 0z5a Review duration: 9949m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.65) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.65 · 569 lines diff across 14 files
    0.65
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 4 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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.380
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    6 items
    yanbao1217 yanbao1217 commented on Oct 10, 2026 13:24 UTC
    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 #48).
  • 🤖 Generated with Claude Code

    0z5a 0z5a commented on code on Oct 10, 2026 14:51 UTC
    Code Review
    vllm_rlt/attention/backend.py:1
    @@ -47,15 +48,16 @@ def generation(self):
         3: BackendCapabilities(cuda_graphs=True, async_scheduling=True),
         4: BackendCapabilities(packed_prefill=True, cuda_graphs=True, async_scheduling=True),
     }
    -_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")

    [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.

    0z5a 0z5a requested changes on Oct 10, 2026 14:51 UTC
    Changes Requested Reviewer

    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.

    yanbao1217 yanbao1217 commented on Oct 10, 2026 15:01 UTC
    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.

    bjf-frz bjf-frz commented on Oct 12, 2026 08:39 UTC
    Contributor

    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.

    Reviewers
    Assignees
    yanbao1217 yanbao1217
    Labels
    risk: low confidence: 90.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 65% (HIGH) · Higher = larger blast radius
    65%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.1% · Lower = rushed or shallow review
    90.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.4% · Safe to merge
    6.4%