Skip to content

Fix init_quantized_weights: from_pretrained kwargs leak into dispatch, broken dtype fallback - #2161

Merged
kevalmorabia97 merged 9 commits into
NVIDIA:mainfrom
spped2000:fix/init-quantized-weights-kwargs-and-tied-weights
Oct 28, 2026
Merged

kevalmorabia97 merged 9 commits into
NVIDIA:mainfrom
spped2000:fix/init-quantized-weights-kwargs-and-tied-weights

Conversation

@spped2000

@spped2000 spped2000 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

Two defects in init_quantized_weights (public API, and the loader behind hf_ptq.py --low_memory_mode):

  1. from_pretrained kwargs reach load_checkpoint_and_dispatch(). patched_from_pretrained forwarded every kwarg except config and trust_remote_code to load_checkpoint_and_dispatch(), which takes only its own loading options (dtype, max_memory, offload_*, ...), so any other kwarg raised a TypeError. On current main, hf_ptq.py --low_memory_mode --attn_implementation sdpa fails with:

    TypeError: load_checkpoint_and_dispatch() got an unexpected keyword argument 'attn_implementation'
    

    The kwargs are now split by what each call takes:

    • load_checkpoint_and_dispatch() gets only the kwargs in its signature. A caller's dtype/torch_dtype reaches it as dtype=, as main already did for dtype; without one, dispatch keeps casting each tensor to the dtype the model was built with.
    • Without config=, AutoConfig.from_pretrained(..., return_unused_kwargs=True) takes the Hub options (revision, token, local_files_only, ...) and config attributes such as use_cache=False, as from_pretrained() does. The weights are still read from the local directory passed (load_pretrained() resolves a Hub ID to one first; a Hub ID passed directly fails in accelerate, on main too).
    • subfolder is joined into the checkpoint path, as load_pretrained() does, so the config and the weights are read from the same place.
    • from_config() gets the rest (e.g. attn_implementation when config= is passed) and raises on any the model doesn't take. With config= there is no config load, so Hub options also end up here and raise; they raised at dispatch before.
    • A non-None device_map or quantization_config raises a ValueError up front, since this loader computes the device map and quantizes with quant_cfg. device_map is in dispatch's own signature, so the split alone would collide with the computed map. With None, both now load where main raised.
  2. The float16 dtype fallback never fires. config.torch_dtype is a deprecated alias of config.dtype that returns None when unset instead of being absent, so for a config without a dtype getattr(config, "torch_dtype", torch.float16) returns None and the model is built and loaded in float32. The dtype now resolves as dtype > torch_dtype > config.dtype > float16 (the existing default).

This PR originally also added model.tie_weights(); #2951 landed the same fix, so it was dropped when merging main.

Usage

No API change.

