Repository navigation
Support per expert weight quantizer in TEGroupedMLP - #1550
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughTEGroupedMLP weight quantization now uses independent per-expert quantizers, with grouped calibration, restore, checkpoint, export, optional compiled execution, and Megatron validation support. ChangesPer-expert TEGrouped quantization
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant TEGroupedLinear
participant GroupedQuantizer
participant Calibration
participant MegatronCheckpoint
participant Exporter
TEGroupedLinear->>GroupedQuantizer: create per-expert quantizers
Calibration->>GroupedQuantizer: collect and synchronize per-expert amax
MegatronCheckpoint->>GroupedQuantizer: restore expert quantizer state
Exporter->>GroupedQuantizer: derive expert-specific scales and qformats
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
|
There was a problem hiding this comment.
Warning
CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.
Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
modelopt/torch/quantization/plugins/transformer_engine.py (1)
147-166:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftPer-expert restore is still unsafe when TP/EP changes.
This branch creates
weight_quantizer_{i}modules, butmodelopt_post_restore()still runs the base restore path that only knows aboutself.weight_quantizer. If a checkpoint is restored under different TP/EP, the per-expert_amaxtensors can keep the old shape and no code here reinitializes them. Please either block this mode on topology changes or add a per-expert reset/recalibration path during restore.🤖 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 `@modelopt/torch/quantization/plugins/transformer_engine.py` around lines 147 - 166, The per-expert weight-quantizer path (_per_expert_weight_quantizer and the created modules weight_quantizer_{i}) is unsafe on TP/EP topology change because modelopt_post_restore currently only runs the base path and does not reinitialize per-expert _amax buffers; update modelopt_post_restore to detect topology/shape mismatch and either (a) fail-fast by raising a clear error when _per_expert_weight_quantizer is enabled and the restored per-expert _amax shapes don't match the current weight shapes, or (b) perform a per-expert recalibration: iterate over each created module name weight_quantizer_{i} (use self.num_gemms to enumerate), reset/recreate their _amax buffers to the correct shape for the current self.weight{i} and call the quantizer's max_calibrate (or its equivalent reinit routine) so each per-expert quantizer is re-calibrated after restore; implement one of these branches in modelopt_post_restore to ensure shapes/amax are consistent after load.
🧹 Nitpick comments (1)
tests/gpu_megatron/torch/quantization/plugins/test_megatron.py (1)
738-750: ⚡ Quick winKeep these GPU assertions on-device.
tensor.item()andmath.isfinite(...)force host syncs on every worker here. Prefer tensor comparisons/reductions plustorch.isfinite, and only materialize Python scalars for failure messages or rank-0 logging.As per coding guidelines, "Performance note: avoid GPU syncs in hot paths/tests (don’t use
tensor.item()/float(tensor)/min(tensor))—use tensor ops instead."Also applies to: 800-813
🤖 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 `@tests/gpu_megatron/torch/quantization/plugins/test_megatron.py` around lines 738 - 750, The test is forcing GPU->CPU syncs by calling .item() inside the assert message and in the divergence check; change the assert to keep comparisons on-device and only materialize scalars when needed: replace the assert torch.allclose(te_amax.view(()), seq_max, ...) with an if-not pattern (if not torch.allclose(...): raise AssertionError(f"...{te_amax.item()}...{seq_max.item()}...")) so the .item() calls only run on failure, and compute the per-expert divergence using tensor ops (delta = seq_amaxes.max() - seq_amaxes.min(); if (delta > 1e-5): saw_per_expert_divergence = True) while ensuring you only call .item() when you must convert to a Python bool for logging or failure paths; update references to seq_amaxes, seq_mlp.local_experts, linear_name, te_amax, and saw_per_expert_divergence accordingly.
🤖 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 `@tests/gpu_megatron/torch/quantization/plugins/test_megatron.py`:
- Around line 698-761: The default-path helper
_test_te_grouped_vs_sequential_default_amax_helper must explicitly disable the
feature flag: set os.environ["MODELOPT_TEGROUPED_PER_EXPERT_QUANTIZER"]="0"
(saving the original and restoring it after the test) before calling
initialize_for_megatron so the shared-quantizer behavior is forced; then add a
new test variant that sets
os.environ["MODELOPT_TEGROUPED_PER_EXPERT_QUANTIZER"]="1" and runs the same
checks to cover the env-on path. Apply the same explicit env-off/restore and
corresponding env-on test change to the other similar helper/test pair
exercising TEGrouped vs Sequential (the companion helper referenced in the
review) so both default and env-enabled code paths have dedicated coverage.
---
Outside diff comments:
In `@modelopt/torch/quantization/plugins/transformer_engine.py`:
- Around line 147-166: The per-expert weight-quantizer path
(_per_expert_weight_quantizer and the created modules weight_quantizer_{i}) is
unsafe on TP/EP topology change because modelopt_post_restore currently only
runs the base path and does not reinitialize per-expert _amax buffers; update
modelopt_post_restore to detect topology/shape mismatch and either (a) fail-fast
by raising a clear error when _per_expert_weight_quantizer is enabled and the
restored per-expert _amax shapes don't match the current weight shapes, or (b)
perform a per-expert recalibration: iterate over each created module name
weight_quantizer_{i} (use self.num_gemms to enumerate), reset/recreate their
_amax buffers to the correct shape for the current self.weight{i} and call the
quantizer's max_calibrate (or its equivalent reinit routine) so each per-expert
quantizer is re-calibrated after restore; implement one of these branches in
modelopt_post_restore to ensure shapes/amax are consistent after load.
---
Nitpick comments:
In `@tests/gpu_megatron/torch/quantization/plugins/test_megatron.py`:
- Around line 738-750: The test is forcing GPU->CPU syncs by calling .item()
inside the assert message and in the divergence check; change the assert to keep
comparisons on-device and only materialize scalars when needed: replace the
assert torch.allclose(te_amax.view(()), seq_max, ...) with an if-not pattern (if
not torch.allclose(...): raise
AssertionError(f"...{te_amax.item()}...{seq_max.item()}...")) so the .item()
calls only run on failure, and compute the per-expert divergence using tensor
ops (delta = seq_amaxes.max() - seq_amaxes.min(); if (delta > 1e-5):
saw_per_expert_divergence = True) while ensuring you only call .item() when you
must convert to a Python bool for logging or failure paths; update references to
seq_amaxes, seq_mlp.local_experts, linear_name, te_amax, and
saw_per_expert_divergence accordingly.
🪄 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: 5fbda55f-b0c7-4054-bc00-63b4bc3a150e
📒 Files selected for processing (2)
modelopt/torch/quantization/plugins/transformer_engine.pytests/gpu_megatron/torch/quantization/plugins/test_megatron.py
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #1550 +/- ##
==========================================
+ Coverage 78.60% 78.68% +0.08%
==========================================
Files 522 522
Lines 60167 60324 +157
==========================================
+ Hits 47294 47468 +174
+ Misses 12873 12856 -17
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:
|
There was a problem hiding this comment.
Design looks good to me overall, left a comment here - https://github.com/NVIDIA/Model-Optimizer/pull/1550/changes#r3468773327
There was a problem hiding this comment.
Warning
CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.
Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.
Actionable comments posted: 1
🧹 Nitpick comments (1)
modelopt/torch/quantization/plugins/transformer_engine.py (1)
167-167: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMove this import to module scope or document why it must stay local.
The new function-local import has no circular/optional/heavy-import justification. As per coding guidelines, “Keep imports at the top of the file; place imports inside functions only when necessary … with explicit justification.”
Proposed fix
+from modelopt.torch.quantization.model_calib import max_calibrate- from modelopt.torch.quantization.model_calib import max_calibrate - for i in range(self.num_gemms):🤖 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 `@modelopt/torch/quantization/plugins/transformer_engine.py` at line 167, The new function-local import of max_calibrate in transformer_engine.py should not stay inside the function unless there is a documented need such as a circular dependency or optional/heavy import. Move the import to module scope near the other top-level imports, or add a clear in-code justification at the exact import site if it must remain local. Use the surrounding transformer_engine plugin code and the max_calibrate reference to locate and update the import placement consistently.Source: Coding guidelines
🤖 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 `@modelopt/torch/quantization/plugins/transformer_engine.py`:
- Around line 147-150: Persist the per-expert quantizer mode alongside the
checkpoint metadata in transformer_engine.py so restore_quantizer_state() sees
the same module topology on load. Update the initialization path around
_per_expert_weight_quantizer_enabled() and add_module(...) to record the
MODELOPT_TEGROUPED_PER_EXPERT_QUANTIZER setting in the saved config or infer it
from restored state before quantizer modules are created, ensuring the number of
weight_quantizer_* modules matches at save and restore time.
---
Nitpick comments:
In `@modelopt/torch/quantization/plugins/transformer_engine.py`:
- Line 167: The new function-local import of max_calibrate in
transformer_engine.py should not stay inside the function unless there is a
documented need such as a circular dependency or optional/heavy import. Move the
import to module scope near the other top-level imports, or add a clear in-code
justification at the exact import site if it must remain local. Use the
surrounding transformer_engine plugin code and the max_calibrate reference to
locate and update the import placement consistently.
🪄 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: d8a388b2-8131-43ce-84b3-1deafe9b0934
📥 Commits
Reviewing files that changed from the base of the PR and between b1e32d9 and 308d8ee8a82e34a07e8c6060743ec1849253feed.
📒 Files selected for processing (1)
modelopt/torch/quantization/plugins/transformer_engine.py
| self._per_expert_weight_quantizer = _per_expert_weight_quantizer_enabled() | ||
| if self._per_expert_weight_quantizer: | ||
| for i in range(self.num_gemms): | ||
| self.add_module(f"weight_quantizer_{i}", TensorQuantizer()) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the target file with line numbers and the surrounding restore/setup logic.
FILE="modelopt/torch/quantization/plugins/transformer_engine.py"
echo "== file length =="
wc -l "$FILE"
echo
echo "== outline =="
ast-grep outline "$FILE" --view expanded || true
echo
echo "== relevant slices =="
sed -n '1,260p' "$FILE" | cat -n
echo
echo "== search for related restore/load paths =="
rg -n "modelopt_post_restore|load_state|state_dict|load\(|amax|per_expert|weight_quantizer_|_per_expert_weight_quantizer_enabled|max_calibrate" modelopt/torch/quantization/plugins/transformer_engine.py modelopt/torch/quantization -SRepository: NVIDIA/Model-Optimizer
Length of output: 50379
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="modelopt/torch/quantization/plugins/transformer_engine.py"
# Read only the relevant ranges around the env-gated modules and the local import.
sed -n '120,240p' "$FILE" | cat -nRepository: NVIDIA/Model-Optimizer
Length of output: 6927
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path("modelopt/torch/quantization/plugins/transformer_engine.py")
text = p.read_text()
for needle in [
"def modelopt_post_restore",
"max_calibrate",
"_per_expert_weight_quantizer_enabled",
"add_module(f\"weight_quantizer_",
]:
idx = text.find(needle)
print(f"\n## {needle} -> {idx}")
if idx != -1:
start = max(0, text.rfind("\n", 0, idx-400))
end = min(len(text), text.find("\n", idx+400))
print(text[start:end])
PYRepository: NVIDIA/Model-Optimizer
Length of output: 3922
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the quantizer restore/load path and the base class used here.
sed -n '90,170p' modelopt/torch/quantization/conversion.py | cat -n
printf '\n====\n'
sed -n '1,240p' modelopt/torch/quantization/plugins/custom.py | cat -n
printf '\n====\n'
rg -n "def quantizer_state|class _ParallelLinear|modelopt_post_restore|load_state_dict|ApplyModeError" modelopt/torch/quantization -SRepository: NVIDIA/Model-Optimizer
Length of output: 18270
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '1,120p' modelopt/torch/quantization/model_calib.py | cat -n
printf '\n====\n'
sed -n '1,120p' modelopt/torch/quantization/plugins/vllm.py | cat -nRepository: NVIDIA/Model-Optimizer
Length of output: 10780
Persist the per-expert quantizer mode in checkpoint metadata. restore_quantizer_state() rejects unmatched/extra quantizer keys, so changing MODELOPT_TEGROUPED_PER_EXPERT_QUANTIZER between save and restore makes the same checkpoint fail to load. Store the mode in the saved config/metadata or derive it from the restored state before add_module(...) runs so the module topology matches.
🤖 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 `@modelopt/torch/quantization/plugins/transformer_engine.py` around lines 147 -
150, Persist the per-expert quantizer mode alongside the checkpoint metadata in
transformer_engine.py so restore_quantizer_state() sees the same module topology
on load. Update the initialization path around
_per_expert_weight_quantizer_enabled() and add_module(...) to record the
MODELOPT_TEGROUPED_PER_EXPERT_QUANTIZER setting in the saved config or infer it
from restored state before quantizer modules are created, ensuring the number of
weight_quantizer_* modules matches at save and restore time.
Source: Coding guidelines
| self._per_expert_weight_quantizer = _per_expert_weight_quantizer_enabled() | ||
| if self._per_expert_weight_quantizer: | ||
| for i in range(self.num_gemms): | ||
| self.add_module(f"weight_quantizer_{i}", TensorQuantizer()) |
There was a problem hiding this comment.
@realAsma previously I did a copy.deepcopy(self.weight_quantizer) but you suggested to remove it .. how does this new quantizer inherit the quant format now?
There was a problem hiding this comment.
We just setup and initialize the tensor quantizers here. (called here
)The actual config will be loaded here -
There was a problem hiding this comment.
BB: Can you add more context if needed here?
There was a problem hiding this comment.
🤖 Bot comment.
Prepared a one-line context comment here explaining that the per-GEMM quantizers keep independent calibration state for each grouped weight.
Validation: git diff --check passed. I did not commit or push because this comment did not explicitly approve publishing; ready to push once approved.
308d8ee to
096d430
Compare
|
/claude review |
There was a problem hiding this comment.
Claude Review — Per-expert weight quantizer in TEGroupedMLP
Reviewed all 6 changed modelopt/ source files plus the two touched test files (9 files total). The core design — a GroupedQuantizer ModuleList holding one TensorQuantizer per fused expert, threaded through calibration/sync/config-matching — is coherent, and the model_calib.py recursion plus the custom.py/megatron.py isinstance updates are consistent. The opt-in torch.compile loop is well-gated (eager default, calibration excluded from capture). I found one blocking correctness bug in the restore path and one backward-compat concern.
Findings by severity: CRITICAL: 1, IMPORTANT: 1, SUGGESTION: 1
Most impactful:
[CRITICAL ModeState] Restore drops _amax for all experts except expert 0 (transformer_engine.py modelopt_post_restore). The base super().modelopt_post_restore() calls weight_quantizer.reset_amax(), which — because reset_amax is a GroupedQuantizer delegated method — wipes _amax on EVERY member, then recalibrates only member 0 (the forward->self[0] representative). The new per-expert loop is meant to recover the rest, but its if not hasattr(q, "_amax"): continue guard runs AFTER that wipe, so it skips exactly the experts that lost their _amax. Result: after restore(), experts 1..N-1 of every TEGroupedMLP have amax is None -> broken static quantization. Snapshot which members had loaded _amax BEFORE calling super() (which also deletes self.weight). The toy tests only cover quantize, not save->restore with num_gemms > 1, so this is not caught.
[IMPORTANT Compatibility] quantizer-state key schema change without migration (megatron.py _process_quantizer_amax). The single weight_quantizer._amax key becomes per-member weight_quantizer.{i}._amax. Existing pre-PR TEGroupedMLP checkpoints then fail restore — ApplyModeError (unmatched keys) on the non-sharded path, KeyError on the Megatron torch-dist path. Needs a migration shim or a state-version bump.
The SUGGESTION notes GroupedQuantizer.get_modelopt_state()/is_grouped_quantizer is currently dead code (no serializer collects the container, no restore code reads the flag).
The PR description already flags the TP/EP restore TODO — the CRITICAL finding shows the restore issue is broader (it affects same-topology restore for num_gemms > 1 too). Risk: high for anyone saving/restoring per-expert-quantized TEGroupedMLP checkpoints. Recommend addressing the restore ordering bug before merge.
| continue | ||
| wq_i = self.weight_quantizer[i] | ||
| q = wq_i[0] if isinstance(wq_i, SequentialQuantizer) else wq_i | ||
| if not hasattr(q, "_amax"): |
There was a problem hiding this comment.
[CRITICAL ModeState] Per-expert restore loses _amax for every expert except expert 0.
What happens: super().modelopt_post_restore() (custom.py:177-181) runs before this loop and executes:
self.weight_quantizer.reset_amax() # GroupedQuantizer delegated method -> broadcasts to ALL members
max_calibrate(self.weight_quantizer, lambda wq: wq(self.weight), distributed_sync=False)reset_amax() is in GroupedQuantizer._delegated_methods, so it deletes _amax on every member. But the max_calibrate forward loop calls self.weight_quantizer(self.weight), which routes through GroupedQuantizer.forward → self[0](...), so only member 0 gets recalibrated. Members 1..num_gemms-1 are left with no _amax.
This loop is then supposed to recalibrate the rest, but the guard if not hasattr(q, "_amax"): continue sees exactly those members with the _amax that super() just deleted, and skips them.
Impact: After restore() (both the non-sharded restore_quantizer_state path and the Megatron torch-dist set_extra_state path, which both call modelopt_post_restore), experts 1..N-1 of every TEGroupedMLP have weight_quantizer[i].amax == None. For a static INT8/FP8/NVFP4 config that means broken/incorrect quantization on all but the first expert — restore is not functionally identical to the saved model. num_gemms == 1 happens to work, which is why the toy tests (which cover quantize, not save→restore) don't catch it.
Fix: determine which members had saved _amax before calling super(), e.g.:
had_amax = []
for i in range(self.num_gemms):
wq_i = self.weight_quantizer[i]
q = wq_i[0] if isinstance(wq_i, SequentialQuantizer) else wq_i
had_amax.append(hasattr(q, "_amax"))
super().modelopt_post_restore(prefix=prefix)
delattr(self, "weight")
from modelopt.torch.quantization.model_calib import max_calibrate
for i in range(self.num_gemms):
weight_i = getattr(self, f"weight{i}", None)
if weight_i is None or not had_amax[i]:
continue
wq_i = self.weight_quantizer[i]
wq_i.reset_amax()
max_calibrate(wq_i, lambda wq, w=weight_i: wq(w), distributed_sync=False)(Note super() deletes self.weight, so snapshotting must happen first anyway.) Please also add a save→restore test covering num_gemms > 1 — the current tests exercise quantize only.
| if re.match(r"weight_quantizer\.\d+\..+_amax$", k): | ||
| quantizer_state_dict[k] = v | ||
| else: | ||
| quantizer_state_dict[k] = v.view(-1) if v.numel() == 1 else v |
There was a problem hiding this comment.
[IMPORTANT Compatibility] This change alters the modelopt_state/quantizer-state key schema for TEGroupedLinear with no migration path.
Before: a single weight_quantizer (TensorQuantizer) → one key ...weight_quantizer._amax.
After: a GroupedQuantizer (ModuleList) → per-member keys ...weight_quantizer.0._amax, ...weight_quantizer.1._amax, …
quantizer_state() (conversion.py:202-208) only collects the leaf TensorQuantizer/SequentialQuantizer members, so a checkpoint saved before this PR has key ...weight_quantizer while the restored model now exposes ...weight_quantizer.0/.1/.... On restore:
- Non-sharded path:
restore_quantizer_statecomputesunmatched_keys = state.keys() - model.keys()and raisesApplyModeErroron the mismatch (conversion.py:144-148). - Megatron
torch-distpath:quant_module_set_extra_statedoesquantizer_state[name]for eachweight_quantizer.iand hits aKeyError.
Either way, existing quantized TEGroupedMLP checkpoints become unloadable after this change. Please add a migration/back-compat shim (e.g. map a legacy scalar weight_quantizer._amax onto all weight_quantizer.{i} members during restore) or a state-version bump with an explicit remap, and document the break in the CHANGELOG if intentional.
|
|
||
| def get_modelopt_state(self) -> dict[str, Any]: | ||
| """Get meta state to be saved in checkpoint.""" | ||
| return {"num_quantizers": len(self), "is_grouped_quantizer": True} |
There was a problem hiding this comment.
[SUGGESTION] GroupedQuantizer.get_modelopt_state() and its is_grouped_quantizer flag appear to be dead code. quantizer_state() (conversion.py:202-208) and quant_module_get_extra_state() (megatron.py:145-148) only collect TensorQuantizer/SequentialQuantizer instances — a GroupedQuantizer itself is never serialized, only its leaf members are — and no restore-side code reads is_grouped_quantizer (unlike is_sequential_quantizer, which conversion.py:559 branches on). Either wire this into save/restore (which would also give you a natural home for the legacy-checkpoint migration noted in the megatron comment) or drop the method to avoid implying a round-trip that doesn't exist.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
modelopt/torch/quantization/model_calib.py (1)
356-357: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUpdate the type annotation to include
GroupedQuantizer.The function now handles
GroupedQuantizerat line 364, but the type hint at line 357 still readsTensorQuantizer | SequentialQuantizer.♻️ Proposed fix
def sync_quantizer_amax_across_tp( - quantizer: TensorQuantizer | SequentialQuantizer, + quantizer: TensorQuantizer | SequentialQuantizer | GroupedQuantizer, linear_name: str,🤖 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 `@modelopt/torch/quantization/model_calib.py` around lines 356 - 357, The type annotation for sync_quantizer_amax_across_tp is outdated and should include GroupedQuantizer now that the function handles it. Update the quantizer parameter type hint alongside TensorQuantizer and SequentialQuantizer so the signature matches the logic in sync_quantizer_across_tp and the GroupedQuantizer branch.modelopt/torch/quantization/plugins/transformer_engine.py (1)
187-187: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a comment explaining the in-function import.
Per coding guidelines, imports inside functions require a brief comment naming the reason (e.g., circular import). This likely avoids a circular dependency between
plugins/transformer_engine.pyandmodel_calib.py, but the reason should be documented.♻️ Proposed fix
- from modelopt.torch.quantization.model_calib import max_calibrate + # Import inside function to avoid circular import: model_calib imports from the + # quantization package which loads this plugins module. + from modelopt.torch.quantization.model_calib import max_calibrateAs per coding guidelines, "Put an import inside a function only when there is a concrete reason: resolving a circular import that cannot be restructured... Add a brief comment in those cases naming the reason."
🤖 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 `@modelopt/torch/quantization/plugins/transformer_engine.py` at line 187, The in-function import of max_calibrate in transformer_engine.py needs a brief explanatory comment per the import guidelines. Update the function containing this import to note the concrete reason for keeping it local, likely the circular dependency between transformer_engine and model_calib, so readers understand why it cannot be moved to the module top level.Source: Coding guidelines
🤖 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.
Nitpick comments:
In `@modelopt/torch/quantization/model_calib.py`:
- Around line 356-357: The type annotation for sync_quantizer_amax_across_tp is
outdated and should include GroupedQuantizer now that the function handles it.
Update the quantizer parameter type hint alongside TensorQuantizer and
SequentialQuantizer so the signature matches the logic in
sync_quantizer_across_tp and the GroupedQuantizer branch.
In `@modelopt/torch/quantization/plugins/transformer_engine.py`:
- Line 187: The in-function import of max_calibrate in transformer_engine.py
needs a brief explanatory comment per the import guidelines. Update the function
containing this import to note the concrete reason for keeping it local, likely
the circular dependency between transformer_engine and model_calib, so readers
understand why it cannot be moved to the module top level.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 9e78ab5d-dfba-434b-90ba-e77b357e483c
📒 Files selected for processing (6)
CHANGELOG.rstmodelopt/torch/quantization/config.pymodelopt/torch/quantization/model_calib.pymodelopt/torch/quantization/nn/modules/tensor_quantizer.pymodelopt/torch/quantization/plugins/transformer_engine.pytests/gpu_megatron/torch/quantization/plugins/test_megatron.py
✅ Files skipped from review due to trivial changes (2)
- modelopt/torch/quantization/config.py
- CHANGELOG.rst
| setattr(parent_module, name, sequential_quantizer) | ||
|
|
||
|
|
||
| class GroupedQuantizer(nn.ModuleList): |
There was a problem hiding this comment.
nit: SequentialQuantizer and GroupedQuantizer share sever overlapping pieces (such delegation, attribute setter etc). Can we create a shared base-class which implements these overlapping pieces and subclass SequentialQuantizer and GroupedQuantizer from it to avoid code level redundancy?
There was a problem hiding this comment.
RB: Can you create a plan on how to do this and share in this thread?
There was a problem hiding this comment.
🤖 Bot comment.
🐝 I’m reviewing the overlapping behavior and will share a concrete refactoring plan here shortly.
There was a problem hiding this comment.
🤖 Bot comment.
Plan:
- Add a private
_QuantizerContainerBasemixin before the two containers. It will own the common representative-property reads, property writes broadcast to every member, delegated lifecycle-method calls, attribute-config fan-out, and the commonget_modelopt_state()shape (using a subclass-provided state-key). - Make
SequentialQuantizerinherit from the mixin plusnn.Sequential, andGroupedQuantizerfrom the mixin plusnn.ModuleList. Keep PyTorch container initialization in each subclass so module registration/state-dict keys remain unchanged. - Keep only semantic differences in the subclasses: accepted member types, sequential chaining vs. grouped representative
forward,disable_rotatedelegation for sequential only, delegated-method return behavior, andconvert_to_single_quantizerfor sequential only. - Add parameterized CPU tests for the shared contract (representative reads, broadcast writes/methods, scalar/list config application, and exact modelopt-state output), plus regression tests that sequential chaining, grouped first-member forward, nested
SequentialQuantizermembers, and checkpoint/state-dict layout are unchanged.
This keeps the refactor local to tensor_quantizer.py and its focused tests; downstream (SequentialQuantizer, GroupedQuantizer) handling does not need to change.
There was a problem hiding this comment.
@jenchen13 could you take a look at this comment?
There was a problem hiding this comment.
RB:
Jenny says "for the other comment about base classes, it really would be an optimization and is not necessary right now. Changing SequentialQuantizer will also require extensive tests to make sure it didn't break"
I do not agree with this. I am not asking to change the interface of SequentialQuantizer -> but to consolidate SequentialQuantizer and GroupedQuantizer to avoid coercion redundancy.
There was a problem hiding this comment.
RB: Can you propose a plan how to do this consolidation without breaking SequentialQuantizer.
There was a problem hiding this comment.
🤖 Bot comment.
🐝 Acknowledged — I’ll outline a behavior-preserving consolidation plan.
There was a problem hiding this comment.
🤖 Bot comment.
Yes—this can be a small behavior-preserving consolidation, not an interface change.
- Add a private
_QuantizerContainerBasemixin (before the PyTorch container in the MRO) for the shared delegated-property read, broadcast__setattr__, lifecycle fan-out, andset_from_attribute_configlogic. Let a small hook preserve each class’s existing delegated-method return shape. - Keep
SequentialQuantizer(nn.Sequential)initialization and forward chaining untouched; it retainsdisable_rotate, its last-member return behavior,get_modelopt_state, andconvert_to_single_quantizer. - Keep
GroupedQuantizer(nn.ModuleList)initialization, accepted member types, and representativeforwarduntouched; it retains its list return from broadcast lifecycle calls. - Add parameterized tests for the shared delegation contract, plus regressions for SequentialQuantizer chaining, module/state-dict keys, checkpoint state, nested sequential members, and GroupedQuantizer indexing/representative-forward behavior.
That removes the duplicated container mechanics while explicitly locking down SequentialQuantizer’s current semantics.
There was a problem hiding this comment.
🤖 Bot comment.
🐝 I’m looking into the consolidation plan and the SequentialQuantizer compatibility constraints.
| # scalar, channel, or block shape instead of flattening them through the legacy | ||
| # single-quantizer path. | ||
| if re.match(r"weight_quantizer\.\d+\..+_amax$", k): | ||
| quantizer_state_dict[k] = v |
There was a problem hiding this comment.
Should we do
| quantizer_state_dict[k] = v | |
| quantizer_state_dict[k] = v.view(-1) if v.numel() == 1 else v |
There was a problem hiding this comment.
the static dict should only be flattened if it is not a per-expert quantizer, which is why this plain = v is inside the if re.match.. statement
| # GroupedQuantizer (an nn.ModuleList) surfaces them as ``weight_quantizer.{i}``, which the | ||
| # fused-experts name normalizer maps to ``*weight_quantizer`` so the stock configs apply. | ||
| self.weight_quantizer = GroupedQuantizer( | ||
| *(copy.deepcopy(self.weight_quantizer) for _ in range(self.num_gemms)) |
There was a problem hiding this comment.
We dont need this deep copy here.
| *(copy.deepcopy(self.weight_quantizer) for _ in range(self.num_gemms)) | |
| TensorQuantizer() for _ in range(self.num_gemms)) |
The TensorQuantizers are always initialized with default args; they are configured after _setup -> so we can safely initialize new TensorQuantizers here. deepcopy seems unwarranted to me.
There was a problem hiding this comment.
RB: Can you please explain concisely "The TensorQuantizers are always initialized with default args; they are configured after _setup -> so we can safely initialize new TensorQuantizers here. deepcopy seems unwarranted to me." with code pointers ?
There was a problem hiding this comment.
🤖 Bot comment.
🐝 I’m tracing the initialization and post-_setup configuration paths now; I’ll reply here shortly with exact code pointers.
There was a problem hiding this comment.
🤖 Bot comment.
Yes—the key is the conversion order:
convert_to_quantized_model()first callsreplace_quant_module(), thenset_quantizer_by_cfg().- Conversion invokes the module's
_setup(). The base setup createsweight_quantizerwith the standard 8-bit per-tensor descriptor (custom.py:113-117); that descriptor is justQuantizerAttributeConfig(num_bits=8)(tensor_quant.py:279), equivalent toTensorQuantizer()'s schema defaults. _QuantTEGroupedLinear._setup()builds the group immediately after that base setup (lines 147-156), still before user config is applied.- Afterwards,
set_quantizer_by_cfg()configures the registeredweight_quantizer.0,.1, … children; the fused-expert name normalization makes them match stock*weight_quantizerrules (conversion.py:319-355).
So deepcopy is only cloning a pristine default quantizer (including an empty/default calibrator). Fresh TensorQuantizer() instances give each expert independent state and are configured identically in the next phase. deepcopy would matter only if setup had already attached non-default config/state, which this path does not.
There was a problem hiding this comment.
I can to TensorQuantizer(self.default_quant_desc_weight) to preserve the axis information. otherwise the axis information will be dropped
|
|
||
| def _iter_leaf_quantizers(quantizer): | ||
| if isinstance(quantizer, SequentialQuantizer): | ||
| if isinstance(quantizer, (SequentialQuantizer, GroupedQuantizer)): |
There was a problem hiding this comment.
nit:
Create QuantizerContainerBase base class and use that here to avoid explicitly listing like this.
Add an explicit @pytest.mark.timeout(90) to test_te_grouped_real_compile_weight_quantizer_loop so a runaway inductor recompile is bounded tighter than the 120s gpu_megatron group default, while keeping headroom over a cold first-compile so CI doesn't flake. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Jennifer Chen <[email protected]>
hychiang-git
left a comment
There was a problem hiding this comment.
Looks good to me. Approve to unblock.
…xpert export Static-NVFP4 output_layer (lm_head) amax was dropped on save and never re-applied on restore, so TE-spec PTQ->HF export crashed on the lm_head with "Weight quantizer does not have attribute amax". Two-sided fix (ported from the LOCAL cherry-new-loss-qad branch), plus export-path robustness. - quantization/plugins/megatron.py: register modelopt get/set_extra_state for EVERY QuantModule incl. output_layer (old is_enabled gate ran pre-replacement so it always skipped output_layer). EP-downsize fallback rewrites only the expert index after weight_quantizer (preserves SequentialQuantizer suffixes). - opt/plugins/mcore_dist_checkpointing.py: after load_state_dict, explicitly call set_extra_state for modules with modelopt callbacks. - quantization/plugins/transformer_engine.py: modelopt_post_restore skips the CUDA-only fp4 dry-run when the weight is on CPU (export loads on CPU). - export/unified_export_megatron.py: assert weight_quantizer is GroupedQuantizer or None; warn on TP/EP-mismatch clamp; revert temporary export amax in finally. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Jennifer Chen <[email protected]>
After 57fe963 registered get/set_extra_state on every QuantModule (incl. output_layer), quant_module_get_extra_state still always returned a non-empty modelopt_quantizer_state (it iterates all TensorQuantizers, including disabled ones). An *unquantized* output_layer therefore emitted a non-empty _extra_state, and Megatron-Bridge's save_megatron_model -> GPTModel.sharded_state_dict (which asserts output_layer._extra_state is empty) failed with "Boolean value of Tensor with more than one value is ambiguous". Gate quant_module_get_extra_state to return {} when the module has no enabled TensorQuantizer and is not a compressed RealQuantLinear; the aggregator then returns None, satisfying Megatron's assert, while a genuinely quantized lm_head still saves its amax. Fixes tests/examples/megatron_bridge/test_quantize_export.py::test_quantize_and_export Signed-off-by: Jennifer Chen <[email protected]> Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # CHANGELOG.rst
| _delegated_properties = ["fake_quant", "is_enabled", "amax"] | ||
| _delegated_methods = [ | ||
| "reset_amax", | ||
| "disable", | ||
| "enable", | ||
| "load_calib_amax", | ||
| "load_calib_bias", | ||
| ] |
There was a problem hiding this comment.
@jenchen13 these are duplicated between Sequential Quantizer and this class which could be avoided by the common base class I mentioned in https://github.com/NVIDIA/Model-Optimizer/pull/1550/changes#r3553373837
There was a problem hiding this comment.
I implemented the QuantizerContainerBase
There was a problem hiding this comment.
Can we move these attributes to the QuantizerContainerBase? Currently the same properties are repeated across Sequential and Grouped Quantizer.
In addition "disable_rotate", is missing from GroupedQuantizer. We can avoid accidentally dropping such things by moving them to their unified shared class and not repeat here.
Signed-off-by: Jennifer Chen <[email protected]>
Signed-off-by: Jennifer Chen <[email protected]>
realAsma
left a comment
There was a problem hiding this comment.
Looks great! Left a comment here - https://github.com/NVIDIA/Model-Optimizer/pull/1550/changes#r3730695649
Could you please address that before merging?
Signed-off-by: Jennifer Chen <[email protected]>
Signed-off-by: Jennifer Chen <[email protected]>
Signed-off-by: Jenny Chen <[email protected]>
|
/ok to test 76e4924 |
| destroy_model_parallel() | ||
|
|
||
|
|
||
| @pytest.mark.timeout(90) # real torch.compile: cap runaway inductor recompiles without flaking CI |
There was a problem hiding this comment.
default timeout is 120s. We dont need to downgrade to 90s here
| def test_te_grouped_vs_sequential_default_loss(dist_workers_size_4, quant_cfg): | ||
| dist_workers_size_4.run( | ||
| partial(_test_te_grouped_vs_sequential_default_loss_helper, 1, 2, quant_cfg) | ||
| ) |
There was a problem hiding this comment.
same comment on 4-gpu requirement
There was a problem hiding this comment.
Most new tests have 2 or 4 gpu requirement hence they would not be run per PR. 2-gpu ones will run nightly or on-demand. Can you trigger manually so we can make sure 2-gpu tests pass before merging this.
You can specify your branch name and trigger workflow here: https://github.com/NVIDIA/Model-Optimizer/actions/workflows/gpu_tests.yml
There was a problem hiding this comment.
I have moved tests that don't require EP to EP=1 and the one that does require EP to EP=2
Signed-off-by: Jennifer Chen <[email protected]>
|
/ok to test 07f2e41 |
What does this PR do?
Type of change: New feature / breaking change
Change TEGroupedMLP to use per-expert weight quantizers by default for MoEs, matching SequentialMLP implementation for quantization. Currently TEGroupedMLP by default has one weight/input quantizer per layer which is different from SequentialMLP's one quantizer per expert implementation.
This is a breaking change for 0.47. If you are using Transformer Engine for PTQ/QAD in Megatron-Core (with
--export-default-te-specin Megatron-LM), checkpoints produced with 0.46 in TE will not be compatible with Model-Optimizer version 0.47.Usage
# Add a code snippet demonstrating how to use thisTesting
Tested on Nemotron Nano 3 PTQ & QAD that the accuracy & loss curves are identical
Before your PR is "Ready for review"
Make sure you read and follow Contributor guidelines and your commits are signed (
git commit -s -S).Make sure you read and follow the Security Best Practices (e.g. avoiding hardcoded
trust_remote_code=True,torch.load(..., weights_only=False),pickle, etc.).CONTRIBUTING.md: ✅ / ❌ / N/AAdditional Information
Summary by CodeRabbit
GroupedQuantizersupport (andAnyQuantizertyping) for container-style quantizers.amaxacross calibration, restore, and export.torch.compilepath viaMODELOPT_TEGROUPED_COMPILE_WEIGHT_LOOP=1(eager remains the default).amaxshapes).amaxlayout changes.amaxshapes, grouped-quantizer behavior, and compiled-vs-eager parity.