KEMBAR78
[TRTLLM-5966][feat] Helix: add custom position ids to MLA kernels by MatthiasKohl · Pull Request #6904 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@MatthiasKohl
Copy link
Collaborator

@MatthiasKohl MatthiasKohl commented Aug 14, 2025

Summary by CodeRabbit

  • New Features

    • Attention supports optional helix_position_offsets for rotary embeddings (per-token positioning). No change when not provided.
    • Python attention wrapper gains an optional helix_position_offsets parameter.
  • Refactor

    • Multiple MLA context inputs consolidated into a single mla_tensor_params vector across native and Python APIs.
    • Argument ordering updated; callers must migrate from the old separate MLA context arguments to the new grouped parameter.

Description

This PR adds the possibility of using custom position IDs for MLA generation, in the MLA kernels. This is useful for Helix to allow the different GPUs to obtain the right RoPE parameters for the output token even if it is at a much later position in the full sequence (compared to the local sequence of the GPU).

Test Coverage

No tests are needed as this PR only makes the feature available and does not actually call it anywhere.

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.

@MatthiasKohl MatthiasKohl requested a review from a team as a code owner August 14, 2025 14:34
@MatthiasKohl MatthiasKohl requested a review from QiJune August 14, 2025 14:34
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 14, 2025

📝 Walkthrough

Walkthrough

Adds optional helix_position_offsets support across CUDA kernel, C++ attention op, nanobind/pybind bindings, and Python TRT-LLM attention. Consolidates MLA-related inputs into an mla_tensor_params vector and threads helix offsets from Python into the kernel, which conditionally uses the override for rotary position_id.

Changes

Cohort / File(s) Summary of changes
CUDA kernel and params
cpp/tensorrt_llm/kernels/mlaKernels.cu, cpp/tensorrt_llm/kernels/mlaKernels.h
Adds int32_t const* helix_position_offsets to applyMLARopeAndAssignQKVKernelGeneration and to MlaParams. Kernel computes position_id from helix_position_offsets when non-null; host invoke passes the new field.
THOP bindings (nanobind / pybind)
cpp/tensorrt_llm/nanobind/thop/bindings.cpp, cpp/tensorrt_llm/pybind/thop/bindings.cpp
Replaces the two optional MLA context args (mla_context_paged_kv, mla_context_kv_cache_block_offsets) with a single mla_tensor_params vector parameter and reorders arguments accordingly.
Attention operator (C++)
cpp/tensorrt_llm/thop/attentionOp.cpp, cpp/tensorrt_llm/thop/attentionOp.h
Replaces separate MLA-context parameters with std::vector<std::optional<torch::Tensor>> mla_tensor_params. Reads indices: [0]=context_paged_kv, [1]=kv_cache_block_offsets, [2]=helix_position_offsets if present; wires values into mla_params and downstream calls. Public interfaces updated.
Python TRT-LLM attention
tensorrt_llm/_torch/attention_backend/trtllm.py
TrtllmAttentionWrapper.plan and TrtllmAttention.forward gain optional helix_position_offsets; wrapper stores it and builds mla_tensor_params = [context_paged_kv, kv_cache_block_offsets, helix_position_offsets] for kernel invocation.

Sequence Diagram(s)

sequenceDiagram
  participant Py as TrtllmAttention.forward
  participant Wr as TrtllmAttentionWrapper
  participant Op as attention (C++)
  participant Run as Runner::run
  participant K as applyMLARopeAndAssignQKVKernelGeneration

  Py->>Wr: plan(..., helix_position_offsets)
  Wr->>Wr: store helix_position_offsets
  Py->>Wr: run(...)
  Wr->>Op: attention(..., mla_tensor_params=[ctx_paged_kv, kv_block_offsets, helix_pos_offsets], ...)
  Op->>Run: Runner::run(..., mla_tensor_params, ...)
  Run->>K: launch(..., helix_position_offsets)
  K->>K: position_id = helix_pos_offsets ? override : default
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Possibly related PRs

Suggested labels

SW Architecture

Suggested reviewers

  • PerkzZheng
  • kaiyux
  • zhhuang-nv
  • litaotju
  • jinyangyuan-nvidia

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MatthiasKohl
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15310 [ run ] triggered by Bot

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: 7