Testing

  • test_real_quantize_linear (tests/gpu) gains four load cases on the real path:

    • torch_dtype=torch.float16, attn_implementation="eager";
    • a config= without a dtype, with attn_implementation="eager", which then reaches from_config();
    • local_files_only=True, a Hub option that load_pretrained() forwards;
    • subfolder="tiny_llama", loaded from the parent directory.

    Against main's accelerate.py, the first three fail with TypeError: load_checkpoint_and_dispatch() got an unexpected keyword argument ..., and the fourth with ValueError: Unrecognized model in ..., because the config is looked up in the parent directory. With this PR all 10 parametrizations (5 load cases × tied/untied) pass. This replaces the mock-based unit test from an earlier revision of this PR, per the test-design guidance in CONTRIBUTING.

  • Reverting each fix alone fails exactly its own cases (checked on CPU):

    • the kwargs split: model_kwargs, config_without_dtype and hub_kwargs;
    • passing the remaining kwargs to from_config() (that call reverted to from_config(config, dtype=dtype)): config_without_dtype (assert 'sdpa' == 'eager');
    • the subfolder join: subfolder;
    • the dtype fallback: config_without_dtype (assert torch.float32 == torch.float16).
  • Checked by hand on CPU (transformers 5.5.4 and 5.18.0), not in the test:

    • a non-None device_map or quantization_config raises the ValueError above, and with None both load;
    • an unknown kwarg raises a TypeError from from_config() before quantization;
    • use_cache=False reaches the config;
    • revision and token are accepted, as no-ops for a local directory, as in from_pretrained();
    • experts_implementation and offload_buffers load;
    • torch_dtype=torch.bfloat16 with a config= that has no dtype builds the model in bfloat16; without the torch_dtype→dtype mapping the float16 fallback would win.
  • End-to-end, loading the way hf_ptq.py --low_memory_mode does (init_quantized_weights(NVFP4_DEFAULT_CFG) + load_pretrained(..., attn_implementation="sdpa")): a tiny tied llama and a local copy of Qwen/Qwen2.5-0.5B-Instruct raise the TypeError above on main. With this PR they load, also with local_files_only=True passed through load_pretrained(). No parameters are left on meta, and lm_head stays tied.

  • Environment: GB10 (SM121, aarch64) in nvcr.io/nvidia/vllm:26.05.post1-py3 (torch 2.12.0a0, transformers 5.6.0, accelerate 1.15.0). test_real_quantize_linear also passes on CPU with torch 2.14.1 and transformers 5.5.4 and 5.18.0.

  • Not run: the full hf_ptq.py --low_memory_mode calibrate-and-export flow.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ (no API change; a config without a dtype now builds in float16, the intended fallback, instead of float32; attn_implementation, local_files_only, revision, token and use_cache=False, which raised a TypeError at dispatch, now load, and an unknown kwarg now raises in from_config() before quantization)
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: N/A
  • Did you get Claude approval on this PR?: ❌ (the Claude bot review of ddea80c was LGTM with one open item, a human sign-off on the test edit; it hasn't run on this head)

Additional Information

With #2951 and this PR, hf_ptq.py --low_memory_mode loads with --attn_implementation.

Disclosure: prepared with assistance from Claude (Anthropic); everything listed under Testing was run on the hardware stated there.

🤖 Generated with Claude Code

…tie_weights

Two defects on the init_quantized_weights path (also reached via
hf_ptq.py --low_memory_mode):

1. patched_from_pretrained forwarded **kwargs verbatim into
   load_checkpoint_and_dispatch(), so any model-construction kwarg raised
   TypeError. attn_implementation is the common case:
   'load_checkpoint_and_dispatch() got an unexpected keyword argument
   attn_implementation'. It now goes to cls.from_config(), where it belongs.

2. tie_weights() was never called before quantization. Tied parameters such
   as lm_head.weight (tie_word_embeddings=true, e.g. Qwen2.5-0.5B) are not
   present in the checkpoint, so they stayed on meta and dispatch_model()
   raised 'Cannot copy out of meta tensor; no data!'. accelerate documents
   tie_weights() as a prerequisite of load_checkpoint_and_dispatch().

Reproduced with Qwen/Qwen2.5-0.5B-Instruct, nvfp4, --low_memory_mode on
modelopt 0.43.0; both failures occur before any weight is written.

Note: these two fixes let the path run to completion but do not make its
output correct - see NVIDIA#2160 for the separate root-cause defect (quantization
runs on meta tensors before real weights are loaded).

Signed-off-by: spped2000 <[email protected]>
Co-authored-by: Claude <[email protected]>
Signed-off-by: spped2000 <[email protected]>
@spped2000
spped2000 requested a review from a team as a code owner August 12, 2026 08:31
@copy-pr-bot

copy-pr-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: f5caf057-db1c-4aae-ab67-4874054895f9

📥 Commits

Reviewing files that changed from the base of the PR and between baeb792 and 407a919.

📒 Files selected for processing (1)
  • tests/unit/torch/quantization/plugins/test_accelerate.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/unit/torch/quantization/plugins/test_accelerate.py
Walkthrough

patched_from_pretrained separates construction and checkpoint-loading arguments, resolves dtype aliases with fallbacks, forwards attn_implementation, ties model weights, and passes the resolved dtype to checkpoint dispatch.

Changes: Accelerate loading

