Skip to content

Fix import modelopt.torch without the [hf] extra - #2671

Merged
kevalmorabia97 merged 3 commits into
NVIDIA:mainfrom
LinCanNerd:fix/modelopt-torch-base-install-imports
Oct 17, 2026
Merged

kevalmorabia97 merged 3 commits into
NVIDIA:mainfrom
LinCanNerd:fix/modelopt-torch-base-install-imports

Conversation

@LinCanNerd

@LinCanNerd LinCanNerd commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

import modelopt.torch fails on a base install (pip install nvidia-modelopt, no extras), although the installation docs state that the base install provides the modelopt.torch requirements. Reproduced with the released 0.47.0 in a fresh venv containing only torch and nvidia-modelopt==0.47.0:

>>> import modelopt.torch.quantization
ModuleNotFoundError: No module named 'requests'
# after `pip install requests`:
ModuleNotFoundError: No module named 'huggingface_hub'

Root cause: two modules that modelopt.torch always imports have module-scope imports of packages that are not base dependencies:

  • modelopt/torch/utils/dataset_utils.py imports requests (since Allow basename of dataset paths to match registered names #997). It is only used in download_hf_dataset_as_jsonl, which already imports datasets and huggingface_hub locally. requests is not declared anywhere; it was only present transitively.
  • modelopt/torch/opt/plugins/huggingface.py imports huggingface_hub (since Add experimental support for transformers>=5.0 + min torch 2.8 #975). modelopt/torch/opt/__init__.py imports this plugin under import_plugin("huggingface"), but opt/plugins/__init__.py imports it unconditionally, and unified_export_hf.py imports from it directly. It is only used in _get_modelopt_state_path.

The fix moves each import into the only function that uses it. CI did not catch this because every test environment installs extras that bring both packages in, so the new tests/unit/torch/test_import.py imports modelopt.torch in a subprocess with the [hf] extra's modules (plus requests) made unavailable.

Out of scope: modelopt.torch.export (imports huggingface_hub deliberately via utils/plugins/hf_checkpoint_utils.py, #2427) and modelopt.torch.puzzletron (has its own [puzzletron] extra) still need their optional dependencies.

Usage

No API changes.

Testing

  • Fresh venv with only CPU torch and this branch installed (pip install -e ., base dependencies only): import modelopt.torch and modelopt.torch.{opt,quantization,sparsity,distill,nas,prune,speculative,peft,trace,utils,fastgen,models} all import; before the change every one failed with the ModuleNotFoundError above.
  • tests/unit/torch/test_import.py fails on main (import of requests halted; None in sys.modules) and passes with this change.
  • pytest tests/unit/torch/utils/test_dataset_utils.py tests/unit/torch/opt tests/unit/torch/test_import.py: 122 passed (with datasets installed, test_dataset_utils.py: 70 passed).
  • pre-commit run on the changed files: all hooks pass.

Found while setting up ModelOpt with pip-only dependencies on a Jetson AGX Thor.

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

  • Is this change backward compatible?: ✅
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅
  • Did you get Claude approval on this PR?: N/A

Additional Information

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue that could prevent modelopt.torch from importing when optional Hugging Face dependencies were not installed. The package can now be imported without those dependencies. Features that need them, such as downloading datasets or checking the Hugging Face model cache, still require the relevant optional dependencies.

modelopt.torch failed to import on a base `pip install nvidia-modelopt`:
utils/dataset_utils.py imported `requests` and opt/plugins/huggingface.py
imported `huggingface_hub` at module scope, but neither is a base
dependency. Both modules are imported unconditionally by modelopt.torch, so
the import failed with ModuleNotFoundError even though the docs state the
base install covers modelopt.torch.

Import each one inside the only function that uses it, next to the other
optional Hugging Face imports there, and add a test that imports
modelopt.torch with the [hf] extra's modules unavailable.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: LinCanNerd <[email protected]>
@LinCanNerd
LinCanNerd requested review from a team as code owners October 6, 2026 09:05
@LinCanNerd
LinCanNerd requested a review from ChenhanYu October 6, 2026 09:05
@copy-pr-bot

copy-pr-bot Bot commented Oct 6, 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 6, 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: 6d1004a9-9972-4b9b-84de-2ad2426d7279
📥 Commits

Reviewing files that changed from the base of the PR and between 55cd05d and 43eaad9.

📒 Files selected for processing: 3
  • CHANGELOG.rst
  • modelopt/torch/opt/plugins/huggingface.py
  • modelopt/torch/utils/dataset_utils.py
💤 Files with no reviewable changes: 2
  • modelopt/torch/utils/dataset_utils.py
  • modelopt/torch/opt/plugins/huggingface.py
🚧 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.

📝 Walkthrough

The change defers imports of huggingface_hub and requests until their functions run. A subprocess test checks that modelopt.torch imports without these optional dependencies. The changelog records the import fix.

Changes: Optional dependency imports

Layer / File(s) Summary
Defer optional dependency imports
modelopt/torch/opt/plugins/huggingface.py, modelopt/torch/utils/dataset_utils.py, tests/unit/torch/test_import.py, CHANGELOG.rst
Hub helpers are imported inside _get_modelopt_state_path, after its local-directory check. requests is imported inside download_hf_dataset_as_jsonl. A subprocess test checks the modelopt.torch import when optional modules are unavailable. The changelog records the fix.

Priority: ⬇️ Low

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

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: kevalmorabia97, ajrasane, cjluo-nv

Merge Risk: ⚪ Minimal · up to 43eaa

The base-install import fix is ready to merge after normal checks.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 3 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: allowing modelopt.torch to import without the optional [hf] extra.
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 authoritative diff changes only two lazy imports, a changelog entry, and an import test. The added Python lines contain no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=T…
Full details: Security Anti-Patterns

Explanation

PASS. The authoritative diff changes only two lazy imports, a changelog entry, and an import test. The added Python lines contain no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), hardcoded trust_remote_code=True, external-input eval/exec, or # nosec. No pyproject.toml or requirements.txt file changed, so no new PIP dependency was added.

Full details: Docstring Coverage

Explanation

Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 3 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@LinCanNerd

Copy link
Copy Markdown
Contributor Author

@AAnoosheh When you have a moment, could you run /ok to test on this PR? CI has not started here yet. Thanks!

@AAnoosheh
AAnoosheh requested review from kevalmorabia97 and removed request for ChenhanYu October 12, 2026 14:15

@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 (gpt-6.1-sol) — DM the bot to share feedback.

Approve: deferring optional dependency imports fixes base-install loading without changing the affected feature logic, and the subprocess test covers the regression.

No action needed.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

@LinCanNerd can you fix merge conflicts?

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.66667% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 78.87%. Comparing base (83b1e69) to head (43eaad9).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
modelopt/torch/utils/dataset_utils.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2671      +/-   ##
==========================================
+ Coverage   76.93%   78.87%   +1.93%     
==========================================
  Files         658      658              
  Lines       73815    73815              
==========================================
+ Hits        56791    58222    +1431     
+ Misses      17024    15593    -1431     
Flag Coverage Δ
examples-diffusers 20.09% <66.66%> (+<0.01%) ⬆️
examples-gpt-oss 13.54% <66.66%> (+0.01%) ⬆️
examples-hf_ptq 23.23% <66.66%> (-0.05%) ⬇️
examples-llm_distill 13.62% <66.66%> (+0.01%) ⬆️
examples-llm_eval 17.28% <66.66%> (+<0.01%) ⬆️
examples-llm_qat 17.53% <66.66%> (+<0.01%) ⬆️
examples-llm_sparsity 15.80% <66.66%> (+0.01%) ⬆️
examples-megatron_bridge 26.46% <66.66%> (-0.19%) ⬇️
examples-specdec_bench 13.32% <0.00%> (+0.01%) ⬆️
examples-speculative_decoding 17.52% <66.66%> (-0.06%) ⬇️
examples-torch_onnx 21.45% <66.66%> (-0.01%) ⬇️
examples-torch_trt 15.27% <66.66%> (+0.01%) ⬆️
examples-vllm_serve 15.02% <0.00%> (+0.01%) ⬆️
gpu 59.35% <66.66%> (+8.46%) ⬆️
regression 15.13% <66.66%> (+0.01%) ⬆️
unit 60.44% <66.66%> (-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.

LinCanNerd and others added 2 commits October 13, 2026 14:57
@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/ok to test 43eaad9

@kevalmorabia97
kevalmorabia97 enabled auto-merge (squash) October 17, 2026 06:38
@kevalmorabia97
kevalmorabia97 merged commit d7cbff3 into NVIDIA:main Oct 17, 2026
55 checks passed
kevalmorabia97 pushed a commit that referenced this pull request Oct 26, 2026
### What does this PR do?

Type of change: new tests

#2671 made `import modelopt.torch` work on a base install and added
`tests/unit/torch/test_import.py` to keep it that way. This extends that
test: in the same subprocess, with the `[hf]` extra's modules still made
unavailable, it also quantizes a small model (`mtq.INT8_DEFAULT_CFG`,
max calibration).

The import alone doesn't cover this. In 0.47.0, even with #2671 applied,
`mtq.quantize` on a base install fails:

```
  File ".../modelopt/torch/quantization/model_calib.py", line 99, in _collect_grouped_linears
    from modelopt.torch.export.layer_utils import _GATE_UP_PAIRS
  File ".../modelopt/torch/export/__init__.py", line 28, in <module>
    from .unified_export_megatron import *
  File ".../modelopt/torch/export/unified_export_megatron.py", line 32, in <module>
    from huggingface_hub import get_safetensors_metadata, hf_hub_download
ModuleNotFoundError: No module named 'huggingface_hub'
```

Max calibration checks that fused sibling linears share one weight
`global_amax`, and since #1605 (0.46.0) it looked up the gate/up
projection names in `modelopt.torch.export`. #1828 replaced that lookup
with `modelopt.torch.models.list_all_possible`, so main and
`release/0.48.0` quantize fine. No test would catch it coming back:
every CI environment has `huggingface_hub`, if only through `timm` from
`dev-test`.

The quantize step goes into the existing subprocess rather than a second
one, following CONTRIBUTING's rule for unit tests that spawn processes.
On a shared x86 builder, over 5 interleaved runs, the subprocess used a
median 4.37 s of CPU time both with and without the quantize step; the
difference is within the run-to-run spread (4.1 to 4.7 s), so nearly all
of it is the import.

### Usage

N/A

### Testing

`tests/unit/torch/test_import.py`, on main at efda42c, in an
environment with `huggingface_hub` installed (through `timm`):

- With this PR: passes.
- The same, with `import modelopt.torch.export` added back to
`_collect_grouped_linears`: fails at the quantize step, with
`ModuleNotFoundError: import of huggingface_hub halted; None in
sys.modules`.
- 0.47.0 with #2671 and this test: fails the same way, at the
`_GATE_UP_PAIRS` import.
- `pre-commit run` with this repository's configuration (ruff 0.15.20,
mypy 2.1.0) passes on the changed file.

Earlier, without the test, in environments that really lack the `[hf]`
extra (modelopt and its required dependencies only): INT8 quantization
of a small model, in one process and in two gloo ranks, fails on 0.47.0
with #2671, and passes on main (then 3788881) and on `release/0.48.0`
with #2671.

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ✅
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
N/A
- Did you get Claude approval on this PR?: N/A

### Additional Information

Found while packaging 0.47.0 for Nixpkgs (NixOS/nixpkgs#577198).
`release/0.48.0` doesn't have `test_import.py` yet, so this belongs with
#2671's cherry-pick, if it's wanted there.

**AI disclosure:** this change, the testing described above and this
description were produced with Claude Code (Claude Opus 5.5).

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Tests**
* Expanded PyTorch import coverage to verify that a small model can be
quantized with calibration when optional Hugging Face modules are
unavailable.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Connor Baker <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
kevalmorabia97 added a commit that referenced this pull request Oct 28, 2026
#2928 #2885 #2908 #2929 #2950 #2972 #2877 #2951 #2816 #3005 #3012 #2971 #3015 #3006 #3026 #2988 #3028 #1860 #3030 #2612 #3033 #2653 #2599 #2655 #2618 #2868 #3032 #3027 #2869 #2984 #2975 #2345 #3020 #2997 (#3072)

## Cherry-picked PRs

- #2817
- #2671
- #2892
- #2876
- #2910
- #2911
- #2919
- #2904
- #2937
- #2928
- #2885
- #2908
- #2929
- #2950
- #2972
- #2877
- #2951
- #2816
- #3005
- #3012
- #2971
- #3015
- #3006
- #3026
- #2988
- #3028
- #1860
- #3030
- #2612
- #3033
- #2653
- #2599
- #2655
- #2618
- #2868
- #3032
- #3027
- #2869
- #2984
- #2975
- #2345
- #3020
- #2997

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Diffusion exports now offer more control over attention-quantizer
metadata and preserve sparse-attention settings in a format compatible
with downstream tooling.
* Model loading better handles select bundled model implementations, and
Docker guidance now covers writable CUDA-extension cache locations.
* **Bug Fixes**
* Improved reliability for model export and checkpoint saving,
quantization across devices, ONNX processing, and calibration.
* Temporary TensorRT and autotuning artifacts now use private
directories by default.
* **Documentation**
* Updated installation guidance, compatibility notes, and links;
corrected typos across guides and examples.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Chad Voegele <[email protected]>
Signed-off-by: Rohan Joshi <[email protected]>
Signed-off-by: LinCanNerd <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
Signed-off-by: weimingc <[email protected]>
Signed-off-by: Noey Yang <[email protected]>
Signed-off-by: Kai Xu <[email protected]>
Signed-off-by: Zhehao Hu <[email protected]>
Signed-off-by: noeyy-mino <[email protected]>
Signed-off-by: joe-nv <[email protected]>
Signed-off-by: yingguo-trt <[email protected]>
Signed-off-by: Shengliang Xu <[email protected]>
Signed-off-by: Chenjie Luo <[email protected]>
Signed-off-by: anmaurya001 <[email protected]>
Signed-off-by: Connor Baker <[email protected]>
Signed-off-by: wiederse <[email protected]>
Signed-off-by: Vu Dinh <[email protected]>
Signed-off-by: Pratik Gandhi <[email protected]>
Signed-off-by: Michael Rusu <[email protected]>
Signed-off-by: Michael-Rusu <[email protected]>
Signed-off-by: namgyu-youn <[email protected]>
Signed-off-by: Sylvester Kaczmarek <[email protected]>
Signed-off-by: Javier de Jesus <[email protected]>
Signed-off-by: javierdejesusda <[email protected]>
Signed-off-by: Zhiyu Cheng <[email protected]>
Signed-off-by: Juhi Mittal <[email protected]>
Signed-off-by: Dmitry Rantovov <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
Co-authored-by: Chad Voegele <[email protected]>
Co-authored-by: LinCanNerd <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Keval Morabia <[email protected]>
Co-authored-by: Wei-Ming Chen <[email protected]>
Co-authored-by: noeyy-mino <[email protected]>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: kaix-nv <[email protected]>
Co-authored-by: Zhehao Hu <[email protected]>
Co-authored-by: joe <[email protected]>
Co-authored-by: yingguo-trt <[email protected]>
Co-authored-by: Shengliang Xu <[email protected]>
Co-authored-by: Chenjie Luo <[email protected]>
Co-authored-by: anmaurya001 <[email protected]>
Co-authored-by: Connor Baker <[email protected]>
Co-authored-by: Jiao Mingyang <[email protected]>
Co-authored-by: Vu Dinh <[email protected]>
Co-authored-by: Pratik Gandhi <[email protected]>
Co-authored-by: Michael R <[email protected]>
Co-authored-by: Michael-Rusu <[email protected]>
Co-authored-by: namgyu-youn <[email protected]>
Co-authored-by: Sylvester Kaczmarek <[email protected]>
Co-authored-by: Javier De Jesus <[email protected]>
Co-authored-by: Zhiyu <[email protected]>
Co-authored-by: Juhi Mittal <[email protected]>
Co-authored-by: Dmitry Rantovov <[email protected]>
Co-authored-by: h-guo18 <[email protected]>
@rohansjoshi rohansjoshi added the cherry-pick-done Added by bot once PR is cherry-picked to the release branch label Oct 28, 2026
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.

4 participants