Repository navigation
[None][perf] optimize qwen3.5 perf by removing gather and scatter op - #17365
Conversation
4006a73 to
660b2f1
Compare
|
/bot run |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThe change adds an SM100/SM103 fast path for indexed state updates. It passes state pools and indices directly to FlashInfer and preserves gather/scatter behavior for other cases. Tests validate BF16 parity, in-place updates, and untouched slots. ChangesIndexed state update
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant StatePool
participant chunk_gated_delta_rule
participant FlashInfer
StatePool->>chunk_gated_delta_rule: Provide state pool and slot indices
chunk_gated_delta_rule->>FlashInfer: Submit indexed state update
FlashInfer->>StatePool: Write selected final states in place
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
PR_Github #64349 [ run ] triggered by Bot. Commit: |
|
PR_Github #64349 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #64371 [ run ] triggered by Bot. Commit: |
|
PR_Github #64371 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #64470 [ run ] triggered by Bot. Commit: |
|
PR_Github #64470 [ run ] completed with state
|
zhaoyangwang-nvidia
left a comment
There was a problem hiding this comment.
LGTM overall — nice removal of the gather/scatter round-trip. Two small asks below.
660b2f1 to
d52eaae
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/unittest/_torch/modules/mamba/test_flashinfer_chunk_gdn.py`:
- Around line 364-417: Update
test_indexed_state_pool_fast_path_bf16_matches_triton to require the same
architecture predicate as is_sm_100f(), and before invoking fi_cgdr monkeypatch
flashinfer_chunk.gather_cast_vk_to_fp32_vk to raise if called. Keep the existing
output and pool-state comparisons, ensuring the test fails whenever indexed-pool
dispatch falls back through the gather/scatter helper.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 11111e8e-4bbe-4331-b231-de75a5723d23
📒 Files selected for processing (2)
tensorrt_llm/_torch/modules/fla/flashinfer_chunk.pytests/unittest/_torch/modules/mamba/test_flashinfer_chunk_gdn.py
🚧 Files skipped from review as they are similar to previous changes (1)
- tensorrt_llm/_torch/modules/fla/flashinfer_chunk.py
d52eaae to
06fb264
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #64571 [ run ] triggered by Bot. Commit: |
|
/bot run --disable-fail-fast |
|
PR_Github #64624 [ run ] triggered by Bot. Commit: |
|
PR_Github #64571 [ run ] completed with state |
|
PR_Github #64624 [ run ] completed with state
|
brnguyen2
left a comment
There was a problem hiding this comment.
Approving — the comments below are optional touch-ups, not blockers.
Verified the fast path against FlashInfer 0.6.16's gdn_prefill.py: the guard matches FI's own dispatch condition (state_indices only on the SM100/SM103 non-CP kernel; the CP heuristic can't fire on arch 10 with use_cp unset), the metadata's state_indices are int32 as FI requires, and output_state=initial_state is the documented in-place form. The pool (layer_cache.temporal) is a contiguous dim-0 slice, so the TMA contiguity requirement holds. Nice touch monkeypatching the gather helper so the test proves the dispatch rather than just value parity.
On the CodeRabbit QA note: the new test does run in CI — l0_b200.yml/l0_b300.yml register the whole unittest/_torch/modules/mamba directory, and those are SM100/SM103 runners.
The one thing I'd fix before merge is the flip side of that: those are the only runners registered for this directory, and the pre-existing test_indexed_gather_inplace_scatter_matches_triton uses exactly the flag combination the new guard matches — so it now silently exercises the fast path too, and the indexed gather/scatter branch (still shipped for SM90/SM120) loses all CI coverage. Details inline.
Minor: a perf change like this would normally carry a TRTLLM JIRA rather than [None] in the title — worth adding if one exists.
06fb264 to
9afc27d
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/unittest/_torch/modules/mamba/test_flashinfer_chunk_gdn.py`:
- Around line 309-314: Add both Mamba tests, including
test_indexed_gather_inplace_scatter_matches_triton, to
tests/integration/test_lists/qa/llm_function_core.txt, preserving the existing
test-list format. Then run the complete tests/unittest suite with pytest and
verify it passes.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 72676413-19ae-4bed-9d6f-0a1c8848c599
📒 Files selected for processing (1)
tests/unittest/_torch/modules/mamba/test_flashinfer_chunk_gdn.py
3435727 to
ccac19f
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #64974 [ run ] triggered by Bot. Commit: |
|
PR_Github #64974 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #65040 [ run ] triggered by Bot. Commit: |
|
PR_Github #65040 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #65179 [ run ] triggered by Bot. Commit: |
|
PR_Github #65179 [ run ] completed with state
|
ccac19f to
731cade
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #71843 [ run ] triggered by Bot. Commit: |
…catter FlashInfer 0.6.16 lets the SM100/SM103 GDN prefill kernel read and write the SSM state pool by slot index, so the in-place prefill path passes the pool plus cache indices straight through and drops the Triton gather and scatter passes. The wrappers stay for what FlashInfer rejects: SM90/SM120, which also still need the fp32 round-trip, and the MTP target-verify call site, which hands in a pre-gathered state. Signed-off-by: nv-guomingz <[email protected]>
731cade to
eb1901e
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #71870 [ run ] triggered by Bot. Commit: |
|
PR_Github #71843 [ run ] completed with state |
|
PR_Github #71870 [ run ] completed with state |
…ng gather and scatter op (#17365)" (#19578) Signed-off-by: nv-guomingz <[email protected]>
## 📌 Description
With `state_indices`, the SM100/SM103 GDN prefill kernel
(`GatedDeltaNetChunkedKernel`) runs up to ~3.2x slower than with a
packed initial state. Both paths produce bitwise-identical results.
**Cause.** In pool mode, `_mark_state_layout` applies only
`mark_layout_dynamic()` so that padded slot strides are accepted. That
drops the stride divisibility the packed path gets from
`mark_compact_shape_dynamic(..., divisibility=DK)`. The per-(sequence,
head) state load/store in `_load_initial_state` / `_store_final_state`
then vectorizes narrower. The cost is fixed per work item, so it
dominates when a call holds many short sequences, e.g. chunked prefill
at high concurrency.
**Fix.** The wrapper computes the largest power of two (at most the head
size) that divides the slot, head and V strides of the initial and
output state. It adds that value to the compiled-kernel cache key and
kernel name, and the kernel applies it with `cute.assume()` when it
builds the state view. This covers compact and padded pools. Packed mode
and the CP path are unchanged.
### How to trigger
All of these must hold:
- SM100/SM103, non-CP path: `use_cp=False`, or `use_cp="auto"` with
`num_seqs * num_heads * 4 >= num_sms`.
- `state_indices` is passed, with the state pool as `initial_state` and
`output_state`.
- The call holds several sequences. The slowdown grows with the sequence
count and shrinks as sequences get longer.
The script below uses only the public API and times
`GatedDeltaNetChunkedKernel` with `torch.profiler`:
<details><summary>repro_gdn_indexed_state.py</summary>
```python
"""Minimal repro: SM100 GDN prefill is slower with state_indices than with a packed state.
Both variants compute bit-identical results; only the state I/O differs.
Run on an SM100/SM103 GPU: python repro_gdn_indexed_state.py
"""
import torch
import torch.nn.functional as F
from torch.profiler import ProfilerActivity, profile
from flashinfer.gdn_prefill import chunk_gated_delta_rule
HQ, HV, D, TOTAL, N_POOL = 16, 48, 128, 2048, 512
dev = torch.device("cuda")
def kernel_us(fn, iters=20):
"""Median GatedDeltaNetChunkedKernel time in microseconds (host overhead excluded)."""
for _ in range(3):
fn()
torch.cuda.synchronize()
with profile(activities=[ProfilerActivity.CUDA]) as prof:
for _ in range(iters):
fn()
torch.cuda.synchronize()
times = sorted(
e.device_time_total for e in prof.events() if "GatedDeltaNetChunkedKernel" in e.name
)
return times[len(times) // 2]
def make_pool(layout):
if layout == "compact": # [N_pool, H, V, K]
return torch.zeros(N_POOL, HV, D, D, dtype=torch.bfloat16, device=dev)
# 4 same-shape layers coalesced into each slot: slot stride = 4 * H * V * K
return torch.zeros(N_POOL, 4, HV, D, D, dtype=torch.bfloat16, device=dev)[:, 1]
torch.manual_seed(0)
q = F.normalize(torch.randn(TOTAL, HQ, D, device=dev), dim=-1).bfloat16()
k = F.normalize(torch.randn(TOTAL, HQ, D, device=dev), dim=-1).bfloat16()
v = torch.randn(TOTAL, HV, D, device=dev).bfloat16()
g = 0.9 + 0.1 * torch.rand(TOTAL, HV, device=dev) # linear-space decay
beta = torch.rand(TOTAL, HV, device=dev)
out = torch.empty(TOTAL, HV, D, dtype=torch.bfloat16, device=dev)
print(f"{'pool':<9}{'seqs':>5}{'packed us':>11}{'indexed us':>12}{'ratio':>7} bitwise")
for layout in ("compact", "coalesced"):
for num_seqs in (1, 16, 128):
cu = torch.arange(0, TOTAL + 1, TOTAL // num_seqs, dtype=torch.int32, device=dev)
pool = make_pool(layout)
pool.copy_(0.05 * torch.randn_like(pool))
idx = torch.arange(num_seqs, dtype=torch.int32, device=dev) * 3
rows = idx.long()
pool0 = pool.clone()
def packed():
state = pool[rows] # gather into [num_seqs, H, V, K]
final = torch.empty_like(state)
chunk_gated_delta_rule(
q, k, v, g, beta, initial_state=state, output_final_state=True,
cu_seqlens=cu, output=out, output_state=final, use_cp=False,
)
pool[rows] = final # scatter back
def indexed():
chunk_gated_delta_rule(
q, k, v, g, beta, initial_state=pool, output_final_state=True,
cu_seqlens=cu, output=out, output_state=pool, state_indices=idx,
use_cp=False,
)
pool.copy_(pool0)
packed()
ref_out, ref_state = out.clone(), pool[rows].clone()
pool.copy_(pool0)
indexed()
same = torch.equal(out, ref_out) and torch.equal(pool[rows], ref_state)
t_packed, t_indexed = kernel_us(packed), kernel_us(indexed)
print(
f"{layout:<9}{num_seqs:>5}{t_packed:>11.1f}{t_indexed:>12.1f}"
f"{t_indexed / t_packed:>7.2f} {same}"
)
```
</details>
Indexed / packed kernel time. Outputs and final states are
bitwise-identical in every case.
| pool layout | seqs | before | after |
|---|---|---|---|
| compact | 1 | 1.40 | 0.99 |
| compact | 16 | 3.20 | 0.96 |
| compact | 128 | 3.17 | 0.89 |
| 4 layers per slot | 1 | 1.40 | 0.99 |
| 4 layers per slot | 16 | 3.29 | 0.95 |
| 4 layers per slot | 128 | 3.18 | 0.90 |
## 🔍 Related Issues
Found while adopting `state_indices` in NVIDIA/TensorRT-LLM#17365.
## 🚀 Pull Request Checklist
### ✅ Pre-commit Checks
- [x] 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`.
- [x] I have run the hooks on the changed files and fixed any reported
issues.
## 🧪 Tests
- [x] Tests have been added or updated as needed.
- `test_state_stride_divisibility`: divisibility derived from compact,
coalesced, padded and non-unit-K layouts.
- `test_prefill_state_indices_compact_and_padded_pools_in_one_process`:
alternates compact and padded pools with identical shapes in one process
and checks every call against the packed baseline bitwise.
- `test_prefill_name_varies_with_every_argument`: covers the new
cache-key component.
- `test_blackwell_prefill_workspace_not_in_compile_cache`: passes the
new key component when it rebuilds the cache key.
- [x] All tests are passing on SM100 for
`tests/gdn/test_prefill_delta_rule.py`,
`test_prefill_qk_normalization.py`, `test_prefill_state_indices.py`,
`test_cute_dsl_kernel_cache.py`, `test_prefill_cp_delta_rule.py`,
`test_prefill_auto_backend.py`, `test_multistream_overlap.py` and
`test_gdn_device_target.py`: 3422 passed, 866 skipped.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Bug Fixes**
* Improved Blackwell prefill handling of recurrent state buffers with
different stride alignments, including compact and padded layouts used
within the same process.
* Kernel selection now accounts for state-buffer alignment, helping
maintain correct results when switching between layouts across supported
low-precision data types.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Signed-off-by: Guoming Zhang <[email protected]>
…catter
FlashInfer 0.6.16 lets the SM100/SM103 GDN prefill kernel read and write the SSM state pool by slot index, so the in-place prefill path passes the pool plus cache indices straight through and drops the Triton gather and scatter passes.
The wrappers stay for what FlashInfer rejects: SM90/SM120, which also still need the fp32 round-trip, and the MTP target-verify call site, which hands in a pre-gathered state.
Dev Engineer Review
flashinfer_chunk.py.QA Engineer Review
test_indexed_gather_inplace_scatter_matches_triton(monkeypatch, pool_dtype).test_indexed_state_pool_fast_path_bf16_matches_triton(monkeypatch, cache_indices_list).tests/integration/test_lists/for CI or manual QA coverage.Description
Test Coverage
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
If PR introduces API changes, an appropriate PR label is added - either
api-compatibleorapi-breaking. Forapi-breaking, includeBREAKINGin the PR title.Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
Update tava architecture diagram if there is a significant design change in PR.
The 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, please comment
/bot help.