Layer / File(s) Summary
Model loading and weight tying
modelopt/torch/quantization/plugins/accelerate.py, tests/unit/torch/quantization/plugins/test_accelerate.py
patched_from_pretrained resolves dtype precedence, forwards attn_implementation to from_config, removes unsupported loader arguments, ties model weights, and passes the resolved dtype to checkpoint dispatch. Tests cover aliases, configuration fallback, default torch.float16, and consumed kwargs.

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

Suggested reviewers: kinjalpatel27

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.
Security Anti-Patterns Passed The PR changes only accelerate.py and its test; added-line scans found no forbidden deserialization, remote-code, eval/exec, or # nosec patterns, and no dependency changes.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main defect and its area: kwargs from from_pretrained leak into dispatch and the dtype fallback is broken in init_quantized_weights. The raw summary and objectives confirm that the…
Full details: Title check

Explanation

The title names the main defect and its area: kwargs from from_pretrained leak into dispatch and the dtype fallback is broken in init_quantized_weights. The raw summary and objectives confirm that the change routes construction kwargs to from_config, consumes dtype aliases, and fixes the float16 fallback. The title is specific and on topic. It is long at 92 characters, but it still conveys the primary change.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

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

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.

👉 Steps to fix this

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 `@modelopt/torch/quantization/plugins/accelerate.py`:
- Around line 225-237: Update the model-construction kwargs handling around
cls.from_config to pop both dtype and torch_dtype from kwargs before
load_checkpoint_and_dispatch receives them, while preserving the existing
precedence and fallback selection. Pass the normalized selected value explicitly
as dtype= when constructing the model, and ensure neither alias remains in
kwargs.
🪄 Autofix

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: 52088e16-a681-425e-86ca-e488c54f6b0d

📥 Commits

Reviewing files that changed from the base of the PR and between a21173a and 38c2536.

📒 Files selected for processing (1)
  • modelopt/torch/quantization/plugins/accelerate.py

…citly

CodeRabbit correctly noted that dtype/torch_dtype were read with kwargs.get()
and therefore stayed in kwargs. load_checkpoint_and_dispatch() accepts dtype
but NOT torch_dtype, so a caller using the legacy alias hit the same TypeError
class this PR fixes for attn_implementation.

Both aliases are now popped, precedence (dtype > torch_dtype > config) is
unchanged, and the resolved value is passed explicitly to
load_checkpoint_and_dispatch() so weight casting behaves exactly as before for
callers who passed dtype.

Signed-off-by: spped2000 <[email protected]>
Co-authored-by: Claude <[email protected]>
Signed-off-by: spped2000 <[email protected]>
@spped2000

Copy link
Copy Markdown
Contributor Author

Good catch, fixed and pushed.

Confirmed the concern is real: inspect.signature(accelerate.load_checkpoint_and_dispatch) accepts dtype but not torch_dtype, so a caller using the legacy alias hit the same TypeError class this PR fixes for attn_implementation — kwargs.get() left it in place.

Both aliases are now popped, precedence (dtype > torch_dtype > config.torch_dtype > fp16) is unchanged, and I pass the resolved value explicitly as dtype= to load_checkpoint_and_dispatch() rather than dropping it — otherwise callers who previously passed dtype would silently lose the weight cast on load.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
modelopt/torch/quantization/plugins/accelerate.py (1)

236-266: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Use config.dtype for the fallback.

When config.dtype is None, config.torch_dtype also returns None because it is a deprecated alias. The model is then constructed with the default float32, and load_checkpoint_and_dispatch() receives dtype=None. This bypasses the intended float16 fallback and can cause low-memory loading failures.

Use getattr(config, "dtype", None) or torch.float16 and add a regression test for a config without a dtype.

🤖 Prompt for 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.

In `@modelopt/torch/quantization/plugins/accelerate.py` around lines 236 - 266,
Update the torch_dtype fallback in the model construction flow to use
config.dtype, defaulting to torch.float16 when it is missing or None; do not use
the deprecated config.torch_dtype alias. Ensure the resolved dtype is passed
consistently to both cls.from_config and load_checkpoint_and_dispatch, and add a
regression test covering a configuration without a dtype.
🤖 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.

