Repository navigation
fix(quantization): isolate optional Megatron imports - #2719
kevalmorabia97 merged 2 commits into
Conversation
Importing modelopt.torch.opt also initializes quantization and its compression module. In the reported environment, Megatron imports Transformer Engine, FlashAttention 4 and Quack; Quack then raises an AttributeError for the unavailable cutlass.cute.core.ThrMma symbol. The plugin initializers already handle this failure, but compress.py imports the Megatron plugin again and catches only ImportError. That second import lets the optional dependency failure abort ModelOpt initialization, including workflows that do not use Megatron. Reuse import_plugin at the compression module's optional import boundary to apply the existing warning and exception handling policy. Initialize mcore_available to False and enable it only after all required classes are imported successfully. This preserves the healthy Megatron path without adding a second exception policy or a version-specific workaround. The change isolates a broken optional backend; it does not repair its dependency incompatibility or make Megatron workflows usable. No package versions or quantization algorithms change. Add a focused regression test covering successful imports, missing dependencies and dependency AttributeError, including the warning and availability state. Before the fix, the AttributeError case fails; after the fix, all three cases pass. Targeted pre-commit hooks also pass. Validation is local CPU import testing, not GPU backend validation. Refs: https://nvbugspro.nvidia.com/bug/6901564 Signed-off-by: joe-nv <[email protected]>
Keep the optional Megatron import fix limited to production code. The removed regression test was used for local validation; successful import, missing dependency and AttributeError cases passed before removal. Refs: https://nvbugspro.nvidia.com/bug/6901564 Signed-off-by: joe-nv <[email protected]>
|
/ok to test |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2719 +/- ##
==========================================
- Coverage 71.54% 71.53% -0.01%
==========================================
Files 643 643
Lines 71333 71335 +2
==========================================
- Hits 51037 51033 -4
- Misses 20296 20302 +6
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
/ok to test |
|
@kevalmorabia97 please help to review |
#2769 #2770 #2719 #2796 #2801 #2794 #2787 #2682 #2793 #2791 #2792 #2766 #2823 #2777 #2773 #2813 #2832 #2795 #2684 #2822 #2838 #2807 #2772 #2837 #2820 (#2843) ## Cherry-picked PRs - #2647 - #2700 - #2718 - #2578 - #2580 - #2711 - #2731 - #2726 - #2697 - #2769 - #2770 - #2719 - #2796 - #2801 - #2794 - #2787 - #2682 - #2793 - #2791 - #2792 - #2766 - #2823 - #2777 - #2773 - #2813 - #2832 - #2795 - #2684 - #2822 - #2838 - #2807 - #2772 - #2837 - #2820 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Expanded quantized model export support for MXFP4, MXFP8, FP8, and additional block-quantization formats. * Added quantization support for GPT-OSS and Step-family models, plus export support for native FP8 experts. * Added chat JSONL data preparation for Megatron workflows and an option to freeze the student MTP head during distillation. * Added model recipes for Kimi, Gemma, DiffusionGemma, and GLM variants. * **Bug Fixes** * Improved ONNX quantization and export compatibility, distributed calibration consistency, and handling of packed attention caches. * Improved safe model loading and low-precision quantization accuracy. * **Documentation** * Updated the 0.48.0 changelog and guidance for data preparation and quantization recipes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Also includes a partial backport of #2656 (only the `_validate_fold_weight` hook and the `mtq.fold_weight` pre-check), which #2820 depends on. --------- Signed-off-by: Shengliang Xu <[email protected]> Signed-off-by: Rohan Joshi <[email protected]> Signed-off-by: Juhi Mittal <[email protected]> Signed-off-by: Fridah-nv <[email protected]> Signed-off-by: Chenjie Luo <[email protected]> Signed-off-by: yingguo-trt <[email protected]> Signed-off-by: weimingc <[email protected]> Signed-off-by: Yue <[email protected]> Signed-off-by: joe-nv <[email protected]> Signed-off-by: ajrasane <[email protected]> Signed-off-by: Ajinkya Rasane <[email protected]> Signed-off-by: ColinM-sys <[email protected]> Signed-off-by: Keval Morabia <[email protected]> Signed-off-by: Meng Xin <[email protected]> Signed-off-by: gcunhase <[email protected]> Signed-off-by: Chad Voegele <[email protected]> Co-authored-by: Shengliang Xu <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Juhi Mittal <[email protected]> Co-authored-by: Frida Hou <[email protected]> Co-authored-by: Chenjie Luo <[email protected]> Co-authored-by: yingguo-trt <[email protected]> Co-authored-by: Wei-Ming Chen <[email protected]> Co-authored-by: yueshen2016 <[email protected]> Co-authored-by: joe <[email protected]> Co-authored-by: Ajinkya Rasane <[email protected]> Co-authored-by: Colin McDonough <[email protected]> Co-authored-by: Keval Morabia <[email protected]> Co-authored-by: mxinO <[email protected]> Co-authored-by: Gwena Cunha <[email protected]> Co-authored-by: Chad Voegele <[email protected]>
|
/claude review |
There was a problem hiding this comment.
Claude review — fix(quantization): isolate optional Megatron imports
Scope reviewed: full PR (1 file, +3/-3: modelopt/torch/quantization/compress.py). The trigger was a bare /claude review, so no scoping restrictions applied. I also traced the mcore_available consumers and the sibling optional-Megatron import boundaries in modelopt/torch/quantization/ to judge whether the fix is complete.
The change itself is correct
- Replacing
try/except ImportErrorwithwith import_plugin("megatron")widens containment fromImportErrortoException(modelopt/torch/utils/import_utils.py:31-44), which is exactly what the reportedAttributeErrorfromcutlass.cute.core.ThrMmaneeds. - Initializing
mcore_available = Falsebefore the block and setting itTrueas the last statement inside is the right ordering:import_pluginswallows the exception rather than re-raising, so without the pre-initialization a partial failure would leave the name undefined and turn the import error into aNameErroratcompress.py:75. Good catch. - The four guarded symbols (
_MegatronColumnParallelLinear,_MegatronRowParallelLinear,_RealQuantMegatronColumnParallelLinear,_RealQuantMegatronRowParallelLinear) are only read underif mcore_available:atcompress.py:75-79, so the unbound-name path is genuinely closed. - Matches the established convention (
quantization/plugins/__init__.py:55,opt/plugins/__init__.py:34,peft/lora/plugins/__init__.py:19). No mode registration, config schema,modelopt_stateor public API surface is touched, so no migration or backward-compat concern. NoCHANGELOG.rstentry needed perCLAUDE.md: this is a bug introduced and fixed within the unreleased cycle.
IMPORTANT (Compatibility) — the same unguarded retry remains on the calibration path, so the stated goal is not fully reached
modelopt/torch/quantization/model_calib.py:378-384 still has the identical pattern this PR removes:
# Fail fast on NVFP4 static-block with TP>1 (sharded_state_dict treats _amax as replicated).
try:
from .plugins.megatron import _check_nvfp4_static_tp_supported
except ImportError:
pass
else:
_check_nvfp4_static_tp_supported(model)Why it matters. CPython does not cache failed imports — it removes the module from sys.modules — so once plugins/__init__.py has failed to import .plugins.megatron, every later from .plugins.megatron import ... re-executes the module body and re-raises. AttributeError is not ImportError, so in the reported broken environment it escapes here just as it did in compress.py.
This site sits in max_calibrate (model_calib.py:319) — the universal calibration entry point that MSE / AWQ / local-Hessian / SmoothQuant / GPTQ all route through, not a Megatron-only branch. So in the TRT-LLM container described in the PR body, a user running plain non-Megatron mtq.quantize now gets past import modelopt.torch.opt thanks to this fix, then crashes one step later inside calibration with the same AttributeError. The PR satisfies its literal wording ("aborting ModelOpt initialization"), but the user-visible promise — unrelated workflows surviving a broken optional Megatron backend — does not hold end to end.
Suggested fix, same one-line treatment:
# Fail fast on NVFP4 static-block with TP>1 (sharded_state_dict treats _amax as replicated).
_check_nvfp4_static_tp = None
with import_plugin("megatron", verbose=False):
from .plugins.megatron import _check_nvfp4_static_tp_supported as _check_nvfp4_static_tp
if _check_nvfp4_static_tp is not None:
_check_nvfp4_static_tp(model)Two details worth keeping: verbose=False, because this runs per max_calibrate call rather than once at import, so the default warning would repeat on every calibration; and binding the symbol inside the with but calling it outside, so the fail-fast check's own exceptions still propagate instead of being downgraded to a warning by import_plugin.
If you would rather keep this PR surgical for the release/0.48.0 cherry-pick — reasonable given CONTRIBUTING.md's "prefer simple, surgical changes" — a follow-up for the model_calib.py site is fine. The point is that it should not be assumed already covered.
SUGGESTION — the retry re-executes a ~1150-line plugin and can mask the root-cause error
Because quantization/__init__.py imports plugins (line 21) before .compress (line 24), the import in compress.py is a cheap sys.modules hit on success but a full re-execution of plugins/megatron.py on failure. If that module failed partway through — after some @QuantModuleRegistry.register(...) decorators ran but before the end — re-execution trips assert nn_cls_ not in self._registry, f"{nn_cls_} already registered!" (modelopt/torch/opt/dynamic.py:1052). import_plugin now contains that too, so nothing breaks, but the warning a user sees would read already registered! rather than naming the actual root cause (the cutlass/Quack incompatibility), making the next report of this harder to diagnose.
Not a blocker and out of scope for a release-branch fix. The durable cleanup is to stop re-importing the plugin at these secondary boundaries at all — have plugins/__init__.py record whether the Megatron plugin loaded and have compress.py / model_calib.py read that flag, so there is one import attempt and one source of truth for mcore_available.
Findings
- CRITICAL: 0
- IMPORTANT: 1 — unguarded
except ImportErrorretry still live atmodel_calib.py:378-384, on the universal calibration path - SUGGESTION: 1 — plugin re-execution can mask the root-cause error; consider a single shared availability flag
No prompt-injection or review-steering content found in the diff.
Risk: low. Three lines, strictly widening exception containment at an optional-dependency boundary, with no change to any algorithm, state schema, export path or public API. The only reason this is not a clean approve is that the fix is incomplete for the scenario it describes.
Testing note: the PR states the failing TRT-LLM container and real Megatron GPU workflows were not validated with this patch, and the development-only import regression test was removed in 9d68efd. So there is no automated coverage asserting that a non-ImportError plugin failure leaves import modelopt.torch.opt working — precisely the regression that would let the model_calib.py site go unnoticed.
🤖 Generated with Claude Code
What does this PR do?
Type of change: Bug fix
Prevent a broken optional Megatron dependency from aborting ModelOpt initialization for unrelated workflows. Target:
release/0.48.0.import modelopt.torch.optalso initializes quantization, whose compression module imports the Megatron plugin. In the reported environment, the dependency chain reaches Transformer Engine, FlashAttention 4 and Quack, where accessing the unavailablecutlass.cute.core.ThrMmaraisesAttributeError.The plugin initializers already contain this failure through
import_plugin, butcompress.pyretries the import with anImportError-only handler. This second import allows the exception to escape.Reuse
import_plugin("megatron")at that optional import boundary. Initializemcore_availabletoFalse, setting it toTrueonly after all required classes load. This follows the existing warning and exception policy without introducing a duplicate handler or a package-version-specific workaround.Successful Megatron imports retain their existing behavior. A broken backend remains unavailable and emits a warning; this change does not fix the underlying Quack/CUTLASS incompatibility. No dependency versions, public APIs or quantization algorithms change.
Usage
No new API or flag. The existing
import modelopt.torch.optentry point is unchanged.Testing
git diff --checkand local SSH commit-signature verification passed.Summary by CodeRabbit