← Back to Pull requests

feat(prims-ts): support independently inferred device global scales #8093

Closed
unknown closed this pull request without merging on Nov 06, 2026 19:32 UTC
View on GitHub
unknown unknown commented on Oct 31, 2026 05:06 UTC
Author

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

📌 Description

Dynamic per-input FP8 attention, including TRT-LLM VisualGen, computes current-input descales on the GPU. Its effective QK multiplier is attention_scale q_descale k_descale and its output multiplier includes v_descale. Converting those values to Python floats requires device-to-host synchronization; caching them once would use stale scales, and captured floats cannot observe later GPU updates. Add independent host-float or scalar-shaped or one-element CUDA FP32 global scales throughout PrimTS while retaining runtime scalar values and existing quantization/layout gates.

plan() infers each argument kind from its scale defaults. run() inherits omitted defaults or binds same-kind overrides. Callers can independently select float/float, float/tensor, tensor/float, or tensor/tensor without a separate mode flag. Softmax scales use natural-exponential units for either type. Tensor values are read inside the GPU kernel; type and metadata checks never read their contents.

Coverage includes contiguous/paged context, standard and prepared decode, QToken sparse attention, dense/sparse MLA, and contiguous/paged block-sparse attention. Sparse MLA also supports a device kv_cache_scale for its FP8-primary format. Block-sparse attention gains an optional global output_scale multiplier. Existing Sage/VC block/channel scale tensors and generated output-quantization scale buffers keep their separate roles.

Compilation and persistent-cache identities include only the independently inferred scale kinds, never values or tensor addresses. Global softmax conversion uses FP32 arithmetic: float operands convert in compiled host launchers, and tensor operands load/convert in device kernels; the standalone decode reducer drops unused scale arguments. Trace schemas and examples represent device inputs without scalar readback.