🔭 Outside diff range comments (1)
cpp/tensorrt_llm/thop/attentionOp.cpp (1)

167-175: Bounds-check mla_tensor_params before indexing [0] and [1] to prevent OOB

Accessing mla_tensor_params[0] and [1] without checking size risks out-of-bounds access if the caller provides fewer entries. Also make refs const to reflect read-only usage.

Apply this diff:

-                auto& mla_context_paged_kv = mla_tensor_params[0];
-                auto& mla_context_kv_cache_block_offsets = mla_tensor_params[1];
+                TORCH_CHECK(
+                    mla_tensor_params.size() > 1,
+                    "mla_tensor_params must contain at least 2 tensors: [0]=context_paged_kv, [1]=context_kv_cache_block_offsets");
+                auto const& mla_context_paged_kv = mla_tensor_params[0];
+                auto const& mla_context_kv_cache_block_offsets = mla_tensor_params[1];
                 TORCH_CHECK(mla_context_paged_kv.has_value());
                 TORCH_CHECK(mla_context_kv_cache_block_offsets.has_value());
 
                 mla_params.context_paged_kv_ptr = mla_context_paged_kv->data_ptr();
                 mla_params.context_kv_cache_block_offsets_ptr = mla_context_kv_cache_block_offsets->data_ptr();
                 mla_params.context_paged_kv_max_blocks_per_seq = mla_context_kv_cache_block_offsets->size(-1);

Optional (readability): document the expected layout locally.
// mla_tensor_params layout: [0]=context_paged_kv, [1]=context_kv_cache_block_offsets, [2]=helix_position_offsets (optional)

🧹 Nitpick comments (5)
cpp/tensorrt_llm/kernels/mlaKernels.h (1)

93-94: Helix offsets plumbed into MlaParams — looks good; clarify contract (shape/index space).

The addition is correct and non-intrusive. Please clarify the expected index space and shape in the comment to avoid confusion at call sites (global token index across the entire batch, device pointer). This helps prevent subtle misuse.

Apply this diff to enrich the comment:

-    // for Helix parallelism: the rotary position offsets [b]
-    int32_t const* helix_position_offsets{nullptr};
+    // For Helix parallelism: rotary position offsets in global-token index space.
+    // Shape: [total_s_len] (sum of per-seq lengths), device pointer on CUDA.
+    // When nullptr, the default positional indexing is used by the kernels.
+    int32_t const* helix_position_offsets{nullptr};
tensorrt_llm/_torch/attention_backend/trtllm.py (2)

223-223: Fix line too long (Ruff E501) in docstring.

Split the helix_position_offsets docstring line to stay within the 120-char limit.

-            helix_position_offsets (torch.Tensor): The tensor to store the helix position offsets, with shape (num_tokens) on GPU.
+            helix_position_offsets (torch.Tensor): The tensor to store the helix position offsets,
+                with shape (num_tokens) on GPU.

1113-1114: Forward API: helix_position_offsets threading is OK; add a short docstring note.

The param is optional and does not change default behavior. Consider documenting its expected shape/dtype to guide users.

cpp/tensorrt_llm/thop/attentionOp.cpp (2)

80-83: Avoid copying MLA tensor params; pass by ArrayRef like spec-decoding tensors

Pass mla_tensor_params as c10::ArrayRef to avoid an extra vector copy and to align with the spec_decoding_tensor_params pattern.

Apply this diff to the RunnerBase::run signature:

-        std::vector<std::optional<torch::Tensor>> mla_tensor_params,
+        c10::ArrayRef<std::optional<torch::Tensor>> mla_tensor_params,

134-137: Mirror ArrayRef change in Runner::run override

Keep the override consistent with the base class, and avoid copies here as well.

Apply this diff to the Runner::run signature:

-        std::vector<std::optional<torch::Tensor>> mla_tensor_params,
+        c10::ArrayRef<std::optional<torch::Tensor>> mla_tensor_params,
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1095dfd and 9cfed31.

