Skip to content

[None][perf] Fuse QK-norm + RoPE and overlap qkv/idx_qk math - #16906

Merged
brb-nv merged 1 commit into
NVIDIA:mainfrom
brb-nv:user/brb/fuse-qknorm-rope
Jul 31, 2026
Merged

[None][perf] Fuse QK-norm + RoPE and overlap qkv/idx_qk math#16906
brb-nv merged 1 commit into
NVIDIA:mainfrom
brb-nv:user/brb/fuse-qknorm-rope

Conversation

@brb-nv

@brb-nv brb-nv commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Description

This MR does the following:

  • Fuses qk-norm + rope for both main and indexer branches.
  • Overlaps the two branches where possible.

Test Coverage

$ pytest tests/integration/defs/accuracy/test_llm_api_pytorch.py::TestMiniMaxM3::test_nvfp4[use_msa=True] -s -v

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-compatible or api-breaking. For api-breaking, include BREAKING in 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.

Dev Engineer Review

  • Fuses QK normalization with partial RoPE for MiniMax-M3 main and indexer branches.
  • Adds bf16 guards, fallback handling, contiguity support, and assertions for unexpected fused-kernel fallbacks.
  • Introduces a shared auxiliary CUDA stream to overlap Q/K normalization and sparse main/indexer processing.
  • Adds the optional aux_stream parameter to MiniMaxM3Attention and wires it through model initialization.
  • No configuration or test-list changes were identified. Focused validation remains appropriate for CUDA synchronization, fused-kernel availability, and dense/sparse regressions.

QA Engineer Review

Added tests:

  • test_minimax_m3_fused_qk_norm_rope_main_matches_separate
  • test_minimax_m3_fused_qk_norm_rope_index_matches_separate
  • test_minimax_m3_fused_qk_norm_rope_fallbacks
  • test_minimax_m3_expect_fused_qk_norm_rope_predicate

The tests cover fused main and index paths, fallback behavior, and fusion predicate guards. Coverage in tests/integration/test_lists/ was not confirmed.

Verdict: needs follow-up

@brb-nv
brb-nv requested a review from a team as a code owner July 27, 2026 17:58
@brb-nv
brb-nv requested a review from QiJune July 27, 2026 17:58
@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

MiniMax-M3 attention now uses shared auxiliary-stream parallelism and fused BF16 QK normalization with partial RoPE across dense and sparse paths. CUDA tests cover fused correctness, fallback behavior, and fusion predicates.

Changes

MiniMax-M3 attention execution

Layer / File(s) Summary
Attention stream and parallel normalization
tensorrt_llm/_torch/models/modeling_minimaxm3.py
Adds shared attention auxiliary-stream wiring, activation-dtype tracking, synchronization events, and concurrent normalization for main and index branches.
Fused dense and sparse preprocessing
tensorrt_llm/_torch/models/modeling_minimaxm3.py
Adds fused BF16 QK normalization with partial RoPE, validated fallback handling, and concurrent sparse branch preprocessing.
Fused-path CUDA validation
tests/unittest/_torch/models/test_minimax_m3.py
Tests fused dense and sparse outputs against separate reference flows and verifies fallback and fusion-predicate behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • NVIDIA/TensorRT-LLM#16904: Modifies the MiniMax-M3 sparse attention index Q/K path alongside this PR’s fused normalization and RoPE handling.

Suggested reviewers: qijune

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the performance optimization: fused QK normalization with RoPE and overlapping QKV/indexer computations.
Description check ✅ Passed The description includes the required sections, explains the optimization, lists test coverage, and confirms the checklist review.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
tests/unittest/_torch/models/test_minimax_m3.py (3)

836-842: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Docstring overstates coverage.

Only one bf16 config is constructed; MXFP8 and NVFP4 flavors are never instantiated here. Trim the claim to what the test actually asserts.

🤖 Prompt for 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.

In `@tests/unittest/_torch/models/test_minimax_m3.py` around lines 836 - 842,
Update the docstring describing the fused-path expectation near the forward
assertions to reflect only the single bf16 configuration constructed by this
test. Remove claims about MXFP8 and NVFP4 coverage, while retaining the behavior
described for non-bf16 activations or missing position_ids if those cases remain
tested.

