← Back to Pull requests

Add optional sparse-prefill statistics without conversion launches #17

Closed
unknown closed this pull request without merging on Oct 19, 2026 19:57 UTC
View on GitHub
unknown unknown commented on Oct 02, 2026 13:59 UTC
Author

Motivation

SGLang's compatibility entry point csrc/python_api.cpp::sparse_prefill_fwd currently launches two Tensor::mul_ kernels after attention to convert max_logits and lse from natural-log to base-2 units. For short H64 prefill, these launches cost about 2.2–2.5 us even under CUDA Graph replay.

This removes compatibility-layer overhead, not attention computation. Following DarkSharpness's review, sparse prefill now supports optional statistics without post-attention mul_ launches on any supported prefill path. Native FlashMLA keeps its natural-log default.

Related: https://github.com/sgl-project/sglang/pull/41512 skips these conversions for a packed output-only serving API. This change instead preserves all three outputs on the ordinary H64 API. It does not add conversion savings to that packed output-only path. When combined with #14, its packed parameter initializer and the downstream dependency pin will need updating.

Changes

  • Add return_log2_lse: the SGL compatibility API defaults to True, preserving its base-2 statistics; False returns (output, None, None) and skips both statistics allocations/stores.

  • Preserve the native API's existing natural-log default with return_log2_lse=None. Explicit True requests base-2 statistics; False requests output only. This intentional default distinction avoids silently changing existing native callers' numerical contract. Legacy seven-argument native calls still work, and the returned list container is preserved.

  • Write requested units in the SM90 and SM100-family H64/regular-H128/small-topk-H128 epilogues. There are no host Tensor::mul_ conversions in either statistics-enabled or output-only mode.

  • Preserve the parameter layout, decode branches, attention/sink normalization, synchronization, and inherited fused norm/RoPE behavior.

  • Extend native tests across all three modes, masks/empty attention, both head dimensions/head counts, top-k 128/512/2048, legacy calls, sinks, and graph replay after Q mutation. The paired SGLang PR opts both ordinary DSA and DeepSeek V4 serving callers out of unused statistics.
  • No head-width/dispatch expansion, QK/PV changes, shared-memory/TMEM layout changes, or decode changes. Sinks still affect only output normalization. Empty-row sentinels remain output=0, max=-inf, LSE=+inf. Auxiliary results are numerically equivalent, not promised bitwise identical after eliminating the max's base2->natural->base2 round trip.

    Historical fusion-only A/B

    The measurements below validated the earlier 1dd928b implementation, not the latest optional-statistics API changes. H128 still had the two conversion launches in that measured implementation.

    Clean baseline from 3620b63, versus that patch; identical compiler flags, inputs, allocation contracts, and all three outputs. Built separate symbol-isolated DSOs from the actual C++ entry points, with a third same-binary control that restores the two multiplies. No native-head or Gluon experiment code is included.

    Median of nine interleaved CUDA-graph measurements; 32 real H64 queries, D512, 8192 cached tokens:

    | GPU | Top-k | Original us | Fused us | Speedup |
    |---|---:|---:|---:|---:|
    | GB200 | 128 | 8.533 | 6.374 | 1.34x |
    | GB300 | 128 | 8.925 | 6.454 | 1.38x |
    | GB200 | 512 | 14.620 | 12.417 | 1.18x |
    | GB300 | 512 | 14.664 | 12.203 | 1.20x |
    | GB200 | 2048 | 38.337 | 36.211 | 1.06x |
    | GB300 | 2048 | 37.385 | 34.960 | 1.07x |

    The restored-multiplies control at top-k128 is 8.543/8.925 us respectively, matching the original rather than the fused path. Profiling confirms 3 GPU kernels -> 1 for H64, while H128 correctly retains 3. The one-kernel regression test fails on the untouched baseline and passes on the candidate.

    Additional sweeps varied queries 1/32/128/512, D512/D576, top-k128/512/2048, and selected KV allocations 1K/8K/128K/1M. These are operator microbenchmarks, primarily warm-cache graph replay, not model throughput or a blanket 30% gain for arbitrary contexts. Eviction controls were also checked, but are not used for the headline result.

    Validation

    Fresh optional-API validation (6f9da943b2454d46af89bcb0cf3e67aae4203ed6): 144/144 native prefill cases passed on GB300/SM103 with CUDA 13.0.88 and PyTorch 2.14.1+cu130, including natural-log defaults, explicit base-2/output-only modes, legacy seven-argument calls, masks/empty rows, sinks, regular/small-topk H128, H64, D512/D576, and mutated CUDA Graph replay. These used a separately compiled prefill-only DSO with the actual native pybind registration and unmodified Python facade, not a complete installed FlashMLA wheel. The paired merged SGLang head 0fb8a8f742 now built its actual SM100f/SM103a CMake flashmla_ops target, including both bindings and all 18 Mega CUDA sources. Against that real target, optional-statistics tests passed 193/193, MegaAttention 4/4, serving caller contracts 37 with 2 SM90-only skips, and server-args 428/428: 662 passed / 2 architecture skips / 0 failures/errors. The profiler cases confirm a single attention kernel with no statistics-conversion launches for True/False, H64/H128, D512/D576, and small/regular top-k paths. This is a full FlashMLA target build, not a complete SGLang wheel/all-common-ops rebuild or Hopper validation. Earlier isolated compatibility/boxing evidence at 5e7360cc64 remains separately archived, not relabeled.

    Native job 1218787 completed in 3m37s; compatibility retry 1220016 in 11m59s; actual merged-target CPU build 1220991 in 10m06s and GPU tests 1221154 in 1m47s. All allocations were released; cumulative related four-GPU time is 18m23s. Evidence: /tmp/fresh-review-evidence-bd90b/optional-stats/results/native.xml, results/retry/optional-stats/, and results/merged-full-aot/ in the author's environment. Python AST/compile, targeted formatting/lint, mocked wrapper forwarding, layout/synchronization static comparisons, independent changed-code review, and git diff --check also pass. No numerical tolerances were relaxed. Full wheel CI and Hopper runtime coverage remain outstanding.

    Historical validation of 1dd928b, CUDA 13.0, PyTorch 2.13.0+cu130, aarch64, on GB200 and GB300:

  • 192 numerical/graph-mutation cases per GPU: H64/H128, D512/D576, two top-k sizes, optional sinks/lengths, invalid/empty rows, negative/rising logits, extreme sinks, and strided inputs.

  • Independent FP32 references for both native natural-log and compatibility base-2 statistics; output bitwise equal to the baseline in these A/B cases.

  • Another 48 cases with reversed library load order, guarding against symbol-interposition artifacts.

  • 77 PR tests pass per GPU: 16 native tests using the actual native pybind registration/Python facade, plus 61 companion SGLang tests using its Python facade and the actual compatibility C++ function through an isolated operator adapter. No installed package was overwritten.

  • Prefill CUDA TUs compiled for SM90a/SM100f/SM103a. Also compiled the fused norm/RoPE C++ API and representative H64/H128 fused-prefill CUDA TUs after updating their inherited parameter initialization.

  • Python formatting/lint and git diff --check pass.
  • Remaining: full repository/wheel CI and Hopper runtime coverage. No claim of whole-library sanitizer cleanliness or end-to-end serving improvement. Ready for review; full wheel CI and Hopper runtime validation remain outstanding. Companion SGLang pin update and compatibility-unit/launch-count tests: https://github.com/sgl-project/sglang/pull/42232.

    Native test: python -m pytest -q tests/test_sparse_prefill_stats_units.py.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: DarkSharpness Review duration: 24838m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    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%
    60%
    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
    Real PR Conversation Timeline
    1 comments
    "Review active on #17"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 60.5% · Lower = rushed or shallow review
    60.5%
    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: 20.5% · Safe to merge
    20.5%