Skip to content

[OMNIML-6533] Find the models' PTQ modules through the import system instead of listing model types - #3510

Merged
shengliangxu merged 2 commits into
mainfrom
shengliangx/model-ptq-load-on-use
Nov 24, 2026
Merged

shengliangxu merged 2 commits into
mainfrom
shengliangx/model-ptq-load-on-use

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Type of change: Refactor

Problem: The Hugging Face and vLLM quantization plugins import each named model's PTQ module (modelopt/torch/models/<model_type>/modeling_ptq.py, and modeling_ptq_vllm.py from #3368) from a hard-coded list of model types. So the core library names models, and each new model needs an entry in a plugin's list.

Fix: modelopt.torch.models.import_model_modules(name) imports <package>/<name>.py from every model package that has one, in name order, and both plugins call it instead of their lists. It imports the same modules in the same order as the lists did, so every registration stays the same; a new model's module needs no list entry, and the plugins name no model. It finds the modules through the import system (pkgutil.iter_modules, then importlib.util.find_spec), so a zipped or bytecode-only install loads them too, and guards each import on its own, so a module that fails to import loses only its model's wrappers.

Follow-up to #3368, which has merged; this PR now targets main. Its first commit was #3368's third until 2026-11-21, and the second answers the review's question on finding the modules. #3542, stacked on this PR, then imports only the modules of the model being used. It adds 30 source lines (counted with the PR-size command in the repository's CLAUDE.md).

Modules touched

  • modelopt.torch.models: it holds the per-model packages, so the helper that finds their modules (import_model_modules) belongs here.
  • modelopt.torch.quantization: both plugins call that helper instead of naming model types.

Usage

A model's PTQ wrappers go in modelopt/torch/models/<model_type>/modeling_ptq.py (modeling_ptq_vllm.py for vLLM), with no list to update. The HF plugin runs:

from modelopt.torch.models import import_model_modules

import_model_modules("modeling_ptq")  # imports every models/*/modeling_ptq.py, in name order

Testing

The first commit was tested as 2a18aca6203, on #3368's head at the time (5b9ae6972f0), then moved here unchanged (git range-diff showed the same patch) and rebased onto main b735732ef59. On 2026-11-23 it took over #3368's per-model import guard, and a second commit moved the lookup from files on disk to the import system.

