Skip to content

Conversation

@Fridah-nv
Copy link
Collaborator

@Fridah-nv Fridah-nv commented Sep 1, 2025

This PR does the following:

  1. patch MLP forward layer to custom kernel (MXFP4 routing+expert triton kernel)
  2. update model with MXFP4 modules in build_model
  3. export the model

env requirements for huggingface to load MXFP4 model

pip install triton==3.4.0
pip install kernels

and the latest transformers

Summary by CodeRabbit

  • New Features
    • Added an MXFP4-based routed MLP operator with fused activation for faster inference; now available under the custom_ops namespace.
    • Enabled automatic quantization pre-processing during model build, adjusting dtype and preparing weights for quantized execution to improve performance and memory efficiency.

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.

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 the stage-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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

📝 Walkthrough

Walkthrough

Adds a new MXFP4 Triton-backed Torch custom op and exports it via custom_ops. Updates HF model build flow to run a quantization pre-processing pass (dtype update and preprocess) before returning the model. No public API signatures changed beyond the new custom op registration.

Changes

Cohort / File(s) Summary
Custom ops export
tensorrt_llm/_torch/auto_deploy/custom_ops/__init__.py
Exposes mxfp4 symbols to custom_ops by adding from .mxfp4 import *.
MXFP4 Triton custom op
tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py
Introduces auto_deploy::mxfp4_mlp Torch custom op. Implements MXFP4 swizzling, routing, precision config, fused matmuls with optional swiglu, and a fake variant. Includes lazy Triton kernel hub access.
HF model build quantization pass
tensorrt_llm/_torch/auto_deploy/models/hf.py
Adds local import and invocation of AutoHfQuantizer in _build_model: updates dtype, moves model, and runs preprocess_model (no kernels) post model.eval().

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as Caller
  participant T as Torch Custom Op<br/>auto_deploy::mxfp4_mlp
  participant H as Kernel Hub (_hub)
  participant R as Router/Gating
  participant S as Swizzle MXFP4
  participant M1 as Matmul (gate_up)
  participant Act as Fused Activation (swiglu)
  participant M2 as Matmul (down)
  participant O as Output

  U->>T: mxfp4_mlp(hidden_states, weights, scales, biases, top_k, alpha, limit)
  T->>H: get_kernel hub (cached)
  T->>R: compute router_logits and routing_data
  T->>S: swizzle gate_up/down weights + scales (MXFP4 layout)
  T->>M1: routed matmul(hidden_states, gate_up) + bias
  M1-->>T: intermediate_cache1
  T->>Act: apply swiglu(alpha, limit)
  Act-->>T: activated_cache
  T->>M2: routed matmul(activated_cache, down) + bias
  M2-->>T: routed_out
  T->>O: reshape to [B,S,H]
  O-->>U: tensor
  note over T,H: Uses PrecisionConfig / FlexCtx from hub
Loading
sequenceDiagram
  autonumber
  actor C as AutoModelForCausalLMFactory._build_model
  participant M as Model
  participant Q as AutoHfQuantizer

  C->>M: model.eval()
  C->>Q: construct from model_config.quantization_config<br/>(pre_quantized=True)
  C->>Q: update_dtype(model_config.dtype)
  Q-->>C: dtype
  C->>M: model.to(updated_dtype)
  C->>Q: preprocess_model(model, device_map=None,<br/>keep_in_fp32_modules, config, use_kernels=False)
  Q-->>C: preprocessed model
  C-->>C: print(model)
  C-->>C: return model
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • yuxianq
  • hyukn
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (6)
tensorrt_llm/_torch/auto_deploy/models/hf.py (1)

1-1: Add 2025 NVIDIA copyright header at file top.

Per repo guidelines, prepend the NVIDIA copyright header (current year) above the module docstring.

Apply this diff:

+# Copyright (c) 2025, NVIDIA CORPORATION.  All rights reserved.
+
 """Interface to initialize and load HF models."""
tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py (3)

1-1: Add 2025 NVIDIA copyright header.

Apply this diff:

+# Copyright (c) 2025, NVIDIA CORPORATION.  All rights reserved.
+
 import torch

79-81: Device guard may fail on non-CUDA tensors.

with torch.cuda.device(router_logits.device) will error if tensors are on CPU/MPS. Consider using the tensor’s device without entering a CUDA device context.

Apply this diff:

-    with torch.cuda.device(router_logits.device):
-        routing_data, gather_idx, scatter_idx = routing(router_logits, top_k)
+    routing_data, gather_idx, scatter_idx = routing(router_logits, top_k)

70-76: Validate inputs early (top_k bounds, dimensions).

Add checks for top_k in [1, local_experts] and dim compat between hidden_states and router_weight.

Apply this diff:

-    hub = _hub()
+    hub = _hub()
@@
-    router_logits = torch.nn.functional.linear(hidden_states, router_weight, router_bias)
+    assert 1 <= top_k <= router_weight.shape[0], "top_k must be within [1, num_experts]"
+    assert router_weight.shape[1] == hidden_size, "router_weight H mismatch"
+    router_logits = torch.nn.functional.linear(hidden_states, router_weight, router_bias)

Also applies to: 94-96

tensorrt_llm/_torch/auto_deploy/custom_ops/__init__.py (2)

1-1: Add 2025 NVIDIA copyright header.

Apply this diff:

+# Copyright (c) 2025, NVIDIA CORPORATION.  All rights reserved.
+
 """Custom ops and make sure they are all registered."""

9-9: Star re-export is fine here, but consider narrowing public surface later.

Importing everything from mxfp4 is consistent with this module, but a curated all can reduce accidental symbol leakage.

📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 9f2dc30 and 718eb4f.

📒 Files selected for processing (3)
  • 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)
🧰 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/custom_ops/__init__.py
  • tensorrt_llm/_torch/auto_deploy/models/hf.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/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/custom_ops/__init__.py
  • tensorrt_llm/_torch/auto_deploy/models/hf.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/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/custom_ops/__init__.py
  • tensorrt_llm/_torch/auto_deploy/models/hf.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/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/custom_ops/__init__.py
  • tensorrt_llm/_torch/auto_deploy/models/hf.py
  • tensorrt_llm/_torch/auto_deploy/custom_ops/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/custom_ops/mxfp4.py (1)
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.h (2)
  • top_k (221-221)
  • intermediate_size (226-226)
⏰ 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 (2)
tensorrt_llm/_torch/auto_deploy/models/hf.py (1)

186-192: Double-check attribute access to private _keep_in_fp32_modules.

This is a private attribute and may not exist across models. The proposed guard above mitigates it; please confirm downstream paths don’t rely on strict type of this value.

tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py (1)

106-117: Ignore typo concerns: API uses gather_indx/scatter_indx and gate_scal
Verified that matmul_ogs() in kernels-community/triton_kernels indeed defines gather_indx and scatter_indx, and the RoutingData field is named gate_scal (no “e”). [1][2]

Likely an incorrect or invalid review comment.

Comment on lines +6 to +13
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")
return _triton_kernels_hub

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden hub loading with clear error if kernels are missing.

Raise a helpful error when kernels-community/triton_kernels is unavailable.

Apply this diff:

 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
+        except Exception as e:
+            raise ImportError(
+                "Required Triton kernels hub 'kernels-community/triton_kernels' not found. "
+                "Install or make it discoverable in PYTHONPATH."
+            ) from e
+        _triton_kernels_hub = get_kernel("kernels-community/triton_kernels")
     return _triton_kernels_hub
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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")
return _triton_kernels_hub
def _hub():
global _triton_kernels_hub
if _triton_kernels_hub is None:
try:
from kernels import get_kernel
except Exception as e:
raise ImportError(
"Required Triton kernels hub 'kernels-community/triton_kernels' not found. "
"Install or make it discoverable in PYTHONPATH."
) from e
_triton_kernels_hub = get_kernel("kernels-community/triton_kernels")
return _triton_kernels_hub
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py around lines 6 to 13, the
hub loader blindly imports from kernels and calls get_kernel which can raise
ModuleNotFoundError/ImportError or a lookup failure; wrap the import and
get_kernel call in a try/except that catches ImportError/ModuleNotFoundError and
any exception from get_kernel, then raise a clear RuntimeError (or re-raise
ImportError) with a helpful message that "kernels-community/triton_kernels" is
unavailable and include the original exception text and actionable guidance
(e.g., how to install or configure the kernels package); ensure you still set or
return _triton_kernels_hub when successful.

