[None][feat] integrate PrimTS FMHA kernels - #17399
Conversation
74f5bf0 to
69753c5
Compare
|
/bot run |
|
PR_Github #70067 [ run ] triggered by Bot. Commit: |
|
PR_Github #70067 [ run ] completed with state
|
|
/bot run |
1 similar comment
|
/bot run |
9969311 to
586531d
Compare
|
/bot run |
|
PR_Github #70140 [ run ] triggered by Bot. Commit: |
|
PR_Github #70140 [ run ] completed with state
|
Re-vendor the PrimTS source after restoring its upstream trace imports and preserve TensorRT-LLM package compatibility in the generated vendor patch. Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
63aaadc to
895c2c2
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #71688 [ run ] triggered by Bot. Commit: |
|
PR_Github #71663 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #71714 [ run ] triggered by Bot. Commit: |
|
PR_Github #71688 [ run ] completed with state |
|
PR_Github #71714 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #71724 [ run ] triggered by Bot. Commit: |
|
PR_Github #71724 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #71761 [ run ] triggered by Bot. Commit: |
|
PR_Github #71761 [ run ] completed with state |
… backends NVIDIA#17899 moved tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py under the new kv_cache/ subpackage. NVIDIA#17399, which added the phased and PrimTS FMHA libraries, was in flight at the same time and still imports the old path, so main now fails at: ModuleNotFoundError: No module named 'tensorrt_llm._torch.pyexecutor.kv_cache_manager_v2' fmha/__init__.py imports phased and prims_ts, and attention/backends/__init__.py reaches fmha through trtllm.py, so the whole attention.backends package is unimportable and every unit test that touches an attention backend fails collection. Point the three fmha modules and the three FMHA unit tests at pyexecutor.kv_cache.kv_cache_manager_v2, matching the sibling backends (interface.py, sparse/dsa/cache_manager.py). Adds a CPU-only import guard so a future move of this module is caught by the unit tests. Signed-off-by: Brian Nguyen <brnguyen@nvidia.com>
…ak main Two module moves landed while dependent PRs were in flight, and main now fails to import the PyTorch runtime: 1. NVIDIA#17899 moved tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py under the new kv_cache/ subpackage. NVIDIA#17399, which added the phased and PrimTS FMHA libraries, still imports the old path: ModuleNotFoundError: No module named 'tensorrt_llm._torch.pyexecutor.kv_cache_manager_v2' fmha/__init__.py imports phased and prims_ts, and attention/backends/__init__.py reaches fmha through trtllm.py, so the whole attention.backends package is unimportable. 2. NVIDIA#17968 moved tensorrt_llm/_torch/attention_backend/ to tensorrt_llm/_torch/attention/backends/. NVIDIA#18652 extracted pyexecutor/engine/lora.py with the old path, and model_engine.py imports engine.lora, so the executor is unimportable even with (1) fixed. Point the three fmha modules, engine/lora.py and the affected unit tests at the current paths, matching the sibling modules. Adds a CPU-only import guard covering both chains so a future move is caught by the unit tests. Signed-off-by: Brian Nguyen <brnguyen@nvidia.com>
…ak main Two module moves landed while dependent PRs were in flight, and main now fails to import the PyTorch runtime: 1. NVIDIA#17899 moved tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py under the new kv_cache/ subpackage. NVIDIA#17399, which added the phased and PrimTS FMHA libraries, still imports the old path: ModuleNotFoundError: No module named 'tensorrt_llm._torch.pyexecutor.kv_cache_manager_v2' fmha/__init__.py imports phased and prims_ts, and attention/backends/__init__.py reaches fmha through trtllm.py, so the whole attention.backends package is unimportable. 2. NVIDIA#17968 moved tensorrt_llm/_torch/attention_backend/ to tensorrt_llm/_torch/attention/backends/. NVIDIA#18652 extracted pyexecutor/engine/lora.py with the old path, and model_engine.py imports engine.lora, so the executor is unimportable even with (1) fixed. Point the three fmha modules, engine/lora.py, the visual-gen FlashInfer backend and the affected unit tests at the current paths, matching the sibling modules. Adds a CPU-only import guard covering both chains so a future move is caught by the unit tests. Signed-off-by: Brian Nguyen <brnguyen@nvidia.com>
…ak main Two module moves landed while dependent PRs were in flight, and main now fails to import the PyTorch runtime: 1. NVIDIA#17899 moved tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py under the new kv_cache/ subpackage. NVIDIA#17399, which added the phased and PrimTS FMHA libraries, still imports the old path: ModuleNotFoundError: No module named 'tensorrt_llm._torch.pyexecutor.kv_cache_manager_v2' fmha/__init__.py imports phased and prims_ts, and attention/backends/__init__.py reaches fmha through trtllm.py, so the whole attention.backends package is unimportable. 2. NVIDIA#17968 moved tensorrt_llm/_torch/attention_backend/ to tensorrt_llm/_torch/attention/backends/. NVIDIA#18652 extracted pyexecutor/engine/lora.py with the old path, and model_engine.py imports engine.lora, so the executor is unimportable even with (1) fixed. Point the three fmha modules, engine/lora.py, the visual-gen FlashInfer backend and the affected unit tests at the current paths, matching the sibling modules. Adds a CPU-only import guard covering both chains so a future move is caught by the unit tests. Signed-off-by: Brian Nguyen <brnguyen@nvidia.com> (cherry picked from commit 0c221e3) Signed-off-by: Brian Nguyen <brnguyen@nvidia.com>
…ak main Two module moves landed while dependent PRs were in flight, and main now fails to import the PyTorch runtime: 1. NVIDIA#17899 moved tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py under the new kv_cache/ subpackage. NVIDIA#17399, which added the phased and PrimTS FMHA libraries, still imports the old path: ModuleNotFoundError: No module named 'tensorrt_llm._torch.pyexecutor.kv_cache_manager_v2' fmha/__init__.py imports phased and prims_ts, and attention/backends/__init__.py reaches fmha through trtllm.py, so the whole attention.backends package is unimportable. 2. NVIDIA#17968 moved tensorrt_llm/_torch/attention_backend/ to tensorrt_llm/_torch/attention/backends/. NVIDIA#18652 extracted pyexecutor/engine/lora.py with the old path, and model_engine.py imports engine.lora, so the executor is unimportable even with (1) fixed. Point the three fmha modules, engine/lora.py, the visual-gen FlashInfer backend and the affected unit tests at the current paths, matching the sibling modules. Adds a CPU-only import guard covering both chains so a future move is caught by the unit tests. Signed-off-by: Brian Nguyen <brnguyen@nvidia.com> (cherry picked from commit 0c221e3) Signed-off-by: Brian Nguyen <brnguyen@nvidia.com>
## 📌 Description This PR extends PrimTS contiguous block-sparse attention with **proxy compensation** and a packed **bitmask** sparse format. The proxy path keeps selected blocks exact while approximating omitted KV blocks with one arithmetic-mean K summary and one summed-V summary per semantic KV block. Route preparation emits score-keep metadata so a block already covered by an exact route is not counted again by its proxy. The softmax denominator is corrected by the represented token mass, including the true length of the final partial KV block. ### Sol-Attn motivation and scope This PR is intended to provide the PrimTS **core-attention** substrate for [Sol-Attn's sparse-attention flow](https://github.com/NVlabs/Sana/tree/sol-engine/techniques/sparse_backends), described in the [Sol-Attn paper](https://arxiv.org/abs/2607.24027). Sol-Attn identifies critical KV blocks for exact computation and reuses block-level proxy information from omitted blocks to approximate their contribution during online softmax. At the API boundary, the intended flow is: `prediction / routing (out of scope) → exact-block BSR or bitmask + K/V summaries → PrimTS route preparation → proxy-compensated core attention` This PR implements only the PrimTS route-preparation and core-attention stages. It does **not** include the Sol-Attn predictor, thresholding and exact-block selection, summary generation, or the end-to-end Sana integration; callers provide the selected-block metadata and K/V summaries. ### Bitmask format In addition to canonical BSR `block_indptr` / `block_indices`, contiguous block-sparse attention can now consume packed `UInt32` exact-block bitmaps owned per `(batch, KV head, Q block)`. Each bit selects one semantic KV block and out-of-range padding bits in the final word are ignored. BSR and bitmask inputs are prepared into the same internal route stream, so the attention core remains format-independent. Bitmask and proxy modes can be combined: set bits use raw K/V exact routes, while unset blocks are represented by proxy summaries. Both reusable plan/run and one-shot contiguous APIs are supported. Proxy execution currently requires a dense mask; paged-KV proxy execution is outside this PR. The PR also teaches Trace Apply to honor a runtime-selected trace template, which keeps BSR/bitmask and exact/proxy schemas isolated instead of binding every call to template zero. ## 📊 Proxy overhead Controlled A/B on one NVIDIA B200 with identical inputs, exact-block pattern, capacity, and static scheduler; only `use_proxy_routes` and the required summaries change. | Path | Proxy disabled | Proxy enabled | Additional overhead | | --- | ---: | ---: | ---: | | Public `BlockSparseTSWrapper.run` | 1.3172 ms | 1.4298 ms | **+8.55%** | | Prevalidated adapter | 1.3162 ms | 1.4318 ms | **+8.78%** | Workload: BF16 Q/K/V `[1, 32760, 12, 128]`, Q-block 64, KV-block 64, physical KV route 256, dense bitmask, and 84 of 512 exact blocks per row (16.4%). Proxy adds two prepared routes per row (21 → 23). Results use five balanced rounds with 80 CUDA-event samples per arm (400 samples/arm). Timings include route preparation and attention; summary construction is excluded. Each mode was checked against its own independent reference because proxy compensation intentionally changes the output semantics. Kernel split diagnostic: attention p50 increased by 7.64% (1.1261 → 1.2121 ms); prepare increased by 0.0030 ms (0.0145 → 0.0176 ms). ## 🧪 Tests - [x] `tests/trace_apply/test_trace_apply.py`: 26 passed - [x] `tests/trace/test_fi_trace_template_consistency.py`: 774 passed - [x] `tests/attention/test_attention_ts_block_sparse.py`: 140 passed, 88 skipped - [x] BK8 SWAPS and BK64 Keeps GPU proxy validation passed for both BSR and bitmask - [x] BSR/bitmask results are bitwise identical in the focused GPU cases; final-word padding bits are ignored - [x] Repository pre-commit hooks passed, including mypy, Ruff check, and Ruff format ## 🚀 Pull Request Checklist ### ✅ Pre-commit Checks - [x] I have run the hooks manually and fixed all reported issues. ### ✅ Tests - [x] Tests have been added or updated as needed. - [x] All targeted tests are passing. ## Reviewer Notes The commits are separated into generic runtime trace dispatch, block-sparse functionality, focused correctness/trace tests, and review-driven cleanup. `experimental/sol_attention` is not part of this PR. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added BSR and bitmask routing options for block-sparse attention. * Added proxy-route support using caller-provided K/V summaries. * Added route-specific validation and metadata handling for wrapper and one-shot APIs. * Expanded tracing to support all sparse format and route-mode combinations. * Improved trace application to select and execute only the runtime-matched template. * **Documentation** * Documented contiguous bitmask routing, proxy routes, capacity semantics, and summary behavior. * **Tests** * Added GPU coverage for BSR and bitmask proxy routes and multi-template trace dispatch. <!-- end of auto-generated comment: release notes by coderabbit.ai --> ## Current integration stack (2026-09-04) - This branch is rebased onto FlashInfer `main` `60b49158ab4fb81718aef486c2d3c89aec4c1901`; current PR head: `6b5b2d31f3314be77ccf6655c899b7b971863a1a`. - The TRT-LLM composite pin is [heyuhhh/flashinfer@`71bf7842`](https://github.com/heyuhhh/flashinfer/tree/yuhangh/tmp-sol-attn-trtllm-pr17399), which reapplies all eight commits from Yuxian's newest `trtllm-prims-ts` head (`edddf6f5`) on top of this PR. - TensorRT-LLM stack: [#17399 PrimTS base](NVIDIA/TensorRT-LLM#17399) → [general block-sparse FMHA](yuxianq/TensorRT-LLM#2) → [VisualGen VSA/shared workflow](heyuhhh/TensorRT-LLM#7) → [VisualGen SOL integration](heyuhhh/TensorRT-LLM#9). - Final B200 integration verification includes raw/proxy/paged generic routes, VSA CUDA Graph live routes, SOL all-exact parity, and mixed proxy parity at sequence lengths 256 and 257. --------- Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
Description
Integrate FlashInfer's experimental task-scheduled PrimTS attention kernels into the PyTorch TensorRT-LLM attention backend for supported Blackwell workloads. The integration is opt-in and depends on flashinfer-ai/flashinfer#4829.
Integration and supported scope
PrimsTSFmhafor SM100 and SM103. Enable it withTLLM_FMHA_LIBS=+prims_ts; it precedesflashinfer_trtllm_genandfallbackin canonical order but is excluded from the default FMHA set. Unsupported requests continue through the remaining enabled FMHA libraries._FmhaCacheKey; this invariant is now documented next to the key. TensorRT-LLM does not enable CUDA Graph capture for context-only or mixed batches, and fused-QKV/cache-update mode is fixed for a layer within an LLM instance.Unified page-table metadata
Context, decode, and MLA now use the same native PrimTS contract: an
int32fixed row-strided page table[B, C]plus liveint32sequence lengths[B].[B, 2, C]view. Plane 0 contains the K-page IDs used by PrimTS; plane 1 is the V-page field. The adapter passesblock_tables[:B, 0, :]directly, producing a zero-copy[B, C]view with stride(2*C, 1), while the normalized K/V cache views retain their respective pool displacement.pfor requestbresolves asblock_tables[b, p].seq_lens[b]determines the active page count, so unused capacity columns are never semantically consumed.params.sequence_lengths[:batch_size]directly instead of recovering the same lengths by differencingcu_kv_seqlens.Planning, preprocessing, and workspace ownership
run()time.skip_fmha_workspace=FalseTHOP option. PrimTS uses it to omit the unused fixed 32 MiB TRTLLM-Gen FMHA slice while retaining compact preprocessing buffers.plan_state.workspace.split_kv_counterwhen the fused global split-reduction path needs it, rather than clearing unrelated workspace bytes.PhasedFmhapopulate both phase batch fields and compute the active layer's page-pool bound. V1 and V2 KV-cache managers use explicit type-specific bounds; V2 queries the local layer'sRole.KEYupper bound.Vendoring and dependencies
flashinfer/attention/prims_tsfromyuxianq/flashinfer@20d8afb4through the locked-source workflow. The lock records the source revision, persistent TensorRT-LLM compatibility patch, patch digest, and materialized-tree digest and supports offline and remote reconstruction checks.security_scanning/poetry.lockunchanged; its refresh is intentionally handled separately.Performance Analysis
Current-head paired B200 performance
These measurements were taken at current PR head
895c2c2with FlashInfer pine500966b.One exclusive B200 ran BF16, TP/PP/EP=1, page size 32, and fixed 1024-token input/output. C1 used 10 measured requests plus one warmup; C64 used 64 measured requests plus 64 warmups at concurrency 64. Every arm used a fresh process in N/P/P/N order.
NusedTLLM_FMHA_LIBS=-prims_ts;PusedTLLM_FMHA_LIBS=+prims_ts. Values are geometric means of the forward and reverse passes. Positive speedup means that enabling PrimTS is better.The forward/reverse primary-metric ratio spans were 0.055 percentage points for Qwen C1 latency, 0.683 for DeepSeek C1 latency, 0.170 for Qwen C64 throughput, and 0.084 for DeepSeek C64 throughput. DeepSeek C64 therefore shows a clear repeatable gain; the other three cells retain small regressions.
All 16 counted arms passed import, provenance, dispatch, requested-length, and repeatability checks. DeepSeek output tokens matched exactly between N and P. Qwen output tokens were exact across repeats within each condition but differed between the two FMHA backends; cross-backend equality was informational rather than gating. Dispatch probes confirmed Qwen P used PrimTS context and decode, while DeepSeek P used fallback context and PrimTS MLA decode.
One Qwen C64 P-reverse process hit a KV-cache-manager-v2 introspection segfault before timing. That partial attempt was excluded; the single retry with the sealed, unchanged configuration passed and supplied the counted sample.
Historical paired B200 baseline
The following measurements were taken on PR revision
3063375cwith FlashInfer pin5a6a73a2, before the unified fixed-row metadata path. They remain a historical baseline, not a performance sign-off for the current head.One exclusive B200 ran BF16, TP/PP/EP=1, page size 32, fixed 1024-token input/output, and fresh processes in ABBA order.
ONusedTLLM_FMHA_LIBS=+prims_ts;OFFusedTLLM_FMHA_LIBS=-prims_ts.All 16 runs completed and dispatch instrumentation proved the expected ON/OFF backend selection. PrimTS used less average GPU power in all four cells; DeepSeek C64 reduced measurement-window energy by 4.426% and improved output-token energy efficiency by 4.624% despite its throughput gap.
Test Coverage
tests/unittest/_torch/attention/test_prims_ts_attention_backend.pypassed18/18on both B200 SM100 and B300 SM103, withthreadleakenabled. Coverage includes context/generation/mixed Qwen2 GQA, V1/V2 KV-cache managers, FP16 context, V-tail sanitization, DeepSeek MLA, fixed-row metadata mutation, workspace reset/sharing, generation CUDA Graph replay, and fallback behavior.test_fmha_manager.py(29),test_prims_ts_fmha.py(77), andtest_combined_fmha.py(152).20d8afb4; the vendor test suite passed25/25. Ruff, formatting, Python compilation, diff checks, DCO, and applicable pre-commit hooks passed.l0_b200.ymland instrument real PrimTS phase calls./bot run --disable-fail-fast. The latest full pipeline is in progress; see the PR checks for live status.The B200/B300
18/18runs were made on the fixed-row revision before the final rebase and subsequent vendor/manager follow-ups. The later CPU/vendor checks cover those follow-ups; the historical performance section is not a current-head performance claim.PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why.
PR follows the TRT-LLM coding guidelines to the best of my knowledge.
Test cases are provided for new code paths.
No public TensorRT-LLM API change is introduced;
skip_fmha_workspaceis an internal THOP parameter and defaults toFalse.New and updated dependencies were checked through the security-scanning declarations and locked-source attribution workflow.
CODEOWNERS and attention documentation are updated.
The base container and system CUDA toolkit remain unchanged.
Reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
To see a list of available CI bot commands, comment
/bot help.