Repository navigation
Fix HF PTQ empty-init dtype kwargs - #1857
Conversation
|
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. |
📝 WalkthroughWalkthrough
Changesdtype kwarg fix in get_model
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 5 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
realAsma
left a comment
There was a problem hiding this comment.
BB: Did you do an end to end export test for the DeciLM model?
|
BB: did you see this: #1857 (review) |
Replying to #1857 (review) I saw it. Short answer: not a clean end-to-end export pass on the current PR head yet. What I verified so far:
So the dtype fix is not complete as currently pushed. I have local evidence for the extra real-load dtype patch, but export still has a separate follow-up failure after calibration. |
BB: okay ping me in slack when this is done. |
Signed-off-by: realAsma <[email protected]>
Signed-off-by: realAsma <[email protected]>
Signed-off-by: realAsma <[email protected]>
Signed-off-by: realAsma <[email protected]>
0f50049 to
2641497
Compare
Pushed the follow-up fix as This keeps the empty-init device-map path unchanged, but for the final real Validation already completed on |
Signed-off-by: realAsma <[email protected]>
Signed-off-by: realAsma <[email protected]>
realAsma
left a comment
There was a problem hiding this comment.
BB: Approve. Make this a regular PR.
Llama Nemotron3 end-to-end export validationFresh validation passed on the current PR head.
python hf_ptq.py \
--pyt_ckpt_path nvidia/Llama-3_3-Nemotron-Super-49B-v1 \
--recipe general/ptq/nvfp4_default-kv_fp8 \
--export_path <export_dir> \
--trust_remote_code \
--calib_size 1 \
--batch_size 1 \
--use_seq_device_map \
--inference_tensor_parallel 6 \
--attn_implementation eager \
--skip_generateResult from the log: |
Signed-off-by: realAsma <[email protected]>
There was a problem hiding this comment.
Warning
CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.
Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/examples/hf_ptq/test_example_utils.py`:
- Around line 209-210: The DeciLM test is still branching on whether
`transformers.DeciLMForCausalLM` exists, so the behavior can drift with package
versions. In the DeciLM parametrization in `test_example_utils.py`, make
`get_model()` take the `AutoModelForCausalLM` path explicitly by stubbing or
deleting `example_utils.transformers.DeciLMForCausalLM` before the call, while
leaving the `LlamaForCausalLM` case unchanged. Use the `get_model` and
`example_utils.transformers` symbols to locate the affected test setup.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 9e8119c2-de2e-4ede-9cd8-f91eb5b59553
📒 Files selected for processing (2)
examples/hf_ptq/example_utils.pytests/examples/hf_ptq/test_example_utils.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1857 +/- ##
==========================================
+ Coverage 74.12% 77.40% +3.28%
==========================================
Files 515 515
Lines 57118 57118
==========================================
+ Hits 42338 44213 +1875
+ Misses 14780 12905 -1875
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
cjluo-nv
left a comment
There was a problem hiding this comment.
Bot review — DM the bot to share feedback.
Small, focused fix (+103/-3, 2 files) for NVBug 6359821: avoids leaking the dtype kwarg into custom remote-code constructors (e.g. DeciLMForCausalLM) by special-casing "DeciLM" in architecture to use torch_dtype for the empty-weight from_config() probe and dropping dtype entirely from the real from_pretrained() load. Also robustifies dtype derivation (hf_config.dtype → torch_dtype → bf16, with str→torch resolution). A new parametrized test covers both the DeciLM and Llama paths, asserting the correct dtype kwarg name, trust_remote_code forwarding, and eval(). No licensing concerns (test header is the standard NVIDIA Apache-2.0 block); no injection in the untrusted blocks. Nudging rather than approving for human sign-off on a few points:
- 💬 Author validated end-to-end on
Llama-3_3-Nemotron-Super-49B-v1(6 GPUs, Transformers 4.48.3) per the PR comment — but the DeciLM path is GPU/remote-code-only and can't be exercised in CI here, so the actual-load behavior change warrants an owner who knows DeciLM. - The PR body says the fix "sets PyTorch's default dtype only around the empty-weight construction" — that's not what the diff does (it sets
torch_dtype/dtypekwargs explicitly and never touchestorch.set_default_dtype). The description appears stale relative to the implementation; worth reconciling so future readers aren't misled. - Asymmetry worth a sanity check: for DeciLM the empty-weight probe is told
torch_dtype=config_dtype, but the realfrom_pretrained()gets no dtype at all (dtypepopped), so it falls back to the checkpoint's native dtype. That's probably fine (and matches what the probe was approximating), but a quick confirmation that DeciLM loads at the intended precision would be good. - The
"DeciLM" in architecturesubstring check is a hardcoded special case; fine for a targeted bugfix but a fragile pattern if more remote-code architectures need the same treatment later.
Signed-off-by: realAsma <[email protected]>
| hf_config, auto_model_module, ckpt_path, config_kwargs | ||
| ) | ||
|
|
||
| is_decilm = "DeciLM" in architecture |
There was a problem hiding this comment.
Is it possible to make this a general WAR instead of DiciLM specific?
There was a problem hiding this comment.
🤖 Bot comment.
Thanks Wei-Ming. I agree this may be generalizable to other older remote-code models with the same Transformers 5+ incompatibility, but finding and validating those models would be a broader follow-up. For this PR, I would like to keep the fix scoped to the observed Llama Nemotron / DeciLM failure since broader remote-code fallback support is lower value and would need dedicated coverage.
There was a problem hiding this comment.
🤖 Bot comment.
Thanks Wei-Ming. I agree this could probably be generalized to older remote-code models with the same constructor mismatch, but that would require identifying and validating the affected model set.
For this RC bug, I would keep the fix scoped to Llama Nemotron / DeciLM because that is the reported failure and the broader remote-code support case is lower value without dedicated coverage. I can follow up separately if we find more models with the same failure.
Signed-off-by: realAsma <[email protected]>
meenchen
left a comment
There was a problem hiding this comment.
Approve to unblock, please see if we can avoid model arch hardcode
…t-resolve Signed-off-by: realAsma <[email protected]> # Conflicts: # examples/hf_ptq/example_utils.py # tests/examples/hf_ptq/test_example_utils.py
| model_kwargs2 = model_kwargs.copy() | ||
| if is_decilm: | ||
| model_kwargs2.pop("dtype", None) |
There was a problem hiding this comment.
BB: can we use the same if is_decilm: model_kwargs2["torch_dtype"] = config_dtype model_kwargs2.pop("dtype", None) behavior here as well to be safe? we can create a helper to get the config with the correct dtype.
|
cjluo-nv
left a comment
There was a problem hiding this comment.
Bot review — DM the bot to share feedback.
Re-review of small, focused bugfix (+104/-3, 2 files) for NVBug 6359821: avoids leaking the modern dtype kwarg into the DeciLM remote-code constructor by special-casing "DeciLM" in architecture to use torch_dtype for the empty-weight from_config() probe and dropping dtype from the real from_pretrained() load. Dtype derivation is also robustified (config.dtype → torch_dtype → bf16, with str→torch resolution). No licensing concerns (test header matches the canonical LICENSE_HEADER; file is modified, not new). No injection attempts in the untrusted blocks.
Status of previous review comments:
- 💬 CodeRabbit (test:210) — force the
AutoModelForCausalLMpath so the test doesn't drift withtransformersversions: addressed — DeciLM parametrization now doesmonkeypatch.delattr(example_utils.transformers, architecture, raising=False). - 💬 kevalmorabia97 (test:249) — make
FakeLlamaForCausalLMa subclass ofFakeAutoModelForCausalLM: addressed (subclass overriding onlyfrom_pretrained). - 💬 Author asked for end-to-end DeciLM/Nemotron export validation: addressed — fresh e2e run posted on the current head
acb6e702e0(Llama-3_3-Nemotron-Super-49B-v1, 6 GPUs, TF 4.48.3): 21 shards loaded, 1461 quantizers, calibration + export succeeded.
Why nudge rather than approve:
- 💬 meenchen/realAsma asked whether the fix could be a general WAR instead of DeciLM-specific — author justified keeping it scoped to the reported RC bug. The
"DeciLM" in architecturesubstring check is a deliberate, accepted hardcode but remains fragile if more remote-code architectures hit the same constructor mismatch; an owner familiar with DeciLM should confirm this is the right scope. - The behavior change (different dtype kwarg + dropping dtype on the real load) only affects the GPU/remote-code path and can't be exercised in CI; the unit test uses fakes/monkeypatch, so the actual-load precision behavior rests on the author's manual e2e run — worth an owner sign-off.
- 💬 realAsma asked to simplify the tests using tiny Qwen/Deci fixtures; the pushed version instead folds coverage into a parametrized
get_modeltest usingFakeModelstubs. Reasonable, but diverges from the requested fixture-based approach — owner should confirm this is acceptable. - Minor: the PR body's claim that the fix "sets PyTorch's default dtype only around the empty-weight construction" is stale relative to the diff (it sets
dtype/torch_dtypekwargs explicitly, nevertorch.set_default_dtype). Worth reconciling so future readers aren't misled.
cjluo-nv
left a comment
There was a problem hiding this comment.
Bot review — DM the bot to share feedback.
Re-review of a small, focused bugfix (+104/-3, 2 files) for NVBug 6359821: avoids leaking the modern dtype kwarg into the DeciLM remote-code constructor by special-casing "DeciLM" in architecture to (a) use torch_dtype=config_dtype for the empty-weight from_config() probe and (b) drop dtype entirely from the real from_pretrained() load. Dtype derivation is robustified (config.dtype → torch_dtype → bf16, with str→torch resolution). No licensing concerns: the test header matches the canonical LICENSE_HEADER, and both files are modified (not new). No prompt-injection attempts in the untrusted blocks (the "BB: Approve"/"Approve to unblock" lines are genuine human reviewer comments, not directives aimed at me).
Status of previous review comments:
- 💬 realAsma (example_utils:799) — apply the same
is_decilmdtype-drop to the realfrom_pretrainedload: addressed — the diff now doesif is_decilm: model_kwargs2.pop("dtype", None)on that path. - 💬 kevalmorabia97 (test:249) — make
FakeLlamaForCausalLMa subclass ofFakeAutoModelForCausalLM: addressed (subclass overriding onlyfrom_pretrained). - 💬 CodeRabbit (test:210) — force the
AutoModelForCausalLMpath deterministically: addressed — the DeciLM parametrization now doesmonkeypatch.delattr(example_utils.transformers, architecture, raising=False). - 💬 PR-body staleness ("sets PyTorch's default dtype") flagged in prior review: addressed — the body now describes forwarding/dropping kwargs, matching the diff.
Why nudge rather than approve:
- 💬 Author posted a fresh e2e on the current head
acb6e702e0(Llama-3_3-Nemotron-Super-49B-v1, 6 GPUs, TF 4.48.3): 21 shards, 1461 quantizers, export succeeded — but an earlier run on this PR hit a separate DeciLM/Transformers tied-weight export failure (_get_tied_weight_keys), and the "now clean" claim rests entirely on a manual GPU run that CI cannot reproduce. The unit test only exercises fakes/monkeypatch, so the actual-load precision behavior (dropping dtype → falling back to the checkpoint's native dtype) needs an owner who knows DeciLM to confirm. - 💬 meenchen/realAsma asked whether this could be a general WAR instead of DeciLM-specific; author justified keeping it scoped to the reported RC bug. The
"DeciLM" in architecturesubstring is a deliberate, accepted hardcode but remains fragile if more remote-code archs hit the same constructor mismatch — worth an owner confirming the scope is right.
Processed the Outcome:
|
## Summary - factor config dtype resolution into helpers for HF PTQ model loading - keep DeciLM empty-init and final-load kwargs on `torch_dtype` while avoiding unsupported `dtype` forwarding - update the DeciLM dtype unit assertion for the follow-up behavior Follow-up to #1857 for NVBug 6359821. ## Validation - `pytest_pwd tests/examples/hf_ptq/test_example_utils.py -q -x` (`15 passed`) - `git diff --check` - `pre-commit run --files examples/hf_ptq/example_utils.py tests/examples/hf_ptq/test_example_utils.py` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved model loading so precision (dtype) is applied more consistently across supported loading paths, including DeciLM models. * Updated initialization to derive dtype from model configuration and pass the expected precision into model loading kwargs. * **Tests** * Updated test expectations to reflect the new dtype kwarg behavior during `from_pretrained` for causal language model loading scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: realAsma <[email protected]>
Transplant the combined get_model fix from PRs #1839, #1857 and #1869 onto release/0.45.0's examples/llm_ptq/example_utils.py. These PRs could not be cherry-picked directly because the file was renamed llm_ptq -> hf_ptq (#1759) and surrounding get_model code diverged on main, but the actual fix targets the init_empty_weights / from_config block that already exists on the release branch: - _resolve_init_config: re-derive a built-in config for remote-code checkpoints so device-map inference matches the model definition's version (fixes Nemotron-H moe_latent_size AttributeError on transformers 5.x, #1839). - _get_config_dtype / _apply_dtype_to_config: derive dtype from the resolved config and forward the DeciLM-supported dtype kwarg, dropping unsupported dtype forwarding on the real from_pretrained load (#1857, #1869). Ports the accompanying unit tests (path-adjusted to llm_ptq). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Keval Morabia <[email protected]>
#1858 #1839 #1857 #1869 (#1880) ## Cherry-picked PRs - #1801 - #1808 - #1629 - #1627 - #1824 - #1826 - #1830 - #1760 - #1831 - #1858 - #1839 - #1857 - #1869 #1839, #1857 and #1869 were back-ported (not a clean cherry-pick): the file was renamed `llm_ptq` -> `hf_ptq` (#1759) and surrounding `get_model` code diverged on `main`, but the actual fix targets the `init_empty_weights` / `from_config` block that already exists on the release branch. Accompanying unit tests were ported (15 passed). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a new PTQ recipe for NVFP4 MLP/MoE quantization with FP8 KV-cache calibration. * **Bug Fixes** * Improved ONNX mixed-precision/FP16 conversion reliability with stricter type handling and better stale output-shape reconciliation. * Fixed quantization/export edge cases: MoE router/gate handling, FP8 calibration/reduction failures, and additional FP8/INT8 robustness during export. * Standardized Puzzletron validation split naming to `validation`. * **Documentation** * Refreshed LM-Eval and TensorRT-Edge-LLM CLI instructions, including updated command names and examples. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Meng Xin <[email protected]> Signed-off-by: Keval Morabia <[email protected]> Signed-off-by: ajrasane <[email protected]> Signed-off-by: dimapihtar <[email protected]> Signed-off-by: Chenjie Luo <[email protected]> Signed-off-by: Zhiyu Cheng <[email protected]> Signed-off-by: Grzegorz Karch <[email protected]> Signed-off-by: Daniel Korzekwa <[email protected]> Co-authored-by: mxinO <[email protected]> Co-authored-by: Ajinkya Rasane <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Dmytro Pykhtar <[email protected]> Co-authored-by: Chenjie Luo <[email protected]> Co-authored-by: Zhiyu <[email protected]> Co-authored-by: Grzegorz K. Karch <[email protected]> Co-authored-by: Daniel Korzekwa <[email protected]>
The example has passed a DeciLM checkpoint its precision as torch_dtype since #1857 (NVBug 6359821, checked end to end on Llama-3.3-Nemotron-Super-49B): the checkpoint's own code does not take dtype on the paths the example loads it through. The example matched "DeciLM" in the architecture, and its README lists Llama-Nemotron Super and Ultra, so the registry keeps the two model types that carry that architecture, deci and nemotron-nas. The spec cut had dropped them; PTQSpec.dtype_kwarg, the two specs and the test rows come back as they were. Signed-off-by: Shengliang Xu <[email protected]>
…bration rules into the model registry (#3224) ### What does this PR do? Type of change: Refactor Part 2 of 2 of the series that makes `examples/hf_ptq` free of named-model branches; part 1, #3223, is merged. The example decided how to load, calibrate, preview and refuse a model by testing its name (`model_type == "t5"`, `startswith(("deepseek", "kimi_k2"))`, `"DeciLM" in architecture`, `"nemotron"` in the architectures, `model_type == "whisper"`, `"vila"` in the checkpoint path, ...). That knowledge belongs with the model. This PR moves it into `modelopt/torch/models`, the per-model-type registry from #1828 and #2576-#2580, in two forms, and the example then carries no branch on a named model. Adding a model's PTQ facts becomes a registry entry, not an edit to the example. - **Facts.** `ModelSpec` gets a `PTQSpec` section, read through `get_ptq_spec(model_type)`, which returns an all-default section for a model without one. Its fields are reasons, so each special case carries its *why* and the example prints it when it acts: `no_device_map`, `no_auto_device_map`, `sequential_device_map`, `generation_unsupported`, `post_ptq_generation_unsupported`, `generate_includes_prompt` and `fsdp2_unsupported`. Two fields are not reasons: `dtype_kwarg`, the precision keyword a checkpoint's own loading code takes, and `vlm_wrapper`, which marks a VLM wrapper (image-text calibration by default, the preview through the wrapper's own chat path). - **Code.** Four optional per-model hooks in `modelopt.torch.models.hf`, which the example calls without knowing which model type provides them: `forward_calibration_batch`, `load_calibration_processor`, `make_calibration_dataloader` and `calibration_sample_input`. The modules that provide them sit next to the model. A model type may now list several plugin modules in `hf._PLUGINS`; two that define the same hook are refused. | Was in the example | Now | |---|---| | `model_type == "t5"` / `"bart"` -> `device_map=None` | `no_device_map` on `t5`, `bart` | | `"DeciLM" in architecture` -> `torch_dtype` keyword | `dtype_kwarg` on `deci` and `nemotron-nas` | | `startswith(("deepseek", "kimi_k2"))`, `== "nemotron_h"` -> skip the generation preview | `generation_unsupported` on `deepseek`, `deepseek_v3`, `deepseek_v32`, `deepseek_v4`, `kimi_k2`, `kimi_k25` and `nemotron_h` | | `not in ("llama4", "llama4_text")` -> skip the post-quantization generation | `post_ptq_generation_unsupported` on `llama4`, `llama4_text` | | `"Deepseek" in architecture` -> bundled checkpoint code | the existing `prefers_bundled_code` hook, through a new `deepseek.bundled_code` plugin registered for the same DeepSeek types and `kimi_k2` | | `is_diffusion_gemma` (sequential multi-GPU map; `generate()` includes the prompt) | `sequential_device_map`, `generate_includes_prompt` on `diffusion_gemma` | | `"vila" in args.local_checkpoint_path` (FSDP2 refusal) | `fsdp2_unsupported` on `llava_llama` (VILA, NVILA, NVILA-Lite; LLaVA-repo fine-tunes share the type and are covered too) | | `is_nemotron_vl` (`"nemotron"` in the architectures) and `examples/hf_ptq/nemotron_vl_calib.py` | `vlm_wrapper` and `no_auto_device_map` on `NemotronH_Nano_VL_V2`, `Llama_Nemotron_Nano_VL`, `NemotronH_Nano_Omni_Reasoning_V3`, `nemotron_h_omni` and `nemotron_parse`, and a `forward_calibration_batch` hook for all but `nemotron_parse`; the file moves to `modelopt/torch/models/nemotron_h_nano_vl_v2/calibration.py` (`git mv`; the calibration forward is unchanged, the hook wrapper around it is new) | | `model_type == "whisper"` in five places (processor, speech calibration data, batch-probe sample shape, preview input key, preview decoding) | hooks `load_calibration_processor`, `make_calibration_dataloader`, `calibration_sample_input` in `modelopt/torch/models/whisper/calibration.py`; the preview takes `input_ids` when the batch has them, else `input_features` | Two device-map precedences are kept exactly, which is why there are two fields: `no_auto_device_map` (Nemotron VL) still yields to an explicit `--use_seq_device_map`, since users shard these wrappers; `no_device_map` (T5, BART) yields to nothing. ### Model types this PR adds to the registry The registry is keyed by exact `model_type`, where the example matched by prefix and by architecture substring. It does not enumerate every type those patterns reached: a type gets a spec only when the old code or its tests name it, when checkpoints that the repository's tests use declare it (Nemotron-3 Nano Omni), or, for VILA, when no other key can hold the old check. Each new spec is its own package, the registry's convention. | Model type | Checkpoints | Why it is added | |---|---|---| | `t5` | T5 | The example loaded it without a device map (`model_type == "t5"`): `device_map="auto"` can shard its tied encoder/decoder embeddings and position-bias buffers across GPUs, which non-deterministically gives NaN activations in multi-GPU calibration (transformers#21093). Carried as `no_device_map`. | | `bart` | BART | The example loaded it without a device map (`model_type == "bart"`): `device_map="auto"` and `"cuda"` raise a meta-tensor error from its safetensors. Carried as `no_device_map`. | | `deci` | DeciLM (remote code) | The example passed a DeciLM checkpoint its precision as `torch_dtype` (`"DeciLM" in architecture`, the #1857 fix for NVBug 6359821): the checkpoint's own code does not take `dtype` on the paths the example loads it through. Carried as `dtype_kwarg`. | | `nemotron-nas` (package `nemotron_nas`) | Llama-Nemotron Super and Ultra (remote code; the DeciLM architecture under another type) | The same architecture check reached them, and the example's README lists them as supported. Carried as `dtype_kwarg`. | | `deepseek_v32` | DeepSeek-V3.2 | The example skipped the generation preview for every `deepseek*` type ("DeepSeek generation may go OOM"), and its tests name `deepseek_v32`. Carried as `generation_unsupported`. Like the other DeepSeek types, it also maps to the `deepseek.bundled_code` plugin, which replaces the `"Deepseek" in architecture` test. | | `kimi_k2` | Kimi-K2 (remote code; a DeepSeek-V3 architecture under its own type) | The example named it in the same preview skip (`startswith(("deepseek", "kimi_k2"))`), and its tests name it. Carried as `generation_unsupported`. It maps to the same bundled-code plugin, since its architecture, `DeepseekV3ForCausalLM`, matched the old test. | | `diffusion_gemma` | DiffusionGemma | The example detected it (`is_diffusion_gemma`) to load it with `device_map="sequential"` on several GPUs, since the balanced map can split a tied encoder/decoder pair, and to know that its `generate()` returns the prompt with the output. Carried as `sequential_device_map` and `generate_includes_prompt`. | | `llava_llama` | VILA, VILA1.5, NVILA, NVILA-Lite (remote code); LLaVA-repo fine-tunes share the type | The example refused `--use_fsdp2` when the checkpoint path contained "vila" ("custom builder + non-standard layer layout"). VILA has no model type of its own: its checkpoints declare `llava_llama`, the only key a per-model-type registry can hold that refusal under. Carried as `fsdp2_unsupported`. | | `NemotronH_Nano_VL_V2` (snake_case package `nemotron_h_nano_vl_v2`) | Nemotron Nano VL v2 (remote code) | The example's Nemotron VL support was written for this wrapper: `nemotron_vl_calib.py` runs a calibration forward in place of the wrapper's own `forward()`, which calls `torch.distributed.get_rank()` unconditionally and assumes `past_key_values`, and the example's tests name the type. The example found it by "nemotron" in the architecture of any multimodal model; the registry needs the exact type. The spec carries `vlm_wrapper` and `no_auto_device_map`, and the package holds the moved forward behind the `forward_calibration_batch` hook. | | `Llama_Nemotron_Nano_VL` (snake_case package `llama_nemotron_nano_vl`) | Llama-3.1-Nemotron-Nano-VL (remote code) | The old "nemotron" match gave it the VLM-wrapper handling, which its remote code needs: `generate()` takes `pixel_values` first, so the generic token-id preview would hand it token ids, and `forward()` squeezes `image_flags`, which a plain image batch does not carry. The spec carries `vlm_wrapper` and `no_auto_device_map`, and the type maps to the same `forward_calibration_batch` hook as `NemotronH_Nano_VL_V2`. | | `NemotronH_Nano_Omni_Reasoning_V3` (snake_case package `nemotron_h_nano_omni_reasoning_v3`) | Nemotron-3-Nano-Omni-30B-A3B-Reasoning in BF16, FP8 and NVFP4 (remote code); the repository's deploy tests use the FP8 and NVFP4 ones | The published Omni checkpoints declare this type. `nemotron_h_omni` is the type of transformers' port of the model (from 5.18), which refuses these checkpoints without `trust_remote_code`, so that entry does not reach them. The old "nemotron" match gave them the VLM-wrapper handling: the architecture is `NemotronH_Nano_Omni_Reasoning_V3` and the config has a `vision_config`. The spec carries `vlm_wrapper` and `no_auto_device_map`, and the type maps to the same `forward_calibration_batch` hook as `nemotron_h_omni`. | | `nemotron_parse` | Nemotron-Parse (remote code) | The example names it: its comments and a test cover its encoder-decoder calibration batch, and export detects its architecture. The old "nemotron" match gave it the VLM-wrapper handling, which it needs: its main input is `pixel_values`, so the generic token-id preview would hand its vision encoder token ids, and text-only calibration reaches only its decoder, never the cross-attention. The spec carries `vlm_wrapper` and `no_auto_device_map`. It has no calibration hook, since its batch keeps the plain forward. | | `whisper` | Whisper | The example tested `model_type == "whisper"` in five places. The package holds the three hooks that replace them, in `whisper/calibration.py`. Its spec records only the transformers floor, since every package in the registry has a `specs.py` (models README). | Types already in the registry gain a `ptq_spec`: `deepseek`, `deepseek_v3`, `deepseek_v4`, `kimi_k25` and `nemotron_h` (`generation_unsupported`), `llama4` and `llama4_text` (`post_ptq_generation_unsupported`), and `nemotron_h_omni`, the type of transformers' port of Nemotron-3 Nano Omni (the VLM-wrapper fields and the calibration hook: the old architecture match covered it too, and the moved forward already handles its layout). ### Behavior differences (deliberate) - Models that the old checks reached only through a prefix or a substring, and that no spec names, now take the flow's generic path. The other `deepseek*` types (`deepseek_v2`, `deepseek_vl*`, ...) are not skipped by the generation preview and do not prefer the bundled code. A text-only DiffusionGemma type (`diffusion_gemma_text`) gets the generic device map and preview. - DiffusionGemma is no longer recognised from its architecture alone or from a nested `text_config` (the real root type is `diffusion_gemma`). - The FSDP2 refusal for VILA keys on the `llava_llama` model type instead of the checkpoint path containing "vila", and names that type next to VILA. The type is shared with LLaVA-repo fine-tunes (15 of the 68 `llava_llama` repos that a hub search for llava or vila finds), which are now refused too, and a renamed VILA checkpoint no longer slips through. The other way round, two kinds of checkpoint that the path test refused are no longer refused: those that declare the model type `vila` (VILA's four `-hf-preview` ports and one third-party port, 11 to 21 downloads each), and unrelated models whose path contains "vila" (for example Qwen2 fine-tunes named `vilaw-*`). This is by design: the registry holds one spec per model type, not one per variant. - Five model types get the VLM-wrapper defaults, `NemotronH_Nano_VL_V2`, `Llama_Nemotron_Nano_VL`, `NemotronH_Nano_Omni_Reasoning_V3`, `nemotron_h_omni` and `nemotron_parse`, where the old test matched any multimodal architecture containing "nemotron". README footnote 13 names them, and the two cases where the image-text default does not apply, as on main: `--use_fsdp2` and AutoQuantize recipes. - Plain InternVL wrappers (`internvl_chat`) take the generic load, calibration and preview. Under `--calib_with_images` their batches go through the plain forward, where the old code gave any wrapper with `img_context_token_id` the InternVL-style calibration forward; no code or test named that model type. - The generation preview takes `input_ids` when the batch has them, else `input_features` (it was Whisper by name), and decodes through the processor's tokenizer when there is no tokenizer. - New stdout lines when a spec acts: `Loading without a device map: ...`, `Skipping the generation preview: ...`, `Using device_map='sequential': ...`. The FSDP2 MTP refusal says "MTP weights (...)", and "VLM wrapper" replaces "Nemotron VL" in the log. Left out on purpose: `dataset_utils.model_type_is_enc_dec`, `export.model_utils.is_multimodal_model` (a Nemotron-Parse name test) and the `/no_think` prompt in `vlm_utils` are library code with the same smell, and are not touched here. ### The series Two PRs, independent of each other. #3223 merged first, and this branch merges `main` back in: both PRs edited a few neighboring lines of `examples/hf_ptq/example_utils.py` and its test (each removed one of two adjacent functions and one of two paired test lines), and the merge keeps both removals, so this PR's diff against `main` is unchanged line for line. This PR also carries what was #3225, the third part of an earlier three-part stack; #3225 is closed, and its review threads stay there. It also moves #3223's `test_trtllm_enc_dec.py` into `tests/unit/torch/export/trtllm/`, so that the test goes with that folder when the TensorRT-LLM export is removed (a review comment on #3223). | PR | What | Added source lines | |---|---|---| | 1/2 #3223 (merged) | Move the speculative-draft check and the TRT-LLM enc-dec list into library modules | 14 | | 2/2 (this PR) | Move hf_ptq's per-model loading, preview and calibration rules into the model registry | 407 | Lines are counted as the review guideline does: lines added to Python source, without blank lines, comments and docstrings, tests excluded, and a move that git detects as a rename not counted as new (the 78 lines of `nemotron_vl_calib.py` that move verbatim). The quick count in CLAUDE.md keeps comments and docstrings and gives 970 for this PR: 392 of those lines are the license headers of its 28 new files, and the other 171 are docstrings and comments. ### Usage ```python # modelopt/torch/models/<model_type>/specs.py: a model's PTQ facts are a registry entry from ..specs import ModelSpec, PTQSpec, register register( ModelSpec( model_type="my_model", min_transformers_version="5.5", ptq_spec=PTQSpec(generation_unsupported="its generation runs out of memory"), ) ) ``` ```python # modelopt/torch/models/<model_type>/calibration.py: an optional hook, listed in hf._PLUGINS["my_model"] __all__ = ["forward_calibration_batch"] def forward_calibration_batch(model, batch) -> bool: ... # run one calibration batch and return True, or return False to leave it to the default ``` ### Testing The CPU and Hub-config rows were measured at 8711fcd against its base 4cc8cdc, before `main` was merged in; the row after them covers the merge and the rename. | Check | Result | |---|---| | pre-commit, every hook including mypy and bandit, over `main..HEAD` | clean | | CPU, `tests/examples/hf_ptq` and `tests/unit/torch/{models,export,speculative}`, transformers 5.5.4 (the floor) | main 4cc8cdc: 66 failed / 1787 passed / 79 skipped; this branch: 66 failed / 1825 passed / 79 skipped. The 66 are the same ids on both (no GPU or diffusers in the test environment) | | Same, transformers 5.18 | main: 66 failed / 1969 passed / 19 skipped; this branch: 66 failed / 2007 passed / 19 skipped; the same 66 ids | | CPU, `tests/unit/torch` with transformers and the ONNX packages hidden (the selection of the torch-only CI job) | main: 3016 passed, 226 skipped; this branch: 3036 passed, 227 skipped; 0 failed on both | | Real checkpoints on CPU through the example's own `get_model`, calibration data, batch-probe sample, `pre_quantize` and `post_quantize`: `t5-small`, `whisper-tiny` (synthetic audio in place of the audio dataset, which needs torchcodec and ffmpeg), a tiny Llama and a tiny Qwen3-VL, main vs this branch | identical loaded class, devices, weights digest, preview input and generated text. The differences are the new `Loading without a device map: ...` line for T5, and Whisper's batch-probe sample, which now comes from the hook and equals the old inline tensor (`torch.equal`) | | Hub configs of Llama-3.3-Nemotron-Super-49B-v1 (`nemotron-nas`, `DeciLMForCausalLM`), Llama-3.1-Nemotron-Nano-VL-8B-V1 (`Llama_Nemotron_Nano_VL`), Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 (`NemotronH_Nano_Omni_Reasoning_V3`) and Nemotron-Parse v1.1 (`nemotron_parse`): what the example decides for them, main vs this branch | Nemotron-Super: the precision keyword `get_model` passes to the empty-weight probe and to the load is `torch_dtype` on both. The three VL types: main's `is_nemotron_vl` is `True` for all three (image-text calibration default, wrapper preview, no automatic device map); this branch sets `vlm_wrapper` and `no_auto_device_map` for all three, and the calibration hook for Nano VL and Omni | | After merging `main` (90ff1a2, with #3223) and the rename, at a5dab18: pre-commit over `main..HEAD`, and on CPU `tests/unit/torch/models`, `tests/unit/torch/export/trtllm`, `tests/examples/hf_ptq/test_example_utils.py` and `test_hf_ptq_model_type.py` | pre-commit clean; 640 passed on transformers 5.18.0; 498 passed and 20 skipped on 5.5.4 | | GPU end to end, 1 GPU: this PR's base 4cc8cdc vs its head 8711fcd, both in one job and one environment, each importing its own checkout, with `hf_ptq.py --pyt_ckpt_path <model> --qformat fp8 --export_path <dir>` and default calibration; the exports compared file by file (sha256), tensor by tensor (bitwise) and JSON key by key | the two rows below | | Whisper large-v3, transformers 5.18.0, with datasets 3.6.0, soundfile 0.13.1 and librosa 0.11.0 | Identical: 1612 of 1612 tensors bit-identical, and 17 of 18 files byte-identical. The 18th, `encoder/config.json`, differs only in the order of the three `quantization.exclude_modules` entries, which the TensorRT-LLM exporter collects in a set. The transcripts before and after quantization are identical on both sides | | Nemotron-Parse v1.1, with `--trust_remote_code --attn_implementation eager`, transformers 5.13.0, and albumentations 2.0.8, opencv-python-headless 4.11.0.86 and mistral_common 1.13.1 for its remote code and processor | Identical: 35 of 35 files byte-identical, 866 of 866 tensors equal. The base logs "Nemotron VL model detected", the head "VLM wrapper detected"; both calibrate on image-text pairs by default. Neither prints a preview: the text-only preview cannot run for this model, and the image preview needs `examples/hf_ptq/images`, which is not in the repository (the same on main), so this compares the exported checkpoints, not generation | | Llama-3.1-Nemotron-Nano-VL-8B-V1, with `--trust_remote_code --attn_implementation eager`, transformers 5.5.4 and 5.13.0, on the earlier three-part stack (its base 219b34a vs its top f7cc01a) | Blocked on the base and on the top alike, before any changed code: the checkpoint's remote code does not load under transformers 5.x (`'Llama_Nemotron_Nano_VL' object has no attribute 'all_tied_weights_keys'`). Its handling is checked at the config level (the Hub-config row above) | | **Not run locally:** GPU tests on this branch's tip | CI runs them, since this PR targets `main` | ### Before your PR is "*Ready for review*" Commits are signed (`git commit -s -S`). - Is this change backward compatible?: ✅ (example behavior is unchanged except for the differences listed above; registry additions only) - 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?: ✅ (`tests/unit/torch/models/test_ptq_specs.py`, `test_nemotron_vl_calibration.py`, `test_whisper_calibration.py`, `test_hf_hooks.py` and the example tests) - Did you update Changelog?: N/A (internal refactor) - Did you get Claude approval on this PR?: ❌ not yet requested ### Additional Information Tracked by OMNIML-6429, for ModelOpt v0.49.0. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit - **New Features** - Added model-specific settings for Hugging Face post-training quantization, including device placement, dtype handling, FSDP2 support, and generation previews. - Extended model support across additional language, vision-language, speech, encoder-decoder, and diffusion models, including Whisper calibration. - Added model-specific calibration and preview handling, with image-text calibration defaults for selected vision-language models. - **Bug Fixes** - Improved model loading and calibration behavior, and clarified when generation previews are unavailable. - Updated preview handling for models whose output includes the input prompt. - **Documentation** - Expanded guidance on model specifications, calibration hooks, and quantization behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Shengliang Xu <[email protected]>
Summary
Fixes NVBug 6359821:
hf_ptq.pycan fail for remote/custom architectures likeDeciLMForCausalLMwhen dtype-related kwargs are forwarded into model construction paths that do not accept them.This change keeps the fix scoped to the observed DeciLM/Llama Nemotron path. It resolves the init config used for empty-weight construction, derives dtype consistently from the resolved config, forwards the supported dtype kwarg for the DeciLM empty-weight probe, and drops unsupported dtype forwarding from the DeciLM real
from_pretrained()load.NVBug: https://nvbugspro.nvidia.com/bug/6359821
Validation
pre-commit run --files examples/hf_ptq/example_utils.py tests/examples/hf_ptq/test_example_utils.pypytest_pwd tests/examples/hf_ptq/test_example_utils.py -q -x(15 passed)Llama-3_3-Nemotron-Super-49B-v1end-to-endhf_ptq.pyexport on one node with 6 GPUs, Transformers 4.48.3: Fix HF PTQ empty-init dtype kwargs #1857 (comment)Summary by CodeRabbit
Bug Fixes
trust_remote_code, and avoided passingmax_memoryduring config loading.Tests
trust_remote_codebehavior, and eval-mode initialization.