-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-10318][feat] Fixing Nemotron sharding: support for sharding buffers #10319
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
base: main
Are you sure you want to change the base?
[TRTLLM-10318][feat] Fixing Nemotron sharding: support for sharding buffers #10319
Conversation
|
/bot run |
|
PR_Github #30056 [ run ] triggered by Bot. Commit: |
📝 WalkthroughWalkthroughThis change refactors weight node extraction and handling across the AutoDeploy transform library to support multiple weight nodes per linear operation. New data models ( Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Pre-merge checks and finishing touches❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
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: 5
🧹 Nitpick comments (3)
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (2)
1328-1341: Remove commented-out dead code.This large block of commented-out code should be removed rather than left in place. It clutters the codebase and the git history preserves the old implementation if needed.
🔎 Proposed cleanup
rank, world_size = config.rank, config.world_size allreduce_strategy = config.allreduce_strategy.name - # num_users = num_users_of_weight_node(node) - # if num_users > 1 or num_users == 0: - # ad_logger.warning( - # f"Weight node {node} has {num_users} users. This is not supported for sharding. Skipping." - # ) - # return - # # get weight and bias key - # weight_key, bias_key = extract_param_names_from_node(node) - - # modname = weight_key.rpartition(".")[0] - # submod = gm.get_submodule(modname) - - # # Shard weight using the unified function (also updates the parameter) - # original_weight = gm.get_parameter(weight_key) weight_nodes = extract_weight_nodes(node)
1792-1793: Remove commented-out code.This commented-out conditional check should be removed. If the check is no longer needed, delete it; if it's needed for debugging, add a TODO comment explaining why it's preserved.
🔎 Proposed cleanup
for weight_node in weight_nodes: - # if is_any_ssm_op(list(weight_node.users)[0]): - # continue weight_key = weight_node.targettensorrt_llm/_torch/auto_deploy/utils/node_utils.py (1)
68-106: Annotate mutable class attributes withClassVar.The static analysis correctly identifies that mutable class attributes
_parametersand_buffersshould be annotated withtyping.ClassVarto indicate they are class-level, not instance-level attributes.🔎 Proposed fix
+from typing import ClassVar, Dict, Set + class ModuleParams: """Static class for caching module parameters and buffers to avoid repeated lookups.""" - _parameters: dict = {} - _buffers: dict = {} + _parameters: ClassVar[Dict[GraphModule, Set[str]]] = {} + _buffers: ClassVar[Dict[GraphModule, Set[str]]] = {}
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
tensorrt_llm/_torch/auto_deploy/transform/library/quantization.pytensorrt_llm/_torch/auto_deploy/transform/library/sharding.pytensorrt_llm/_torch/auto_deploy/utils/node_utils.pytensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Code developed for TensorRT-LLM 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 files should use snake_case naming:some_file.py
Python classes should use PascalCase naming:class SomeClass
Python functions and methods should use snake_case naming:def my_awesome_function():
Python local variables should use snake_case naming:my_variable = ...
Python variable names that start with a number should be prefixed with 'k':k_99th_percentile = ...
Python global variables should use upper snake_case with prefix 'G':G_MY_GLOBAL = ...
Python constants should use upper snake_case naming: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 Python interfaces that may be used outside a file, prefer docstrings over comments
Python comments should be reserved for code within a function, or interfaces that are local to a file
Use Google style docstrings in Python for classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with type and description
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except to the smallest set of errors possible
When using try-except blocks in Python to handle multiple possible variable types (duck-typing), keep the body of the try as small as possible, using the else block for logic
Files:
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.pytensorrt_llm/_torch/auto_deploy/utils/node_utils.pytensorrt_llm/_torch/auto_deploy/transform/library/quantization.pytensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py
**/*.{cpp,h,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the year of its latest meaningful modification
Files:
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.pytensorrt_llm/_torch/auto_deploy/utils/node_utils.pytensorrt_llm/_torch/auto_deploy/transform/library/quantization.pytensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py
🧠 Learnings (2)
📚 Learning: 2025-10-20T16:54:09.824Z
Learnt from: nvchenghaoz
Repo: NVIDIA/TensorRT-LLM PR: 8469
File: tensorrt_llm/_torch/auto_deploy/custom_ops/rms_norm.py:6-6
Timestamp: 2025-10-20T16:54:09.824Z
Learning: In tensorrt_llm/_torch/auto_deploy/custom_ops/rms_norm.py, the import `from ...modules.mamba.layernorm_gated import _layer_norm_fwd` is correct and should not be changed to modules.fla.layernorm_gated. The _layer_norm_fwd function exists in both modules/mamba/layernorm_gated.py and modules/fla/layernorm_gated.py, but the mamba version is the intended implementation for this use case.
Applied to files:
tensorrt_llm/_torch/auto_deploy/utils/node_utils.pytensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
Repo: NVIDIA/TensorRT-LLM PR: 7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM's bench configuration, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which is a Dict[str, Any] that can contain default values including `cuda_graph_config`, making the fallback `llm_args["cuda_graph_config"]` safe to use.
Applied to files:
tensorrt_llm/_torch/auto_deploy/utils/node_utils.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (1)
tensorrt_llm/_torch/auto_deploy/utils/node_utils.py (2)
extract_weight_name(186-188)extract_weight_nodes(200-267)
tensorrt_llm/_torch/auto_deploy/transform/library/quantization.py (1)
tensorrt_llm/_torch/auto_deploy/utils/node_utils.py (1)
extract_weight_nodes(200-267)
tensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py (1)
tensorrt_llm/_torch/auto_deploy/utils/node_utils.py (1)
extract_weight_name(186-188)
🪛 Ruff (0.14.10)
tensorrt_llm/_torch/auto_deploy/utils/node_utils.py
71-71: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
72-72: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
197-197: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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 (10)
tensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py (2)
10-18: LGTM - Import updated to use new weight extraction API.The import change from
extract_param_names_from_nodetoextract_weight_namealigns with the refactored weight node extraction utilities.
120-122: LGTM - Simplified weight name extraction.The refactored logic correctly uses
extract_weight_name()and derives the module name viarpartition("."). This is cleaner than the previous approach and properly integrates with the new multi-weight handling.tensorrt_llm/_torch/auto_deploy/transform/library/quantization.py (2)
16-21: LGTM - Import updated to new weight extraction API.The import change to
extract_weight_nodesaligns with the multi-weight handling refactor.
170-175: LGTM - Scale registration and load hook properly updated.The refactored code correctly:
- Registers default scales on
lin_weight.submodusinglin_weight.tensor.shape- Uses
lin_weight.node_keyfor the load hook registrationThis properly integrates with the new
WeightNodestructure.tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (4)
41-42: LGTM - Imports updated for new weight extraction utilities.The import changes to
extract_weight_nameandextract_weight_nodesalign with the refactored multi-weight handling across the codebase.
1342-1364: LGTM - Multi-weight sharding iteration correctly implemented.The refactored loop properly:
- Iterates over all weight nodes extracted from the parametrized node
- Shards each weight tensor using
shard_weight_tensor()- Invokes the quantization callback for each weight with the correct context (
weight_node.submod,weight_node.node_key, etc.)This is the core fix enabling sharding of buffers (not just parameters) for Nemotron SSM.
2150-2152: LGTM - Config matching now uses weight name instead of module name.Using
extract_weight_name(lin_node)for pattern matching against the tp_plan config is correct. The weight name (e.g.,model.layers.0.self_attn.q_proj.weight) provides the full path needed for matching sharding patterns.Also applies to: 2176-2176, 2215-2215
1366-1391: Bias handling logic for dim 1 is correct; args[2] assumption is safe.The logic correctly handles biases when
dim == 1andrank != world_size - 1. The assumption that bias is at index 2 innode.argsis safe:_shard_parameter_nodeonly processes linear operations (validated viadetect_column_row_shardwhich filters withis_any_lin_op), and both supported linear ops—torch.ops.aten.linearandtorch.ops.auto_deploy.torch_linear_simple—have the same signature with bias at position 2:(input, weight, bias). No further validation is needed before accessingargs[2].tensorrt_llm/_torch/auto_deploy/utils/node_utils.py (2)
55-66: LGTM - New data models for multi-weight representation.The
WeightNodeandWeightNodesPydantic models provide a clean structure for representing weight/bias nodes with their associated metadata (node, tensor, node_key, submod). This enables proper handling of multiple weights per operation.
191-198: LGTM -get_const_tensorcorrectly handles both parameters and buffers.This is the core fix for the PR objective. The function checks
ModuleParams.get_parameters()first, thenget_buffers(), allowing weight retrieval to work for bothnn.Parameterand buffer tensors.
| class WeightNode(BaseModel): | ||
| model_config = ConfigDict(arbitrary_types_allowed=True) | ||
| node: Node | ||
| tensor: torch.Tensor | ||
| node_key: str | ||
| submod: nn.Module |
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.
WeightNode.submod should be Optional for BMM case.
The WeightNode model defines submod: nn.Module as required, but the BMM handling path (lines 227-238) doesn't provide this field. Either make submod optional with a default of None, or ensure all code paths provide it.
🔎 Proposed fix - make submod optional
class WeightNode(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
node: Node
tensor: torch.Tensor
node_key: str
- submod: nn.Module
+ submod: Optional[nn.Module] = NoneThen update consumers to handle None case where needed.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/utils/node_utils.py around lines 55 to 60,
the WeightNode Pydantic model declares submod: nn.Module as required but the BMM
code path (lines ~227-238) constructs WeightNode without providing submod;
change the model to make submod Optional[nn.Module] = None so it is not
required, and then update any consumers to handle the None case (add guards or
conditional logic where submod is used) to avoid attribute access on None.
|
PR_Github #30056 [ run ] completed with state
|
1f66353 to
72d9189
Compare
|
/bot run |
|
PR_Github #30060 [ run ] triggered by Bot. Commit: |
|
PR_Github #30060 [ run ] completed with state
|
|
/bot run --reuse-test |
|
PR_Github #30062 [ run ] triggered by Bot. Commit: |
|
PR_Github #30062 [ run ] completed with state
|
|
/bot run --reuse-test |
|
PR_Github #30064 [ run ] triggered by Bot. Commit: |
|
PR_Github #30064 [ run ] completed with state
|
|
/bot run --reuse-test |
|
PR_Github #30066 [ run ] triggered by Bot. Commit: |
|
PR_Github #30066 [ run ] completed with state |
72d9189 to
2b7ff7c
Compare
|
/bot run |
|
PR_Github #30176 [ run ] triggered by Bot. Commit: |
lucaslie
left a comment
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 add a tp>1 test here:
| def test_fp8(self): |
Note that it must be correctly configured here: https://github.com/NVIDIA/TensorRT-LLM/tree/main/tests/integration/test_lists/test-db
Signed-off-by: Lucas <11156568+lucaslie@users.noreply.github.com>
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
|
PR_Github #30176 [ run ] completed with state |
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
2b7ff7c to
c5a1754
Compare
Fixes #10318
Summary by CodeRabbit
Release Notes
✏️ Tip: You can customize this high-level summary in your review settings.
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
Update tava architecture diagram if there is a significant design change in PR.
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/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.
Details
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-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.