-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[#5860][autodeploy] GPT-OSS MXFP4 support #7451
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
📝 WalkthroughWalkthroughAdds MXFP4 MoE support: new custom ops (mxfp4_mlp, torch_moe_router, torch_moe_dense_mlp), FX transforms to match/insert MXFP4 MoE, a GPT‑Oss router export patch, adjustments to AutoDeploy pipeline (remove quantize/sharding/fusion stages, add cache initialization steps), and HF model dtype selection via quantizer. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Exporter
participant Model
participant Patch as GptOssTopKRouterPatch
participant Op as torch.ops.auto_deploy.torch_moe_router
Exporter->>Patch: apply()
Exporter->>Model: forward(hidden_states)
Note over Model: Router.forward replaced
Model->>Op: torch_moe_router(hs, weight, bias, top_k)
Op-->>Model: router_scores [T,E]
Model-->>Exporter: (router_scores, None)
Exporter->>Patch: revert()
sequenceDiagram
autonumber
participant FX_Graph
participant PatternMatcher
participant InsertMXFP4
participant CacheInit
participant Compile
FX_Graph->>PatternMatcher: match_dense_moe_pattern / match_moe_router
PatternMatcher-->>FX_Graph: replace nodes with torch_moe_* calls
FX_Graph->>InsertMXFP4: insert_mxfp4_mlp
InsertMXFP4-->>FX_Graph: add mxfp4_mlp nodes + expert params
FX_Graph->>CacheInit: update_in_out_nodes / insert_cached_* / initialize_cache / resize_kv_cache
CacheInit-->>FX_Graph: kvcache nodes added
FX_Graph->>Compile: compile_model
Compile-->>FX_Graph: compiled artifact
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
✨ 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
|
76c0156 to
89d5727
Compare
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: 3
🧹 Nitpick comments (9)
tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py (4)
1-3: Add NVIDIA copyright header.All source files must include the current-year NVIDIA header.
Apply:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + import torch
45-69: Docstring return mismatch.Docstring says the op returns routed_out and router_logits, but the function returns only routed_out. Fix the docstring to avoid confusion in downstream users and tooling.
Apply:
- Return: - routed_out: same leading shape as hidden_states, last dim = H - router_logits: [T, E] (T = number of tokens = prod(hidden_states.shape[:-1])) + Return: + routed_out: same leading shape as hidden_states, last dim = H
6-13: Harden kernel hub import with a clear error message.If kernels hub is unavailable, the import will fail at runtime without context. Raise a descriptive error.
Apply:
def _hub(): global _triton_kernels_hub if _triton_kernels_hub is None: - from kernels import get_kernel - - _triton_kernels_hub = get_kernel("kernels-community/triton_kernels") + try: + from kernels import get_kernel + _triton_kernels_hub = get_kernel("kernels-community/triton_kernels") + except Exception as e: + raise RuntimeError( + "Failed to load Triton kernels hub 'kernels-community/triton_kernels'. " + "Ensure kernels are installed and discoverable." + ) from e return _triton_kernels_hub
15-26: Follow codebase globals convention (G_ prefix, UPPER_SNAKE_CASE)._global _triton_kernels_hub violates the repository’s Python globals naming rule.
Apply:
-_triton_kernels_hub = None +G_TRITON_KERNELS_HUB = None @@ - global _triton_kernels_hub - if _triton_kernels_hub is None: + global G_TRITON_KERNELS_HUB + if G_TRITON_KERNELS_HUB is None: @@ - _triton_kernels_hub = get_kernel("kernels-community/triton_kernels") - return _triton_kernels_hub + G_TRITON_KERNELS_HUB = get_kernel("kernels-community/triton_kernels") + return G_TRITON_KERNELS_HUBAlso update its single reference at Line 17 accordingly.
tensorrt_llm/_torch/auto_deploy/transform/library/mxfp4.py (5)
1-3: Add NVIDIA copyright header.New source files must include the current-year NVIDIA header.
Apply:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + from typing import Tuple
124-139: Router pattern return annotation is incorrect.Function returns a single Tensor, but type hints declare a Tuple. Align annotation to avoid confusion and tooling issues.
Apply:
-def _router_pattern( +def _router_pattern( hidden_states: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, top_k: int = 2, -) -> Tuple[torch.Tensor, torch.Tensor]: +) -> torch.Tensor: @@ - return router_scores + return router_scores(Only the return type changes.)
150-163: Remove stray debug print.Printing the FX graph during transforms is noisy and pollutes logs. Use logging if needed.
Apply:
- print(str(graph))
215-218: Register expert blocks/scales as buffers, not parameters.These tensors are inference-only metadata. Registering as parameters can perturb optimizers and state dict semantics.
Apply:
-def _ensure_param(mod: nn.Module, name: str, tensor: torch.Tensor) -> None: - if not hasattr(mod, name): - mod.register_parameter(name, nn.Parameter(tensor, requires_grad=False)) +def _ensure_param(mod: nn.Module, name: str, tensor: torch.Tensor) -> None: + if not hasattr(mod, name): + mod.register_buffer(name, tensor, persistent=True)No other call sites need changes since attributes are accessed via get_attr nodes.
356-359: Potential name collisions for newly registered attributes.gate_up_proj_blocks/scales and down_proj_blocks/scales are generic. If users re-run transforms, these may exist already. Consider suffixing with a stable tag or checking existence before registering.
You already guard with hasattr in _ensure_param, but add a prefix (e.g., ad) or a model-unique tag to avoid clashes across different experts modules if multiple MoE blocks exist.
📜 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/custom_ops/__init__.py(1 hunks)tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py(1 hunks)tensorrt_llm/_torch/auto_deploy/models/hf.py(1 hunks)tensorrt_llm/_torch/auto_deploy/transform/library/mxfp4.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- tensorrt_llm/_torch/auto_deploy/custom_ops/init.py
- tensorrt_llm/_torch/auto_deploy/config/default.yaml
🧰 Additional context used
📓 Path-based instructions (4)
**/*
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Filenames compiled into a target must be case-insensitively unique
Files:
tensorrt_llm/_torch/auto_deploy/models/hf.pytensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.pytensorrt_llm/_torch/auto_deploy/transform/library/mxfp4.py
**/*.{h,hpp,hh,hxx,cc,cpp,cxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use spaces, not tabs; indent 4 spaces
Files:
tensorrt_llm/_torch/auto_deploy/models/hf.pytensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.pytensorrt_llm/_torch/auto_deploy/transform/library/mxfp4.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Code must target Python 3.8+
Indent with 4 spaces; do not use tabs (Python)
Maintain module namespace on import: prefer from package.subpackage import foo; use foo.Symbol()
Python filenames use snake_case
Python class names use PascalCase
Python functions and methods use snake_case
Python local variables use snake_case; if starting with a number concept, prefix with k (e.g., k_99th_percentile)
Python global variables use G_ prefix with UPPER_SNAKE_CASE
Python constants use UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes
Initialize all externally visible class members in init
For public interfaces, prefer docstrings over comments; comments should be for in-function or file-local interfaces
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes and variables inline with docstrings immediately after assignment
Avoid reflection when a non-reflective approach suffices
Limit except clauses to specific exceptions where possible
When using try/except for duck-typing, keep try body minimal and move logic to else
Files:
tensorrt_llm/_torch/auto_deploy/models/hf.pytensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.pytensorrt_llm/_torch/auto_deploy/transform/library/mxfp4.py
**/*.{cpp,cc,cxx,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend NVIDIA copyright header (current year) to all source files
Files:
tensorrt_llm/_torch/auto_deploy/models/hf.pytensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.pytensorrt_llm/_torch/auto_deploy/transform/library/mxfp4.py
🧬 Code graph analysis (2)
tensorrt_llm/_torch/auto_deploy/models/hf.py (2)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (1)
to(336-340)tensorrt_llm/_torch/auto_deploy/shim/interface.py (1)
to(33-37)
tensorrt_llm/_torch/auto_deploy/transform/library/mxfp4.py (6)
tensorrt_llm/_torch/auto_deploy/utils/pattern_matcher.py (2)
ADPatternMatcherPass(61-67)register_ad_pattern(99-182)tensorrt_llm/_torch/auto_deploy/utils/node_utils.py (1)
is_op(183-206)tensorrt_llm/_torch/auto_deploy/transform/interface.py (3)
BaseTransform(139-378)TransformInfo(108-133)TransformRegistry(381-409)tensorrt_llm/_torch/auto_deploy/custom_ops/torch_moe.py (1)
torch_moe_dense_mlp(343-372)tensorrt_llm/_torch/auto_deploy/custom_ops/torch_router.py (1)
torch_moe_router(6-31)tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py (1)
mxfp4_mlp(46-140)
⏰ 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 (1)
tensorrt_llm/_torch/auto_deploy/models/hf.py (1)
174-183: Approve import guard and dtype fallbackThe try-except around
AutoHfQuantizerimport handles missingtransformers,quantization_config is Noneis checked, andmodel.to()is only called when a valid dtype is determined.
f06b436 to
27d15ec
Compare
27d15ec to
9e77893
Compare
38117f0 to
b6291d0
Compare
e61f11f to
6cc41b1
Compare
tests/unittest/_torch/auto_deploy/unit/multigpu/custom_ops/test_mxfp4_moe_ep.py
Show resolved
Hide resolved
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.
In general, looks good for me. I left comments throughout the files. My only concern is the sharding logic when num_experts % world_size != 0, and a mismatch between the test and the actual logic.
33fa7ba to
94a0490
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #19987 [ run ] triggered by Bot |
|
PR_Github #19987 [ run ] completed with state |
|
/bot run |
|
PR_Github #19998 [ run ] triggered by Bot |
|
PR_Github #19998 [ run ] completed with state |
|
/bot run |
|
PR_Github #20017 [ run ] triggered by Bot |
|
PR_Github #20017 [ run ] completed with state |
Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> minor update on default.yaml Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> minor update on default.yaml Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> add new custom op Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> add HfQuantizer Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> use TRTLLM EPRouter for sharding support Signed-off-by: Fridah-nv <201670829+Fridah-nv@users.noreply.github.com>
…de duplication Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> minor file rename Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> update quantize_mxfp4_moe transform to read from quant config Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
…tter naming and comments use simple expert load balancing Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> minor Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> minor Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> move get_submodule to new util function Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com> minor:move QuantConfigReader detection to quant_config_reader.py Signed-off-by: Frida Hou <201670829+Fridah-nv@users.noreply.github.com>
54d8edd to
bc5edc1
Compare
|
/bot run |
|
PR_Github #20043 [ run ] triggered by Bot |
|
PR_Github #20043 [ run ] completed with state |
|
/bot run |
|
PR_Github #20107 [ run ] triggered by Bot |
|
PR_Github #20107 [ run ] completed with state |
|
/bot run |
|
PR_Github #20114 [ run ] triggered by Bot |
|
PR_Github #20114 [ run ] completed with state |
This PR does the following:
GptOssExpertsseparately:torch.ops.auto_deploy.torch_moe_routerandtorch.ops.auto_deploy.torch_moe_dense_mlptotorch.ops.auto_deploy.triton_mxfp4_moe, register the new params expected from checkpointtorch.ops.auto_deploy.triton_mxfp4_moeenv requirements for huggingface to load MXFP4 model
Currently sharding uses
tensorrt_llm._torch.modules.fused_moe.fused_moe_triton.TritonEPRouterwhich requires building triton from source:Verified with triton version 3.5 +, commit sha: f22c53ad7
Tested on 8*H200, model is able to load onto one H200.
Tested with command:
Output (WS=1 and WS=8 are the same)
It's a bit repetitive, but the BF16 model gives something similar with torch attention backend. See discussions: https://nvidia.slack.com/archives/C08T55LHSG4/p1756162597642669?thread_ts=1756142462.162129&cid=C08T55LHSG4
Summary by CodeRabbit
New Features
Refactor
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-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.