📒 Files selected for processing (6)
  • cpp/tensorrt_llm/kernels/mlaKernels.cu (3 hunks)
  • cpp/tensorrt_llm/kernels/mlaKernels.h (1 hunks)
  • cpp/tensorrt_llm/nanobind/thop/bindings.cpp (1 hunks)
  • cpp/tensorrt_llm/pybind/thop/bindings.cpp (1 hunks)
  • cpp/tensorrt_llm/thop/attentionOp.cpp (7 hunks)
  • tensorrt_llm/_torch/attention_backend/trtllm.py (7 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/kernels/mlaKernels.h
  • cpp/tensorrt_llm/pybind/thop/bindings.cpp
  • cpp/tensorrt_llm/nanobind/thop/bindings.cpp
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/mlaKernels.cu
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/kernels/mlaKernels.h
  • cpp/tensorrt_llm/pybind/thop/bindings.cpp
  • cpp/tensorrt_llm/nanobind/thop/bindings.cpp
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/mlaKernels.cu
**/*.{h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Header files must use include guards named TRTLLM__H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)

Files:

  • cpp/tensorrt_llm/kernels/mlaKernels.h
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • cpp/tensorrt_llm/kernels/mlaKernels.h
  • cpp/tensorrt_llm/pybind/thop/bindings.cpp
  • cpp/tensorrt_llm/nanobind/thop/bindings.cpp
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/mlaKernels.cu
  • tensorrt_llm/_torch/attention_backend/trtllm.py
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/pybind/thop/bindings.cpp
  • cpp/tensorrt_llm/nanobind/thop/bindings.cpp
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/mlaKernels.cu
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/_torch/attention_backend/trtllm.py
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/attention_backend/trtllm.py

223-223: Line too long (130 > 120)

(E501)

🔇 Additional comments (6)
cpp/tensorrt_llm/kernels/mlaKernels.cu (2)

362-363: Kernel signature extension is consistent and preserves ordering.

The extra parameter is appended at the end, keeping ABI alignment with the launch site. No concerns.


999-999: Host-side wiring passes helix offsets correctly.

The added argument is forwarded in the proper position to match the kernel signature.

tensorrt_llm/_torch/attention_backend/trtllm.py (2)

180-181: Plan API: helix_position_offsets exposure is fine.

The new parameter is threaded cleanly through plan() and forward(). Ensure downstream validation to avoid dtype/device mismatches.


489-489: Wrapper forwards mla_tensor_params correctly.

The binding call site matches the updated pybind/nanobind signatures.

cpp/tensorrt_llm/thop/attentionOp.cpp (2)

683-685: LGTM: correctly forwards MLA params for context stage

The added mla_tensor_params and softmax_stats_tensor/spec params are forwarded in the right order to Runner::run.


699-701: LGTM: correctly forwards MLA params for generation stage

The generation call mirrors the context call and keeps the same parameter ordering.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15310 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #11559 completed with status: 'FAILURE'

@MatthiasKohl
Copy link
Collaborator Author

/bot run

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: 2

🧹 Nitpick comments (2)
cpp/tensorrt_llm/thop/attentionOp.cpp (2)

80-80: Avoid copies: accept mla_tensor_params as ArrayRef in Runner interfaces

The vector is passed by value into RunnerBase::run and Runner::run, causing unnecessary copies. Use c10::ArrayRef (consistent with spec_decoding_tensor_params) to avoid allocations and copying.

Apply these diffs:

-        std::vector<std::optional<torch::Tensor>> mla_tensor_params,
+        c10::ArrayRef<std::optional<torch::Tensor>> mla_tensor_params,
-        std::vector<std::optional<torch::Tensor>> mla_tensor_params,
+        c10::ArrayRef<std::optional<torch::Tensor>> mla_tensor_params,

Also applies to: 134-134


165-172: Replace magic indices (0/1/2) with named constexpr constants

Per guidelines (avoid magic numbers), introduce named indices to improve readability and reduce error-proneness.

Apply this diff:

-            TORCH_CHECK(mla_tensor_params.size() == 3,
+            TORCH_CHECK(mla_tensor_params.size() == 3,
                 "Expecting 3 tensors for custom MLA tensor params: context_paged_kv, "
                 "context_kv_cache_block_offsets, helix_position_offsets.");
+            constexpr size_t kMlaContextPagedKvIdx = 0;
+            constexpr size_t kMlaContextKvCacheBlockOffsetsIdx = 1;
+            constexpr size_t kMlaHelixPositionOffsetsIdx = 2;
             if (is_context && op.mPagedContextFMHA && op.mPagedKVCache)
             {
-                auto& mla_context_paged_kv = mla_tensor_params[0];
-                auto& mla_context_kv_cache_block_offsets = mla_tensor_params[1];
+                auto const& mla_context_paged_kv = mla_tensor_params[kMlaContextPagedKvIdx];
+                auto const& mla_context_kv_cache_block_offsets = mla_tensor_params[kMlaContextKvCacheBlockOffsetsIdx];
                 TORCH_CHECK(mla_context_paged_kv.has_value());
                 TORCH_CHECK(mla_context_kv_cache_block_offsets.has_value());
@@
-            auto& mla_helix_position_offsets = mla_tensor_params[2];
-            if (mla_helix_position_offsets.has_value())
+            auto const& mla_helix_position_offsets = mla_tensor_params[kMlaHelixPositionOffsetsIdx];
+            if (mla_helix_position_offsets.has_value())
             {
                 mla_params.helix_position_offsets = mla_helix_position_offsets->data_ptr<int32_t>();
             }

Also applies to: 205-209

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9cfed31 and d4204d6.

📒 Files selected for processing (2)
  • cpp/tensorrt_llm/thop/attentionOp.cpp (7 hunks)
  • cpp/tensorrt_llm/thop/attentionOp.h (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/thop/attentionOp.h
  • cpp/tensorrt_llm/thop/attentionOp.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/thop/attentionOp.h
  • cpp/tensorrt_llm/thop/attentionOp.cpp
**/*.{h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Header files must use include guards named TRTLLM__H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)

Files:

  • cpp/tensorrt_llm/thop/attentionOp.h
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • cpp/tensorrt_llm/thop/attentionOp.h
  • cpp/tensorrt_llm/thop/attentionOp.cpp
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/thop/attentionOp.cpp
🧠 Learnings (3)
📚 Learning: 2025-08-14T15:41:16.775Z
Learnt from: MatthiasKohl
PR: NVIDIA/TensorRT-LLM#6904
File: cpp/tensorrt_llm/thop/attentionOp.cpp:202-206
Timestamp: 2025-08-14T15:41:16.775Z
Learning: The PyTorch tensor's templated data_ptr<T>() method automatically validates that the tensor's dtype matches the requested type T and will throw a runtime error if there's a mismatch, making explicit dtype checks redundant before calling data_ptr<T>().

Applied to files:

  • cpp/tensorrt_llm/thop/attentionOp.cpp
📚 Learning: 2025-08-14T15:38:01.730Z
Learnt from: MatthiasKohl
PR: NVIDIA/TensorRT-LLM#6904
File: cpp/tensorrt_llm/pybind/thop/bindings.cpp:55-57
Timestamp: 2025-08-14T15:38:01.730Z
Learning: In TensorRT-LLM Python bindings, tensor parameter collections like mla_tensor_params and spec_decoding_tensor_params are kept as required parameters without defaults to maintain API consistency, even when it might affect backward compatibility.

Applied to files:

  • cpp/tensorrt_llm/thop/attentionOp.cpp
📚 Learning: 2025-08-14T15:43:23.067Z
Learnt from: MatthiasKohl
PR: NVIDIA/TensorRT-LLM#6904
File: tensorrt_llm/_torch/attention_backend/trtllm.py:259-262
Timestamp: 2025-08-14T15:43:23.067Z
Learning: In TensorRT-LLM's attention backend, tensor parameters in the plan() method are assigned directly without validation (dtype, device, contiguity checks). This maintains consistency across all tensor inputs and follows the pattern of trusting callers to provide correctly formatted tensors.

Applied to files:

  • cpp/tensorrt_llm/thop/attentionOp.cpp
⏰ 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). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (2)
cpp/tensorrt_llm/thop/attentionOp.cpp (2)