Outside diff comments:
In `@modelopt/torch/quantization/plugins/accelerate.py`:
- Around line 236-266: Update the torch_dtype fallback in the model construction
flow to use config.dtype, defaulting to torch.float16 when it is missing or
None; do not use the deprecated config.torch_dtype alias. Ensure the resolved
dtype is passed consistently to both cls.from_config and
load_checkpoint_and_dispatch, and add a regression test covering a configuration
without a dtype.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e4aab36c-0c2b-49d9-8a1d-2cd43f0eec59

📥 Commits

Reviewing files that changed from the base of the PR and between 38c2536 and 2939044.

📒 Files selected for processing (1)
  • modelopt/torch/quantization/plugins/accelerate.py

…regression test

getattr(config, "torch_dtype", torch.float16) never reaches its default on
transformers >= 5: torch_dtype is a deprecated alias of dtype that RETURNS
None when unset rather than being absent, so the attribute exists and getattr
hands back None. The model was then built as float32 and dtype=None reached
load_checkpoint_and_dispatch, on the code path whose entire purpose is loading
under tight memory.

Verified on transformers 5.13.1:
  PretrainedConfig().torch_dtype -> None
  getattr(cfg, 'torch_dtype', torch.float16) -> None   # not float16

Reads config.dtype first, falls back to the alias, then to float16 explicitly.
Adds a unit test covering kwarg precedence, kwarg consumption, and the
no-dtype-in-config fallback.

Signed-off-by: spped2000 <[email protected]>
Co-authored-by: Claude <[email protected]>
Signed-off-by: spped2000 <[email protected]>
@spped2000

Copy link
Copy Markdown
Contributor Author

Third finding addressed (the out-of-diff one) — and it reproduces, so thank you for catching it.

Verified on transformers 5.13.1:

>>> PretrainedConfig().torch_dtype
None
>>> getattr(PretrainedConfig(), "torch_dtype", torch.float16)
None          # not float16 — the getattr default never fires

Because torch_dtype is a deprecated alias that returns None rather than being absent, the existing getattr(config, "torch_dtype", torch.float16) yields None whenever the config carries no dtype. The model is then constructed as float32 and dtype=None reaches load_checkpoint_and_dispatch() — on the one code path whose purpose is loading under tight memory. Pre-existing, but squarely in the lines this PR touches.

Now reads config.dtype first, then the alias, then falls back to float16 explicitly. Added test_init_quantized_weights_dtype_resolution covering kwarg precedence, kwarg consumption (so neither alias leaks into dispatch), and the no-dtype-in-config fallback; assertions verified against transformers 5.13.1.

Note the PR now carries three distinct fixes. Happy to split the dtype one out if you would rather review them separately.

@spped2000
spped2000 requested a review from a team as a code owner August 12, 2026 09:18

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

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.

👉 Steps to fix this

Actionable comments posted: 2

