-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-10064][feat] MoE all-to-all paradigm #10985
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-10064][feat] MoE all-to-all paradigm #10985
Conversation
Signed-off-by: greg-kwasniewski1 <213329731+greg-kwasniewski1@users.noreply.github.com>
|
/bot run |
|
PR_Github #33491 [ run ] triggered by Bot. Commit: |
|
PR_Github #33491 [ run ] completed with state |
📝 WalkthroughWalkthroughThe changes introduce Expert Parallelism all-to-all paradigm support to AutoDeploy by adding mapping_config parameters across MoE operators, implementing dual-path execution (all-to-all vs. all-reduce), extending sharding configuration with new transform types and attention DP mode, and updating configuration flags for graph preparation and shape propagation. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant fused_moe_kernel as Fused MoE Kernel
participant MoeAlltoAll
participant RankN as Rank N
participant RankM as Rank M
participant AllGather
alt All-to-All Path (mapping_config enabled)
Client->>fused_moe_kernel: trtllm_moe_fused(tokens, experts, weights, mapping_config)
fused_moe_kernel->>MoeAlltoAll: create MoeAlltoAll object
MoeAlltoAll->>RankN: dispatch tokens to responsible ranks
MoeAlltoAll->>RankM: dispatch tokens to responsible ranks
RankN->>fused_moe_kernel: compute MoE on local experts
RankM->>fused_moe_kernel: compute MoE on local experts
fused_moe_kernel->>AllGather: gather results from all ranks
AllGather->>Client: reshape to original shape
else All-Reduce Path (default)
Client->>fused_moe_kernel: trtllm_moe_fused(tokens, experts, weights)
fused_moe_kernel->>RankN: compute MoE on local experts
fused_moe_kernel->>AllGather: all-reduce across ranks
AllGather->>Client: return output
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py (1)
268-360: apply_routing_on_input is ignored in quantized MoE ops.
When callers setapply_routing_on_input=True(BMM-style routing), both FP8 and NVFP4 paths still use output-side routing, producing incorrect results. Please pass the flag through to_template_moe.🐛 Proposed fix
- return _template_moe(x, selected_experts, routing_weights, mlps) + return _template_moe( + x, selected_experts, routing_weights, mlps, apply_routing_on_input + )- return _template_moe(x, selected_experts, routing_weights, mlps) + return _template_moe( + x, selected_experts, routing_weights, mlps, apply_routing_on_input + )Also applies to: 404-510
🤖 Fix all issues with AI agents
In `@tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py`:
- Around line 1632-1716: The injection of default_params (is_gated_mlp, act_fn,
apply_routing_on_input, mapping_config) overwrites caller intent and can
conflict with existing node.kwargs; instead, read and preserve any of these
values from node.kwargs (keys like "is_gated_mlp", "act_fn",
"apply_routing_on_input", "mapping_config"), remove those keys from node.kwargs
to avoid duplicate-argument errors, and only fill missing positions in args
starting at params_start_idx with the preserved or default values
(mapping_config kept/inserted last). Modify the logic around
params_start_idx/default_params to prefer node.kwargs values, clear consumed
kwargs, and then extend/assign into args as done currently so
selected_experts_local and final_scales_local assignment remains compatible.
🧹 Nitpick comments (4)
tensorrt_llm/_torch/auto_deploy/transform/library/fused_moe.py (1)
1368-1377: Preserve traceback when re-raising stack errors.
Usingraise eresets the traceback; a bareraisekeeps the original context.♻️ Suggested fix
- except Exception as e: + except Exception: print(f"Error stacking parameters: {e}") print(f"param_list: {param_list}") print(f"dim: {dim}") - raise e + raisetensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/torch_moe.py (1)
181-182: Avoid mutable list defaults for fake ops’ mapping_config.
Shared default lists are a common Python footgun; useNoneto avoid shared state.♻️ Suggested fix
- mapping_config: List[int] = [], + mapping_config: Optional[List[int]] = None,Also applies to: 380-381, 532-533
tensorrt_llm/_torch/auto_deploy/custom_ops/fused_moe/trtllm_moe.py (1)
256-256: Avoid mutable list defaults for mapping_config in fake op.
UseNoneto prevent shared state across calls.♻️ Suggested fix
- mapping_config: List[int] = [], + mapping_config: Optional[List[int]] = None,tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py (1)
174-186: Remove duplicated enable_attention_dp field.
The second definition overwrites the first; keep a single field to avoid confusion.♻️ Suggested fix
- enable_attention_dp: bool = Field( - default=False, - description="When True, skip TP sharding as attention data parallelism is enabled.", - ) - - dist_mapping: dict[str, int] = Field(default_factory=dict) - - mapping: Mapping = Field(default_factory=Mapping) - - enable_attention_dp: bool = Field( - default=False, - description="When True, skip TP sharding as attention data parallelism is enabled.", - ) + enable_attention_dp: bool = Field( + default=False, + description="When True, skip TP sharding as attention data parallelism is enabled.", + ) + + dist_mapping: dict[str, int] = Field(default_factory=dict) + + mapping: Mapping = Field(default_factory=Mapping)
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>
|
/bot run |
|
PR_Github #33494 [ run ] triggered by Bot. Commit: |
|
PR_Github #33494 [ run ] completed with state |
|
/bot run |
|
PR_Github #33551 [ run ] triggered by Bot. Commit: |
| # MoE Mapping Configuration Indices | ||
| # These indices define the layout of the mapping_config list parameter | ||
| # that encodes sharding information for MoE operators when enable_alltoall=True. | ||
| # Note: mapping_config is only used in all-to-all mode. | ||
| MOE_MAPPING_WORLD_SIZE = 0 | ||
| MOE_MAPPING_TP_SIZE = 1 | ||
| MOE_MAPPING_TP_RANK = 2 | ||
| MOE_MAPPING_EP_SIZE = 3 | ||
| MOE_MAPPING_EP_RANK = 4 | ||
| MOE_MAPPING_CLUSTER_SIZE = 5 | ||
| MOE_MAPPING_CLUSTER_RANK = 6 | ||
| MOE_MAPPING_MAX_NUM_TOKENS = 7 # Max tokens for workspace allocation | ||
| # Future indices can be added here without breaking compatibility | ||
| # e.g., MOE_MAPPING_PP_SIZE, MOE_MAPPING_CP_SIZE, etc. | ||
| MOE_MAPPING_LENGTH = 8 # Current length of mapping_config |
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.
maybe use an enum MoeMapping?
|
PR_Github #33551 [ run ] completed with state
|
|
/bot run --extra-stage "DGX_B200-4_GPUs-AutoDeploy-1, DGX_H100-4_GPUs-AutoDeploy-1" |
|
PR_Github #33563 [ run ] triggered by Bot. Commit: |
|
PR_Github #33563 [ run ] completed with state
|
|
/bot run --extra-stage "DGX_B200-4_GPUs-AutoDeploy-1, DGX_H100-4_GPUs-AutoDeploy-1" |
|
PR_Github #33569 [ run ] triggered by Bot. Commit: |
|
PR_Github #33569 [ run ] completed with state
|
|
/bot run --extra-stage "DGX_B200-4_GPUs-AutoDeploy-1, DGX_H100-4_GPUs-AutoDeploy-1" |
|
PR_Github #33577 [ run ] triggered by Bot. Commit: |
|
PR_Github #33577 [ run ] completed with state
|
|
/bot run --extra-stage "DGX_B200-4_GPUs-AutoDeploy-1, DGX_H100-4_GPUs-AutoDeploy-1" |
|
PR_Github #33594 [ run ] triggered by Bot. Commit: |
|
PR_Github #33594 [ run ] completed with state
|
|
/bot run --extra-stage "DGX_B200-4_GPUs-AutoDeploy-1, DGX_H100-4_GPUs-AutoDeploy-1" |
|
PR_Github #33597 [ run ] triggered by Bot. Commit: |
|
PR_Github #33597 [ run ] completed with state
|
|
/bot run --extra-stage "DGX_B200-4_GPUs-AutoDeploy-1, DGX_H100-4_GPUs-AutoDeploy-1" |
|
PR_Github #33605 [ run ] triggered by Bot. Commit: |
| pre_graph_cleanup: false | ||
| export_to_gm: | ||
| stage: export | ||
| clone_state_dict: false | ||
| strict: false | ||
| run_per_gm: false | ||
| requires_clean_graph: false | ||
| pre_graph_cleanup: false | ||
| cleanup_noop_slice: | ||
| stage: post_export | ||
| cleanup_noop_add: | ||
| stage: post_export | ||
| cleanup_input_constraints: | ||
| stage: post_export | ||
| ############################################################################################ | ||
| # RUN PATTERN MATCHER TRANSFORMATIONS TO STANDARDIZE GRAPH REPRESENTATION | ||
| ############################################################################################ | ||
| match_moe_pattern: | ||
| stage: pattern_matcher | ||
| match_dense_moe_pattern: | ||
| stage: pattern_matcher | ||
| match_bmm_moe_pattern: | ||
| stage: pattern_matcher | ||
| match_repeat_kv: | ||
| stage: pattern_matcher | ||
| run_shape_prop: true | ||
| post_shape_prop: true | ||
| match_eager_attention: | ||
| stage: pattern_matcher | ||
| requires_shape_prop: true | ||
| pre_shape_prop: true |
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.
looks like a left over from a rebase. This PR isn't merged yet
| sharding_source: ['manual', 'factory', 'heuristic'] | ||
| support_partial_config: true | ||
| sharding_dims: ['tp', 'ep', 'bmm'] | ||
| sharding_dims: ['TP','EP'] |
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.
did you remove bmm on purpose? It'd be nice to keep vanilla bmm sharding around in case we encounter a bmm operator that we cannot pattern match
| allreduce_strategy: 'NCCL' | ||
| dist_backend: auto | ||
| requires_shape_prop: true | ||
| enable_attention_dp: false |
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.
left over from rebase
| MOE_MAPPING_MAX_NUM_TOKENS = 7 # Max tokens for workspace allocation | ||
| # Future indices can be added here without breaking compatibility | ||
| # e.g., MOE_MAPPING_PP_SIZE, MOE_MAPPING_CP_SIZE, etc. | ||
| MOE_MAPPING_LENGTH = 8 # Current length of mapping_config |
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.
no global variables please. How does the PT backend solve this? Mapping object that already exists might be a good resolution
| # It assumes that the closer ranks are physically closer | ||
| # e.g., on the same multi-gpu node. | ||
| # If desired, the order can be changed by reordering the dimensions. | ||
| PP = 0 # Pipeline parallelism |
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.
we don't have PP yet?
| self.new_node.replace_input_with(self.new_node, node) | ||
|
|
||
|
|
||
| class TPtoDPTransformInfo(ShardingTransformInfo): |
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.
this seems complicated to support. Before we add support for this, can you confirm in the PT backend that this is something that needs support?
| with gm.graph.inserting_after(node): | ||
| batch_size_node = gm.graph.call_method("size", args=(node, 0)) | ||
| with gm.graph.inserting_after(batch_size_node): | ||
| remainder_node = gm.graph.call_function( | ||
| operator.mod, args=(batch_size_node, self.config.world_size) | ||
| ) | ||
| with gm.graph.inserting_after(remainder_node): | ||
| pad_size_node = gm.graph.call_function( | ||
| operator.sub, args=(self.config.world_size, remainder_node) | ||
| ) | ||
| with gm.graph.inserting_after(pad_size_node): | ||
| pad_size_node = gm.graph.call_function( | ||
| operator.mod, args=(pad_size_node, self.config.world_size) | ||
| ) | ||
| with gm.graph.inserting_after(pad_size_node): | ||
| dim1_node = gm.graph.call_method("size", args=(node, 1)) | ||
| with gm.graph.inserting_after(dim1_node): | ||
| dim2_node = gm.graph.call_method("size", args=(node, 2)) | ||
| with gm.graph.inserting_after(dim2_node): | ||
| pad_tensor_node = gm.graph.call_method( | ||
| "new_zeros", args=(node, (pad_size_node, dim1_node, dim2_node)) | ||
| ) | ||
| with gm.graph.inserting_after(pad_tensor_node): | ||
| padded_node = gm.graph.call_function( | ||
| torch.ops.aten.cat.default, args=((node, pad_tensor_node), 0) | ||
| ) | ||
| with gm.graph.inserting_after(padded_node): | ||
| padded_batch_size_node = gm.graph.call_function( | ||
| operator.add, args=(batch_size_node, pad_size_node) | ||
| ) | ||
| with gm.graph.inserting_after(padded_batch_size_node): | ||
| local_batch_size_node = gm.graph.call_function( | ||
| operator.floordiv, args=(padded_batch_size_node, self.config.world_size) | ||
| ) | ||
| with gm.graph.inserting_after(local_batch_size_node): | ||
| local_batch_start_node = gm.graph.call_function( | ||
| operator.mul, args=(local_batch_size_node, self.config.rank) | ||
| ) | ||
| with gm.graph.inserting_after(local_batch_start_node): | ||
| local_batch_end_node = gm.graph.call_function( | ||
| operator.mul, args=(local_batch_size_node, self.config.rank + 1) | ||
| ) | ||
| with gm.graph.inserting_after(local_batch_end_node): | ||
| mask_node = gm.graph.call_function( | ||
| torch.ops.aten.slice.Tensor, | ||
| args=(padded_node, 0, local_batch_start_node, local_batch_end_node, 1), | ||
| ) |
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.
You don't need these repeated inserting_after statements. Here is an overview from AI:
Example: add multiple pointwise ops after the linear
# find the linear call
linear_node = None
for node in graph.nodes:
if node.op == "call_module" and node.target == "linear":
linear_node = node
break
assert linear_node is not None
with graph.inserting_after(linear_node):
relu = graph.call_function(torch.relu, args=(linear_node,))
add = graph.call_function(torch.add, args=(relu, 1.0))
mul = graph.call_function(torch.mul, args=(add, 2.0))
This guarantees strict ordering:
linear → relu → add → mul
| # Extract max_num_tokens from sequence info for MoE all-to-all workspace allocation | ||
| if cm and cm.info: | ||
| config.max_num_tokens = cm.info.max_batch_size * cm.info.max_seq_len | ||
| else: | ||
| config.max_num_tokens = 0 |
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.
do not assume max_num_tokens. cm.info has max_num_tokens stored
| class ShardingTransformConfig(TransformConfig): | ||
| """Configuration for sharding the model.""" | ||
|
|
||
| model_config = ConfigDict(arbitrary_types_allowed=True) |
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.
remove model_config ?
| class NodeInsertInfo(ShardingTransformInfo): | ||
| """Configuration for node insert transformations.""" | ||
|
|
||
| model_config = ConfigDict(arbitrary_types_allowed=True) |
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.
| model_config = ConfigDict(arbitrary_types_allowed=True) |
remove
|
PR_Github #33605 [ run ] completed with state
|
|
/bot run --extra-stage "DGX_B200-4_GPUs-AutoDeploy-1, DGX_H100-4_GPUs-AutoDeploy-1" |
Fixes #10064
Summary by CodeRabbit
New Features
Improvements
✏️ 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.