Skip to content

[OMNIML-6533] [1/2] Move the HF quantization plugin's remaining named-model code into modelopt/torch/models - #3367

Merged
shengliangxu merged 2 commits into
mainfrom
shengliangx/hf-plugin-named-models
Nov 12, 2026
Merged

shengliangxu merged 2 commits into
mainfrom
shengliangx/hf-plugin-named-models

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Type of change: Refactor

Part 1 of 2 of a stack that leaves the Hugging Face and vLLM quantization plugins with only generic support. Their remaining model-specific code moves to its model package in modelopt/torch/models, as earlier moves did (#2576-#2580, #3067). This part covers the Hugging Face plugin; [2/2] #3368, stacked on it, covers vLLM. No behavior change: registrations, dispatch order and quantized results are the same.

  • T5: _T5QuantAttention moves verbatim, with its T5Attention import, from quantization/plugins/huggingface.py to models/t5/modeling_ptq.py. register_hf_attentions_on_the_fly now tries the wrappers in an ordered list, _QUANT_ATTENTION_WRAPPERS, which starts as [_QuantAttention] and to which T5's module appends its wrapper. The first match wins, and the AST-based fallback still comes last. So T5Attention and its subclasses keep _T5QuantAttention where T5 bypasses transformers' attention interface (before 5.15), and get _QuantAttention from 5.15 on. A static registration would not do: the registry matches a subclass only when it shares forward, and it would pre-empt _QuantAttention on 5.15+. Nor would a CUSTOM_MODEL_PLUGINS callback: that is a set, run in no fixed order.
  • Nemotron-H: is_homogeneous_hf_model no longer special-cases it. The decoder-layer registry's first-match order already gives Nemotron-H's own discoverer precedence, and for a native Nemotron-H both discoverers return the same model.model.layers (checked on transformers 5.5, 5.9 and 5.18), so get_decoder_layers is unchanged in either order.
  • The explicit modeling_ptq import list in huggingface.py stays the registration point and gains t5. models/README.md describes the attention-wrapper route.

The stack

Merge in order: [2/2] is based on this PR's branch. Each PR builds and carries its own tests.

PR What Added source lines
[1/2] (this PR) Hugging Face plugin: T5's KV-cache attention wrapper, the Nemotron-H check 73 (31 moved, 14 license header)
[2/2] #3368 vLLM plugins: the DeepSeek-V4, GLM-5.3-Flash and Kimi-K3 wrappers 556 (about 470 moved, 56 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.

Usage

N/A: no new or changed API.

Testing

Check Result
pre-commit, every hook including mypy and bandit, over main..HEAD clean
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
Same, transformers 5.5.4 (the CI minimum) and 5.18 5.5.4: 625 passed, 20 skipped, 4 failed, 1 error. 5.18: 767 passed, 4 failed, 1 error. The same ids fail on the base: diffusers tests (no ONNX in those environments) and a timeout in test_kv_cache_auto_quant_distributed
CPU, tests/unit/torch/quantization and tests/unit/torch/export, transformers 5.18 2387 passed, 3 skipped, 17 failed, 1 error; the same ids fail on the base, for the same reasons
The moved T5 path, with T5's append to _QUANT_ATTENTION_WRAPPERS removed test_kv_quant_hf[get_tiny_t5-None] fails on transformers 5.9 and 5.5.4 (the AST-based fallback then wraps T5's attention and breaks it), so the existing test covers the move
The registration test, with T5's append removed or with T5's wrapper inserted first its new asserts fail for each of the 9 modules it imports first
Nemotron-H on transformers 5.5.4, 5.9 and 5.18 its layers are all NemotronHBlock, both discoverers return the same model.model.layers, and get_decoder_layers is unchanged
GPU tests at 1 GPU (CI's PR jobs: gpu, gpu_megatron, gpu_trtllm, gpu_vllm, examples, regression) all green at this head
2 GPUs (GB200), the 16 tests/gpu files that use need_2_gpus (CI runs that width only on main), main vs this PR 168 passed and 9 skipped on both, and no test id's outcome differs. The skips are GPU-count and environment conditions, the same on both

The CPU runs above predate the rebase onto current main, whose 5 new commits don't touch the moved code; git range-diff shows the patches unchanged, and pre-commit ran again at this tip.

Before your PR is "Ready for review"

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

  • Is this change backward compatible?: ✅ (_T5QuantAttention is private; it now lives in modelopt.torch.models.t5.modeling_ptq)
  • 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?: ✅ (asserts in tests/gpu/torch/models/test_modeling_ptq_registration.py that T5's wrapper is listed once, after _QuantAttention; the existing test_kv_quant_hf[get_tiny_t5-None] covers the moved wrapper)
  • Did you update Changelog?: N/A (internal refactor)
  • Did you get Claude approval on this PR?: ✅ (at e0e71ad)

Additional Information

Tracked by OMNIML-6533, for ModelOpt v0.50.0.

Summary by CodeRabbit

  • New Features
    • Added post-training quantization support for T5 attention, including quantization of query, key, and value tensors.
  • Bug Fixes
    • Nemotron-H models can now be recognized through decoder-layer homogeneity checks.
  • Documentation
    • Clarified how to configure key-value cache quantization for attention layers outside the standard Transformers interface.

@copy-pr-bot

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

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The Hugging Face quantization plugin now supports ordered, model-specific attention wrappers. T5 adds a wrapper that quantizes attention operands. Nemotron-H proceeds through homogeneous decoder-layer discovery.

Changes: T5 attention quantization

Layer / File(s) Summary
Ordered attention wrapper registration
modelopt/torch/quantization/plugins/huggingface.py, modelopt/torch/models/README.md
The plugin tries _QUANT_ATTENTION_WRAPPERS in order and uses the AST-based fallback when no wrapper matches. The modeling instructions document this order.
T5 wrapper and registration test
modelopt/torch/models/t5/modeling_ptq.py, tests/gpu/torch/models/test_modeling_ptq_registration.py
_T5QuantAttention quantizes query and transposed key operands during the first matrix multiplication, then the value operand during the second. The test checks that the wrapper appears once and follows _QuantAttention.

Nemotron-H model discovery

Layer / File(s) Summary
Homogeneous model discovery
modelopt/torch/quantization/plugins/huggingface.py, modelopt/torch/models/nemotron_h/modeling_ptq.py
The homogeneous model check no longer excludes Nemotron-H. The related comment no longer states that the discoverer explicitly rejects it.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant T5Attention
  participant torch.matmul
  participant T5QuantAttention
  T5Attention->>torch.matmul: First matrix multiplication with query and transposed key
  torch.matmul->>T5QuantAttention: Quantize query and key operands
  T5Attention->>torch.matmul: Second matrix multiplication with value operand
  torch.matmul->>T5QuantAttention: Quantize value operand
Loading

Possibly related issues

  • NVIDIA/Model-Optimizer#1699 describes a modeling-library layout with per-model modules. This PR adds T5 PTQ modeling under that layout.

Suggested reviewers: kevalmorabia97

Merge Risk: Minimal · up to 8a7a1

This refactor moves T5 attention quantization into its model package and routes Nemotron-H through the shared checks. No concrete regression was identified, and the author reports no behavior change. Merge risk is minimal after normal CI.

Security architecture risk: Low · up to 8a7a1

The change keeps dispatch within the existing application process and adds no identified privileged entrypoint. Risk is limited by preserved selection checks, but concurrent initialization and recovery after interrupted imports remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated effect is process-local class registration and quantization dispatch. Registry contributions come from explicitly named Python modules; the inspected change does not introduce an externally supplied module-name selector. These sources do not establish deployment-specific tenant or service exposure.

Trust Boundaries and Controls

  • observed — Attention registration retains supported-model eligibility, nested-attention filtering, original-class resolution, and an existing-registration check before selecting a wrapper. These are compatibility and dispatch controls, not authentication or sandbox boundaries for untrusted Python model code.

Resilience and Maintainability Implications

  • observed — The unchanged replacement helper restores the original function and removes its temporary cache attribute in a finally block when the context body returns or raises. This provides exception cleanup for the existing process-wide mutation; it does not establish safety for overlapping concurrent replacements.
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 names the main change: moving the Hugging Face quantization plugin's remaining named-model code (T5 attention wrapper, Nemotron-H special case) into modelopt/torch/models. The raw summary sh…
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 "Security anti-patterns" check passes. The PR patch (base..head) contains none of the listed patterns in added lines. - Changed files: modelopt/torch/models/README.md, nemotron_h/modeling_ptq.py, …
Full details: Title check

Explanation

The title names the main change: moving the Hugging Face quantization plugin's remaining named-model code (T5 attention wrapper, Nemotron-H special case) into modelopt/torch/models. The raw summary shows T5 wrapper relocation, the Nemotron-H special-case removal, and the registration-order changes, all consistent with that title. The title also carries the [1/2] stack marker and the OMNIML-6533 ticket ID, which are acceptable. The title is slightly broad because it does not name the Nemotron-H change or the Transformers-version rationale, but it still describes the primary change.

Full details: Security Anti-Patterns

Explanation

The "Security anti-patterns" check passes. The PR patch (base..head) contains none of the listed patterns in added lines. - Changed files: modelopt/torch/models/README.md, nemotron_h/modeling_ptq.py, t5/modeling_ptq.py (new), quantization/plugins/huggingface.py, and tests/gpu/torch/models/test_modeling_ptq_registration.py. Total: 104 insertions, 61 deletions. - Criteria 1–3 (torch.load weights_only=False, numpy.load allow_pickle=True, hardcoded trust_remote_code=True): no added-line matches. - Criterion 4 (eval()/exec()): no matches. - Criterion 5 (# nosec): no matches. - Criterion 6 (new pip dependencies): no changes to pyproject.toml, setup.py, or requirements*.txt. The PR moves the existing T5 attention wrapper and makes the wrapper list ordered. It adds no loading, code-execution, or dependency paths, so no failure condition applies.

Finishing Touches

Generate unit tests (beta)

  • 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 e0e71ad and 8a7a142.

Files selected for processing: 2

  • modelopt/torch/quantization/plugins/huggingface.py
  • tests/gpu/torch/models/test_modeling_ptq_registration.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.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test b85e4b6

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.2
Preview removed because the pull request was closed.
2026-11-12 23:53 UTC

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.08%. Comparing base (a3a487f) to head (8a7a142).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3367      +/-   ##
==========================================
+ Coverage   79.39%   81.08%   +1.68%     
==========================================
  Files         719      719              
  Lines       80608    80604       -4     
==========================================
+ Hits        64000    65356    +1356     
+ Misses      16608    15248    -1360     
Flag Coverage Δ
examples-diffusers 19.92% <42.85%> (+<0.01%) ⬆️
examples-gpt-oss 13.55% <42.85%> (+<0.01%) ⬆️
examples-hf_ptq 24.12% <100.00%> (-0.85%) ⬇️
examples-llm_distill 13.61% <42.85%> (+<0.01%) ⬆️
examples-llm_eval 17.54% <60.00%> (+0.01%) ⬆️
examples-llm_qat 17.36% <60.00%> (-0.02%) ⬇️
examples-llm_sparsity 16.90% <42.85%> (+<0.01%) ⬆️
examples-megatron_bridge 26.13% <42.85%> (-0.09%) ⬇️
examples-specdec_bench 13.33% <42.85%> (+<0.01%) ⬆️
examples-speculative_decoding 17.75% <60.00%> (-0.05%) ⬇️
examples-torch_onnx 21.02% <42.85%> (-0.01%) ⬇️
examples-torch_trt 15.26% <60.00%> (+0.01%) ⬆️
examples-vllm_serve 17.62% <60.00%> (+0.01%) ⬆️
gpu 59.38% <60.00%> (+3.81%) ⬆️
regression 15.01% <42.85%> (+<0.01%) ⬆️
unit 64.24% <62.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.

# the first whose is_compatible_attention accepts the class gets it, and a class none accepts falls
# back to the AST-based quantized class. A model whose attention needs a wrapper of its own (T5's)
# appends it from its modeling_ptq.
_QUANT_ATTENTION_WRAPPERS: list[type[QuantModule]] = [_QuantAttention]

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.

[SUGGESTION] The annotation list[type[QuantModule]] doesn't capture the contract entries actually have to satisfy: register_hf_attentions_on_the_fly calls wrapper.is_compatible_attention(attention_type), and that staticmethod is not declared on QuantModule. A wrapper appended without it type-checks fine and then raises AttributeError mid-calibration, at the first attention class it is tried on — a confusing place to learn about a missing method.

Since the list is the documented extension point for other modeling_ptq.py modules (vLLM's wrappers land on it in [2/2]), a Protocol would make the required method part of the declared type and catch the omission at the append site:

class _QuantAttentionWrapper(Protocol):
    @staticmethod
    def is_compatible_attention(attn: type) -> bool: ...

_QUANT_ATTENTION_WRAPPERS: list[type[QuantModule] & _QuantAttentionWrapper] = [_QuantAttention]

Non-blocking — the intersection syntax isn't available yet, so a plain Protocol-typed alias or just naming the required staticmethod in the existing comment would do. Behavior is unchanged either way.

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.

Stated the contract in the comment above the list, in e0e71ad: each entry must define the staticmethod is_compatible_attention(attention_type) -> bool, which QuantModule does not declare. I kept the annotation as it is, since a Protocol can't be combined with type[QuantModule] today.

One correction to the premise: [2/2]'s vLLM wrappers don't go through this list. It holds only the Hugging Face attention wrappers (_QuantAttention and T5's).

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

Approving: a behavior-preserving move of T5's KV-cache wrapper into its model package, with the dispatch-order change covered by tests.

What I traced rather than took on trust:

  • The new for/else over _QUANT_ATTENTION_WRAPPERS is equivalent to the old if/elif/else — the else binds to the for and runs only when no wrapper broke out, so a class no wrapper claims still reaches the AST fallback.
  • _QUANT_ATTENTION_WRAPPERS is defined at huggingface.py:382, well before the modeling_ptq import loop at the module tail, so t5's append works in both import orders. Importing t5.modeling_ptq first leaves no window where a caller sees the list without T5, and the extended registration test pins that order.
  • The dropped Nemotron-H guard was redundant: is_homogeneous_hf_model has exactly one non-test caller — its registration, which runs after the model imports — and the guard fired precisely when is_nemotron_h_model was true, which is when Nemotron-H's discoverer already wins first match. No existing test asserted the old False.
  • The new file's header matches LICENSE_HEADER verbatim.

The test edit is purely additive, and 73 added source lines is far under the size budget. One non-blocking inline suggestion on the wrapper-list type annotation.

No action needed.

  • Baseline: 73b3f74 (.agents/review-guidelines/code-review.md). Reviewed head: b85e4b6, all 5 changed files.
  • Source review only — I ran no tests and did not consult CI, so the GPU registration test and the transformers-version matrix in the PR body are unverified here.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test e0e71ad

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

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

Approving: re-review of e0e71ad confirms the T5 wrapper move and the dispatch-order change are behavior-preserving, and the one prior suggestion is answered.

What I re-traced rather than carried over from the b85e4b6 review:

  • The for/else at huggingface.py:426 binds to the for, so a class no wrapper claims still reaches the AST fallback — equivalent to the old if/elif/else, with the same print text via wrapper.__name__.
  • _QUANT_ATTENTION_WRAPPERS is defined at line 383, before the modeling_ptq import loop at line 2014, so t5's append resolves in both import orders and appends exactly once even when t5.modeling_ptq is imported first (the partially-initialized module short-circuits the loop's re-import). The new count(...) == 1 assert pins that.
  • The dropped Nemotron-H guard was provably redundant: is_nemotron_h_model is defined as get_nemotron_h_decoder_layers(...) is not None, and get_decoder_layers returns on first non-None discoverer, so is_homogeneous_hf_model — one non-test caller, its own registration — is never reached for a Nemotron-H. No fallthrough corner exists, and no test asserted the old False.
  • The new file's header matches LICENSE_HEADER verbatim; t5/__init__.py still keeps transformers out of import modelopt.torch.models.

No action needed.

  • ✔️ Resolved since the last review: the _QUANT_ATTENTION_WRAPPERS annotation question, now answered by the comment naming the required is_compatible_attention staticmethod. A Protocol would type it, but the comment is adequate for a private list.
  • 73 added source lines, far under the size budget; the test edit is purely additive. The PR body addresses why static registration and CUSTOM_MODEL_PLUGINS were rejected.
  • Baseline: 73b3f74 (.agents/review-guidelines/code-review.md). Reviewed head: e0e71ad, all 5 changed files.
  • Source review only — I ran no tests and did not consult CI, so the GPU registration test and the transformers 5.5/5.9/5.18 matrix in the PR body are unverified here.

@shengliangxu
shengliangxu marked this pull request as ready for review November 12, 2026 20:33
@shengliangxu
shengliangxu requested review from a team as code owners November 12, 2026 20:33

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

Bot review (gpt-6.1-sol) — DM the bot to share feedback.

Nudge: the refactor looks sound, but the generated release notes incorrectly describe existing T5 support as a new feature.

Needs action:

  • Correct the CodeRabbit release notes in the PR body to describe the T5 wrapper relocation, not newly added PTQ support.

No action needed:

  • The design rationale addresses static registration and unordered callbacks; the ordered wrapper list preserves existing dispatch.
  • The existing-test edit is justified: it adds T5 import-order, uniqueness, and precedence checks without removing coverage.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

Corrected the CodeRabbit release notes in the description: they now describe moving T5's existing wrapper into its model package, with no new PTQ support. #3368's notes had the same problem and are corrected too.

…elopt/torch/models

huggingface.py keeps only generic Hugging Face support. A pure refactor: registrations,
dispatch order and quantized results are unchanged.

- T5: _T5QuantAttention moves verbatim, with its T5Attention import, to
  modelopt/torch/models/t5/modeling_ptq.py. register_hf_attentions_on_the_fly now tries
  the wrappers in an ordered list, _QUANT_ATTENTION_WRAPPERS, which starts as
  [_QuantAttention] and to which T5's module appends its wrapper; the first match wins and
  the AST-based fallback still comes last. So T5Attention and its subclasses keep
  _T5QuantAttention where T5 bypasses transformers' attention interface (before 5.15), and
  _QuantAttention from 5.15 on. A static registration would not do: the registry matches a
  subclass only when it shares forward, and would pre-empt _QuantAttention on 5.15+. Nor
  would a CUSTOM_MODEL_PLUGINS callback: that is a set, run in no fixed order.
- Nemotron-H: is_homogeneous_hf_model no longer special-cases it. The decoder-layer
  registry's first-match order already gives Nemotron-H's own discoverer precedence, and
  for a native Nemotron-H both discoverers return the same model.model.layers (checked on
  transformers 5.5, 5.9 and 5.18), so get_decoder_layers is unchanged in either order.
- The explicit modeling_ptq import list stays the registration point, after the generic
  wrappers and before the generic decoder discoverer, and gains t5.

Signed-off-by: Shengliang Xu <[email protected]>
register_hf_attentions_on_the_fly calls is_compatible_attention on every
entry of the list, and QuantModule does not declare it, so a wrapper that
lacks it would fail only when first tried during calibration. Say so where
the list is defined, for the modeling_ptq modules that append to it.

Signed-off-by: Shengliang Xu <[email protected]>
@shengliangxu
shengliangxu force-pushed the shengliangx/hf-plugin-named-models branch from e0e71ad to 8a7a142 Compare November 12, 2026 23:20

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

Bot review (gpt-6.1-sol) — DM the bot to share feedback.

LGTM: prior concerns are resolved; the justified existing-test edit needs human sign-off.

Needs action:

  • Sign off on tests/gpu/torch/models/test_modeling_ptq_registration.py: the additive T5 import-order, uniqueness, and precedence checks retain all existing coverage.

No action needed:

  • ✔️ Resolved since the last review: the inaccurate CodeRabbit release notes and the wrapper-contract annotation concern.
  • The design rationale addresses existing registration alternatives; dispatch and decoder discovery remain equivalent for their callers.
  • Source review only; reported test runs and CI results were not independently verified.

@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: the supplied diff preserves attention dispatch, and the additive registration tests address import order, uniqueness, and precedence without removing coverage.

The review request from shengliangx, on behalf of U05R5LDGRNG, supplies acceptance of the justified test edit. The wrapper-contract suggestion is resolved in code. The PR explains the registration alternatives; 41 core additions are under budget. Prior review records an exact canonical license-header match.

Baseline commit: 60689c73f7fed08bb836f988f4e8942e11e8d744. Base-revision AGENTS.md and CONTRIBUTING.md were unavailable. Review and duplicate checking cover the bounded supplied diff/history; tests were not executed and reported results were not independently verified.

No action needed.

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

Review run: 4d4e1404305e4ddd97b585d8d3381404

@shengliangxu
shengliangxu merged commit 6cac13b into main Nov 12, 2026
50 checks passed
@shengliangxu
shengliangxu deleted the shengliangx/hf-plugin-named-models branch November 12, 2026 23:53
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]>
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