🤖 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/unit/torch/quantization/plugins/test_accelerate.py`:
- Line 94: At module scope in the test module, guard the optional dependency
with pytest.importorskip("transformers"), then move the PretrainedConfig import
into the top-level module imports alongside the other imports. Remove any
deferred or test-local PretrainedConfig import while preserving the existing
test behavior.
- Around line 85-93: Update test_init_quantized_weights_dtype_resolution to
invoke the real patched_from_pretrained loader with checkpoint I/O stubbed,
rather than testing a local resolve() helper. Configure conflicting dtype
sources and a non-None deprecated config.torch_dtype, then assert
init_quantized_weights/from_config receives the selected dtype and
attn_implementation, while load_checkpoint_and_dispatch receives only the
supported dispatch arguments; cover the precedence dtype > torch_dtype >
config.dtype > config.torch_dtype > torch.float16.
🪄 Autofix

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: 172afdc2-0dc2-4fc0-ac70-80e4040120ad

📥 Commits

Reviewing files that changed from the base of the PR and between 2939044 and b675631.

📒 Files selected for processing (2)
  • modelopt/torch/quantization/plugins/accelerate.py
  • tests/unit/torch/quantization/plugins/test_accelerate.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • modelopt/torch/quantization/plugins/accelerate.py

The previous test asserted against a local mirror of the resolution logic, so
it would have passed even if patched_from_pretrained were broken. It now drives
the real init_quantized_weights context manager with checkpoint I/O stubbed
(mtq.quantize/compress, the accelerate device-map helpers and
load_checkpoint_and_dispatch are patched) and asserts what each callee
actually receives:

- from_config gets the resolved dtype and attn_implementation;
- dispatch receives neither torch_dtype nor attn_implementation, which it
  cannot accept, but does receive the resolved dtype;
- tie_weights() is called before quantization;
- with no dtype anywhere the float16 fallback fires, including the case where
  the deprecated config.torch_dtype alias returns None.

Verified it fails against the pre-PR implementation and passes with the fix.
Also moved the transformers import to module scope behind
pytest.importorskip, per review.

Signed-off-by: spped2000 <[email protected]>
Co-authored-by: Claude <[email protected]>
Signed-off-by: spped2000 <[email protected]>
@spped2000

Copy link
Copy Markdown
Contributor Author

Both review points addressed — the first one was a fair hit and I have rewritten the test.

The test was testing a copy of the logic, not the code. As written it mirrored the resolution order in a local resolve() helper, so it would have passed even with patched_from_pretrained completely broken. It now drives the real init_quantized_weights context manager with the checkpoint I/O stubbed (mtq.quantize/compress, the accelerate device-map helpers, and load_checkpoint_and_dispatch) and asserts what each callee actually receives:

  • from_config gets the resolved dtype and attn_implementation;
  • dispatch receives neither torch_dtype nor attn_implementation (which it cannot accept) but does receive the resolved dtype;
  • tie_weights() runs before quantization;
  • with no dtype anywhere the float16 fallback fires — including the case where the deprecated config.torch_dtype alias returns None.

I checked it actually protects the code: reverting accelerate.py to the pre-PR implementation makes it fail on the attn_implementation assertion, and it passes with the fix. Full file: 3 passed.

transformers import moved to module scope behind pytest.importorskip, as suggested.

(One note on the suggested precedence dtype > torch_dtype > config.dtype > config.torch_dtype > float16 — that is exactly what is implemented; config.dtype is read first and the alias only serves older transformers where dtype does not exist.)

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

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.

👉 Steps to fix this

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/unit/torch/quantization/plugins/test_accelerate.py`:
- Line 98: Move the accel_plugin import from the test method to module scope,
placing it after the module-level pytest.importorskip("transformers") guard.
Keep the existing test behavior unchanged; only retain a deferred import if an
optional-dependency constraint requires it, and document that reason briefly.
🪄 Autofix

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: 4c7fe034-d661-4717-b8eb-1ba87daae621

📥 Commits

Reviewing files that changed from the base of the PR and between b675631 and baeb792.

📒 Files selected for processing (1)
  • tests/unit/torch/quantization/plugins/test_accelerate.py

Per the repo's coding guidelines, imports belong at the top of test files. The
plugin import now sits after the module-level accelerate/transformers guards.

Signed-off-by: spped2000 <[email protected]>
Co-authored-by: Claude <[email protected]>
Signed-off-by: spped2000 <[email protected]>
@spped2000

Copy link
Copy Markdown
Contributor Author

Done — accel_plugin now imports at module scope, right after the accelerate skip guard and pytest.importorskip("transformers"), with an # noqa: E402 since it necessarily follows those guards. Full test file still 3 passed.

That is all five review points from this round addressed. Summary of where the PR stands: three independent fixes on the init_quantized_weights path (kwargs routing, tie_weights(), dtype fallback) plus one regression test that drives the real loader. Root-cause defect on the same path — quantization running on meta tensors before weights load — remains #2160 and is deliberately out of scope here.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

Thanks for the contribution! This PR now has merge conflicts with main. Could you update your branch with the latest main and fix the conflicts so we can continue the review?

We've added the waiting for feedback label while we wait for your update.

spped2000 and others added 3 commits October 27, 2026 14:50
…eights

