← Back to Pull requests

perf: group tiny-KV GQA context requests on SM103 #8736

Closed
unknown closed this pull request without merging on Nov 05, 2026 18:33 UTC
View on GitHub
unknown unknown commented on Nov 05, 2026 00:57 UTC
Author

<!-- .github/pull_request_template.md -->

📌 Description

For BF16 paged context attention with two query tokens per request, the Context kernel schedules one CTA per query head even when each request has only a few KV tokens. This change selects the existing grouped Q32 generation kernel for the measured SM103 region: batch 4–256, maximum KV length 1–32, Hq/Hkv=16/1, head dimensions 128 and page size 128.

The dispatch retains packed HND/layout and feature restrictions, Context persistent scheduling and no split-KV workspace. A zero-default runner flag retains the initial Q32 tile so both query rows share a CTA, preserving fully masked-row writes. Other workloads keep their existing selection. Both the native context API and BatchPrefillWithPagedKVCacheWrapper(backend="trtllm-gen") benefit.

Observed on one B300 (SM103), CUDA 13.0.88, PyTorch 2.14.0+cu130, BF16 Q/K/V/output, causal Q2, H16/1, D128, page128, PDL enabled. Wrapper warm-graph medians for KV32:

| Batch | Context baseline (µs) | Grouped Q32 (µs) | Speedup |
| ---: | ---: | ---: | ---: |
| 4 | 6.770 | 5.980 | 1.13× |
| 64 | 23.393 | 6.310 | 3.71× |
| 256 | 79.175 | 8.888 | 8.91× |

At the original KV2/B64 shape, native latency falls from 23.446 to 6.317 µs (3.71×); the profiled grid changes from 1,024 CTAs to 64.

Measurements used matched inputs and serialized baseline/candidate/candidate-reversed/baseline-reversed runs, with 3 rounds of 10 samples per case. Warm timings amortize 100 calls per CUDA graph. The baseline disables only this dispatch branch on the same source based on a02329da80605b823ad64bf053fc5f744abcddf4. Source, loaded library, cubin and actual kernel-route identities were checked before accepting results. Across 48 warm comparisons, observed speedups are 1.117–8.936×; every baseline round median exceeds every candidate round median by at least 0.3 µs and 5%.

Cold one-call graph comparisons used an eviction buffer at least twice L2, excluded eviction work from timing, and checked outputs immediately after evicted replay. B64/B256 improve 2.325–5.250×; B4 is neutral. All 14 neighboring fallback and 12 mixed/long-KV comparisons remain on Context and show no material regression by the same 0.3 µs/5% separation criterion. These are observed-round comparisons, not statistical confidence intervals.

🔍 Related Issues

Related to https://github.com/flashinfer-ai/flashinfer/issues/7965. This PR covers the validated BF16 subset; exact GB300 and the original FP8 comparison remain open.

