-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[TRTLLM-5966][feat] Helix: extend mapping to support different CP types #6816
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
📝 WalkthroughWalkthroughReplaces string-based CP type identifiers with a new Changes
Sequence Diagram(s)sequenceDiagram
participant ExampleTests as Examples/Tests
participant Mapping
participant Runtime as Executor/ResourceMgr
ExampleTests->>Mapping: provide cp_config (contains CpType)
Mapping-->>ExampleTests: expose mapping.cp_type (CpType enum) and world-size info
ExampleTests->>Runtime: pass mapping / cp_config
Runtime->>Mapping: inspect mapping.cp_type
alt CpType.STAR
Runtime->>Runtime: select star-attention paths (merge/prepare/release)
else CpType.RING
Runtime->>Runtime: route to ring-attention (NotImplemented/other)
else
Runtime->>Runtime: ULYSSES/HELIX paths or validations
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested labels
Suggested reviewers
📜 Recent review detailsConfiguration used: .coderabbit.yaml 📒 Files selected for processing (10)
🚧 Files skipped from review as they are similar to previous changes (10)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this 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
🔭 Outside diff range comments (3)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
1461-1467
: Replace assert with explicit exception and fix message grammar for unsupported cp_type.Asserts can be stripped in optimized runs and the message grammar is off. Raise a concrete exception to avoid undefined behavior in production.
Apply this diff:
if cp_type == CpType.STAR: self._update_request_states_star_attention(scheduled_requests) else: - assert False, f'Unsupport cp_type {cp_type}' + raise NotImplementedError(f"Unsupported cp_type {cp_type}")tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
2111-2116
: Replace assert with explicit exception and fix message grammar in cp_type dispatch.Use a clear exception to avoid disappearing behavior under optimized runs, and fix the message.
Apply this diff:
if CpType.STAR == cp_type: return self._prepare_star_attention_inputs( scheduled_requests, kv_cache_manager, attn_metadata) else: - assert False, f'Unsupport cp_type {cp_type}' + raise NotImplementedError(f"Unsupported cp_type {cp_type}")tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
405-414
: Avoid potential NoneType error when accounting for query length.
req.query_id
can be None; calling len(None) will raise. Guard the length computation.Apply this diff:
- if req.ctx_iters == 0: - seq_len = sum( - len(ctx_block) for ctx_block in req.ctx_blocks) - self.impl.add_sequence( - req.py_request_id, - seq_len + (len(req.query_id) if self.mapping.cp_rank - == self.mapping.cp_size - 1 else 0), - req_beam_width, req) + if req.ctx_iters == 0: + seq_len = sum(len(ctx_block) for ctx_block in req.ctx_blocks) + # Only the last rank accounts for query tokens, and query_id may be None + query_len = ( + len(req.query_id) + if (self.mapping.cp_rank == self.mapping.cp_size - 1 and req.query_id) + else 0 + ) + self.impl.add_sequence( + req.py_request_id, + seq_len + query_len, + req_beam_width, + req, + )
🧹 Nitpick comments (4)
tensorrt_llm/mapping.py (2)
180-183
: Fix typo in error message.There's a typo in the error message: "ulysse" should be "ulysses".
- f"attn_cp_size must be 1 for now for ulysse, but got {attn_tp_size}, {attn_cp_size}." + f"attn_cp_size must be 1 for now for ulysses, but got {attn_tp_size}, {attn_cp_size}."
198-201
: Fix line length violation.The error message on line 200 exceeds the 120-character limit as flagged by the static analysis tool.
if moe_tp_cluster_ep_size != moe_world_size: raise ValueError( - f"moe_tp_size * moe_ep_size * moe_cluster_size must equal to moe_world_size, but got {moe_tp_cluster_ep_size} != {moe_world_size}" + f"moe_tp_size * moe_ep_size * moe_cluster_size must equal to moe_world_size, " + f"but got {moe_tp_cluster_ep_size} != {moe_world_size}" )tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)
573-579
: Improve error messages and consistency in cp_type branch.
- Use consistent, user-friendly wording.
- Keep specific message for unimplemented ring attention.
Apply this diff:
if cp_type == CpType.STAR: return self._merge_star_attention_requests(new_requests) elif cp_type == CpType.RING: - raise NotImplementedError("ring attention not implemented yet") + raise NotImplementedError("Ring attention is not implemented yet") else: - raise NotImplementedError(f'unsupport cp type {cp_type}') + raise NotImplementedError(f"Unsupported cp_type {cp_type}")tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
667-669
: Skipping warmup for STAR attention: verify impact and optionally log the decision.Early-returning from warmup for CpType.STAR may degrade first-iteration latency and skip resource priming (e.g., CUDA graphs, autotuner). If intentional, log once to aid diagnostics.
Apply this minimal logging diff to make the behavior explicit:
- if cp_type == CpType.STAR: - return + if cp_type == CpType.STAR: + logger.info("Skipping warmup for Star attention (CpType.STAR)") + returnPlease confirm this skip is expected in your deployment scenarios and won’t regress throughput/latency targets.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
examples/llm-api/star_attention.py
(2 hunks)tensorrt_llm/_torch/pyexecutor/_util.py
(2 hunks)tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
(2 hunks)tensorrt_llm/_torch/pyexecutor/model_engine.py
(3 hunks)tensorrt_llm/_torch/pyexecutor/py_executor.py
(2 hunks)tensorrt_llm/_torch/pyexecutor/resource_manager.py
(2 hunks)tensorrt_llm/mapping.py
(9 hunks)tests/unittest/_torch/multi_gpu/test_star_attention.py
(2 hunks)tests/unittest/_torch/test_flashinfer_star_attn.py
(3 hunks)tests/unittest/others/test_mapping.py
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
**/*.py
: Python code should conform to Python 3.8+.
Indent Python code with 4 spaces. Do not use tabs.
Always maintain the namespace when importing in Python, even if only one class or function from a module is used.
Python filenames should use snake_case (e.g., some_file.py).
Python classes should use PascalCase (e.g., class SomeClass).
Python functions and methods should use snake_case (e.g., def my_awesome_function():).
Python local variables should use snake_case. Prefix k for variable names that start with a number (e.g., k_99th_percentile).
Python global variables should use upper snake_case and prefix G (e.g., G_MY_GLOBAL).
Python constants should use upper snake_case (e.g., MY_CONSTANT).
Avoid shadowing variables declared in an outer scope in Python.
Initialize all externally visible members of a Python class in the constructor.
For interfaces that may be used outside a Python file, prefer docstrings over comments.
Comments in Python should be reserved for code within a function, or interfaces that are local to a file.
Use Google style docstrings for Python classes and functions, which can be parsed by Sphinx.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the class docstring.
Avoid using reflection in Python when functionality can be easily achieved without it.
When using try-except blocks in Python, limit the except to the smallest set of errors possible.
When using try-except blocks to handle multiple possible variable types in Python, keep the body of the try as small as possible, using the else block to implement the logic.
Files:
examples/llm-api/star_attention.py
tests/unittest/_torch/test_flashinfer_star_attn.py
tests/unittest/_torch/multi_gpu/test_star_attention.py
tensorrt_llm/_torch/pyexecutor/py_executor.py
tensorrt_llm/_torch/pyexecutor/_util.py
tests/unittest/others/test_mapping.py
tensorrt_llm/_torch/pyexecutor/resource_manager.py
tensorrt_llm/_torch/pyexecutor/model_engine.py
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
tensorrt_llm/mapping.py
**/*.{cpp,h,hpp,cc,cxx,cu,py}
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.
Files:
examples/llm-api/star_attention.py
tests/unittest/_torch/test_flashinfer_star_attn.py
tests/unittest/_torch/multi_gpu/test_star_attention.py
tensorrt_llm/_torch/pyexecutor/py_executor.py
tensorrt_llm/_torch/pyexecutor/_util.py
tests/unittest/others/test_mapping.py
tensorrt_llm/_torch/pyexecutor/resource_manager.py
tensorrt_llm/_torch/pyexecutor/model_engine.py
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
tensorrt_llm/mapping.py
🧠 Learnings (1)
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.
Applied to files:
examples/llm-api/star_attention.py
🪛 Ruff (0.12.2)
tensorrt_llm/mapping.py
199-199: Line too long (146 > 120)
(E501)
⏰ 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 (19)
tests/unittest/others/test_mapping.py (1)
48-84
: LGTM! Excellent test coverage for CP functionality.The new test cases comprehensively validate CP (Context Parallelism) functionality across different configurations:
- Basic CP test (world_size=2, cp_size=2): Tests fundamental CP group formation
- Multi-dimensional test (world_size=8, tp_size=2, pp_size=2, cp_size=2): Validates complex interactions between TP, PP, and CP
- Large-scale test (world_size=16, tp_size=2, pp_size=2, cp_size=4): Tests scalability and boundary conditions
The tests properly verify:
- Group formations (tp_groups, pp_groups, cp_groups)
- Individual group memberships (tp_group, pp_group, cp_group)
- Boundary condition checks (is_first_, is_last_)
- Navigation methods (prev_, next_)
These tests align well with the new CP functionality introduced in the mapping.py changes.
tensorrt_llm/mapping.py (10)
21-30
: Well-designed enum for CP types.The
CpType
enum provides a clean, type-safe way to represent different context parallelism strategies. The choice ofIntEnum
allows for backward compatibility while providing meaningful names for different CP approaches.
150-152
: Good separation of CP type logic and MOE world size calculation.The implementation correctly derives
cp_type
from thecp_config
and uses it to determine the appropriatemoe_world_size
. The logic properly handles the ULYSSES case where CP doesn't contribute to MOE parallelism.
164-172
: Improved default attention size logic based on CP type.The conditional logic for setting default
attn_tp_size
andattn_cp_size
values is well-structured and properly differentiates between ULYSSES and HELIX CP types. The fallback behavior is intuitive and aligns with each CP type's characteristics.
185-189
: Verify CP size constraint for auto-parallel mode.The validation correctly ensures
cp_size
must be 1 when auto-parallel is enabled, which aligns with the current auto-parallel implementation limitations.
209-212
: Improved error handling for CP-MOE compatibility.The validation correctly identifies the incompatibility between ULYSSES CP and MOE expert parallelism, with a clear error message that helps users understand the current limitation.
300-301
: Good addition of cp_config to equality comparison.Including
cp_config
in the equality check ensures that Mapping objects with different CP configurations are correctly identified as different, which is essential for caching and comparison operations.
316-318
: Proper handling of cp_config in hash function.The hash implementation correctly includes
cp_config
as a sorted tuple of items, ensuring consistent hashing behavior. The comment about not allowingcp_config
updates after initialization is helpful for understanding the design constraint.
400-409
: Useful CP type helper methods.The
has_cp_ulysses()
andhas_cp_helix()
methods provide convenient ways to check for specific CP types, andis_last_helix_rank()
adds specific functionality for HELIX parallelism.
447-468
: Well-implemented CP rank navigation methods.The CP rank navigation methods (
is_first_cp_rank
,is_last_cp_rank
,prev_cp_rank
,next_cp_rank
) provide essential functionality for CP communication patterns. The logic correctly handles wraparound behavior within the same pipeline stage.
508-508
: Good addition of cp_config to serialization.Including
cp_config
in theto_dict()
method ensures that CP configuration is preserved during serialization/deserialization, maintaining consistency with the equality and hash implementations.tests/unittest/_torch/multi_gpu/test_star_attention.py (1)
11-11
: Enum migration looks correct (CpType.STAR).
- Importing CpType and using CpType.STAR in cp_config is consistent with the new enum-based API.
Also applies to: 58-58
examples/llm-api/star_attention.py (1)
10-10
: Good switch to CpType enum in example flow.
- Import of CpType and using CpType.STAR in cp_config aligns the example with the refactor.
Also applies to: 63-66
tests/unittest/_torch/test_flashinfer_star_attn.py (1)
16-16
: Enum-based cp_type usage in tests is correct.
- Importing CpType and replacing string literals with CpType.STAR in both scenarios keeps tests aligned with core changes.
Also applies to: 147-150, 582-585
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
34-34
: Import of CpType is appropriate.
- Keeps this module aligned with cp_type enum usage elsewhere.
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)
14-14
: Import of CpType aligns with enum migration.
- No further changes needed.
tensorrt_llm/_torch/pyexecutor/_util.py (1)
20-20
: Sampler selection based on CpType.STAR is correct.
- Equality against the enum value is the right choice here; do not switch to identity (is).
- The assertion on attn_backend ensures configuration consistency.
Also applies to: 592-595
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
33-33
: Import of CpType is consistent with enum migration.tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
20-20
: Import of CpType is appropriate.
/bot run |
PR_Github #14927 [ run ] triggered by Bot |
PR_Github #14927 [ run ] completed with state |
/bot run |
PR_Github #15000 [ run ] triggered by Bot |
PR_Github #15000 [ run ] completed with state |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM. Minor comments.
c2b7c4d
to
57c6885
Compare
/bot run |
PR_Github #15082 [ run ] triggered by Bot |
PR_Github #15082 [ run ] completed with state |
Signed-off-by: Matthias Jouanneaux <[email protected]>
Signed-off-by: Matthias Jouanneaux <[email protected]>
Signed-off-by: Matthias Jouanneaux <[email protected]>
Signed-off-by: Matthias Jouanneaux <[email protected]>
2aa56f3
to
a7da313
Compare
/bot run |
PR_Github #15133 [ run ] triggered by Bot |
PR_Github #15133 [ run ] completed with state |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Approved on behalf of nemotron devs
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure why this PR requires doc owners to approve but I'm approving to unblock the merge. Thanks.
…es (NVIDIA#6816) Signed-off-by: Matthias Jouanneaux <[email protected]>
…es (NVIDIA#6816) Signed-off-by: Matthias Jouanneaux <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…es (NVIDIA#6816) Signed-off-by: Matthias Jouanneaux <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…es (NVIDIA#6816) Signed-off-by: Matthias Jouanneaux <[email protected]>
…es (NVIDIA#6816) Signed-off-by: Matthias Jouanneaux <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…es (NVIDIA#6816) Signed-off-by: Matthias Jouanneaux <[email protected]>
…es (NVIDIA#6816) Signed-off-by: Matthias Jouanneaux <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Summary by CodeRabbit
New Features
Refactor
Bug Fixes
Tests
Description
This PR adss a
CpType
enum to mapping and uses the enum throughout the code-base.Test Coverage
Added tests for CP rank in mapping: tests/unittest/others/test_mapping.py
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 thestage-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.