Resolve conflicts with NVIDIA#2951 in accelerate.py and NVIDIA#2665 in
test_accelerate.py. NVIDIA#2951 added the same model.tie_weights() call after
from_config(): keep upstream's call and comment, drop this branch's
duplicate. In test_accelerate.py keep both NVIDIA#2665's buffer-offload test and
this branch's kwargs/dtype routing test.

Signed-off-by: spped2000 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replace the mock-based unit test with two cases in test_real_quantize_linear,
which loads a tiny llama through init_quantized_weights: torch_dtype plus
attn_implementation (TypeError on main) and a config without a dtype
(float32 instead of float16 on main).

Signed-off-by: spped2000 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pass the resolved dtype to from_config() only. load_checkpoint_and_dispatch()
gets a dtype only when the caller supplied one (dtype, or torch_dtype mapped
to dtype), so a load without one dispatches exactly as on main. Resolve the
dtype from config.dtype with an explicit float16 fallback (config.torch_dtype
is only an alias of it) and trim the comments; the root-cause notes live in
the PR description.

Signed-off-by: spped2000 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@spped2000 spped2000 changed the title Fix init_quantized_weights: model kwargs leak into dispatch, missing tie_weights() Fix init_quantized_weights: model kwargs leak into dispatch, broken dtype fallback Oct 27, 2026
@spped2000

Copy link
Copy Markdown
Contributor Author

Thanks @kevalmorabia97, merged the latest main and resolved the conflicts.

#2951 landed the same tie_weights() fix in the meantime, so I dropped mine in favor of upstream's. This PR now carries only the other two fixes: model-construction kwargs (attn_implementation, torch_dtype) no longer reach load_checkpoint_and_dispatch(), and the float16 dtype fallback now actually fires. One change from the earlier revision: dispatch gets a dtype only when the caller passes one, as on main, so loads without a dtype (e.g. hf_ptq) dispatch exactly as on main. I also replaced the mock-based unit test with real-path cases in test_real_quantize_linear, per CONTRIBUTING. Title and description are updated.

New head: ddea80c7ee64180da927fe0256b7e30709ca0ef5. Ready for another look.

@shengliangxu shengliangxu 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 (bedrock-claude-opus-5-5) — DM the bot to share feedback.

LGTM: the fix is small and correct. It stops attn_implementation and torch_dtype from reaching load_checkpoint_and_dispatch(), makes the float16 fallback actually apply, and adds GPU regression cases on the real load path.

Needs action:

  • Sign off as a human on the edit to the existing test_real_quantize_linear in tests/gpu/torch/quantization/test_real_quantize_cuda.py. The edit is justified: the original case stays as the config_dtype param with its assertions unchanged, and the two new params only add dtype and attn checks.

No action needed:

  • The repo pins transformers>=5.5, so config.dtype always exists. Dropping the config.torch_dtype read doesn't break older versions.
  • The caller's dtype is still forwarded to dispatch as dtype=, the same way main already did, so dispatch behaves as before.
  • No licensing changes, and the PR is well under the size budget.

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

Mostly correct; one remaining gap to fix. I reproduced the getattr(config, "torch_dtype", ...) returning None bug, and the new dtype > torch_dtype > config.dtype > float16 chain fixes it. The GPU test covers both fixes.

Needs action:

  • Stop other from_pretrained kwargs from reaching load_checkpoint_and_dispatch() (inline on accelerate.py); only two are handled today.

No action needed:

  • Keep accepting the legacy torch_dtype here: init_quantized_weights is public and transformers>=5.5 still accepts it with a deprecation warning. Reading config.torch_dtype elsewhere in modelopt/ is tracked in a separate follow-up PR.
  • Not on a setup-owned path, no licensing change, no changelog entry needed for this fix.

…l takes

Split the kwargs by what each call takes instead of listing the ones
dispatch can't take. load_checkpoint_and_dispatch() gets only the kwargs
in its signature. Without a config= kwarg,
AutoConfig.from_pretrained(return_unused_kwargs=True) takes the Hub
options (revision, token, local_files_only, ...) and any config
attributes, as from_pretrained() does; from_config() gets the rest and
raises on any the model does not take. subfolder is joined into the
checkpoint path, as load_pretrained() does, so the config and the weights
are read from the same place. A non-None device_map or quantization_config
is refused up front, since this loader computes the device map and
quantizes with quant_cfg.

