Repository navigation
[#13082][fix] Add fail-fast FP4/MXFP4 GPU compatibility validation - #14573
aashirvad08 wants to merge 1 commit into
Conversation
📝 WalkthroughWalkthroughThis PR unifies GEMM output buffer handling via a ChangesQuantization-aware Linear and GEMM Refactoring
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.py (1)
35-38: 💤 Low valueIncorrect type hint for
quant_modeparameter.The function is called with
QuantModeobjects (e.g.,QuantMode.from_quant_algo(QuantAlgo.NVFP4)), but the type hint saysUnion[QuantAlgo, str]. Theis_mxfp4_supportedhelper useshasattr(quant_mode, "has_w4a8_mxfp4_fp8")which requires aQuantModeobject.✏️ Proposed fix
-def _validate_fp4_runtime_support(quant_mode: Union[QuantAlgo, str]) -> None: +def _validate_fp4_runtime_support(quant_mode: QuantMode) -> None:🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tensorrt_llm/_torch/custom_ops/torch_custom_ops.py` around lines 35 - 38, The type hint for _validate_fp4_runtime_support is incorrect: it must accept QuantMode instances (not just QuantAlgo or str) because is_mxfp4_supported checks for attributes on QuantMode; update the signature of _validate_fp4_runtime_support to include QuantMode (e.g., QuantMode | QuantAlgo | str or Union[QuantMode, QuantAlgo, str]) and adjust imports if necessary, and ensure any callers that pass QuantMode continue to type-check correctly; keep the runtime behavior unchanged and continue using is_mxfp4_supported and get_mxfp4_support_error_message as before.tensorrt_llm/_torch/modules/linear.py (1)
2778-2779: ⚡ Quick winUse explicit conditional with exception instead of assertion.
The
assertstatement can be disabled when Python runs with the-Oflag, which could allow invalidallow_partial_loading=Trueto pass silently for quantized methods.♻️ Proposed fix
- if not isinstance(self.quant_method, UnquantizedLinearMethod): - assert allow_partial_loading is False, "allow_partial_loading is only supported for unquantized linear methods now" + if not isinstance(self.quant_method, + UnquantizedLinearMethod) and allow_partial_loading: + raise ValueError( + "allow_partial_loading is only supported for unquantized linear methods" + )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tensorrt_llm/_torch/modules/linear.py` around lines 2778 - 2779, Replace the assert with an explicit conditional that raises an exception when an unsupported combination is passed: check if not isinstance(self.quant_method, UnquantizedLinearMethod) and allow_partial_loading is True, then raise a clear exception (e.g., ValueError or RuntimeError) with a descriptive message; update the check near the existing code that references self.quant_method, UnquantizedLinearMethod, and allow_partial_loading so the validation is enforced even when Python is run with optimizations.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tensorrt_llm/_torch/custom_ops/torch_custom_ops.py`:
- Around line 1244-1255: The fake kernel registered by
w4a8_mxfp4_fp8_gemm.register_fake declares a parameter act_fp4 but mistakenly
references undefined act_fp8; change the reference to use act_fp4 (e.g., use
act_fp4.size(0) when constructing the output tensor) so the callback uses the
declared parameter name and avoids the NameError during torch.compile tracing.
In `@tensorrt_llm/_torch/modules/fused_moe/create_moe.py`:
- Around line 184-185: The validation currently calls
_validate_moe_backend_support with model_config.quant_config which is
inconsistent when an override_quant_config was used to pick moe_cls in
create_moe; update create_moe_backend to accept an optional
override_quant_config parameter and inside create_moe_backend call
_validate_moe_backend_support with (override_quant_config or
model_config.quant_config) (and propagate swiglu_alpha/swiglu_beta/swiglu_limit
as before), then update the create_moe call site to pass the
override_quant_config chosen earlier so validation is performed against the
effective quant config used to select moe_cls.
In `@tensorrt_llm/_torch/modules/linear.py`:
- Around line 1418-1419: In NVFP4LinearMethod.load_weight_scales(), replace the
hard assert on ws.dtype (ws.dtype == torch.float8_e4m3fn) with an explicit
runtime check that raises a clear exception (TypeError or ValueError) including
the actual dtype; locate the check by the symbols
NVFP4LinearMethod.load_weight_scales and ws. Then decide whether to accept
additional FP4 dtypes (e.g., torch.float8_e8m0 or the MXFP4 dtype referenced in
the TODO) by allowing a set of permitted dtypes and validating against that set,
or remove/update the TODO and make the error message state that only e4m3fn is
supported if MXFP4 is intentionally unsupported.
In `@tensorrt_llm/quantization/mode.py`:
- Around line 506-509: The SM allowlist for the W4A8_MXFP4_MXFP8 check is
missing Blackwell SMs; update the branch that calls
quant_mode.has_w4a8_mxfp4_mxfp8() (in mode.py) so its return condition includes
120 and 121 in addition to 100 and 103 (i.e., accept sm in {100,103,120,121});
this aligns the check with the _QUANT_SUPPORT_TABLE definition used in
fused_moe_cutlass.py.
---
Nitpick comments:
In `@tensorrt_llm/_torch/custom_ops/torch_custom_ops.py`:
- Around line 35-38: The type hint for _validate_fp4_runtime_support is
incorrect: it must accept QuantMode instances (not just QuantAlgo or str)
because is_mxfp4_supported checks for attributes on QuantMode; update the
signature of _validate_fp4_runtime_support to include QuantMode (e.g., QuantMode
| QuantAlgo | str or Union[QuantMode, QuantAlgo, str]) and adjust imports if
necessary, and ensure any callers that pass QuantMode continue to type-check
correctly; keep the runtime behavior unchanged and continue using
is_mxfp4_supported and get_mxfp4_support_error_message as before.
In `@tensorrt_llm/_torch/modules/linear.py`:
- Around line 2778-2779: Replace the assert with an explicit conditional that
raises an exception when an unsupported combination is passed: check if not
isinstance(self.quant_method, UnquantizedLinearMethod) and allow_partial_loading
is True, then raise a clear exception (e.g., ValueError or RuntimeError) with a
descriptive message; update the check near the existing code that references
self.quant_method, UnquantizedLinearMethod, and allow_partial_loading so the
validation is enforced even when Python is run with optimizations.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 4ca0b86e-1493-42f6-92f1-d61a45266637
📒 Files selected for processing (4)
tensorrt_llm/_torch/custom_ops/torch_custom_ops.pytensorrt_llm/_torch/modules/fused_moe/create_moe.pytensorrt_llm/_torch/modules/linear.pytensorrt_llm/quantization/mode.py
| @w4a8_mxfp4_fp8_gemm.register_fake | ||
| def _( | ||
| act_fp4: torch.Tensor, | ||
| weight: torch.Tensor, | ||
| act_sf: torch.Tensor, | ||
| weight_scale: torch.Tensor, | ||
| alpha: torch.Tensor, | ||
| output_dtype: torch.dtype, | ||
| output_buffer_kind: int = int(BufferKind.DEFAULT), | ||
| act_fp4: torch.Tensor, | ||
| weight: torch.Tensor, | ||
| act_sf: torch.Tensor, | ||
| weight_scale: torch.Tensor, | ||
| alpha: torch.Tensor, | ||
| output_dtype: torch.dtype, | ||
| to_userbuffers: bool = False, | ||
| ) -> torch.Tensor: | ||
| return act_fp4.new_empty((act_fp4.size(0), weight.size(0)), | ||
| return act_fp8.new_empty((act_fp8.size(0), weight.size(0)), | ||
| dtype=output_dtype) |
There was a problem hiding this comment.
NameError: Parameter named act_fp4 but code references act_fp8.
The register_fake function parameter is named act_fp4 (line 1246), but line 1254 references act_fp8 which is undefined. This will cause a NameError when the fake kernel is invoked during torch.compile tracing.
🐛 Proposed fix (align with main function naming)
`@w4a8_mxfp4_fp8_gemm.register_fake`
def _(
- act_fp4: torch.Tensor,
+ act_fp8: torch.Tensor,
weight: torch.Tensor,
act_sf: torch.Tensor,
weight_scale: torch.Tensor,
alpha: torch.Tensor,
output_dtype: torch.dtype,
to_userbuffers: bool = False,
) -> torch.Tensor:
return act_fp8.new_empty((act_fp8.size(0), weight.size(0)),
dtype=output_dtype)🧰 Tools
🪛 Flake8 (7.3.0)
[error] 1254-1254: undefined name 'act_fp8'
(F821)
[error] 1254-1254: undefined name 'act_fp8'
(F821)
🪛 Ruff (0.15.14)
[error] 1254-1254: Undefined name act_fp8
(F821)
[error] 1254-1254: Undefined name act_fp8
(F821)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tensorrt_llm/_torch/custom_ops/torch_custom_ops.py` around lines 1244 - 1255,
The fake kernel registered by w4a8_mxfp4_fp8_gemm.register_fake declares a
parameter act_fp4 but mistakenly references undefined act_fp8; change the
reference to use act_fp4 (e.g., use act_fp4.size(0) when constructing the output
tensor) so the callback uses the declared parameter name and avoids the
NameError during torch.compile tracing.
| _validate_moe_backend_support(moe_cls, model_config.quant_config, dtype, | ||
| swiglu_alpha, swiglu_beta, swiglu_limit) |
There was a problem hiding this comment.
Inconsistent validation when override_quant_config is used.
This validation uses model_config.quant_config, but when called from create_moe (line 445), the moe_cls was selected based on override_quant_config (line 396) and validation already passed with the override (lines 398-399). If override_quant_config differs from model_config.quant_config, this could cause:
- False validation failures (override passes but model_config fails)
- Validation passing for the wrong quant_config
Consider adding override_quant_config parameter to create_moe_backend and using override_quant_config or model_config.quant_config for validation, consistent with create_moe.
🐛 Proposed fix
def create_moe_backend(
moe_cls: Type[MoE],
routing_method: BaseMoeRoutingMethod,
# TODO: remove num_experts, hidden_size, intermediate_size, dtype parameters
# these parameters will be inferred from model_config.pretrained_config.
num_experts: Optional[int] = None,
hidden_size: Optional[int] = None,
intermediate_size: Optional[int] = None,
dtype: Optional[torch.dtype] = None,
reduce_results: bool = False,
model_config: ModelConfig = ModelConfig(),
+ override_quant_config: Optional[QuantConfig] = None,
aux_stream_dict: Optional[Dict[AuxStreamType, torch.cuda.Stream]] = None,
...
) -> MoE:
...
- _validate_moe_backend_support(moe_cls, model_config.quant_config, dtype,
- swiglu_alpha, swiglu_beta, swiglu_limit)
+ quant_config = override_quant_config or model_config.quant_config
+ _validate_moe_backend_support(moe_cls, quant_config, dtype,
+ swiglu_alpha, swiglu_beta, swiglu_limit)Then update the call site in create_moe (line 445+) to pass override_quant_config.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tensorrt_llm/_torch/modules/fused_moe/create_moe.py` around lines 184 - 185,
The validation currently calls _validate_moe_backend_support with
model_config.quant_config which is inconsistent when an override_quant_config
was used to pick moe_cls in create_moe; update create_moe_backend to accept an
optional override_quant_config parameter and inside create_moe_backend call
_validate_moe_backend_support with (override_quant_config or
model_config.quant_config) (and propagate swiglu_alpha/swiglu_beta/swiglu_limit
as before), then update the create_moe call site to pass the
override_quant_config chosen earlier so validation is performed against the
effective quant config used to select moe_cls.
| assert ws.dtype == torch.float8_e4m3fn # TODO: or e8m0 for mxfp4 recipe? | ||
| weight_scale.append(ws.view(fp4_utils.float4_sf_dtype)) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if MXFP4 weight loading flows through this method
rg -n "load_weight_scales" --type=py -C3 | grep -i "mxfp4"Repository: NVIDIA/TensorRT-LLM
Length of output: 45
Harden ws.dtype validation in NVFP4LinearMethod.load_weight_scales()
NVFP4LinearMethod.load_weight_scales() hard-asserts ws.dtype == torch.float8_e4m3fn at lines 1418-1419, while the inline TODO suggests MXFP4 may use a different dtype (e.g., e8m0). If MXFP4 weights ever reach this path, this will hard-fail.
- Replace the
assertwith an explicit runtime check (raising a real exception). - Either widen the accepted dtype(s) to cover the MXFP4 case, or remove/adjust the TODO if this method is intentionally not used for MXFP4.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tensorrt_llm/_torch/modules/linear.py` around lines 1418 - 1419, In
NVFP4LinearMethod.load_weight_scales(), replace the hard assert on ws.dtype
(ws.dtype == torch.float8_e4m3fn) with an explicit runtime check that raises a
clear exception (TypeError or ValueError) including the actual dtype; locate the
check by the symbols NVFP4LinearMethod.load_weight_scales and ws. Then decide
whether to accept additional FP4 dtypes (e.g., torch.float8_e8m0 or the MXFP4
dtype referenced in the TODO) by allowing a set of permitted dtypes and
validating against that set, or remove/update the TODO and make the error
message state that only e4m3fn is supported if MXFP4 is intentionally
unsupported.
| if hasattr( | ||
| quant_mode, | ||
| "has_w4a8_mxfp4_mxfp8") and quant_mode.has_w4a8_mxfp4_mxfp8(): | ||
| return sm in (100, 103) |
There was a problem hiding this comment.
W4A8_MXFP4_MXFP8 SM allowlist is missing SM 120/121.
Per the _QUANT_SUPPORT_TABLE in tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py, W4A8_MXFP4_MXFP8 should be supported on SM in {100, 103, 120, 121}, not just {100, 103}. This would incorrectly reject valid configurations on newer Blackwell architectures.
🐛 Proposed fix
if hasattr(
quant_mode,
"has_w4a8_mxfp4_mxfp8") and quant_mode.has_w4a8_mxfp4_mxfp8():
- return sm in (100, 103)
+ return sm in (100, 103, 120, 121)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tensorrt_llm/quantization/mode.py` around lines 506 - 509, The SM allowlist
for the W4A8_MXFP4_MXFP8 check is missing Blackwell SMs; update the branch that
calls quant_mode.has_w4a8_mxfp4_mxfp8() (in mode.py) so its return condition
includes 120 and 121 in addition to 100 and 103 (i.e., accept sm in
{100,103,120,121}); this aligns the check with the _QUANT_SUPPORT_TABLE
definition used in fused_moe_cutlass.py.
| return CutlassFusedMoE | ||
| elif moe_backend.upper() == "DEEPGEMM": | ||
| return DeepGemmFusedMoE | ||
| elif moe_backend.upper() == "DENSEGEMM": |
There was a problem hiding this comment.
This PR mixes a small valid feature with a large accidental revert — please rebase onto latest main.
The intended change (FP4/MXFP4 fail-fast validation in quantization/mode.py + call sites) is reasonable, but the branch is based on a stale main, so the diff (+448 / −1089) reverts a lot of recently merged code. Most of the deletions are unintended.
Critical :
create_moe.py deletes 3 MoE backends that exist on current main: CuteDslB12xFusedMoE, DenseGEMMFusedMoE, MegaMoEDeepGemm — plus resolve_moe_cls(), the TRTLLMGen BF16 path, and layer_idx/activation_type plumbing. This would revert those features entirely.
Copyright/license headers removed from torch_custom_ops.py (full SPDX + Apache header) and create_moe.py (SPDX header). This violates the repo header policy. (mode.py correctly just bumps the year; linear.py header is untouched.)
torch_custom_ops.py reverts other recent work: removes tunable_fp4_quantize / Fp4QuantKernelRunner (166-line block), NCCL symmetric-memory window logic, MoERunner.clear_all_workspaces(), and the BufferKind/group GEMM signatures (reverting to to_userbuffers) — which is incompatible with current callers on main.
Action: rebase onto latest main and keep only the mode.py helpers + the validation calls. After rebase the diff should be nearly pure additions (~+100 lines, almost no deletions).
Validation-logic issues (please also address):
validate_fp4_runtime_support(quant_mode: Union[QuantAlgo, str]) is annotated as QuantAlgo|str but is actually called with a QuantMode. Since is_mxfp4_supported relies on hasattr(quant_mode, "has*"), passing an actual QuantAlgo/str would silently return True (validation becomes a no-op). Please unify the type and drop the hasattr fallbacks.
Signed-off-by: rampofin <[email protected]>
94519b3 to
0a9de97
Compare
|
Resolved the issues @xxi-nv pointed out. I rebased onto latest upstream/main and removed the accidental revert. The final diff is now limited to the intended FP4/MXFP4 validation changes in mode.py and linear.py. Also fixed the validation typing issue by using QuantMode directly and removing the hasattr-based fallback logic. |
|
Generated by an AI-assisted triage bot; please correct any mistaken assumptions. Your check can give users a clearer error before FP4 Linear weights are created. In the final diff, unsupported GPUs still cannot run that configuration, so the established improvement is earlier reporting rather than restored execution. Based on the assessment above, we're giving this PR lower review priority for now and adding Evidence that early validation prevents a consequence beyond a later unsupported-GPU failure, or enables recovery, would warrant reconsideration. You're welcome to reply, update the PR description, or request maintainer review; a code change is not necessarily required. If there is no further activity for 14 days, this PR will be automatically closed. |
|
Closing as superseded by #12591, which covers the same fail-fast check with the issues here fixed. |
Fixes #13082
Description
Adds fail-fast validation for FP4/MXFP4 quantization modes on unsupported GPU architectures
Previously, unsupported FP4/MXFP4 execution paths could proceed into lower-level kernels or backend initialization and fail later with less actionable errors. This patch centralizes GPU support checks in
QuantModehelpers and applies validation across custom ops, linear layers, and fused MoE backend creationChanges
quantization/mode.pyThis change is independent of VILA multimodal chunked prefill fixes
Test Coverage
Summary by CodeRabbit