🚀 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

  • I have installed pre-commit by running pip install pre-commit (or used your preferred method).

  • I have installed the hooks with pre-commit install.

  • I have run the hooks manually with pre-commit run --all-files and fixed any reported issues.
  • The changed-file equivalent was run and passed; the all-files checkbox is intentionally unchecked.

    If you are unsure about how to set up pre-commit, see the pre-commit documentation.

    🧪 Tests

  • Tests have been added or updated as needed.

  • All tests are passing (unittest, etc.).

  • This PR requires full-scope CI, not targeted tests (expensive; justify below).

  • Reason: Targeted attention coverage; full-repository CI is not requested.

    Suggested CI test targets (optional; paths under tests/, whitespace-separated — a starting
    point for @flashinfer-bot run <targets> / /bot run <targets>, reviewers may adjust): tests/attention/test_trtllm_gen_attention_prefill.py tests/attention/test_trtllm_gen_attention_decode.py

    Targeted GPU validation completed on B300:

    python3 -m pytest tests/attention/test_trtllm_gen_attention_prefill.py -q -k tiny_kv
    # 76 passed, 14906 deselected
    

    Coverage includes independent FP64 references, nonunit scalar/device scales, native/wrapper graph input/scale updates, changing device KV lengths, finite-sentinel empty/fully masked writes, and neighboring feature/layout/shape fallbacks. Production probes additionally validate wrapper metadata updates and actual dispatched kernels. All 344 case/API/run rows across 16 benchmark processes passed.

    Changed-file pre-commit checks pass. The full repository suite was not run.

    <details>
    <summary>Warm-shape reproduction using public APIs</summary>

    Run this recipe on the base revision above and the PR head in the same B300/software environment, after the targeted correctness checks on the PR. It reproduces the shape and warm-graph timing method; it is a source-checked convenience recipe, not the harness that produced the table or a new validation result.

    from statistics import median
    
    import torch
    import flashinfer
    from flashinfer.testing import bench_gpu_time
    
    torch.manual_seed(7965)
    device, dtype = "cuda", torch.bfloat16
    workspace = torch.empty(128 << 20, device=device, dtype=torch.uint8)
    print("batch,kv,median_us")
    for batch in (4, 8, 64, 256):
        q = torch.randn(batch * 2, 16, 128, device=device, dtype=dtype)
        kv = torch.randn(batch, 2, 1, 128, 128, device=device, dtype=dtype)
        out = torch.empty_like(q)
        qo = torch.arange(batch + 1, device=device, dtype=torch.int32) * 2
        indptr = torch.arange(batch + 1, device=device, dtype=torch.int32)
        indices = torch.arange(batch, device=device, dtype=torch.int32)
        for length in (1, 2, 5, 16, 31, 32):
            lengths = torch.full((batch,), length, device=device, dtype=torch.int32)
            wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper(
                workspace, "HND", backend="trtllm-gen", use_cuda_graph=True,
                qo_indptr_buf=qo, paged_kv_indptr_buf=indptr,
                paged_kv_indices_buf=indices,
                paged_kv_last_page_len_buf=lengths,
            )
            wrapper.plan(
                qo, indptr, indices, lengths, 16, 1, 128, 128, causal=True,
                q_data_type=dtype, kv_data_type=dtype, o_data_type=dtype,
                block_tables=indices[:, None], seq_lens=lengths,
                max_token_per_sequence=2, max_sequence_kv=length,
            )
    
            def run():
                return wrapper.run(q, kv, out=out, enable_pdl=True)
    
            run()  # Compile/initialize before timing.
            samples = []
            for _ in range(3):
                samples.extend(bench_gpu_time(
                    run, dry_run_iters=10, repeat_iters=10,
                    num_iters_within_graph=100, use_cuda_graph=True,
                    enable_cupti=False, cold_l2_cache=False,
                ))
            print(f"{batch},{length},{median(samples) * 1000:.3f}")
    

    The repository benchmark CLI can also exercise KV≥2, but currently rejects Q2/KV1 and uses cold-L2 timing; its numbers should not be equated with the warm table.

    </details>

    🔬 Experimental Track

    <!-- Only for PRs submitted under the experimental policy (CONTRIBUTING.md → "Experimental APIs and Backends").
    Leave this section untouched for normal PRs. -->

  • This PR is experimental: it adds or changes code under 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 from backend="auto" without FLASHINFER_ALLOW_EXPERIMENTAL_AUTO_BACKENDS=1. (Calling an @flashinfer_experimental_api or 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-tests tag — the experimental-track
    watcher 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

  • Exact GB300 NVL validation remains open. B300 evidence is preliminary for the issue's target.

  • This is a BF16 optimization; it does not establish FP8/FlashAttention parity or end-to-end serving benefit.

  • Only uniform actual KV equal to the declared maximum is timed. Shorter/mixed/empty actual lengths receive correctness coverage. Intermediate eligible batch/KV values are sampled interpolation; B4 has no demonstrated cold-cache gain.

  • Retaining Q32 is a compatibility choice as well as a scheduling choice: a Q16 experiment left fully masked leading rows unwritten.

  • The new runner flag defaults to false; ordinary decode keeps the existing occupancy model.

  • Review focused on dispatch bounds, workspace compatibility, numerical/masked-write behavior and graph replay. No required findings remain.
  • <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

    Improvements
    Small-KV context attention now uses an optimized processing path for a specific workload on compatible GPUs. Existing attention options and output behavior remain supported.
    * Improved handling covers short and empty KV sequences, varying sequence lengths, and replay after input changes.

    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: qsang-nv Review duration: 1056m
    All Vouch review confidence checks passed
    Residual risk 0.25 = Change Risk (0.57) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 650 lines diff across 8 files
    0.57
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #8736"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% 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: 57% (MEDIUM) · Higher = larger blast radius
    57%
    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: 56.8% · Lower = rushed or shallow review
    56.8%
    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: 24.7% · Safe to merge
    24.7%