🔍 Related Issues

  • #6925 introduced the current host-runtime global-scale ABI.

  • #8021 covers paged decode with a paired device-scale flag. This PR includes that behavior through independent type inference and covers the other PrimTS entry points.

  • NVIDIA/TensorRT-LLM#21354 preserves live FP8 context scales in its upstream refresh compatibility patch.
  • 🚀 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.
  • 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: <!-- e.g. cross-cutting change to shared infrastructure -->

    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_attention_ts_block_sparse.py tests/attention/test_attention_ts_context.py tests/attention/test_attention_ts_context_sage.py tests/attention/test_attention_ts_decode.py tests/attention/test_attention_ts_features.py tests/attention/test_attention_ts_mla_decode.py tests/attention/test_attention_ts_q_token_kv_block_sparse_metadata.py tests/attention/test_attention_ts_sage.py tests/attention/test_attention_ts_sparse_mla.py tests/attention/test_attention_ts_vc.py tests/trace/test_prims_ts_global_scales.py tests/trace/test_fi_trace_template_consistency.py tests/cpu/trace_apply/test_trace_apply.py

    Validation

    Rebased onto FlashInfer main 2f8cd0a1e7069b4f6c3f5db35b01fb28ac3af7ff. Resolved one localized conflict in the 2CTA MLA launcher by retaining upstream staged BF16 output handling together with the PR's host/device scale paths. git range-diff confirms all 13 commits remain patch-equivalent; the changed-file sets are identical, and upstream MLA additions/removals are preserved exactly. No follow-up rebase-fallout commit was needed.

  • Latest revision 56fa98b5d: 7 targeted GPU tests passed on B200 (SM100), PyTorch 2.13.0+cu129 / CUDA 12.9 / CuTe DSL 4.8.1. Coverage includes dense MLA 1CTA/2CTA device scales, sparse MLA device-scale graph replay and its synchronization guard, native FP8 staged BF16 output with prefix/holes, persistent NVFP4, and mixed FP8/NVFP4 host scales. All changed-file pre-commit checks, syntax compilation of 28 Python files, and diff checks pass.
  • Prior revision 8dcc2fb23: 13 reduced GPU regressions passed on B300 with fresh caches; 4 existing rebase controls passed (MXFP8 dense/causal, packed-query statistics, and paged sliding-window attention).

  • 1,275 CPU checks passed, 2 skipped, covering shared scale validation, trace consistency, actual Trace Apply routing/fallback, and context/MXFP8 contracts. Scoped pre-commit and syntax checks pass. Three independent review passes found zero open code issues.

  • Added GPU cases were reduced 21 → 13; explicitly added CPU cases 422 → 48. Metadata-only scale contracts use CPU/FakeTensor. Independent numerical references and tolerances are unchanged. Live scale updates, non-unit output scaling, Sage mean restoration, prepared/one-shot APIs, independent sparse FP8 cache scaling, both MLA schedules, and delayed PDL producers remain covered.

  • In one same-node cold-cache comparison of the old and reduced GPU selections, 21 cases / 23 recorded JIT builds / 558.3 s became 13 cases / 18 builds / 418.2 s, including imports and prewarm. Both runs passed and used matching production source, GPU, CPU affinity, Python/Torch/DSL, and compiler settings. Common build times varied materially, so the observed 140.1 s reduction is one local comparison, not a universal CI speedup.

  • Earlier validation: the full existing PrimTS attention suite passed 2,519 cases with 111 skips; a compiled-host/device-tensor probe matched 4,090 FP32 conversions exactly and 12 overflow rejections; standalone-reducer cache validation shared one reducer across four producer scale-kind variants and reloaded in a fresh process without compilation. Those broader/local probes were not added to CI.

  • Environment: NVIDIA B300 SXM6 AC (SM103), PyTorch 2.14.0+cu130, CuTe DSL 4.8.0. The full PR diff contains no newly added NVIDIA copyright/license notices; existing upstream notices remain intact.
  • PDL review follow-up

    Answered the gate-restoration request: the removed MLA capability gate was newly introduced by this PR and constant true for currently supported MLA devices. The matching producer launch/wait conditions and the race fix remain; existing decode/QToken controls are unchanged. The thread remains open for maintainer agreement.

    Host-float regression check

    On the same B300 allocation, two ABBA blocks (eight fresh processes, four per revision) compare main 17481d293 with review-fix revision 3e75b4499. Each process uses deterministic inputs, preallocated outputs, 20 warmup calls, and 31 samples. CPU submission uses batches of eight eager validate=False calls with synchronization outside the timed segment; GPU timing uses CUDA events around a 32-call graph. All independent reference checks pass before and after timing. Numbers below are medians of the four process medians.

    | Host-float case | CPU submission, main → revised | Change | Graph GPU, main → revised |
    | --- | --- | --- | --- |
    | Context BF16 B1 H32/Hkv32 D128 Q/K2048 | 5.740 → 5.874 us | +2.34% | 36.920 → 36.919 us |
    | Decode BF16 B4 H8/Hkv2 D128 KV4096 | 17.067 → 16.618 us | -2.63% | 6.695 → 6.695 us |
    | MLA BF16 B8 H128 D576/V512 KV8192 | 19.805 → 19.680 us | -0.63% | 21.225 → 21.222 us |

    At that revision, these three representative host-float cases did not show the reported 10–16% submission regression; they do not establish performance across all shapes or a model-throughput improvement. Measurements are scoped to prepared-wrapper calls and use the same test fixtures and dependency stack on both revisions.

    Ordering and cache corrections

  • Omitted runtime scales reuse normalized plan operands through resolve_scale; both context wrappers use that helper directly. Context passes original operands to FmhaTs.__call__() and uses FP32 for both conversion paths. Its input-bound check protects the later launcher conversion without inspecting tensor values. Mixed internal operands are named softmax_scale_operand; scale_softmax_log2 identifies resolved base-2 scalars.

  • Device scale loads in persistent decode occur after the existing deferred dependency acquire and split pruning, immediately before task execution, preserving prologue overlap.

  • The nonpersistent decode acquire precedes producer-owned packed-Q offsets used for tile pruning.

  • The 2CTA MLA producer now waits before reading producer-owned inputs. This fixes a pre-existing PDL race and also affects host-float execution. The new producer wait follows the existing nonpersistent split-KV launch condition. Producer/reducer PDL otherwise retains the existing scheduling conditions.

  • The standalone reducer's persistent identity canonicalizes scale kinds because its ABI does not contain scale operands.

  • All eight affected trace dispatchers publish canonical tensor-scale variants for Trace Apply. Bound scale defaults and zero-dimensional views reach replacement solutions; 36 real routing cases and eight registry checks cover this integration. The shared resolver reuses runtime validation for host values and CUDA device placement, while preserving CPU/meta schema-only tracing and omitted defaults. Invalid host values and malformed or misplaced tensors fall back to the original API instead of reaching a replacement solution. Existing dynamic-template fallback for plan-specific decode/MLA wrappers is preserved.
  • 🔬 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

    Please focus on eager plan/type binding, cache identity and tensor lifetimes, scalar-to-device loading before PDL consumers, softmax units, and applying output scales exactly once through Sage means and split reductions.

    Host scalar values are captured by value. Tensor defaults/overrides must remain alive at their captured addresses; their contents may change between replays. Changing operand kinds requires replanning before capture. Device values must remain positive and finite.

    This updates the existing experimental PrimTS entry points and their established test locations under the normal review process; it does not request a new experimental-track CI lane. No AOT registration or automatic backend selection is added.

    Latest targeted validation: 56fa98b5dcb00edc3524ad3bc47d062de1d913ea`. Earlier broad-suite and performance measurements are identified above. Hosted CI requires an authorized maintainer: public CI and internal CI previously rejected this account. No new CI trigger comment was posted after this rebase.

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->
    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

    New Features
    Attention APIs for context, decode, block-sparse, MLA, and QToken KV-block-sparse workloads now accept positive finite Python numbers or supported CUDA FP32 scalar tensors as global scales.
    Added output scaling to block-sparse attention and expanded scale options for sparse MLA, including FP8 KV-cache scaling.
    Runtime overrides can change scale values when they retain the planned scalar-or-tensor type. CUDA graph replay supports updated device-tensor scale values without rebuilding plans.
    Attention tracing now supports scale-aware variants.
    Documentation
    * Clarified scale formats, defaults, validation, and graph-replay behavior.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: qsang-nv Review duration: 9506m
    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 #8093"
    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%