Add hub_kwargs (local_files_only=True, which load_pretrained() forwards)
and subfolder cases to test_real_quantize_linear, and pass
attn_implementation with the config= of config_without_dtype so a kwarg
reaches from_config().

Signed-off-by: spped2000 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@spped2000 spped2000 changed the title Fix init_quantized_weights: model kwargs leak into dispatch, broken dtype fallback Fix init_quantized_weights: from_pretrained kwargs leak into dispatch, broken dtype fallback Oct 27, 2026
@spped2000

Copy link
Copy Markdown
Contributor Author

Re the bot's checklist item: I reviewed the edit to the existing test_real_quantize_linear and confirm it's intended. The original load is kept as the config_dtype param with its tie and QTensorWrapper checks unchanged, plus a new check that the model is built in the checkpoint's bfloat16. The new params (model_kwargs, config_without_dtype, hub_kwargs, subfolder) only vary the load kwargs and the expected dtype/attn implementation; for subfolder, the load starts from the parent directory.

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

Approving: the kwargs routing is now correct and tested, and it closes the one ask from my earlier review.

No action needed.

No action needed:

  • ✔️ Resolved since the last review: other from_pretrained kwargs no longer reach load_checkpoint_and_dispatch(); quantization_config and device_map now fail with a clear error.
  • dtype="auto" still fails with an AttributeError; not introduced here, fine as a follow-up.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/ok to test ef0dcc4

@kevalmorabia97
kevalmorabia97 enabled auto-merge (squash) October 27, 2026 15:48
@codecov

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.54%. Comparing base (aed61b7) to head (ef0dcc4).
⚠️ Report is 15 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2161      +/-   ##
==========================================
- Coverage   79.94%   78.54%   -1.40%     
==========================================
  Files         661      661              
  Lines       75417    77921    +2504     
==========================================
+ Hits        60291    61203     +912     
- Misses      15126    16718    +1592     
Flag Coverage Δ
examples-diffusers 19.92% <13.33%> (-0.03%) ⬇️
examples-gpt-oss 13.44% <13.33%> (-0.01%) ⬇️
examples-hf_ptq 23.44% <13.33%> (+0.04%) ⬆️
examples-llm_distill 13.52% <13.33%> (-0.01%) ⬇️
examples-llm_eval 17.21% <13.33%> (-0.02%) ⬇️
examples-llm_qat 17.38% <13.33%> (-0.06%) ⬇️
examples-llm_sparsity 16.73% <13.33%> (-0.02%) ⬇️
examples-megatron_bridge 26.45% <13.33%> (-0.30%) ⬇️
examples-specdec_bench 13.22% <13.33%> (-0.01%) ⬇️
examples-speculative_decoding 17.46% <13.33%> (-0.08%) ⬇️
examples-torch_onnx 21.22% <13.33%> (-0.06%) ⬇️
examples-torch_trt 15.19% <13.33%> (-0.01%) ⬇️
examples-vllm_serve 17.42% <13.33%> (-0.02%) ⬇️
gpu 59.14% <100.00%> (-1.18%) ⬇️
regression 15.03% <13.33%> (-0.02%) ⬇️
unit 61.43% <13.33%> (+0.03%) ⬆️

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.

kevalmorabia97 added a commit that referenced this pull request Oct 27, 2026
…3049)

### What does this PR do?

Type of change: Bug fix

`config.torch_dtype` is a deprecated alias of `config.dtype`
(transformers>=5.5) that returns `None` when unset instead of raising,
so a `getattr(config, "torch_dtype", default)` never reaches its
default. This reads `config.dtype` directly in:

- `modelopt/torch/export/plugins/hf_spec_export.py`: the DFlash export
wrote the string `"None"` as `torch_dtype` for a base config without a
dtype; it now falls back to `bfloat16`.
- `modelopt/torch/export/unified_export_hf.py`: `_resolve_export_dtype`
now reads `config.dtype` (behavior unchanged, no deprecation warning).
- `modelopt/torch/opt/plugins/transformers.py`: dropped the redundant
`torch_dtype` fallback.

Left unchanged: the `"torch_dtype"` keys written to exported
`config.json` files and the eagle/spec-dec default configs (on-disk
format), and the legacy `torch_dtype=` kwarg accepted by
`init_quantized_weights` (public API; handled in #2161).

Related: #2161 (same defect in `init_quantized_weights`).

### Usage

N/A, no API change.

### Testing

- `tests/unit/torch/export/test_hf_spec_rope_export.py` and
`test_unified_export_hf.py`: 69 passed (CPU). The new
`test_dflash_torch_dtype_inherits_base_or_defaults` uses a real
`LlamaConfig` and fails without the fix for the unset-dtype case.
- `tests/unit/torch/opt` transformers tests fail at collection with and
without this change in my environment (`TypeError` on `None`), so the
trainer change is covered only by inspection.

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

- Is this change backward compatible?: ✅
- Did you write any new necessary tests?: ✅
- Did you update Changelog?: N/A (internal fix)

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


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

## Summary by CodeRabbit

* **Bug Fixes**
* Exported models now use the configured data type when available, with
a bfloat16 fallback when the configuration does not specify one.
* Data type selection and mismatch warnings now reflect the model’s
configured data type.
* Export behavior is more consistent when configurations provide a data
type through the current configuration field, including when the value
is missing or `None`.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Keval Morabia <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>

@shengliangxu shengliangxu 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 (bedrock-claude-opus-5-5) — DM the bot to share feedback.

LGTM: every earlier concern is fixed, and the kwargs routing and dtype fallback are correct with real-path GPU tests. A human still has to sign off on the edit to an existing test.

Needs action:

  • Sign off on the edit to the existing test_real_quantize_linear in tests/gpu/torch/quantization/test_real_quantize_cuda.py. The edit is justified: the original load stays as the config_dtype case with its tie and QTensorWrapper checks unchanged and one dtype check added. The four new params only change the load kwargs and the expected dtype or attention implementation. kevalmorabia97's approval may already cover this.

No action needed:

  • ✔️ Resolved since the last review: torch_dtype leaking into dispatch, the config.dtype fallback, the mirrored-logic unit test (replaced by real-path cases), and routing every other from_pretrained kwarg by the callee's signature.
  • Nothing that loaded on main fails now. Kwargs in dispatch's signature still reach it, and every other kwarg already raised a TypeError at dispatch.
  • About 35 added logic lines. No licensing change and no CHANGELOG entry needed.

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

Pensieve lgtm review using kmorabia's profile (revision 4).

LGTM: kwargs are now routed by what each callee accepts and the float16 dtype fallback is fixed, but a human must sign off on the edit to an existing test.

Needs action:

  • Sign off on the edit to test_real_quantize_linear in tests/gpu/torch/quantization/test_real_quantize_cuda.py. It looks justified: the original load stays as the config_dtype case with its tie and QTensorWrapper assertions unchanged, and one dtype check is added. The four new params only vary the load kwargs and the expected dtype or attention implementation.

No action needed:

  • ✔️ Resolved since the last review: other from_pretrained kwargs reaching load_checkpoint_and_dispatch() (now filtered via inspect.signature), torch_dtype leaking into dispatch, and the config.dtype fallback. See the earlier review comments in the history.
  • trust_remote_code still reaches only the config load, so a remote-code model class can still fail in from_config(). This predates the PR and the author offered a follow-up; I am not blocking on it.
  • dtype="auto" still fails with an AttributeError. It predates this PR and is fine as a follow-up.
  • About 35 added core lines. No licensing, setup-owned path or changelog concerns.
  • Limitation: I could not run tests or check transformers and accelerate behavior here. The new GPU cases and the author's reported mutation checks (reverting each fix fails its own case) were reviewed from the diff and description only. The history was checked for duplicates and no new inline finding repeats it.

Review run: 5c97326f0fae44c5a4b7958f75833768

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