Comment on lines +63 to +68
"""
Wrapper that forwards to your Python reference implementation.
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]))
"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Return docstring is inconsistent with the actual return type.

Docstring advertises router_logits as a return value, but the function only returns routed_out.

Apply this diff to fix the docstring:

-    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]))
+    Returns:
+      routed_out: same leading shape as hidden_states, last dim = H
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"""
Wrapper that forwards to your Python reference implementation.
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]))
"""
"""
Wrapper that forwards to your Python reference implementation.
Returns:
routed_out: same leading shape as hidden_states, last dim = H
"""
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py around lines 63 to 68,
the docstring claims the function returns both routed_out and router_logits but
the function only returns routed_out; update the docstring to remove the
router_logits entry and only describe routed_out (its shape: same leading shape
as hidden_states with last dim = H) and the return semantics so the docstring
matches the actual return value.

Comment on lines +73 to +77
batch_size = hidden_states.shape[0]
intermediate_size = gate_up_blocks.shape[1] // 2
hidden_size = hidden_states.shape[-1]
hidden_states = hidden_states.reshape(-1, hidden_size)
router_logits = torch.nn.functional.linear(hidden_states, router_weight, router_bias)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Preserve input leading shape (2D vs 3D) when reshaping output.

Current code always reshapes to [batch_size, -1, H], adding an extra dim for 2D inputs.

Apply this diff:

-    batch_size = hidden_states.shape[0]
-    intermediate_size = gate_up_blocks.shape[1] // 2
-    hidden_size = hidden_states.shape[-1]
-    hidden_states = hidden_states.reshape(-1, hidden_size)
+    orig_shape = tuple(hidden_states.shape[:-1])
+    intermediate_size = gate_up_blocks.shape[1] // 2
+    hidden_size = hidden_states.shape[-1]
+    hidden_states = hidden_states.reshape(-1, hidden_size)
@@
-    routed_out = routed_out.reshape(batch_size, -1, hidden_size)
+    routed_out = routed_out.reshape(*orig_shape, hidden_size)

Also applies to: 139-140

🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py around lines 73-77 (and
similarly at 139-140), the code flattens hidden_states to 2D and then
reconstructs outputs but always returns a 3D tensor, which wrongly adds an extra
sequence dimension for original 2D inputs; preserve the input's original ndim by
capturing orig_shape = hidden_states.shape and orig_ndim = hidden_states.dim()
before reshaping, perform the linear op on the flattened tensor, then reshape
router_logits (and any other outputs) back to orig_shape: if orig_ndim == 3 use
(batch_size, -1, feat) otherwise use (batch_size, feat) (or equivalently reshape
to (*orig_shape[:-1], feat)); apply the same pattern for the code at lines
139-140 so 2D inputs remain 2D and 3D inputs remain 3D.

Comment on lines +94 to +99
local_experts = gate_up_blocks.size(0)
gate_up_blocks = gate_up_blocks.view(local_experts, intermediate_size * 2, -1)
triton_gate_up_w, gate_up_w_scale_raw = _swizzle_mxfp4(
gate_up_blocks.transpose(-2, -1), gate_up_scales.transpose(-2, -1)
)
triton_gate_up_w.shape = torch.Size([local_experts, hidden_size, intermediate_size * 2])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Make layout-agnostic with explicit dim detection instead of .view().

Inputs may be [E, 2I, H] or [E, H, 2I] (or [E, I, H]/[E, H, I]). Using view assumes a particular memory layout. Use permute based on which dim equals hidden_size.

Apply this diff:

-    local_experts = gate_up_blocks.size(0)
-    gate_up_blocks = gate_up_blocks.view(local_experts, intermediate_size * 2, -1)
+    local_experts = gate_up_blocks.size(0)
+    # normalize gate_up to [E, 2I, H]
+    if gate_up_blocks.shape[-1] == hidden_size:
+        gu = gate_up_blocks  # [E, 2I, H]
+    else:
+        gu = gate_up_blocks.permute(0, 2, 1).contiguous()  # [E, 2I, H]
+    gate_up_blocks = gu
@@
-    down_blocks = down_blocks.view(local_experts, -1, intermediate_size)
+    # normalize down to [E, I, H]
+    if down_blocks.shape[-1] == hidden_size:
+        dn = down_blocks  # [E, I, H]
+    else:
+        dn = down_blocks.permute(0, 2, 1).contiguous()  # [E, I, H]
+    down_blocks = dn

Also applies to: 101-105

🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py around lines 94 to 99
(and similarly lines 101-105), the code uses .view() assuming the tensor layout
[E, 2I, H]; instead detect which dimension equals hidden_size and call .permute
to move dims into [E, 2I, H] ordering before reshaping so the operation is
layout-agnostic. Concretely: check gate_up_blocks.dim() and which
gate_up_blocks.size(dim) == hidden_size, permute to put hidden_size as the last
dim (or the expected position) then reshape to [local_experts, intermediate_size
* 2, -1] (or set shape to [local_experts, hidden_size, intermediate_size * 2]
after swizzle) and apply the same detection+permute fix to the analogous block
at lines 101-105.

Comment on lines +100 to +101
down_blocks = down_blocks.view(local_experts, -1, intermediate_size // 2)
triton_down_w, down_w_scale_raw = _swizzle_mxfp4(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Shape bug: down path uses intermediate_size // 2; should be intermediate_size.

This halves I and will mis-shape weights/biases.

Apply this diff:

-    down_blocks = down_blocks.view(local_experts, -1, intermediate_size // 2)
+    down_blocks = down_blocks.view(local_experts, -1, intermediate_size)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
down_blocks = down_blocks.view(local_experts, -1, intermediate_size // 2)
triton_down_w, down_w_scale_raw = _swizzle_mxfp4(
down_blocks = down_blocks.view(local_experts, -1, intermediate_size)
triton_down_w, down_w_scale_raw = _swizzle_mxfp4(
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/custom_ops/mxfp4.py around lines 100-101, the
down path reshapes use intermediate_size // 2 which incorrectly halves the
intermediate dimension causing mis-shaped weights/biases; change the view call
to use intermediate_size (not divided by 2) so down_blocks =
down_blocks.view(local_experts, -1, intermediate_size) and ensure any downstream
code that depends on that shape (e.g., calls to _swizzle_mxfp4 and associated
scale/weight unpacking) expects and processes the full intermediate_size.

Comment on lines +175 to +194
# TODO(fridah): this should be handled by QuantConfigReader
from transformers.quantizers import AutoHfQuantizer

hf_quantizer = AutoHfQuantizer.from_config(
model_config.quantization_config,
pre_quantized=True,
)

dtype = hf_quantizer.update_dtype(model_config.dtype)
model.to(dtype)

hf_quantizer.preprocess_model(
model=model,
device_map=None,
keep_in_fp32_modules=model._keep_in_fp32_modules,
config=model.config,
use_kernels=False,
)
print("Model after pre-processing: ", model)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Guard missing quantization_config, avoid local ImportError, and use logger instead of print.

  • If model_config.quantization_config is absent/None, this block will raise.
  • Local import may raise ImportError at runtime; surface a clear message.
  • model._keep_in_fp32_modules may not exist; guard with getattr.
  • Replace print with ad_logger.debug.

Apply this diff:

-        # TODO(fridah): this should be handled by QuantConfigReader
-        from transformers.quantizers import AutoHfQuantizer
-
-        hf_quantizer = AutoHfQuantizer.from_config(
-            model_config.quantization_config,
-            pre_quantized=True,
-        )
-
-        dtype = hf_quantizer.update_dtype(model_config.dtype)
-        model.to(dtype)
-
-        hf_quantizer.preprocess_model(
-            model=model,
-            device_map=None,
-            keep_in_fp32_modules=model._keep_in_fp32_modules,
-            config=model.config,
-            use_kernels=False,
-        )
-        print("Model after pre-processing: ", model)
+        # TODO(fridah): route via QuantConfigReader once available.
+        quant_cfg = getattr(model_config, "quantization_config", None)
+        if quant_cfg is None:
+            ad_logger.debug("No quantization_config found; skipping HF quantizer preprocess.")
+        else:
+            try:
+                from transformers.quantizers import AutoHfQuantizer  # type: ignore[attr-defined]
+            except Exception as e:
+                raise RuntimeError(
+                    "transformers.quantizers.AutoHfQuantizer is required for pre-quantized models."
+                ) from e
+
+            hf_quantizer = AutoHfQuantizer.from_config(quant_cfg, pre_quantized=True)
+            dtype = hf_quantizer.update_dtype(model_config.dtype)
+            model.to(dtype)
+
+            keep_in_fp32_modules = getattr(model, "_keep_in_fp32_modules", ())
+            hf_quantizer.preprocess_model(
+                model=model,
+                device_map=None,
+                keep_in_fp32_modules=keep_in_fp32_modules,
+                config=model.config,
+                use_kernels=False,
+            )
+            ad_logger.debug("Model after quantizer pre-processing: %s", model.__class__.__name__)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# TODO(fridah): this should be handled by QuantConfigReader
from transformers.quantizers import AutoHfQuantizer
hf_quantizer = AutoHfQuantizer.from_config(
model_config.quantization_config,
pre_quantized=True,
)
dtype = hf_quantizer.update_dtype(model_config.dtype)
model.to(dtype)
hf_quantizer.preprocess_model(
model=model,
device_map=None,
keep_in_fp32_modules=model._keep_in_fp32_modules,
config=model.config,
use_kernels=False,
)
print("Model after pre-processing: ", model)
# TODO(fridah): route via QuantConfigReader once available.
quant_cfg = getattr(model_config, "quantization_config", None)
if quant_cfg is None:
ad_logger.debug("No quantization_config found; skipping HF quantizer preprocess.")
else:
try:
from transformers.quantizers import AutoHfQuantizer # type: ignore[attr-defined]
except Exception as e:
raise RuntimeError(
"transformers.quantizers.AutoHfQuantizer is required for pre-quantized models."
) from e
hf_quantizer = AutoHfQuantizer.from_config(quant_cfg, pre_quantized=True)
dtype = hf_quantizer.update_dtype(model_config.dtype)
model.to(dtype)
keep_in_fp32_modules = getattr(model, "_keep_in_fp32_modules", ())
hf_quantizer.preprocess_model(
model=model,
device_map=None,
keep_in_fp32_modules=keep_in_fp32_modules,
config=model.config,
use_kernels=False,
)
ad_logger.debug("Model after quantizer pre-processing: %s", model.__class__.__name__)
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/auto_deploy/models/hf.py around lines 175 to 194, the
block assumes model_config.quantization_config exists, does a local import
without handling ImportError, accesses model._keep_in_fp32_modules directly, and
uses print; change it to first check if model_config.quantization_config is
truthy and skip the whole quantization path if not, wrap the local import of
AutoHfQuantizer in a try/except that raises or logs a clear ImportError message,
call AutoHfQuantizer.from_config only when config is present, use getattr(model,
"_keep_in_fp32_modules", None) when passing keep_in_fp32_modules, and replace
the print with ad_logger.debug to log the post-preprocess model state.

@Fridah-nv
Copy link
Collaborator Author

Will land this feature with #7451

@Fridah-nv Fridah-nv closed this Sep 23, 2025
@github-project-automation github-project-automation bot moved this from Backlog to Done in AutoDeploy Board Sep 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

1 participant