Check Result
pre-commit, every hook including mypy and bandit, over main..HEAD clean
What is registered at 2a18aca6203 vs 5b9ae6972f0 (the lists): the quant module registry, CUSTOM_MODEL_PLUGINS, the attention wrappers and the decoder discoverers in the order they are tried, under vLLM 0.22.1 (HF and vLLM plugins) and transformers 5.18 and 5.5.4 identical, in the same order; also with each of the 10 model modules imported first, in a fresh interpreter
tests/unit/torch/quantization/plugins, tests/unit/torch/models and the registration test under transformers 5.18, and the three vLLM test files under vLLM 0.22.1, on CPU, the same two heads the same outcome per test id
Revert check: a lookup that skips some packages the HF registration test fails naming the skipped gpt_oss, and the vLLM test glm5_next
CI at 2a18aca6203, which then targeted main green, every job including the GPU ones: the GPU job 1875 passed, and tests/gpu_vllm under vLLM 0.30.0 218 passed and 8 skipped, as at 5b9ae6972f0
CPU at b36784c7609 vs #3368's head then: the three vLLM test files under vLLM 0.22.1, without the 11 end-to-end engine tests, whose setup never returns without a GPU; and under transformers 5.4.0, tests/unit/torch/quantization/plugins, tests/unit/torch/models, the keep-fused export tests and the registration test; and all of tests/unit/torch/quantization vs main the same outcome per test id: vLLM 47 passed, 42 skipped and the same 12 failed (No CUDA GPUs are available); transformers 680 passed and 34 skipped; tests/unit/torch/quantization 1,984 passed, 1 skipped and 1 failed, as on main, where test_hybrid_linear_attention_cache_round_trips fails the same way for want of a newer transformers
CI at b36784c7609 green, every job that runs on a stacked PR: code quality, the docs build, the CPU unit tests (linux, windows, the 8 multi-version jobs, the minimum-transformers one included, and the torch-only and onnx-only installs) and codecov/project. The GPU, example and regression jobs skip, and their *-pr-required-check jobs fail on purpose, as noted below the table
Install kinds: the modeling_ptq modules the HF plugin loads from a normal tree, a bytecode-only modelopt/torch/models, a zipped modelopt, and a zipped modelopt whose modelopt/torch/models holds only bytecode, file check (4ca3976bd2c) vs the import system (this head) 7, 0, 0 and 0 vs 7, 7, 7 and 7
Lookup cost on NFS, median of 5 fresh processes 34 ms for the import system vs 0.7 ms for the file check, once per plugin import
CPU at 96f34d54685 vs b36784c7609: the same suites, plus the Kimi tests against stand-ins for vLLM's Kimi-K3 modules, which vLLM 0.22.1 lacks the same outcome per test id, plus #3368's two new isolation cases, which pass: vLLM 49 passed, 42 skipped and the same 12 failed; transformers 680 passed and 34 skipped; tests/unit/torch/quantization 1,984 passed, 1 skipped and 1 failed, as before; the Kimi tests 12 passed and 1 skipped
CI at 96f34d54685 green, every job that runs on a stacked PR: code quality, the docs build, the CPU unit tests (linux, windows, the 8 multi-version jobs, the minimum-transformers one included, and the torch-only and onnx-only installs), codecov/project and CodeRabbit, which approved. The GPU, example and regression jobs skip, and their *-pr-required-check jobs fail on purpose, as noted below the table; two cancelled entries are a duplicate run the push also started
CPU at 05a0a87eb50, rebased onto #3368's DeepSeek-V4 fix, vs 96f34d54685: the vLLM test files the same outcome per test id: vLLM 49 passed, 42 skipped and the same 12 failed
CI at 05a0a87eb50 green, every job that runs on a stacked PR: code quality, the docs build, the CPU unit tests (linux, windows, the 8 multi-version jobs, the minimum-transformers one included, and the torch-only and onnx-only installs) and codecov/project. The GPU, example and regression jobs skip, and their *-pr-required-check jobs fail on purpose, as noted below the table; two cancelled entries are a duplicate run the push also started
CPU at a1e285388ea, rebased onto #3368's Kimi-K3 fix and GLM-5.3-Flash check, vs 05a0a87eb50: the vLLM test files, plus stand-ins for vLLM's Kimi-K3 module and GLM-5.3-Flash's native indexer, which vLLM 0.22.1 lacks the same outcome per test id, plus the new Kimi-K3 case, which skips without Kimi-K3: vLLM 49 passed, 43 skipped and the same 12 failed; against the stand-ins, the Kimi-K3 retry case and the GLM-5.3-Flash registry check pass
CI at a1e285388ea green, every job that runs on a stacked PR: code quality, the docs build, the CPU unit tests (linux, windows, the 8 multi-version jobs, the minimum-transformers one included, and the torch-only and onnx-only installs) and codecov/project, and CodeRabbit approved. The GPU, example and regression jobs skip, and their *-pr-required-check jobs fail on purpose, as noted below the table; two cancelled entries are a duplicate run the push also started
CPU at ec4f172d55b, rebased onto #3368's GLM-5.3-Flash test and Kimi-K3 retry fix, vs a1e285388ea: the vLLM test files, plus stand-ins for vLLM's Kimi-K3 module and GLM-5.3-Flash's native indexer, which vLLM 0.22.1 lacks the same outcome per test id, plus the new GLM-5.3-Flash test, which skips without a native indexer: vLLM 49 passed, 44 skipped and the same 12 failed; against the stand-ins, it and the Kimi-K3 retry case pass
CI at ec4f172d55b, while stacked on #3368 green, every job that runs on a stacked PR: code quality, the docs build, the CPU unit tests (linux, windows, the 8 multi-version jobs, the minimum-transformers one included, and the torch-only and onnx-only installs) and codecov/project, and CodeRabbit approved. The GPU, example and regression jobs skip, and their *-pr-required-check jobs fail on purpose, as noted below the table; two cancelled entries are a duplicate run the push also started
CI at this head, rebased by GitHub after #3368 merged, with the same patches (git range-diff) onto main 1e6408b8307 green, every job, the GPU ones included now that this PR targets main: the GPU job 1930 passed and 175 skipped, tests/gpu_vllm under vLLM 0.30.0 222 passed and 8 skipped, as at #3368's merged head, Megatron 480 passed and TRT-LLM 43 passed; the examples, unit tests, docs and codecov/project passed too

Until #3368 merged, this PR targeted #3368's branch, so CI skipped its GPU, example and regression jobs, and their *-pr-required-check jobs failed on purpose.

Before your PR is "Ready for review"

Commits are signed (git commit -s -S).

  • Is this change backward compatible?: ✅ (the same modules, imported in the same order; a module that fails to import now loses only its model's wrappers)
  • 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?: ✅ (the HF registration test now checks, in a fresh interpreter, that importing the plugin imports every models/*/modeling_ptq.py, as the vLLM test already does for every modeling_ptq_vllm.py)
  • Did you update Changelog?: N/A (internal refactor)
  • Did you get Claude approval on this PR?: ❌ not yet (Claude approved [OMNIML-6533] [2/2] Move the vLLM quantization plugins' named-model code into modelopt/torch/models #3368 at f04698ff43e, before these commits)

Additional Information

Follow-up to #3368, followed by #3542. Tracked by OMNIML-6533, for ModelOpt v0.50.0.

Summary by CodeRabbit

  • Documentation
    • Updated guidance to describe automatic discovery and retain the recommendation to keep model package initialization focused on specifications.
  • Tests
    • Updated checks and descriptions to cover discovery of model-specific modules by the plugins.

@copy-pr-bot

copy-pr-bot Bot commented Nov 21, 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.

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

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

No actionable comments were generated in the recent review.

Walkthrough

The models package adds import_model_modules to discover and import model-specific PTQ modules. The Hugging Face and vLLM quantization plugins use it instead of explicit module lists. Documentation and tests describe or check the discovery behavior.

Changes: PTQ Module Discovery

Layer / File(s) Summary
Add the shared module discovery helper
modelopt/torch/models/__init__.py
The models package exports import_model_modules, which visits model-package directories in sorted order and imports matching modules under individual import_plugin guards.
Use discovery in quantization plugins
modelopt/torch/quantization/plugins/huggingface.py, modelopt/torch/quantization/plugins/__init__.py, modelopt/torch/models/README.md, tests/gpu/torch/models/test_modeling_ptq_registration.py, tests/gpu_vllm/torch/quantization/test_vllm_dynamic_modules.py
The Hugging Face and vLLM plugins call the helper instead of listing model-specific modules. Documentation describes discovery, and the registration test checks that discovered modeling_ptq.py modules are loaded.

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

Change: Refactor

Possibly related issues

Merge Risk: Minimal · up to ec4f1

This refactor changes how model-specific quantization modules are discovered and imported, with no intended change to registrations or results. No concrete defect was identified. The GPU, example and regression suites still need to run once the PR is retargeted to main, as is normal for a stacked PR.

Security architecture risk: Low · up to 96f34

Normal loading keeps the same modules in the same order. The risk is limited to a startup failure: initialization can now finish without model-specific support, and a generic fallback may take precedence even if that support is loaded later.

Retained concerns

  • Low · reliability · inferred: When a model-specific Hugging Face import fails before registering its decoder discoverer, the head still installs the generic discoverer. If the specialized import later succeeds in the same process, its entry is appended; the generic discoverer can continue to win for models that match both. At base, the same import failure prevented the generic discoverer from being installed by that initialization attempt.
Security review details

Trust Boundaries and Controls

  • observed — The production plugin calls pass literal module names, and discovery searches the models package's import path. Imported wrappers execute with the library process's authority; the exception guard controls failure handling, not execution privileges.
Pre-merge checks: Passed 5

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.
Title check Passed The title names the main change: model PTQ modules are now located through the import system instead of a hard-coded list of model types. The raw summary confirms this in the HF and vLLM plugins, the …
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Security Anti-Patterns Passed The "Security anti-patterns" check passes. I compared the PR head (af702a4) with main (1e6408b). The diff touches 6 files: modelopt/torch/models/README.md, modelopt/torch/models/init.py, modelopt/…
Full details: Title check

Explanation

The title names the main change: model PTQ modules are now located through the import system instead of a hard-coded list of model types. The raw summary confirms this in the HF and vLLM plugins, the new import_model_modules helper, and the test updates. The ticket prefix is harmless and the title is specific and concise.

Full details: Security Anti-Patterns

Explanation

The "Security anti-patterns" check passes. I compared the PR head (af702a4) with main (1e6408b). The diff touches 6 files: modelopt/torch/models/README.md, modelopt/torch/models/init.py, modelopt/torch/quantization/plugins/init.py, modelopt/torch/quantization/plugins/huggingface.py, and two test files. It adds no pyproject.toml or requirements.txt changes. I searched every added line for the patterns in the check: torch.load/weights_only=False, numpy.load/allow_pickle, trust_remote_code, eval(/exec(, # nosec, and new dependencies. None matched. The only new dynamic-import code is import_model_modules() in modelopt/torch/models/init.py. It uses importlib.import_module on a name built from the package directory listing (pkgutil.iter_modules) plus a hard-coded module_name constant ("modeling_ptq" or "modeling_ptq_vllm"). No external input reaches it, and it does not use eval or exec. The test change adds an assertion that runs in a subprocess, but it contains no eval, exec, or untrusted input. SECURITY.md was checked for the applicable rules. None of the rules is violated by the added lines.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • 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 a1e2853 and ec4f172.

Files selected for processing: 1

  • tests/gpu_vllm/torch/quantization/test_vllm_dynamic_modules.py
Files skipped from review as they are similar to previous changes: 1

  • tests/gpu_vllm/torch/quantization/test_vllm_dynamic_modules.py

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

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.58%. Comparing base (1e6408b) to head (af702a4).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3510      +/-   ##
==========================================
+ Coverage   73.41%   81.58%   +8.17%     
==========================================
  Files         730      730              
  Lines       82224    82231       +7     
==========================================
+ Hits        60367    67092    +6725     
+ Misses      21857    15139    -6718     
Flag Coverage Δ
examples-diffusers 19.82% <92.85%> (+<0.01%) ⬆️
examples-gpt-oss 13.54% <92.85%> (-0.04%) ⬇️
examples-hf_ptq 24.43% <92.85%> (-0.91%) ⬇️
examples-llm_distill 13.61% <92.85%> (+<0.01%) ⬆️
examples-llm_eval 17.46% <92.85%> (-0.06%) ⬇️
examples-llm_qat 17.40% <92.85%> (-0.08%) ⬇️
examples-llm_sparsity 16.82% <92.85%> (+<0.01%) ⬆️
examples-megatron_bridge 25.96% <100.00%> (-0.22%) ⬇️
examples-specdec_bench 13.33% <92.85%> (+0.01%) ⬆️
examples-speculative_decoding 17.71% <92.85%> (-0.05%) ⬇️
examples-torch_onnx 20.94% <92.85%> (-0.01%) ⬇️
examples-torch_trt 15.23% <92.85%> (-0.05%) ⬇️
examples-vllm_serve 17.69% <100.00%> (+<0.01%) ⬆️
gpu 59.72% <100.00%> (+37.87%) ⬆️
regression 15.01% <92.85%> (-0.05%) ⬇️
unit 64.74% <92.85%> (+<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.

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.2
Preview removed because the pull request was closed.
2026-11-24 01:40 UTC

@shengliangxu
shengliangxu force-pushed the shengliangx/model-ptq-load-on-use branch from b24e4d3 to b36784c Compare November 23, 2026 19:04
@shengliangxu shengliangxu changed the title [OMNIML-6533] Import a model's PTQ modules by its model type when the model is used [OMNIML-6533] Find the models' PTQ modules by file name instead of listing model types Nov 23, 2026
@shengliangxu
shengliangxu marked this pull request as ready for review November 23, 2026 19:16
@shengliangxu
shengliangxu requested review from a team as code owners November 23, 2026 19:16

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

Nudge: PTQ discovery now requires source files on disk, a compatibility constraint the PR description does not address.

Needs action:

  • Explain in the PR description why import_model_modules uses filesystem checks over importlib.resources.files (used in opt/config_loader.py) or pkgutil with find_spec, and clarify whether archive-backed or bytecode-only installs must retain PTQ registration.

No action needed:

  • Both plugins retain their registration order for the listed modules. The HF subprocess test adds coverage for missed discovery without dropping precedence checks; the vLLM assertions are unchanged.
  • Reviewed the diff against shengliangx/vllm-plugin-named-models; the exact base SHA and live CI were unavailable, and I did not run tests.

@shengliangxu
shengliangxu force-pushed the shengliangx/model-ptq-load-on-use branch from b36784c to 96f34d5 Compare November 23, 2026 20:02
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

On the review's question about finding the modules by file: changed rather than only explained, in 96f34d5. import_model_modules now lists the packages with pkgutil.iter_modules and finds each module with importlib.util.find_spec, so zipped and bytecode-only installs keep their registrations, as the explicit lists it replaces did.

Install modeling_ptq modules the HF plugin loads, file check Import system
normal tree 7 of 7 7 of 7
bytecode-only modelopt/torch/models 0 7
modelopt imported from a zip 0 7

The lookup takes about 34 ms on NFS, once per plugin import, against under 1 ms for the file check (median of five fresh processes). The first commit also guards each module's import on its own now, carrying #3368's fix for the vLLM list through to both plugins. #3542 keeps this lookup for a model's own types.

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

Request changes: PTQ discovery silently skips model-specific wrappers when the model packages are shipped in a bytecode-only ZIP.

Needs action:

  • 💬 The import-system switch fixes source ZIPs and unpacked bytecode separately — preserve registration in import_model_modules when a ZIP contains only bytecode, and add a regression test for that layout.

No action needed:

  • The HF subprocess test adds a discovery check before direct imports without weakening the registration-order assertions. The vLLM assertions are unchanged.
  • Reviewed against shengliangx/vllm-plugin-named-models; exact base SHA and live CI were unavailable, and I did not run tests.

found through the import system rather than as files on disk, so a zipped or bytecode-only
install finds them too.
"""
for package in sorted(name for _, name, is_pkg in pkgutil.iter_modules(__path__) if is_pkg):

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

On supported CPython 3.11, pkgutil's ZIP enumerator recognizes name/__init__.py as a package but not name/__init__.pyc. zipimport can import the latter, so the old explicit imports worked in a bytecode-only ZIP, but this loop never reaches find_spec for those packages. Both plugins silently lose wrappers; for example, GptOssExperts no longer gets its dedicated HF registration. Could importlib.resources.files() enumerate candidate directories while find_spec still checks importability? Please cover the combined layout by asserting registration before any direct wrapper imports.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I checked this, and the enumerator does recognize bytecode-only packages: pkgutil.iter_zipimport_modules tests fn[1].startswith('__init__.py'), which also matches __init__.pyc, on the 3.11 branch (Lib/pkgutil.py line 385) as on 3.10, 3.12, 3.13 and 3.14. Empirically, with modelopt imported from a zip whose modelopt/torch/models holds only .pyc files (117 of them, no .py), the HF plugin loads all 7 modeling_ptq modules with this lookup under Python 3.13, against 0 with the earlier file check.

So I'm leaving the enumeration as is. A regression test for this layout would have to byte-compile and zip modelopt in CI, which the one-off check above covers.

@shengliangxu
shengliangxu force-pushed the shengliangx/model-ptq-load-on-use branch from 96f34d5 to 05a0a87 Compare November 23, 2026 21:14

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

LGTM: the prior packaging concerns are resolved; the strengthened Hugging Face registration test needs human sign-off.

Needs action:

  • Sign off on the edit to test_modeling_ptq_registration.py: it checks discovery before direct imports without weakening the registry or precedence assertions.

No action needed:

  • ✔️ Discovery no longer requires source files on disk. The earlier bytecode-only ZIP finding was incorrect: CPython’s ZIP enumerator matches __init__.pyc via startswith('__init__.py'). The author reports all seven HF wrappers load in that layout, so a dedicated CI regression is optional.
  • Both plugins retain the base’s module order. The vLLM test assertions are unchanged.
  • Reviewed the supplied diff against shengliangx/vllm-plugin-named-models. The exact base SHA and live CI were unavailable; I did not run tests.

@shengliangxu
shengliangxu force-pushed the shengliangx/model-ptq-load-on-use branch from 05a0a87 to a1e2853 Compare November 23, 2026 22:05
@shengliangxu
shengliangxu force-pushed the shengliangx/model-ptq-load-on-use branch from a1e2853 to ec4f172 Compare November 23, 2026 22:45
Base automatically changed from shengliangx/vllm-plugin-named-models to main November 24, 2026 00:03
The HF and vLLM quantization plugins imported each model's modeling_ptq / modeling_ptq_vllm
from a hard-coded list of model types, so the core library named models and every new model
needed a list entry. modelopt.torch.models.import_model_modules(name) imports
<model_type>/<name>.py from every model package that has one, in name order: the same modules
in the same order as the lists, so the registrations are unchanged. Each import is guarded on its
own, as the vLLM list's were, so a module that fails to import leaves the others registered; in
the HF plugin it no longer skips the rest of huggingface.py either. The HF registration test now
checks that every modeling_ptq is imported, as the vLLM test already does for modeling_ptq_vllm.

Signed-off-by: Shengliang Xu <[email protected]>
…on disk

import_model_modules listed modelopt/torch/models and checked for <package>/<name>.py on disk, so
a zipped or bytecode-only install loaded no model's PTQ wrappers, which the explicit lists it
replaced still did. It now lists the packages with pkgutil.iter_modules and checks for each
module with importlib.util.find_spec, which work for any of these installs. The HF plugin then
loads all 7 modeling_ptq modules from a normal tree, a bytecode-only modelopt/torch/models and a
zipped modelopt alike, against 7, 0 and 0 before. The lookup takes about 34 ms on NFS, once per
plugin import, against under 1 ms for the file check.

Signed-off-by: Shengliang Xu <[email protected]>
shengliangxu added a commit that referenced this pull request Nov 24, 2026
…ode into modelopt/torch/models (#3368)

### What does this PR do?

Type of change: Refactor

Part 2 of 2 of a stack that leaves the Hugging Face and vLLM
quantization plugins with only generic support. [1/2] #3367 has merged,
and this PR now targets main. The vLLM plugins held the wrappers for
three named models next to the generic vLLM support. They move to their
model packages in `modelopt/torch/models`, as `modeling_ptq_vllm.py`
next to the transformers `modeling_ptq.py`. No behavior change:
registrations and quantized results are the same.

- **DeepSeek-V4** (`models/deepseek_v4/modeling_ptq_vllm.py`): the
indexer wrapper, from `vllm_indexer.py`, and DeepSeek-V4's Mega-MoE
registration, from `vllm_mega_moe.py`.
- **GLM-5.3-Flash** (`models/glm5_next/modeling_ptq_vllm.py`, a new
package): the k-pool indexer with its K-cache writers and DeepGEMM
scorer, from `vllm_indexer.py`. Like `kimi_k3`, `glm5_next` has no
`specs.py`: it holds only vLLM modeling, and a spec would make claims
about the transformers model that nothing here checks.
- **Kimi-K3** (`models/kimi_k3/modeling_ptq_vllm.py`): the MLP
fake-quant preparation, from `vllm.py`, and Kimi-K3's Mega-MoE
registration, from `vllm_mega_moe.py`. The preparation used to run
inside the vLLM plugin's attention-preparation callback; it is now a
`CUSTOM_MODEL_PLUGINS` callback of its own. The two touch disjoint
modules, so their order does not matter. `_VLLMParallelLinear` reads a
generic marker, `_fake_quant_supported_by_model`, instead of a
Kimi-named one.
- The generic indexer base class and its FP8 and scorer helpers, the
Mega-MoE wrapper and the layer scope stay in the plugins.
- `plugins/__init__.py` imports every `modeling_ptq_vllm` from an
explicit list after the generic vLLM modules, inside the
`import_plugin("vllm")` block, each under its own guard, so a model
whose module fails to import loses only its own wrappers. DeepSeek-V4's
module registers its indexer before its Mega-MoE import, which main kept
in a later plugin module. DeepSeek-V4's and Kimi-K3's optional Mega-MoE
imports only warn on an unexpected error, so both modules always
complete: DeepSeek-V4's stays importable with its indexer registered,
and Kimi-K3's MLP preparation is registered even if vLLM's Kimi module
only imports later. The follow-up #3510 replaces this list, and the HF
plugin's, by finding the modules through the import system; #3542 then
imports only a model's own, when the model is used.
- GLM reads the scorer-kwargs registry through `vllm_indexer`, so it and
the indexer base class read one binding even when the registry is
rebound, as tests do.

The moved code is verbatim apart from the callback, the marker and the
registry read. Tests in `tests/gpu_vllm` patch the moved names in their
new modules.

<details><summary>Moved names (old module → new module)</summary>

| Name | From `modelopt/torch/quantization/plugins/` | To
`modelopt/torch/models/` |
|---|---|---|
| `_QuantVLLMDeepseekV4Indexer` | `vllm_indexer.py` |
`deepseek_v4/modeling_ptq_vllm.py` |
| `_QuantVLLMGlm5NextIndexer`, `_DEEP_GEMM_SCORERS`,
`_GLM5NEXT_INDEXER_OP`, `_GLM5NEXT_QUERY_KERNEL`,
`_KPOOL_CACHE_WRITERS`, `_bind`, `_call_deep_gemm_scorer`,
`_glm5next_indexers`, `_import_glm5next_indexer`,
`_kpool_decode_written`, `_kpool_prefill_written`, `_run_scorer`,
`_scorer_deep_gemm`, `_signature`, `_write_k_cache` | `vllm_indexer.py`
| `glm5_next/modeling_ptq_vllm.py` |
| `_KimiGemmRsArFakeQuantGuard`, `_KimiGemmRsFakeQuantGuard`,
`_kimi_down_proj_has_enabled_quantizers`,
`_kimi_mlp_bf16_linear_supports_fake_quant`,
`_prepare_kimi_mlp_fake_quant` | `vllm.py` |
`kimi_k3/modeling_ptq_vllm.py` |
| `prepare_kimi_mlps_on_the_fly` (new callback) | |
`kimi_k3/modeling_ptq_vllm.py` |

</details>

### The stack

[1/2] has merged. Each PR builds and carries its own tests.

| PR | What | Added source lines |
|---|---|---|
| [1/2] #3367 (merged) | Hugging Face plugin: T5's KV-cache attention
wrapper, the Nemotron-H check | 73 (31 moved, 14 license header) |
| [2/2] (this PR) | vLLM plugins: the DeepSeek-V4, GLM-5.3-Flash and
Kimi-K3 wrappers | 572 (about 470 moved, 56 license headers) |
| Follow-up #3510, stacked on this PR | Both plugins: find the models'
PTQ modules through the import system instead of listing model types |
30 |
| Follow-up #3542, stacked on #3510 | Both plugins: import a model's PTQ
modules by its model type when the model is used | 109 (14 license
headers) |

Lines are counted with the PR-size command in the repository's
`CLAUDE.md`: added Python source lines, without blank lines, tests, docs
and config.

Until 2026-11-21 this PR also carried the three commits now in #3510 and
#3542. They moved there unchanged, so the move is again the same two
patches as at `f04698ff43e`, which Claude approved and the GB200 runs
below tested. On 2026-11-23 two commits answered cjluo-nv's review:
`add71b82993` guards each model module's import and registers
DeepSeek-V4's indexer first, and `bf970e5541d` tests Kimi-K3's MLP
preparation through conversion. Its follow-up reviews brought
`f2a837a6c21`, which keeps DeepSeek-V4's module importable when its
Mega-MoE import fails; `3aff43a3ef0`, which registers Kimi-K3's MLP
preparation in that case too; `ba58bf16406` and `51f5f7388ea`, which
check GLM-5.3-Flash's native indexer registration independently of the
module's own lookup; and `c26d765667a`, which hands vLLM's Kimi module
back in the Kimi-K3 retry test instead of re-importing it into a
circular import inside vLLM.

**Why this PR keeps the eager import list.** It changes where the
named-model vLLM wrappers live, not when they are registered: the plugin
still imports all three when modelopt is imported, as main does, so the
registrations stay identical to main's (checked below) and the move can
be reviewed as a relocation. Importing a model's modules on demand, by
its model type, as `models/hf.py` already does for its loading and
calibration hooks, changes behavior in ways that need their own review
and tests, and each came up while that change was part of this PR: a
decoder-layer lookup before conversion, which loading with FSDP2 does,
must import the model's module first; a module quantized without its
model's config no longer gets its wrappers unless its module is
imported; and a model type that holds another type's classes needs a
package that imports the shared one. #3510 first replaces the list with
discovery through the import system, still importing every module, and
#3542 then imports a model's own modules when it is used.

### Usage

N/A: no new or changed API.

### Testing

| Check | Result |
|---|---|
| pre-commit, every hook including mypy and bandit, over `main..HEAD` |
clean |
| What `import modelopt.torch.quantization` registers (the quant module
registry and `CUSTOM_MODEL_PLUGINS`), vLLM 0.22.1 on CPU, [1/2] vs this
PR | identical (DeepSeek-V4's indexer and Mega-MoE entries), plus the
new Kimi-K3 callback; importing any one model module first gives the
same result |
| CPU,
`tests/gpu_vllm/torch/quantization/test_vllm_{indexer_quant,dynamic_modules,mega_moe}.py`,
vLLM 0.22.1 | the same outcome per test id as on [1/2], plus the new
test, which passes: 45 passed, 47 skipped, and 14 failed and 6 errors on
both for lack of a GPU (no CUDA device, a missing TE/cuBLAS symbol). The
passing tests run the moved DeepSeek-V4 indexer's q/k re-quantization
and its refusals, and GLM's query, K-cache and scorer-kwargs paths |
| Revert checks | dropping `glm5_next` from the import list fails
`test_vllm_plugin_imports_every_model_package`, naming it; having GLM
read the scorer-kwargs registry by name fails
`test_registered_quantizers_turn_their_config_into_scorer_kwargs`; one
guard for the whole list fails the Kimi-K3 case of
`test_failed_vllm_model_import_keeps_other_registrations`, and
DeepSeek-V4's old import order its DeepSeek-V4 case; dropping Kimi-K3's
callback registration fails
`test_kimi_gemm_rs_guard_tracks_converted_down_projection` (on CPU,
against stand-ins for vLLM's Kimi-K3 modules); a DeepSeek-V4 module that
aborts on a Mega-MoE error fails that case's later direct import with
`already registered!`; a Kimi-K3 module that skips its MLP preparation
after a failed startup import fails the Kimi-K3 retry case;
`test_vllm_plugin_registers_native_glm5next_indexer` fails with
GLM-5.3-Flash's registration removed, its key renamed or the module's
lookup returning `None` (the last two checks against stand-ins) |
| CPU, `tests/unit/torch/quantization/plugins`,
`tests/unit/torch/models` and
`tests/gpu/torch/models/test_modeling_ptq_registration.py`, transformers
5.9 | 752 passed, 16 skipped, as on [1/2] |
| GPU on GB200, [1/2] vs this PR: all of `tests/gpu_vllm` at 1 and 2
GPUs under a vLLM 0.29.1rc1 nightly, plus the touched test files under
vLLM 0.28.0 and a GLM-5.3-Flash build | no test changes outcome, apart
from 3 timeout flips outside the moved code; details below |
| CI at `5b9ae6972f0`, the same two patches on an earlier main: every
job including the GPU ones; on CI's vLLM 0.30.0 with 1 GPU,
`tests/gpu_vllm` at [1/2]'s head vs that one | green; 217 vs 218 passed,
8 skipped on both: per test id, the only change is the new test, which
passes |
| CPU at `bca69f2a7e9` vs main `b735732ef59`: the three vLLM test files
under vLLM 0.22.1, without the 11 end-to-end engine tests, whose setup
never returns without a GPU; and under transformers 5.4.0,
`tests/unit/torch/quantization/plugins`, `tests/unit/torch/models`, the
keep-fused export tests and the registration test | the same outcome per
test id, plus the new test, which passes: vLLM 47 vs 46 passed, 42
skipped and the same 12 failed on both (`No CUDA GPUs are available`);
transformers 680 passed and 34 skipped on both |
| CI at `bca69f2a7e9`, on main `b735732ef59` | green, every job
including the GPU ones. `tests/gpu_vllm` under vLLM 0.30.0 gives 218
passed and 8 skipped, as at `5b9ae6972f0`, and the GPU job 1930 passed
and 175 skipped. Per test id against `d9c2c6328d0`, the head before
#3510's commits moved out, no shared test changes outcome; the only
other differences are the two tests #3510 took along, back to the
versions they had replaced, which pass, and main's 20 new tests |
| CPU at `bf970e5541d` vs `bca69f2a7e9`: the same suites, plus the Kimi
tests against stand-ins for vLLM's Kimi-K3 modules, which vLLM 0.22.1
lacks | the same outcome per test id, plus the two new isolation cases,
which pass: vLLM 49 passed, 42 skipped and the same 12 failed;
transformers 680 passed and 34 skipped; the Kimi tests 12 passed and 1
skipped (the legacy GEMM-RS test, which the stand-ins do not model) |
| CI at `bf970e5541d` | the GPU jobs green: the GPU job 1930 passed and
175 skipped, as at `bca69f2a7e9`; `tests/gpu_vllm` under vLLM 0.30.0 220
passed and 8 skipped, the 218 before plus the two new isolation cases,
with the Kimi test through `mtq.replace_quant_module` passing against
the real Kimi-K3 classes; Megatron 480 passed and TRT-LLM 43 passed.
Unit tests, code quality, the docs and codecov are green. Two example
jobs failed on pytest timeouts that hit other PRs' runs the same day:
`test_llama_distill` (over 300 s), and in `hf_ptq` `test_ptq_t5[fp8...]`
(over 300 s) and `test_qwen_vl[fp8]` (over 420 s) |
| CI at `f2a837a6c21` | the GPU jobs green: `tests/gpu_vllm` 220 passed
and 8 skipped, the DeepSeek-V4 re-import case passing against vLLM
0.30.0's real classes; `hf_ptq`'s `test_qwen_vl[fp8]` timed out again
(over 420 s) |
| CI at `ba58bf16406` | `tests/gpu_vllm` 220 passed and 1 failed: the
new Kimi-K3 retry case, whose re-import of vLLM's Kimi module hit a
circular import inside vLLM; `c26d765667a` fixes the test |
| CPU at this head vs `bf970e5541d`: the vLLM test files, plus stand-ins
for vLLM's Kimi-K3 module and GLM-5.3-Flash's native indexer, which vLLM
0.22.1 lacks | the same outcome per test id, plus the new Kimi-K3 retry
case and GLM-5.3-Flash test, which skip without them: vLLM 49 passed, 44
skipped and the same 12 failed; against the stand-ins, both pass |
| CI at this head | `tests/gpu_vllm` under vLLM 0.30.0: 222 passed and 8
skipped, the 220 before plus two that ran and passed against vLLM's real
classes: the Kimi-K3 retry case of
`test_failed_vllm_model_import_keeps_other_registrations`, and
`test_vllm_plugin_registers_native_glm5next_indexer`, which found
GLM-5.3-Flash's native indexer and checked its wrapper and config key.
Every other job passed too: the GPU job 1930 passed and 175 skipped, as
at `bca69f2a7e9`, the TRT-LLM and Megatron GPU jobs, the examples
including `hf_ptq`, the unit tests and codecov/project |

The earlier CPU rows and the GB200 runs predate the rebases onto main
since; `git range-diff` shows both patches unchanged by each.

**GPU runs** on GB200, [1/2] (`b85e4b6fa8e`) vs this PR (`f04698ff43e`),
compared per test id. This cluster has no build of CI's vLLM 0.30.0, so
they use three builds that between them contain every vLLM model path
the moved code handles:

| vLLM build | GPUs | Tests | [1/2] | This PR | Outcome changes |
|---|---|---|---|---|---|
| 0.29.1rc1 nightly | 1 | all of `tests/gpu_vllm` | 210 passed, 6
skipped, 6 failed, 3 errors | 211 passed, 6 skipped, 6 failed, 3 errors
| none besides the new test |
| 0.29.1rc1 nightly | 2 | all of `tests/gpu_vllm` | 212 passed, 4
skipped, 6 failed, 3 errors | 214 passed, 4 skipped, 5 failed, 3 errors
| besides the new test, 3 tests outside the moved code that hit the 60 s
per-test timeout: two only on [1/2], one only here |
| 0.28.0 | 1 | the three touched test files | 101 passed, 9 skipped, 1
error | 102 passed, 9 skipped, 1 error | none besides the new test |
| GLM-5.3-Flash build | 1 | the three touched test files | 100 passed, 9
skipped, 1 failed, 1 error | 101 passed, 9 skipped, 1 failed, 1 error |
none besides the new test |

- The failures and errors hit the same tests with the same error on both
sides, and these builds are not the vLLM 0.30.0 that CI uses. The
errors: 60 s test timeouts and vLLM engine-startup timeouts on the
nightly; vLLM rejecting DeepSeek-V4's fp8_ds_mla KV-cache layout with
the default KV-cache dtype on 0.28.0 and the GLM build; on the nightly,
its Kimi-K3 GEMM-RS-AR path calling an `apply` method that ModelOpt's
guard lacks; and on the GLM build, its end-to-end indexer test, whose
indexer the ModelOpt plugins don't support.
- What the runs cover: DeepSeek-V4's 9 tests ran in every build, with
none skipped. GLM-5.3-Flash's tests ran in all three builds, and the
nightly and the GLM build each carry one of its two module layouts.
Kimi-K3's ran in all three: 0.28.0 takes its legacy GEMM-RS branch, the
other two the newer one. In every build the DeepGEMM scorer-numerics
test and the `MLAAttention` test skip, since no build has what they
need.
- The new `test_vllm_plugin_imports_every_model_package` passed in all
four runs.
- CI's GPU jobs, which skip while a PR targets another PR's branch, ran
once this PR targeted main. On CI's runner the moved code's tests all
pass except 5 that skip on [1/2]'s head too: Kimi-K3's legacy GEMM-RS
test, a path vLLM 0.30.0 no longer takes; the 3 end-to-end indexer
tests, which need an SM90 or SM100 GPU (CI's runner is an RTX PRO 6000);
and the DeepGEMM scorer-numerics test.

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

Commits are signed (`git commit -s -S`).

- Is this change backward compatible?: ✅ (every moved name is private;
code that imported one from a plugin module now imports it from its
model package)
- 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?: ✅
(`test_vllm_plugin_imports_every_model_package` in
`tests/gpu_vllm/torch/quantization/test_vllm_dynamic_modules.py`:
importing modelopt in a fresh interpreter imports every
`models/*/modeling_ptq_vllm.py`, where `import_plugin` would otherwise
hide a failed import;
`test_failed_vllm_model_import_keeps_other_registrations`: a model
module that fails to import, GLM's or DeepSeek-V4's Mega-MoE one, leaves
Kimi-K3's callback and DeepSeek-V4's indexer registered, DeepSeek-V4's
module importable, and Kimi-K3's MLPs prepared once vLLM's Kimi module
imports; `test_vllm_plugin_registers_native_glm5next_indexer` checks
GLM-5.3-Flash's native indexer and its config key wherever the vLLM
build has a supported layout)
- Did you update Changelog?: N/A (internal refactor)
- Did you get Claude approval on this PR?: ❌ not yet for this head:
Claude approved the move at `f04698ff43e`, before the review-fix commits

### Additional Information

Tracked by OMNIML-6533, for ModelOpt v0.50.0. Follow-ups: #3510, then
#3542.


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

## Summary by CodeRabbit

* **Documentation**
* Clarified model-type-based loading for Transformers and vLLM, and
documented model package naming and legacy Falcon types.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Shengliang Xu <[email protected]>
@shengliangxu
shengliangxu force-pushed the shengliangx/model-ptq-load-on-use branch from ec4f172 to af702a4 Compare November 24, 2026 00:03
@shengliangxu shengliangxu changed the title [OMNIML-6533] Find the models' PTQ modules by file name instead of listing model types [OMNIML-6533] Find the models' PTQ modules through the import system instead of listing model types Nov 24, 2026

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

Approve: import-system discovery resolves the packaging concerns and preserves registration order, and the signed-off HF test adds coverage without weakening existing assertions.

No action needed.

Complex PR: 2 existing test files modified or removed. Looping in a human for approval.

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

Automatic approval delegated by weimingc (mode: approve).

Pensieve review using weimingc's profile (revision 1).

Review verdict: approve.
GitHub publication: APPROVED.

Approve because import-system discovery resolves the packaging concerns and preserves registration order for both plugins during normal initialization.

  • ✔️ The discovery fix addresses 6028020054. The author’s reply 4672112945 explains why bytecode-only ZIP packages are discovered, closing 4671953696.
  • The signed-off HF test checks discovery before direct wrapper imports and preserves the existing assertions. The vLLM test edit updates only its docstring. shengliangx requested review on behalf of U05R5LDGRNG. The review instructions supplied the human sign-off.
  • Baseline commit 1e6408b830716ec738d07a4398deaba4448f9d36. Base AGENTS.md and CONTRIBUTING.md were unavailable. Duplicate checking covered the supplied history. Tests were not run, and reported CI results were not independently verified.

No action needed.

Review baseline: https://github.com/NVIDIA/Model-Optimizer/blob/1e6408b830716ec738d07a4398deaba4448f9d36/.agents/review-guidelines/code-review.md

Review run: 312fddbb95c14d3c8664c94ae9319192

@shengliangxu
shengliangxu merged commit 7db3ef5 into main Nov 24, 2026
54 checks passed
@shengliangxu
shengliangxu deleted the shengliangx/model-ptq-load-on-use branch November 24, 2026 01:40
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.

3 participants