686-687: LGTM: Correctly forwards new mla_tensor_params to Runner

The updated call sites forward mla_tensor_params and keep spec_decoding_tensor_params ordering consistent with the Runner signature.

Also applies to: 702-703


165-168: Verified — no change required: all call sites pass 3 MLA tensors

Short summary: I searched the repo and confirmed the MLA tensor list is constructed with exactly three entries in the Python backend and is forwarded through the bindings; the C++ check (size()==3) matches the call sites. The helix_position_offsets entry is allowed to be None and is handled in the C++ code.

Files of interest:

  • cpp/tensorrt_llm/thop/attentionOp.cpp:165-172 (TORCH_CHECK(mla_tensor_params.size() == 3) and indexing [0],[1]) and 205-207 (uses mla_tensor_params[2] with has_value() check).
  • tensorrt_llm/_torch/attention_backend/trtllm.py:425-427 — mla_tensor_params = [self.mla_context_paged_kv, self.mla_context_kv_cache_block_offsets, self.helix_position_offsets]
  • cpp/tensorrt_llm/pybind/thop/bindings.cpp and cpp/tensorrt_llm/nanobind/thop/bindings.cpp — mla_tensor_params exposed as a function argument.

Result: no further action required here; the strict size()==3 check is consistent with current call sites.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15319 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15319 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #11564 completed with status: 'FAILURE'

@MatthiasKohl MatthiasKohl force-pushed the user/mjoux/helix-mla-kernels-position-ids branch from d4204d6 to 8037b4e Compare September 16, 2025 16:37
@MatthiasKohl
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18816 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18816 [ run ] completed with state FAILURE

@MatthiasKohl
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18914 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18914 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14180 completed with status: 'FAILURE'

@MatthiasKohl MatthiasKohl force-pushed the user/mjoux/helix-mla-kernels-position-ids branch from 8037b4e to ed4027e Compare September 17, 2025 10:07
@MatthiasKohl
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18978 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18978 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14229 completed with status: 'FAILURE'

@MatthiasKohl
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19005 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19005 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14251 completed with status: 'FAILURE'

Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
@MatthiasKohl MatthiasKohl force-pushed the user/mjoux/helix-mla-kernels-position-ids branch from ed4027e to ca3b354 Compare September 17, 2025 14:36
@MatthiasKohl
Copy link
Collaborator Author

/bot run

@brb-nv
Copy link
Collaborator

brb-nv commented Sep 17, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19034 [ run ] triggered by Bot

@brb-nv
Copy link
Collaborator

brb-nv commented Sep 17, 2025

Previous unrelated failure waived an hour ago.
#7812

@brb-nv
Copy link
Collaborator

brb-nv commented Sep 17, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19041 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19034 [ run ] completed with state ABORTED
LLM/main/L0_MergeRequest_PR #14275 (Blue Ocean) completed with status: ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19041 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14280 completed with status: 'FAILURE'

Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
@MatthiasKohl
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19149 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19149 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14371 completed with status: 'FAILURE'

@MatthiasKohl
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19199 [ run ] triggered by Bot

Copy link
Collaborator

@brb-nv brb-nv left a comment

Choose a reason for hiding this comment

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

LGTM.

@brb-nv brb-nv enabled auto-merge (squash) September 18, 2025 16:55
@tensorrt-cicd
Copy link
Collaborator

PR_Github #19199 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14413 completed with status: 'FAILURE'

@MatthiasKohl
Copy link
Collaborator Author

/bot run

@MatthiasKohl
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19280 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19282 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19280 [ run ] completed with state ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19282 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14482 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@brb-nv brb-nv merged commit 1be7fae into NVIDIA:main Sep 19, 2025
5 checks passed
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull request Sep 20, 2025
…IDIA#6904)

Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
Co-authored-by: brb-nv <169953907+brb-nv@users.noreply.github.com>
MrGeva pushed a commit to nv-auto-deploy/TensorRT-LLM that referenced this pull request Sep 21, 2025
…IDIA#6904)

Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
Co-authored-by: brb-nv <169953907+brb-nv@users.noreply.github.com>
MatthiasKohl added a commit to MatthiasKohl/TensorRT-LLM that referenced this pull request Sep 30, 2025
…IDIA#6904)

Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
Co-authored-by: brb-nv <169953907+brb-nv@users.noreply.github.com>
MatthiasKohl added a commit to MatthiasKohl/TensorRT-LLM that referenced this pull request Sep 30, 2025
…IDIA#6904)

Signed-off-by: Matthias Jouanneaux <mjoux@nvidia.com>
Co-authored-by: brb-nv <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