723-726: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Tolerances are loose enough to mask small regressions.

atol=1e-1 on bf16 activations of order 1 permits ~10% error. bf16 round-trip through two different kernels usually lands well under atol=2e-2; consider tightening (or asserting a relative-error norm) so an epsilon/scale mistake still fails.

🤖 Prompt for 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.

In `@tests/unittest/_torch/models/test_minimax_m3.py` around lines 723 - 726,
Tighten the q_f and k_f versus q_s and k_s assertions in the affected test by
reducing the absolute tolerance from 1e-1 to a stricter value around 2e-2, while
preserving the existing relative tolerance unless needed for consistency. Keep
the exact v_f versus v_s assertion unchanged.

785-831: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Fallback coverage stops at the helper.

Both cases exercise _fused_qk_norm_rope in isolation. Nothing drives _main_norm_rope/_index_norm_rope down the fallback branch, which is why the undefined idx_q/idx_k defect flagged in tensorrt_llm/_torch/models/modeling_minimaxm3.py slips through. A test that calls _sparse_forward's branch helpers with fp16 activations (expecting the separate path, with the assert relaxed) would close the gap.

🤖 Prompt for 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.

In `@tests/unittest/_torch/models/test_minimax_m3.py` around lines 785 - 831,
Extend test_minimax_m3_fused_qk_norm_rope_fallbacks to exercise
_sparse_forward’s fallback branch through _main_norm_rope or _index_norm_rope,
using fp16 activations and position_ids. Assert the separate path completes
successfully rather than only checking _fused_qk_norm_rope returns None, and
relax any branch assertion needed to reach the fallback implementation so
undefined idx_q/idx_k usage is detected.
tensorrt_llm/_torch/models/modeling_minimaxm3.py (1)

792-808: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Nested maybe_execute_in_parallel reuses the same two events.

On the non-bf16 fallback path, _main_norm_rope/_index_norm_rope already run inside a maybe_execute_in_parallel region that uses self.ln_events[0]/[1], and they then call apply_qk_norm/apply_index_qk_norm, which record/wait on those same two events. The re-records only over-synchronize today (no lost ordering), but it silently kills the inner overlap and is easy to break with future edits. Consider giving the inner norm helpers their own event pair (e.g. self.qk_norm_events).

🤖 Prompt for 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.

In `@tensorrt_llm/_torch/models/modeling_minimaxm3.py` around lines 792 - 808,
Give the inner q/k normalization invoked by apply_qk_norm and
apply_index_qk_norm a dedicated event pair, such as self.qk_norm_events, instead
of reusing self.ln_events. Update the nested maybe_execute_in_parallel call and
all corresponding record/wait references so the outer
_main_norm_rope/_index_norm_rope synchronization remains independent and inner
overlap is preserved.
🤖 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 `@tensorrt_llm/_torch/models/modeling_minimaxm3.py`:
- Around line 1353-1380: The sparse index helper _index_norm_rope uses an
undefined self.index_qk_proj and references idx_q/idx_k before assignment in the
fallback. Replace the projection with the existing index_q_proj/index_k_proj
flow (or define the combined module consistently), initialize both tensors
before apply_index_qk_norm, and preserve the fused path’s outputs and subsequent
RoPE handling.
- Around line 880-892: Update the fused RoPE path around the visible
rotary-dimension validation to return None unless head_dim is 64, 128, or 256,
matching the supported fused_qk_norm_rope kernel inputs. Add the same
supported-dimension guard to _expect_fused_qk_norm_rope() so its expectation
logic mirrors the runtime fallback behavior.

---

Nitpick comments:
In `@tensorrt_llm/_torch/models/modeling_minimaxm3.py`:
- Around line 792-808: Give the inner q/k normalization invoked by apply_qk_norm
and apply_index_qk_norm a dedicated event pair, such as self.qk_norm_events,
instead of reusing self.ln_events. Update the nested maybe_execute_in_parallel
call and all corresponding record/wait references so the outer
_main_norm_rope/_index_norm_rope synchronization remains independent and inner
overlap is preserved.

