Skip to content

fix(quantization): isolate optional Megatron imports - #2719

Merged
kevalmorabia97 merged 2 commits into
NVIDIA:mainfrom
joe-nv:fix/6901564-optional-megatron-import-0.48
Oct 14, 2026
Merged

kevalmorabia97 merged 2 commits into
NVIDIA:mainfrom
joe-nv:fix/6901564-optional-megatron-import-0.48

Conversation

@joe-nv

@joe-nv joe-nv commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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.opt also 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 unavailable cutlass.cute.core.ThrMma raises AttributeError.

The plugin initializers already contain this failure through import_plugin, but compress.py retries the import with an ImportError-only handler. This second import allows the exception to escape.

Reuse import_plugin("megatron") at that optional import boundary. Initialize mcore_available to False, setting it to True only 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.opt entry point is unchanged.

Testing

  • During development, local CPU import checks covered successful import, missing dependency and dependency AttributeError. Before the fix, the AttributeError case failed; after the fix, all three passed, including on the release branch.
  • These checks were development-only validation. The test file has been removed from the final PR; only the production import fix remains.
  • Targeted pre-commit hooks passed for the unchanged production code, including Ruff, mypy, license checks and Bandit.
  • After removing the test file, git diff --check and local SSH commit-signature verification passed.
  • The failing TRT-LLM container and real Megatron GPU workflows have not been validated with this patch.

Summary by CodeRabbit

  • Bug Fixes
    • Improved compatibility when loading optional Megatron support, including in environments where Megatron is unavailable. This helps quantization workflows handle Megatron availability more consistently.

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]>
@joe-nv
joe-nv requested review from a team as code owners October 9, 2026 04:39
@joe-nv
joe-nv requested review from cjluo-nv and removed request for a team October 9, 2026 04:39
@copy-pr-bot

copy-pr-bot Bot commented Oct 9, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/Model-Optimizer/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: beae3d14-2040-484a-bf36-2a58f4bc20bd
📥 Commits

Reviewing files that changed from the base of the PR and between e862bdf and 9d68efd.

📒 Files selected for processing (1)
  • modelopt/torch/quantization/compress.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

📝 Walkthrough

The compression module now loads Megatron classes inside the Megatron plugin context. It initializes mcore_available to false before loading and sets it to true after successful imports.

Changes: Megatron imports

Layer / File(s) Summary
Plugin import handling
modelopt/torch/quantization/compress.py
The module uses import_plugin("megatron") to load Megatron classes. It initializes mcore_available to false before loading and removes the explicit ImportError handler.

Priority: ➖ Normal

Estimated code review effort: 1 (Trivial) | ~5 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 9d68e

The optional Megatron import failure is contained, allowing unrelated ModelOpt workflows to use the fallback. No merge-blocking issue is established in the reviewed change.

🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Docstring Coverage Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 1…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The pull request changes only modelopt/torch/quantization/compress.py. The added lines import and use import_plugin and initialize mcore_available; they do not add `torch.load(..., weights…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: isolating optional Megatron imports in the quantization code.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

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]>
@joe-nv

joe-nv commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@codecov

codecov Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 71.53%. Comparing base (e862bdf) to head (9d68efd).
⚠️ Report is 39 commits behind head on main.

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     
Flag Coverage Δ
unit 59.72% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@joe-nv

joe-nv commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@joe-nv

joe-nv commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

@kevalmorabia97 please help to review

@joe-nv
joe-nv changed the base branch from release/0.48.0 to main October 14, 2026 15:01
@kevalmorabia97
kevalmorabia97 merged commit 0dc24dc into NVIDIA:main Oct 14, 2026
30 checks passed
@rohansjoshi rohansjoshi added the cherry-pick-done Added by bot once PR is cherry-picked to the release branch label Oct 16, 2026
rohansjoshi added a commit that referenced this pull request Oct 17, 2026
#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]>
@joe-nv

joe-nv commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

/claude review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 ImportError with with import_plugin("megatron") widens containment from ImportError to Exception (modelopt/torch/utils/import_utils.py:31-44), which is exactly what the reported AttributeError from cutlass.cute.core.ThrMma needs.
  • Initializing mcore_available = False before the block and setting it True as the last statement inside is the right ordering: import_plugin swallows 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 a NameError at compress.py:75. Good catch.
  • The four guarded symbols (_MegatronColumnParallelLinear, _MegatronRowParallelLinear, _RealQuantMegatronColumnParallelLinear, _RealQuantMegatronRowParallelLinear) are only read under if mcore_available: at compress.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_state or public API surface is touched, so no migration or backward-compat concern. No CHANGELOG.rst entry needed per CLAUDE.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 ImportError retry still live at model_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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-0.48.0 cherry-pick-done Added by bot once PR is cherry-picked to the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants