Skip to content

Fix quantization import when torch.jit.script is not re-exported - #3409

Open
970334745 wants to merge 1 commit into
NVIDIA:mainfrom
970334745:fix/torchscript-quantization-import-20261117
Open

970334745 wants to merge 1 commit into
NVIDIA:mainfrom
970334745:fix/torchscript-quantization-import-20261117

Conversation

@970334745

@970334745 970334745 commented Nov 17, 2026 •

Copy link
Copy Markdown

What does this PR do?

Type of change: Bug fix

Importing modelopt.torch.quantization fails on PyTorch 2.16.0.dev20261116 because the backward helper's @torch.jit.script decorator references an entry point that PyTorch no longer re-exports. This also blocks downstream quantized export/runtime tests before a model can run.

Import the same implementation from torch.jit._script under a private alias and use it for the existing decorator. The helper remains a compiled TorchScript function; its math, dtype handling, STE/clipped backward behavior, and device operations are unchanged. The private alias does not expand the module's public star-import surface.

Usage

Existing usage works without changes:

import modelopt.torch.quantization as mtq
from modelopt.torch.quantization.nn import TensorQuantizer

Testing

Matched original/repaired source at base e03b63b27c2a94701e125c429707cc0101aaa5bb, on Linux with Python 3.12.3 and torch==2.16.0.dev20261116+cpu:

  • Original source: test collection fails with AttributeError: module 'torch.jit' has no attribute 'script' from tensor_quant.py.
  • Repaired source: 17 passed, 0 skipped, using existing test_tensor_quant_cpu.py cases: TestFakeTensorQuantCPU (including STE and clipped gradients), INT8/INT4 strict capture, FP8 strict capture, and registered CPU quantization versus eager across scale layouts and dtypes. Longest test call: 0.11 s.
  • Applicable pre-commit formatting, Ruff, RST, license, security, and environment-variable hooks pass. macOS mypy reports a Linux-only os.sched_getaffinity reference in the unchanged Megatron data tool; the same hook version/default arguments with --platform linux pass for this file. No source/config suppression was added.
  • git diff --check passes. The source still matches the tested snapshot after hooks.
  • GPU, multi-rank, and the full library suite were not run. The change affects import-time name resolution only; no tensor hot path changes were introduced.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ The previous public name re-exported the same implementation.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A — neither copied code nor new dependencies.
  • Did you write any new necessary tests?: N/A — existing CPU tests reproduce this regression at collection and exercise the actual backward helper after the fix.
  • Did you update Changelog?: ✅ One quantization bug-fix entry.
  • Did you get Claude approval on this PR?: ❌ Not run.

Additional Information

Observed while repairing the current-PyTorch checks in pytorch/TensorRT#4952. ModelOpt 0.49.0rc0 has the same decorator; please consider the ongoing release branch for the import fix.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue that could prevent the quantization package from being imported with newer PyTorch versions. Quantization can now be imported when torch.jit.script is no longer available through the top-level PyTorch module.
  • Documentation
    • Updated the 0.50.0 changelog to document this compatibility fix.

@970334745
970334745 requested review from a team as code owners November 17, 2026 03:41
@970334745
970334745 requested a review from Edwardf0t1 November 17, 2026 03:41
@copy-pr-bot

copy-pr-bot Bot commented Nov 17, 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 Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The quantization module imports PyTorch’s script function as _script and uses it to decorate _fake_tensor_quant_backward. The changelog records the fix for PyTorch versions that no longer re-export torch.jit.script.

Changes: Quantization Import Compatibility

Layer / File(s) Summary
Import and use the script function
modelopt/torch/quantization/tensor_quant.py, CHANGELOG.rst
The module imports torch.jit.script as _script and applies it to _fake_tensor_quant_backward. The function body is unchanged. The changelog notes the compatibility fix.

Estimated code review effort: 2 (Simple) | ~5 minutes

Change: Bug fix

Suggested reviewers: kevalmorabia97

Merge Risk: Minimal · up to 54be8

This change fixes an import-time failure in the quantization module on PyTorch builds that no longer re-export torch.jit.script. It keeps the same compiled helper and leaves quantization behavior unchanged. No actionable merge-blocking risk remains.

Architecture risk: Low · up to be3f0

The change affects 2 systems.

Changed systems: modelopt, CHANGELOG.rst

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — modelopt (service) was modified; 1 changed file maps to changed impact.
  • observed — CHANGELOG.rst (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in CHANGELOG.rst: The 0.50.0 Quantization bug-fix section adds a changelog entry about importing Torch quantization on PyTorch versions that no longer re-export torch.jit.script.
  • observed — Modified behavior in modelopt/torch/quantization/tensor_quant.py: Adds the torch.jit.script function import under the local alias _script.
  • observed — Modified behavior in modelopt/torch/quantization/tensor_quant.py: Decorates _fake_tensor_quant_backward with the imported _script alias instead of torch.jit.script; the function body is unchanged.
Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Fix quantization import when torch.jit.script is not re-exported" matches the main change. The PR imports the same script implementation from torch.jit._script under a private alias, so the…
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 check covers six security anti-patterns in modelopt and examples Python changes. The PR changes two files: CHANGELOG.rst and modelopt/torch/quantization/tensor_quant.py. The Python change adds `fr…
Full details: Title check

Explanation

The title "Fix quantization import when torch.jit.script is not re-exported" matches the main change. The PR imports the same script implementation from torch.jit._script under a private alias, so the quantization module imports on PyTorch versions that no longer re-export torch.jit.script. The title names the failure and the scope of the fix. It is specific and concise, and it does not use vague terms.

Full details: Security Anti-Patterns

Explanation

The check covers six security anti-patterns in modelopt and examples Python changes. The PR changes two files: CHANGELOG.rst and modelopt/torch/quantization/tensor_quant.py. The Python change adds from torch.jit._script import script as _script and changes the decorator on _fake_tensor_quant_backward from @torch.jit.script to @_script. I scanned all added lines for the listed patterns and found none: 1. No torch.load or weights_only=False usage. 2. No numpy.load or allow_pickle usage. 3. No trust_remote_code usage. 4. No eval() or exec() calls. 5. No # nosec comments. 6. No changes to pyproject.toml or requirements.txt, so no new dependencies were added. The changed code is a private-alias import of the same TorchScript decorator. It does not add a security-sensitive pattern.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between be3f025 and 54be831.

Files selected for processing: 1

  • CHANGELOG.rst
Files skipped from review as they are similar to previous changes: 1

  • CHANGELOG.rst

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

@970334745

Copy link
Copy Markdown
Author

@Edwardf0t1, could you help get the unit-test workflow approved for be3f025 or point me to the right person? It is currently marked action_required with no jobs listed. The patch fixes the quantization import failure when PyTorch nightly no longer re-exports torch.jit.script. The 17 targeted CPU tests passed locally, and CI would help validate the fix for downstream Torch-TensorRT testing. I’d also welcome feedback on the import approach.

@970334745

Copy link
Copy Markdown
Author

I checked this branch against current main (37da734). The conflict is confined to CHANGELOG.rst; the quantization source change merges cleanly. For the update, would you prefer that I retain the changelog entry under the current unreleased quantization section? After the branch is updated, could you confirm which upstream checks and reviewer sign-off are required for this compatibility fix? The current unit-test run is awaiting approval. Thanks.

Resolve the existing scripted backward helper from its defining module. Keep the compiled math and public namespace unchanged.

Signed-off-by: momu <[email protected]>
@970334745
970334745 force-pushed the fix/torchscript-quantization-import-20261117 branch from be3f025 to 54be831 Compare November 23, 2026 02:12
@970334745

Copy link
Copy Markdown
Author

Hi @Edwardf0t1, could you please help get CI approved for the current head, 54be831261d3dce0e841752750e8ad00e73506c9, or route this to an authorized vetter? The unit-test workflow is awaiting approval. The latest revision passed all 47 CPU quantization tests locally on the affected PyTorch nightly, and DCO and CodeRabbit are green.

main has advanced again. I checked the merge against a6d3d73, and the only conflict is in CHANGELOG.rst; the quantization code merges cleanly. If this needs to be resolved before CI can run, could you let me know whether you prefer that I move the changelog entry again or omit it for this patch? After CI, please flag any further changes needed for review. Thanks!

This branch has not been deployed

No deployments
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.

1 participant