In `@tests/unittest/_torch/models/test_minimax_m3.py`:
- Around line 836-842: Update the docstring describing the fused-path
expectation near the forward assertions to reflect only the single bf16
configuration constructed by this test. Remove claims about MXFP8 and NVFP4
coverage, while retaining the behavior described for non-bf16 activations or
missing position_ids if those cases remain tested.
- Around line 723-726: Tighten the q_f and k_f versus q_s and k_s assertions in
the affected test by reducing the absolute tolerance from 1e-1 to a stricter
value around 2e-2, while preserving the existing relative tolerance unless
needed for consistency. Keep the exact v_f versus v_s assertion unchanged.
- Around line 785-831: Extend test_minimax_m3_fused_qk_norm_rope_fallbacks to
exercise _sparse_forward’s fallback branch through _main_norm_rope or
_index_norm_rope, using fp16 activations and position_ids. Assert the separate
path completes successfully rather than only checking _fused_qk_norm_rope
returns None, and relax any branch assertion needed to reach the fallback
implementation so undefined idx_q/idx_k usage is detected.
🪄 Autofix (Beta)

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: a92ab75c-8a5a-426c-a276-4004a0f430b8

📥 Commits

Reviewing files that changed from the base of the PR and between 155847d and b8e8cd4.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/models/modeling_minimaxm3.py
  • tests/unittest/_torch/models/test_minimax_m3.py

Comment thread tensorrt_llm/_torch/models/modeling_minimaxm3.py
Comment thread tensorrt_llm/_torch/models/modeling_minimaxm3.py
@brb-nv
brb-nv force-pushed the user/brb/fuse-qknorm-rope branch from b8e8cd4 to a95a6bb Compare July 27, 2026 18:36
@brb-nv
brb-nv marked this pull request as draft July 27, 2026 18:36
Signed-off-by: Balaram Buddharaju <169953907+brb-nv@users.noreply.github.com>
@brb-nv
brb-nv force-pushed the user/brb/fuse-qknorm-rope branch from a95a6bb to 3eca866 Compare July 30, 2026 23:25
@brb-nv
brb-nv marked this pull request as ready for review July 30, 2026 23:27
@brb-nv

brb-nv commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@brb-nv
brb-nv enabled auto-merge (squash) July 30, 2026 23:28
@brb-nv
brb-nv disabled auto-merge July 30, 2026 23:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 `@tensorrt_llm/_torch/models/modeling_minimaxm3.py`:
- Around line 795-811: Use a dedicated event pair for the outer sparse-forward
parallel scope instead of sharing self.ln_events and self.aux_stream with
apply_qk_norm and apply_index_qk_norm. Update _sparse_forward and its associated
maybe_execute_in_parallel calls to use the new attn_events synchronization
objects, while leaving the normalization helpers on ln_events so nested scopes
cannot overwrite each other’s events.
🪄 Autofix (Beta)

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: 41d84d93-1021-4465-97a0-b167a90740f6

📥 Commits

Reviewing files that changed from the base of the PR and between b8e8cd4 and 3eca866.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/models/modeling_minimaxm3.py

Comment thread tensorrt_llm/_torch/models/modeling_minimaxm3.py
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62876 [ run ] triggered by Bot. Commit: 3eca866 Link to invocation

@brb-nv
brb-nv requested review from WeiHaocheng and removed request for QiJune July 31, 2026 01:21
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62876 [ run ] completed with state SUCCESS. Commit: 3eca866
/LLM/main/L0_MergeRequest_PR pipeline #50998 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@brb-nv

brb-nv commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #63110 [ run ] triggered by Bot. Commit: 3eca866 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #63110 [ run ] completed with state SUCCESS. Commit: 3eca866
/LLM/main/L0_MergeRequest_PR pipeline #51201 completed with status: 'SUCCESS'

CI Report

Link to invocation

@brb-nv
brb-nv enabled auto-merge (squash) July 31, 2026 22:06
@brb-nv
brb-nv merged commit 0a0de1c into NVIDIA:main Jul 31, 2026
13 checks passed
yuanjingx87 pushed a commit that referenced this pull request Aug 1, 2026
Signed-off-by: Balaram Buddharaju <169953907+brb-nv@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants