Skip to content

Add reversible weight folding and support TE grouped weights - #2140

Open
mxinO wants to merge 17 commits into
mainfrom
fix/fold-weight-quantizer-containers
Open

Add reversible weight folding and support TE grouped weights#2140
mxinO wants to merge 17 commits into
mainfrom
fix/fold-weight-quantizer-containers

Conversation

@mxinO

@mxinO mxinO commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds mtq.temporarily_fold_weights(model, snapshot_device=None) for repeated inference over a frozen fake-quantized model. The context snapshots affected weights and quantizer runtime state, calls each module's native fold_weight(keep_attrs=True), and restores state on exit, including after exceptions.

It also:

  • keeps retained weight pre-quant scales inactive while folded;
  • supports permanent folding for Transformer Engine GroupedLinear weights with grouped or shared TensorQuantizers;
  • discovers vLLM fused-MoE w13/w2 weights for weight calibration and temporary snapshots; and
  • keeps SVDQuant LoRA residuals separate when folding with keep_attrs=True.

SequentialQuantizer weights and weights or quantizers shared across QuantModule instances are not supported by the temporary context.

Related use case: NVIDIA-NeMo/RL#3441.

Testing

Focused CPU folding and restoration tests pass. Transformer Engine grouped folding is covered by GPU CI.

Signed-off-by: Meng Xin <mxin@nvidia.com>
@copy-pr-bot

copy-pr-bot Bot commented Aug 11, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@github-actions

github-actions Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://NVIDIA.github.io/Model-Optimizer/pr-preview/pr-2140/

Built to branch gh-pages at 2026-08-13 03:26 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Weight folding now supports temporary state tracking, shared-storage validation, LoRA-aware behavior, and Transformer Engine grouped linear layers. Temporary folding restores weights and quantizer state after normal or exceptional exit. Tests cover restoration, grouped quantizers, calibration attributes, and distributed weight access.

Changes

Weight folding

Layer / File(s) Summary
Transactional folding core
modelopt/torch/quantization/nn/modules/quant_module.py, modelopt/torch/quantization/model_quant.py, tests/unit/torch/quantization/test_tensor_quant_cpu.py
The implementation folds eligible tensor weights, snapshots state, rejects reused storage, and restores weights and quantizer state after temporary or failed folding.
LoRA-aware folding
modelopt/torch/quantization/nn/modules/quant_linear.py, tests/unit/torch/quantization/test_calib.py
Temporary folds skip SVDQuant LoRA residual merging. Tests verify LoRA factors, outputs, and weight restoration.
Grouped linear folding
modelopt/torch/quantization/plugins/transformer_engine.py, tests/gpu_megatron/torch/quantization/plugins/test_transformer_engine.py
Transformer Engine grouped linear layers fold weights for shared and independent fake-quantization quantizers. Tests verify outputs, metadata, and restoration.
Distributed weight handling
modelopt/torch/quantization/plugins/huggingface.py, tests/unit/torch/quantization/plugins/test_huggingface.py
Distributed weight access restores the original DTensor after exceptions. Transposed expert weights support folding through calibration weights.
Release notes
CHANGELOG.rst
The changelog documents mtq.temporarily_fold_weights, snapshots, restoration, and storage restrictions.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Model
  participant FoldingContext
  participant QuantModule
  participant QuantizerState
  Model->>FoldingContext: enter temporarily_fold_weights
  FoldingContext->>QuantModule: fold eligible tensor weights
  QuantModule->>QuantizerState: snapshot and update state
  FoldingContext-->>Model: expose folded weights
  Model->>FoldingContext: exit or raise exception
  FoldingContext->>QuantizerState: restore state and weights
Loading

Possibly related PRs

Suggested labels: cherry-pick-0.46.0

Suggested reviewers: realasma, juhi10071998

🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (5 passed)
Check name Status Explanation
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 The full PR diff adds no prohibited deserialization, pickle, remote-code, eval/exec, nosec, or dependency patterns; the existing trust_remote_code=True line is unchanged.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the two main changes: reversible weight folding and Transformer Engine grouped-weight support.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/fold-weight-quantizer-containers

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

@codecov

codecov Bot commented Aug 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.75862% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.14%. Comparing base (71b3d88) to head (f6eedf8).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...t/torch/quantization/plugins/transformer_engine.py 14.28% 6 Missing ⚠️
modelopt/torch/quantization/model_quant.py 93.75% 2 Missing ⚠️
...lopt/torch/quantization/nn/modules/quant_module.py 80.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2140      +/-   ##
==========================================
+ Coverage   67.09%   67.14%   +0.05%     
==========================================
  Files         522      522              
  Lines       60461    60509      +48     
==========================================
+ Hits        40567    40631      +64     
+ Misses      19894    19878      -16     
Flag Coverage Δ
examples-gpt-oss 13.26% <8.62%> (-0.01%) ⬇️
examples-llm_distill 13.33% <8.62%> (-0.01%) ⬇️
examples-llm_qat 17.58% <8.62%> (-0.02%) ⬇️
examples-llm_sparsity 15.91% <8.62%> (-0.01%) ⬇️
examples-specdec_bench 13.00% <8.62%> (-0.01%) ⬇️
examples-speculative_decoding 17.52% <8.62%> (-0.08%) ⬇️
examples-torch_trt 15.08% <6.89%> (-0.01%) ⬇️
gpu 21.06% <13.79%> (-0.01%) ⬇️
regression 14.88% <8.62%> (+0.06%) ⬆️

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.

@mxinO
mxinO marked this pull request as ready for review August 11, 2026 14:52
@mxinO
mxinO requested review from a team as code owners August 11, 2026 14:52
@mxinO
mxinO requested a review from cjluo-nv August 11, 2026 14:52

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Bot review (bedrock-claude-opus-5) — DM the bot to share feedback.

The core change is correct and well-scoped: _fold_weight_quantizer now iterates the stages of a SequentialQuantizer (its disable()/disable_rotate() already broadcast via _QuantizerContainerBase), the base fold_weight accepts sequential weight quantizers, and the new _QuantTEGroupedLinear.fold_weight fixes a real bug — previously a GroupedQuantizer was silently skipped by the dir() scan, and a shared TensorQuantizer on TEGroupedLinear would even trip the assert hasattr(self, weight_name) since _setup deletes self.weight. Batching weights per quantizer before disable() is the right ordering, and the new CPU unit test verifies output invariance plus the keep_attrs matrix.

Three things worth addressing before merge:

  1. The same bug is left unfixed one file over. _QuantFusedExperts.fold_weight (plugins/huggingface.py) still gates on isinstance(q, TensorQuantizer), so per-expert quantizers that set_quantizer_attributes_full promoted to SequentialQuantizer (a list cfg matches gate_up_proj_weight_quantizers.N via _normalize_fused_experts_quantizer_name, e.g. W4A8) are still silently skipped — folding becomes a no-op there. Since the helper you just generalized handles sequential fine, this is a one-token fix.

  2. Duplicated logic. The new TE fold_weight is entirely generic over iter_weights_for_calibration(); it is a near-copy of _QuantFusedExperts.fold_weight, and vLLM's _QuantFusedMoEBase.fold_weight is a third variant. Consider hoisting the quantizer→weights batching loop into QuantModule (e.g. _fold_weights_from_calibration_iter) and having TE and fused-experts both call it — that removes the duplication and fixes (1) in the same stroke.

  3. Behavior change under keep_attrs=True is undocumented. Setting _enable_pre_quant_scale = False is correct (the weight-quantizer pre_quant_scale is applied before the _disabled early-return in TensorQuantizer.forward, so a retained buffer would double-apply — and _apply_weight_pre_quant_scale with _ENABLE_FOLDING_PQS_TO_WEIGHTS=False does put a live pqs on weight quantizers during auto_quantize). But it means quantizer.pre_quant_scale now returns None after folding while _pre_quant_scale is still present, and pre_quant_scale's setter asserts on _enable_pre_quant_scale. Please state this in the fold_weight docstring, and reconsider "Changelog: N/A" given keep_attrs=True is a public flag whose observable semantics changed.

Also flagging (nudge-level, no action strictly required): the only coverage for the new TE path is a tests/gpu_megatron test the author states was never executed locally, and it asserts only weights/_amax — not post-fold forward equality or the new _enable_pre_quant_scale flag.

Comment thread modelopt/torch/quantization/plugins/transformer_engine.py
Comment thread modelopt/torch/quantization/nn/modules/quant_module.py Outdated
Comment thread tests/gpu_megatron/torch/quantization/plugins/test_transformer_engine.py Outdated
mxinO added 2 commits August 12, 2026 03:56
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>
@mxinO mxinO changed the title Fix folding sequential and TE grouped quantizers Add reversible weight folding and support TE grouped weights Aug 12, 2026

@coderabbitai coderabbitai 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.

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.

👉 Steps to fix this

Actionable comments posted: 2

🧹 Nitpick comments (2)
tests/gpu_megatron/torch/quantization/plugins/test_transformer_engine.py (1)

155-205: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the shared grouped-linear setup into a fixture.

Lines 157-166 duplicate lines 123-132 exactly. A small helper or fixture that returns (model, calib_data, grouped_linear, weights, quantizers) for a given share_weight_quantizer would keep both tests aligned when the grouped path changes.

The coverage itself matches the earlier review request: the test now asserts folded output equality and pre-quant-scale inertness on the grouped and shared paths.

🤖 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_transformer_engine.py`
around lines 155 - 205, Extract the duplicated grouped-linear setup from
test_temporarily_fold_weight_grouped_linear and the earlier grouped-linear test
into a shared fixture or helper. Have it accept share_weight_quantizer and
return model, calib_data, grouped_linear, weights, and quantizers, then update
both tests to reuse it while preserving their existing assertions.
tests/unit/torch/quantization/test_tensor_quant_cpu.py (1)

417-422: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that the first module was folded before the failure.

The test verifies restoration only. It does not prove that first was folded before second raised. If a future change makes the fold of first a silent no-op, this test still passes. Add a probe that records the folded weight of first at the moment the second fold fails, for example by wrapping second.fold_weight instead of raising inside the backend.

Attribution: the path instructions for tests/**/*.py require that tests exercise the behavior they claim to validate.

🤖 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/unit/torch/quantization/test_tensor_quant_cpu.py` around lines 417 -
422, Update the test around the first and second module folding so it records
whether the first module’s weight changed before the second fold raises. Wrap or
spy on second.fold_weight to capture first’s folded weight at failure, assert
that this probe observes the folded state, then retain the existing assertions
verifying weight and quantizer restoration.

Source: Path instructions

🤖 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/nn/modules/quant_linear.py`:
- Around line 72-74: Ensure the standard PyTorch state_dict round trip preserves
the disabled SVDQuant LoRA state set by fold_weight(keep_attrs=True), so
reloaded modules do not re-enable retained factors or apply the residual twice.
Update the relevant quantized linear module serialization or reload behavior
around _enable_svdquant_lora and _svdquant_lora_a, then add a regression test
covering fold, state_dict save/load, and equivalent inference outputs.

In `@modelopt/torch/quantization/nn/modules/quant_module.py`:
- Around line 115-147: Update _shared_parameter_storages to track each
parameter’s actual memory range, accounting for shape, strides, storage offset,
and element size, and mark an allocation as shared only when parameter ranges
overlap; retain conservative handling for unsupported or ambiguous layouts.
Ensure _fold_weight_quantizer continues blocking overlapping aliases while
allowing folds for non-overlapping packed views, and add tests covering both
cases.

---

Nitpick comments:
In `@tests/gpu_megatron/torch/quantization/plugins/test_transformer_engine.py`:
- Around line 155-205: Extract the duplicated grouped-linear setup from
test_temporarily_fold_weight_grouped_linear and the earlier grouped-linear test
into a shared fixture or helper. Have it accept share_weight_quantizer and
return model, calib_data, grouped_linear, weights, and quantizers, then update
both tests to reuse it while preserving their existing assertions.

In `@tests/unit/torch/quantization/test_tensor_quant_cpu.py`:
- Around line 417-422: Update the test around the first and second module
folding so it records whether the first module’s weight changed before the
second fold raises. Wrap or spy on second.fold_weight to capture first’s folded
weight at failure, assert that this probe observes the folded state, then retain
the existing assertions verifying weight and quantizer restoration.
🪄 Autofix

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: 6fa0afd9-94db-4484-a6a8-1c33c42a3a1f

📥 Commits

Reviewing files that changed from the base of the PR and between 8786941 and 10326e3.

📒 Files selected for processing (10)
  • CHANGELOG.rst
  • modelopt/torch/quantization/model_quant.py
  • modelopt/torch/quantization/nn/modules/quant_linear.py
  • modelopt/torch/quantization/nn/modules/quant_module.py
  • modelopt/torch/quantization/plugins/huggingface.py
  • modelopt/torch/quantization/plugins/transformer_engine.py
  • tests/gpu_megatron/torch/quantization/plugins/test_transformer_engine.py
  • tests/unit/torch/quantization/plugins/test_huggingface.py
  • tests/unit/torch/quantization/test_calib.py
  • tests/unit/torch/quantization/test_tensor_quant_cpu.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • modelopt/torch/quantization/plugins/transformer_engine.py

Comment thread modelopt/torch/quantization/nn/modules/quant_linear.py Outdated
Comment thread modelopt/torch/quantization/nn/modules/quant_module.py Outdated
mxinO added 2 commits August 12, 2026 08:06
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>

@coderabbitai coderabbitai 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.

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.

👉 Steps to fix this

Actionable comments posted: 2

🤖 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/model_quant.py`:
- Around line 776-786: Update the restoration logic in the finally block to
catch and collect errors from each weight.copy_ and quantizer-state restoration,
continuing through all remaining weights and states. After both loops complete,
re-raise the first collected restoration error, while preserving the existing
no-grad context and missing-attribute handling.

In `@modelopt/torch/quantization/nn/modules/quant_module.py`:
- Around line 68-78: Update _tensor_storage_key to return None for empty or meta
tensors, and adjust _tied_parameter_storages to exclude None keys from its
counts. Preserve existing storage-key behavior for regular non-empty parameters
so only genuinely tied storages are reported.
🪄 Autofix

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: db6d62ca-3f03-43a2-854e-1a08e0e14176

📥 Commits

Reviewing files that changed from the base of the PR and between 10326e3 and f62e7ab.

📒 Files selected for processing (5)
  • CHANGELOG.rst
  • modelopt/torch/quantization/model_quant.py
  • modelopt/torch/quantization/nn/modules/quant_module.py
  • tests/unit/torch/quantization/plugins/test_huggingface.py
  • tests/unit/torch/quantization/test_tensor_quant_cpu.py
💤 Files with no reviewable changes (1)
  • tests/unit/torch/quantization/plugins/test_huggingface.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.rst

Comment thread modelopt/torch/quantization/model_quant.py Outdated
Comment thread modelopt/torch/quantization/nn/modules/quant_module.py Outdated

@coderabbitai coderabbitai 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.

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/nn/modules/quant_linear.py (1)

72-74: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Prevent double application of the SVDQuant residual after permanent folding.

A non-temporary fold already adds the LoRA residual to self.weight. These getters still return both retained buffers, so SVDQuantLinear.forward can add the same residual again. Keep the factors active only for temporary folds. Otherwise, remove them or persist an explicit inactive state after permanent folding. Add regression tests for fold_weight(keep_attrs=True) and a standard state_dict() round trip. (raw.githubusercontent.com)

Also applies to: 96-98

🤖 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/nn/modules/quant_linear.py` around lines 72 - 74,
Update the SVDQuant LoRA-factor getters around _svdquant_lora_a and the
corresponding factor getter so permanently folded residuals are not returned to
SVDQuantLinear.forward; retain them only for temporary folds, or track an
explicit inactive state after permanent folding. Ensure
fold_weight(keep_attrs=True) and a standard state_dict() round trip do not
reapply the residual, and add regression coverage for both cases.

Source: MCP tools

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

Outside diff comments:
In `@modelopt/torch/quantization/nn/modules/quant_linear.py`:
- Around line 72-74: Update the SVDQuant LoRA-factor getters around
_svdquant_lora_a and the corresponding factor getter so permanently folded
residuals are not returned to SVDQuantLinear.forward; retain them only for
temporary folds, or track an explicit inactive state after permanent folding.
Ensure fold_weight(keep_attrs=True) and a standard state_dict() round trip do
not reapply the residual, and add regression coverage for both cases.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 875b77a0-674a-4f86-b621-1b35699d6687

📥 Commits

Reviewing files that changed from the base of the PR and between f62e7ab and 9a5eed7.

📒 Files selected for processing (6)
  • CHANGELOG.rst
  • modelopt/torch/quantization/model_quant.py
  • modelopt/torch/quantization/nn/modules/quant_linear.py
  • modelopt/torch/quantization/nn/modules/quant_module.py
  • tests/unit/torch/quantization/test_calib.py
  • tests/unit/torch/quantization/test_tensor_quant_cpu.py
💤 Files with no reviewable changes (1)
  • tests/unit/torch/quantization/test_calib.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • modelopt/torch/quantization/model_quant.py
  • tests/unit/torch/quantization/test_tensor_quant_cpu.py
  • modelopt/torch/quantization/nn/modules/quant_module.py

Signed-off-by: Meng Xin <mxin@nvidia.com>

@coderabbitai coderabbitai 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.

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.

👉 Steps to fix this

Actionable comments posted: 1

🤖 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/huggingface.py`:
- Around line 622-627: Update fold_weight to group weight views by each
TensorQuantizer identity before calling QuantModule._fold_weight_quantizer, so
every shared quantizer is folded once with all associated weights. Preserve the
existing fake_quant and keep_attrs conditions, and ensure duplicate quantizer
views are not processed through separate mutation calls.
🪄 Autofix

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: dde3c614-381c-4da2-b3cc-3fe8b3b7d692

📥 Commits

Reviewing files that changed from the base of the PR and between 9a5eed7 and 9243b02.

📒 Files selected for processing (5)
  • CHANGELOG.rst
  • modelopt/torch/quantization/model_quant.py
  • modelopt/torch/quantization/nn/modules/quant_module.py
  • modelopt/torch/quantization/plugins/huggingface.py
  • tests/unit/torch/quantization/test_tensor_quant_cpu.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • CHANGELOG.rst
  • modelopt/torch/quantization/nn/modules/quant_module.py
  • tests/unit/torch/quantization/test_tensor_quant_cpu.py

Comment thread modelopt/torch/quantization/plugins/huggingface.py Outdated
mxinO added 7 commits August 12, 2026 09:24
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>
Signed-off-by: Meng Xin <mxin@nvidia.com>
mxinO added 2 commits August 12, 2026 10:35
Signed-off-by: Meng Xin <mxin@nvidia.com>
…izer-containers

Signed-off-by: Meng Xin <mxin@nvidia.com>

# Conflicts:
#	CHANGELOG.rst

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Bot review (bedrock-claude-opus-5) — DM the bot to share feedback.

Re-review of PR #2140, now reshaped from "fix sequential folding" into a new public API: mtq.temporarily_fold_weights (+ TE grouped fold_weight). Size is fine (10 files, +325/-19) and the CPU tests are much better than the previous round (restore-after-exception, rollback when folding fails, SequentialQuantizer rejection, disabled-transform/weight=None, SVDQuant residual kept separate).

Design-review note (gate fired): the PR body doesn't discuss alternatives for the new context. The main design question is the discovery/mutation split: the context discovers what to snapshot via QuantModule.iter_weights_for_calibration() but delegates mutation to each plugin's fold_weight(). Those two sets are not guaranteed to agree, and where they don't the context silently fails to restore (see inline: vLLM _QuantFusedMoEBase). The repo also already has get_quantizer_state_dict/set_quantizer_state_dict and TensorQuantizer.get_modelopt_state() for capturing quantizer state, versus the four hand-picked private attrs here — please say in the PR body why those weren't reused, and why the snapshot is keyed off the calibration iterator rather than off what fold_weight actually touches.

Status of prior review points:

  • keep_attrs=True pre-quant-scale semantics are now documented in the fold_weight docstring and CHANGELOG.
  • ✅ New CPU coverage for the temporary context is meaningful.
  • ❌ TE GPU test: the reply says the tests "cover permanent and temporary folding ... verify retained PQS is inactive while folded, and verify weights/quantizer state are restored afterward", but the final diff only contains test_fold_weight_grouped_linear (permanent fold; asserts forward equality and _amax removal). The temporary-fold grouped test and the _enable_pre_quant_scale assertion aren't there.
  • 💬 Duplication (TE / HF fused-experts / vLLM fold loops) — author explained the deliberate choice to keep TE's batching module-specific; the third near-copy still stands, flagging for the owner rather than re-arguing.
  • _QuantFusedExperts.fold_weight's isinstance(q, TensorQuantizer) gate (silent no-op fold for W4A8 per-expert SequentialQuantizers) is unchanged, and the base _fold_weight_quantizer's sequential support from the earlier commits was reverted, so mtq.fold_weight now silently skips sequential weight quantizers while the new context raises for them.
  • Also: the earlier reply stated the context "raises before mutation" for weights/quantizers shared across modules and that a shared-storage test verifies rejection + rollback — that guard and test are not in the final diff; the limitation is now only prose in the docstring.

Nit: CHANGELOG mentions the pre-quant-scale change but not the SVDQuant fold_weight(keep_attrs=True) behavior change (residual is no longer baked into the weight), which is also public-facing.

No licensing concerns (standard NVIDIA/Apache headers, no vendored code).


Additional comments (outside the PR diff):

  • modelopt/torch/quantization/nn/modules/quant_module.py:175 — > Bot comment.

With the sequential support from the earlier commits reverted, fold_weight now silently skips a SequentialQuantizer weight quantizer (the isinstance(attr, TensorQuantizer) gate), while temporarily_fold_weights raises NotImplementedError for the same case. That asymmetry means mtq.fold_weight(model, ...) on a W4A8 model reports success while folding nothing — the exact silent no-op flagged last round for _QuantFusedExperts.fold_weight (whose isinstance(q, TensorQuantizer) gate is also unchanged). If sequential folding is out of scope now, please make the permanent path warn or raise too, so the two entry points agree and the no-op isn't silent.

Comment thread modelopt/torch/quantization/model_quant.py
Comment thread modelopt/torch/quantization/model_quant.py
Comment thread modelopt/torch/quantization/model_quant.py
Comment thread modelopt/torch/quantization/plugins/transformer_engine.py
Signed-off-by: Meng Xin <mxin@nvidia.com>
@mxinO
mxinO requested a review from a team August 13, 2026 01:51
Signed-off-by: Meng Xin <mxin@nvidia.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants