-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-6342][feat] Support for partial sharding from factory #7393
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
[TRTLLM-6342][feat] Support for partial sharding from factory #7393
Conversation
📝 WalkthroughWalkthroughUpdates the sharding detection pipeline: replaces DP with BMM in default sharding dimensions, adds a support_partial_config flag across config and utilities, changes default model factory, enhances sharding detection to support partial TP+EP/BMM heuristics and specific local shared-expert handling, and updates a unit test to exercise BMM sharding. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User Config
participant IO as InferenceOptimizer
participant STE as ShardingTransformExecutor
participant DS as detect_sharding_from_factory_config
participant SU as Sharding Utils
U->>IO: config.detect_sharding{sharding_dims=[tp,ep,bmm], support_partial_config}
IO->>STE: _apply(shared_config)
STE->>STE: Propagate sharding_dims + support_partial_config
STE->>DS: Run factory-based sharding detection
DS->>DS: Detect TP matches (incl. local shared colwise/rowwise)
alt support_partial_config == true
DS->>DS: Also run EP and/or BMM heuristics per sharding_dims
DS->>DS: Combine num_matches (TP + EP/BMM)
else support_partial_config == false
DS-->>DS: Return TP-only matches (or require full support)
end
DS-->>STE: TransformInfo (num_matches, plan)
STE->>SU: validate_config(sharding_config)
SU-->>STE: ok / error (TP mode subset check gated by flag)
STE-->>IO: Applied sharding transform
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
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 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: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (7)
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py (3)
79-87
: Fix potential division-by-zero when min_local_shape > tensor dim.max_split_size can be 0, causing a crash in ceil(ws / max_split_size). Clamp to at least 1.
Apply:
- max_split_size = t.shape[d] // min_local_shape + max_split_size = max(1, t.shape[d] // min_local_shape) if ws > max_split_size: - num_groups = math.ceil(ws / max_split_size) + num_groups = math.ceil(ws / max_split_size)
346-352
: Avoid reliance on Node.update_arg; use FX-supported mutation.torch.fx Node has no standard update_arg; use args tuple reassignment.
Apply:
- # Update BMM node to use the sliced tensor - bmm_node.update_arg(arg_idx, tensor_slice) + # Update BMM node to use the sliced tensor + args = list(bmm_node.args) + args[arg_idx] = tensor_slice + bmm_node.args = tuple(args)Alternatively: bmm_node.replace_input_with(tensor_node, tensor_slice) if each tensor is unique.
1-1
: Add NVIDIA copyright header.Required by repo guidelines.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
tensorrt_llm/_torch/auto_deploy/llm_args.py (2)
175-178
: Update default sharding_dims to include "bmm" (not "dp").Keep defaults consistent with YAML and transform logic.
- sharding_dims: List[str] = Field( - default=["tp", "ep", "dp"], + sharding_dims: List[str] = Field( + default=["tp", "ep", "bmm"], description="The sharding methods to apply by the heuristic sharding stage.", )
1-1
: Add NVIDIA copyright header.Applies to all .py files.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (1)
1-1
: Add NVIDIA copyright header.Per guidelines.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
tests/unittest/_torch/auto_deploy/unit/multigpu/transformations/library/test_bmm_sharding.py (1)
1-1
: Add NVIDIA copyright header.Applies to test files too per repo policy.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
🧹 Nitpick comments (4)
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py (1)
536-549
: Reasonable relaxation for partial configs; log message could be clearer.When skipping subset enforcement, consider logging which unsupported modes were seen to aid debugging.
Example:
- if not self.support_partial_config and not values.issubset(supported_modes): + if not self.support_partial_config and not values.issubset(supported_modes): ad_logger.warning("Sharding config contains invalid values. Skipping.")Could become:
+ invalid = sorted(values - supported_modes) + if not self.support_partial_config and invalid: + ad_logger.warning(f"Sharding config contains invalid values: {invalid}. Skipping.")tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (2)
621-676
: Simplify unreachable branch in start/end index calc.You early-return when remainder != 0; the rank<remainder branch is dead code. Remove for clarity.
- # Calculate start and end indices for this rank - if rank < remainder: - start_idx = rank * (base_size + 1) - end_idx = start_idx + base_size + 1 - else: - start_idx = remainder + rank * base_size - end_idx = start_idx + base_size + # Calculate start and end indices for this rank (remainder == 0 guaranteed above) + start_idx = rank * base_size + end_idx = start_idx + base_size
342-374
: Use explicit MoE shared-expert detection instead of substring search
Theif "shared" in module_name
check (around line 344) can misclassify any weight whose name contains “shared.” Gate this on known MoE shared-expert metadata or module types (e.g. from the factory’s MoE config) rather than a substring.tests/unittest/_torch/auto_deploy/unit/multigpu/transformations/library/test_bmm_sharding.py (1)
129-133
: Make pattern-detection test explicit about BMM to avoid default drift.Future default changes to sharding_dims won't affect this test.
"detect_sharding": { "stage": "sharding", "use_sharding_from_factory": False, + "sharding_dims": ["bmm"], },
📜 Review details
Configuration used: Path: .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 sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
tensorrt_llm/_torch/auto_deploy/config/default.yaml
(1 hunks)tensorrt_llm/_torch/auto_deploy/llm_args.py
(2 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py
(4 hunks)tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py
(3 hunks)tests/unittest/_torch/auto_deploy/unit/multigpu/transformations/library/test_bmm_sharding.py
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{cpp,cc,cxx,cu,h,hpp,hh,hxx,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.{cpp,cc,cxx,cu,h,hpp,hh,hxx,cuh,py}
: Use spaces only; no tabs; indent with 4 spaces
Prepend NVIDIA copyright header (current year) to all source files (.cpp, .h, .cu, .py, etc.)
Files:
tests/unittest/_torch/auto_deploy/unit/multigpu/transformations/library/test_bmm_sharding.py
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py
tensorrt_llm/_torch/auto_deploy/llm_args.py
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py
: Python code must target Python 3.8+
Indent Python with 4 spaces; no tabs
Preserve module namespaces when importing: from package.subpackage import foo; then call foo.SomeClass() instead of importing the class directly
Python naming: files snake_case; classes PascalCase; functions/methods snake_case; locals snake_case (prefix k_ when starting with a number); globals UPPER_SNAKE_CASE with G_ prefix; constants UPPER_SNAKE_CASE
Avoid shadowing outer-scope variables; initialize all externally visible members in init
Prefer docstrings for interfaces used outside a file; limit comments to function-internal or file-local interfaces
Use Google-style docstrings for classes and functions; document attributes/variables inline so Sphinx can render them
Avoid reflection when simpler alternatives exist; prefer explicit parameters and return dicts over locals()/dynamic tricks
In try/except, catch the narrowest exceptions possible; keep try bodies minimal and use else for the main logic when doing duck-typing checks
Files:
tests/unittest/_torch/auto_deploy/unit/multigpu/transformations/library/test_bmm_sharding.py
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py
tensorrt_llm/_torch/auto_deploy/llm_args.py
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py
🧬 Code graph analysis (2)
tensorrt_llm/_torch/auto_deploy/llm_args.py (1)
tensorrt_llm/llmapi/llm_args.py (1)
Field
(69-96)
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (2)
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py (2)
TPShardingInfo
(230-265)SplitDimension
(183-191)tensorrt_llm/_torch/auto_deploy/transform/interface.py (1)
TransformInfo
(108-133)
⏰ 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 (7)
tensorrt_llm/_torch/auto_deploy/utils/sharding_utils.py (1)
491-491
: Config flag addition looks good.support_partial_config on ShardingConfig aligns with transform config propagation.
tensorrt_llm/_torch/auto_deploy/llm_args.py (2)
168-173
: Good: introduces support_partial_config in user-facing config.Clear description and default false are appropriate.
61-63
: Default model_factory changed: ensure backward compatibility
- Changing the default from
AutoModelForCausalLM
toAutoModelForImageTextToText
is a breaking change for any scripts or workflows that relied on the prior default.- Add a breaking-change note in the release notes to call this out.
- Add or update tests to cover the default
model_factory
value and verify existing pipelines still function as before.tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (3)
129-131
: Config surface LGTM.support_partial_config and explicit sharding_dims are aligned with utils and YAML.
188-190
: Correct propagation of new flags.Ensures detect_sharding behavior respects user config.
398-423
: Partial factory config path is sensible.Combining TP matches with heuristic EP/BMM when opted-in is a good fallback.
tests/unittest/_torch/auto_deploy/unit/multigpu/transformations/library/test_bmm_sharding.py (1)
67-71
: Good: test explicitly enables BMM sharding.This isolates the BMM path and reduces coupling to other sharding modes.
/bot run |
PR_Github #17080 [ run ] triggered by Bot |
PR_Github #17080 [ run ] completed with state |
/bot run |
PR_Github #17209 [ run ] triggered by Bot |
PR_Github #17209 [ run ] completed with state |
/bot run |
PR_Github #17341 [ run ] triggered by Bot |
PR_Github #17341 [ 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.
Please also make sure to test it e2e on a model like llama4
Done and tested the validity of the partial config from factory on llama4 |
/bot run |
PR_Github #18345 [ run ] triggered by Bot |
PR_Github #18345 [ run ] completed with state |
Signed-off-by: greg-kwasniewski1 <[email protected]>
/bot run |
PR_Github #18367 [ run ] triggered by Bot |
PR_Github #18367 [ run ] completed with state |
/bot run |
PR_Github #18399 [ run ] triggered by Bot |
PR_Github #18399 [ 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.
Partial config is not the default and OK to land it to continue experimentation + feature dev. LGTM
@suyoggupta if we resolved all issues with this PR, could you please merge it? I can't do it. |
/bot run |
PR_Github #18482 [ run ] triggered by Bot |
PR_Github #18482 [ run ] completed with state |
/bot run |
PR_Github #18506 [ run ] triggered by Bot |
PR_Github #18506 [ run ] completed with state |
…#7393) Signed-off-by: greg-kwasniewski1 <[email protected]> Signed-off-by: Grzegorz Kwasniewski <[email protected]>
…#7393) Signed-off-by: greg-kwasniewski1 <[email protected]> Signed-off-by: Grzegorz Kwasniewski <[email protected]>
…#7393) Signed-off-by: greg-kwasniewski1 <[email protected]> Signed-off-by: Grzegorz Kwasniewski <[email protected]>
Description
base_model_tp_plan
from HuggingFace factory often specifies sharding modes that are not supported yet by AutoDeploy (e.g., sequence parallelism or mixed EP+TP. Currently, if any of these unsupported modes is provided, the entire sharding from factory is abandoned and the fallback to the heuristics is executed.This PR provides a way to support partial configuration. If (
default.yaml
):then the column-row TP shard is provided when applicable (QKV + O in attention, gate/up + down in MLP, shared experts). The remaining modes (EP, BMM) are detected by existing heuristics.
NOTE
The default behavior is:
so the runtime performance should not change unless otherwise specified.
Summary by CodeRabbit
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 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.