Skip to content

Conversation

@Fridah-nv
Copy link
Collaborator

@Fridah-nv Fridah-nv commented Oct 24, 2025

Details in/ closes #8389

TODO: manual perf tests after I get access to the clusters

Summary by CodeRabbit

  • Refactor
    • Reorganized internal attention pattern matching and optimization logic.

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)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • 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

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

@Fridah-nv Fridah-nv self-assigned this Oct 24, 2025
@Fridah-nv Fridah-nv requested a review from a team as a code owner October 24, 2025 05:24
@Fridah-nv Fridah-nv changed the title [#8389][fAutoDeploy] Update group attention matching to first map to custom torch attention [#8389][AutoDeploy] Update group attention matching to first map to custom torch attention Oct 24, 2025
@Fridah-nv Fridah-nv changed the title [#8389][AutoDeploy] Update group attention matching to first map to custom torch attention [#8389][fix] Update group attention matching to first map to custom torch attention Oct 24, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 24, 2025

📝 Walkthrough

Walkthrough

Refactored attention pattern matching transforms to rename grouped attention patterns, explicitly separating SDPA-to-torch_attention and repeat_kv-with-torch_attention cases. Updated configuration keys, function names, class names, and registrations to reflect new semantic distinctions in pattern matching strategies.

Changes

Cohort / File(s) Summary
Configuration Transform Entries
tensorrt_llm/_torch/auto_deploy/config/default.yaml
Renamed two transform entries in graph-mode configuration: match_grouped_attention_with_repeat_kvmatch_sdpa_to_torch_attention; match_grouped_attention_without_repeat_kvmatch_grouped_attention. Stage and properties unchanged.
Core Pattern Matching Implementation
tensorrt_llm/_torch/auto_deploy/transform/library/attention.py
Refactored attention pattern generation and registration: renamed make_grouped_attn_pair() to make_sdpa_to_torch_attn_pair() with updated signature (dropped repeat_kv parameter); renamed generate_and_register_grouped_attn_patterns() to generate_and_register_sdpa_to_torch_attn_patterns(); added new make_repeat_kv_torch_attn_pair() and generate_and_register_repeat_kv_torch_attn_patterns() functions. Renamed classes: MatchGroupedAttentionWithRepeatKVMatchSDPAToTorchAttention; MatchGroupedAttentionWithoutRepeatKVMatchRepeatKVWithTorchAttention. Updated registration names and pattern generation logic to distinguish SDPA-to-torch and repeat_kv-with-torch pathways.
Test Configuration Updates
tests/unittest/_torch/auto_deploy/.../test_attention_matcher.py, tests/unittest/_torch/auto_deploy/.../test_attention_matcher_hf.py
Updated grouped attention optimizer configuration keys to match new names: match_grouped_attention_with_repeat_kvmatch_sdpa_to_torch_attention; match_grouped_attention_without_repeat_kvmatch_grouped_attention.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Rationale: Changes involve semantic renaming across multiple related components (configuration, core implementation, tests) with new function and class definitions. While the edits follow a consistent pattern of renaming existing functionality, the implementation of two new generator functions (make_repeat_kv_torch_attn_pair, generate_and_register_repeat_kv_torch_attn_patterns) introduces distinct logic that requires verification. The spread across three file categories with mixed naming and logic changes demands careful review of each mapping to ensure consistency and correctness of the separation between SDPA-to-torch and repeat_kv-with-torch patterns.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description lacks substantial content required by the template. Beyond linking to GitHub issue #8389 and noting a TODO about manual performance tests, the Description and Test Coverage sections are not filled in with actual details. While the PR checklist has one item checked, the description does not explain what issue is being solved, what changes were made to address it, or which tests validate the changes. This is a significant gap in communicating the rationale and validation for this refactoring.
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Linked Issues Check ❓ Inconclusive The linked issue #8389 identifies a bug where attention pattern matching incorrectly yields num_kv_heads=32 instead of the correct value of 2 for the NemotronMoe model, resulting in oversized kv cache. The PR changes focus on refactoring the attention matching logic by renaming functions from "grouped_attn" terminology to "sdpa_to_torch_attn" and introducing new pattern generators for SDPA-to-torch-attention mapping. However, the raw summary provides only high-level structural changes without detailing how these changes fix the underlying bug in num_kv_heads calculation or demonstrating that the fix applies specifically to the NemotronMoe model case mentioned in the issue.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "[#8389][fix] Update group attention matching to first map to custom torch attention" clearly follows the required format with a valid GitHub issue reference and type designation. The title directly corresponds to the main changes in the PR, which involve renaming matcher configurations, refactoring attention-matching functions, and introducing new SDPA-to-torch-attention mapping patterns. The title is specific enough to convey the primary change without being overly vague.
Out of Scope Changes Check ✅ Passed All file modifications in this PR remain focused on the attention pattern matching system: configuration updates to matcher names in default.yaml, refactoring of attention matching functions and classes in attention.py, and corresponding test updates to reflect the new matcher names. The changes consistently implement the PR objective of updating group attention matching to map to custom torch attention, with no apparent additions to unrelated subsystems or functionality.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/auto_deploy/transform/library/attention.py (1)

620-653: Fix docstring reference to use correct transform key.

Line 629 mentions match_repeat_kv_with_torch_attention but the actual registered key is match_grouped_attention (line 656).

Apply this diff:

-    This transform should run BEFORE match_repeat_kv_with_torch_attention to ensure
+    This transform should run BEFORE match_grouped_attention to ensure
     SDPA calls are converted first.
🧹 Nitpick comments (4)
tensorrt_llm/_torch/auto_deploy/transform/library/attention.py (4)

376-428: Consider adding strict=True to zip() calls for safer argument matching.

The zip() calls at lines 400 and 415 should include strict=True to ensure args and argnames have matching lengths, preventing silent bugs if they become misaligned.

Apply this diff:

-        m = dict(zip(argnames, args))
+        m = dict(zip(argnames, args, strict=True))

(Apply to both pattern_fn and replacement_fn at lines 400 and 415)

Based on static analysis hints.


431-490: Consider improving exception chain handling.

At line 473, the exception raised in the except KeyError clause should use raise ... from err to preserve the exception chain, aiding debugging.

Apply this diff:

-            except KeyError:
-                raise RuntimeError(f"Unexpected arg name: {name}")
+            except KeyError as err:
+                raise RuntimeError(f"Unexpected arg name: {name}") from err

Based on static analysis hints.


493-555: Add strict=True to zip() calls for argument safety.

The zip() calls at lines 517 and 541 should include strict=True to catch argument count mismatches early.

Apply this diff:

-        m = dict(zip(argnames, args))
+        m = dict(zip(argnames, args, strict=True))

(Apply to both pattern_fn and replacement_fn at lines 517 and 541)

Based on static analysis hints.


1-1: Copyright header requirement.

As per coding guidelines, Python source files should include the NVIDIA Apache-2.0 copyright header with the current year. This appears to be missing from this file.

If this file is newly created or significantly modified, consider adding the copyright header at the top of the file.

As per coding guidelines.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6b793d5 and fa71580.

📒 Files selected for processing (4)
  • tensorrt_llm/_torch/auto_deploy/config/default.yaml (1 hunks)
  • tensorrt_llm/_torch/auto_deploy/transform/library/attention.py (7 hunks)
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher.py (1 hunks)
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher_hf.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use only spaces, no tabs; indent with 4 spaces.

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher_hf.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/attention.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher_hf.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/attention.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher_hf.py
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher.py
  • tensorrt_llm/_torch/auto_deploy/transform/library/attention.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/auto_deploy/transform/library/attention.py (2)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (4)
  • get (519-521)
  • TransformRegistry (503-531)
  • register (509-516)
  • BaseTransform (213-500)
tensorrt_llm/_torch/auto_deploy/utils/pattern_matcher.py (1)
  • register_ad_pattern (99-182)
🪛 Ruff (0.14.1)
tensorrt_llm/_torch/auto_deploy/transform/library/attention.py

399-399: Avoid specifying long messages outside the exception class

(TRY003)


400-400: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


414-414: Avoid specifying long messages outside the exception class

(TRY003)


415-415: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


473-473: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


473-473: Avoid specifying long messages outside the exception class

(TRY003)


540-540: Avoid specifying long messages outside the exception class

(TRY003)


541-541: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Check PR Checklist Resolution
  • GitHub Check: Pre-commit Check
🔇 Additional comments (5)
tensorrt_llm/_torch/auto_deploy/config/default.yaml (1)

37-39: LGTM! Configuration keys renamed to reflect new attention matching semantics.

The renaming clearly distinguishes SDPA-to-torch_attention mapping from repeat_kv handling, aligning with the refactored transform implementation.

tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher_hf.py (1)

44-47: LGTM! Test configuration updated to use renamed matcher keys.

The configuration now correctly references match_sdpa_to_torch_attention and match_grouped_attention, consistent with the refactored transform registration.

tensorrt_llm/_torch/auto_deploy/transform/library/attention.py (2)

558-617: LGTM! Repeat KV pattern generation correctly handles n_rep parameter.

The function properly enumerates pattern variations and includes n_rep in scalar workarounds, which should help correctly identify GQA scenarios where repeat_kv is applied.


656-691: LGTM! Transform correctly handles repeat_kv with torch_attention patterns.

The class properly registers the match_grouped_attention transform and its docstring accurately describes the ordering dependency with match_sdpa_to_torch_attention.

tests/unittest/_torch/auto_deploy/unit/singlegpu/transformations/library/test_attention_matcher.py (1)

449-452: LGTM! Test configuration correctly updated with new matcher keys.

The test now uses match_sdpa_to_torch_attention and match_grouped_attention, aligning with the refactored transform registration and config updates.

@nvchenghaoz
Copy link
Collaborator

If there is no change in the final graph and no change in the custom ops, I think the perf side should be good.

@github-project-automation github-project-automation bot moved this from Backlog to In review in AutoDeploy Board Oct 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In review

Development

Successfully merging this pull request may close these issues.

[Bug]: Attention pattern matching yield incorrect num_kv_heads

3 participants