Skip to content

[OMNIML-6080] Derive the unplaced source keys once, at load, through a core load_pretrained - #2733

Merged
shengliangxu merged 16 commits into
mainfrom
shengliangx/fix-carry-load-time-conversions
Oct 22, 2026
Merged

shengliangxu merged 16 commits into
mainfrom
shengliangx/fix-carry-load-time-conversions

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Type of change: Bug fix, new API

The export carries every checkpoint tensor the model has no parameter for (an MTP head, an auxiliary tower) into the exported checkpoint unchanged. On main, that list comes from two accountings, unioned at export:

  • the loader's unexpected_keys, recorded by hf_ptq at load;
  • a structural pass over the checkpoint index, run again at export.

Each covers a blind spot of the other: Transformers drops from unexpected_keys whatever an architecture's _keys_to_ignore_on_load_unexpected matches (Qwen3-Next ^mtp.*, DeepSeek-V3 and GLM their MTP layers), and the index can omit a tensor a shard holds. But the union carries either one's mistakes, and the structural pass made one: it replayed only the model's stock conversion mapping, so tensors that loading folds into the weights read as unplaced, and the export carried them beside the weights they became:

  • Mxfp4Config(dequantize=True), which hf_ptq uses for gpt-oss, folds each expert's *_blocks/*_scales into bf16 gate_up_proj/down_proj;
  • FineGrainedFP8Config(dequantize=True) folds every FP8 weight_scale_inv into its weight;
  • an on-the-fly compressed-tensors decompressor feeds weight_packed experts in.

On main this hits gpt-oss. It was found on an expert-parallel Kimi-K3 export through a decompressor, which carried 494,592 packed expert tensors: the checkpoint grew from 1.5 TB to 2.8 TB, and rank 0 spent 21 of the run's 37 minutes writing them.

Fix: work the list out once, at load time; the export only reads it.

  • unplaced_source_keys takes every tensor in the files the loader opens, from their headers so a tensor the index omits is included, maps each through the conversions the load ran, and keeps those that land on no parameter. The conversions are _weight_conversions (Transformers' record of what from_pretrained ran, quantizer and patch additions included) plus the stock mapping. Neither unexpected_keys nor the ignore rules play any part.
  • The loaders record it on the model: the new load_pretrained, and parallel_load_and_prepare_fsdp2 from the single pass it already makes. A model loaded another way, by a caller's own from_pretrained, gets the same derivation once at export, recorded so nothing repeats it.
  • load_pretrained is hf_ptq's recording loader moved into the core library. It makes a Hub checkpoint local (ensure_local_checkpoint, at the revision, token, cache_dir and local_files_only it is given), runs the model type's loading hook (prepare_model_for_loading), loads, and records. Every hf_ptq load path now goes through it, the low-memory one included.
    • With local_files_only=True, as with HF_HUB_OFFLINE, a Hub ID resolves from the cache alone, without asking the Hub; one that is not cached raises.
    • It returns the model alone, so output_loading_info=True, which would make from_pretrained return a tuple, is refused before anything resolves or loads.

Usage

from transformers import AutoModelForCausalLM

from modelopt.torch.export import export_hf_checkpoint
from modelopt.torch.utils.plugins.model_load_utils import load_pretrained

model = load_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct", AutoModelForCausalLM, dtype="auto")
# ... mtq.quantize(model, ...) ...
export_hf_checkpoint(model, export_dir="qwen3-next-nvfp4")  # carries the MTP head the model never loaded

Testing

  • ensure_local_checkpoint options. revision, token and cache_dir reach every Hub call, whether the Hub is online, unreachable or offline, and load_pretrained hands its own over, local_files_only included (tests/unit/torch/utils/test_hf_checkpoint_utils.py, test_unplaced_source_keys.py). The cache-only tests run for HF_HUB_OFFLINE and for local_files_only=True: the Hub is never asked, and an uncached checkpoint raises naming the cause.
  • output_loading_info=True is refused before resolution: load_pretrained("no/such/checkpoint", output_loading_info=True) raises about the option, not about the unresolvable path.
  • tests/unit/torch/utils/test_unplaced_source_keys.py drives a real from_pretrained on CPU through load_pretrained:
    • an FP8-block Llama and a gpt-oss, both with dequantize=True: only the genuinely stray tensor is recorded (before this PR, every FP8 scale, 7, and every expert block/scale tensor, 4, was carried as well);
    • an architecture whose ignore rule matches ^mtp\.: the MTP tensor is recorded, though Transformers' own unexpected_keys comes back empty for it;
    • a tensor the index omits: recorded;
    • per-expert tensors of a layer the model does not build: recorded under their on-disk names, not the fused one.
    • Mutation-checked: an index-only listing, a stock-only mapping, or an export that does not record its derivation each fails its test.
  • Export: a recorded empty list is not derived again, checked against the real derivation, which would find the model's stray tensor if the record were ignored; an unrecorded model derives once, then reads its record.
  • Test trim: duplicate cases fold into the tests that cover them, and the hf_ptq example tests that repeated these unit tests on the same loader are dropped. Each drop is checked by mutation.
  • Locally on this revision, rebased on main 264fd26: the full unit suite on transformers 5.18, and on 5.5 apart from the tests whose ONNX, TensorRT or diffusers packages that environment lacks; CI's transformers-free unit lane; pre-commit over the whole PR against main; and the Sphinx docs build. The same at every PR of the stack.
  • GPU, against main, on an earlier revision of this PR (tests/gpu/torch/export and tests/gpu/torch/utils/test_model_load_utils.py, 179 tests, on 1, 2 and 4 GPUs): no outcome changes, 0 failures. The FSDP2 distributed export still carries a layer the model does not build (test_fsdp2_distributed_export_carries_unplaced_weights_from_provenance).
  • Kimi-K3 expert-parallel export (16 nodes, EP64) through a decompressor, with the first version of this fix (the same mapping, applied at export): 995,715 keys, 1.5 TB, matching a reference export key for key.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ The carry-over is new in the unreleased 0.48.0 cycle. Within it, record_unplaced_source_keys now derives the keys itself instead of taking the loader's unexpected_keys.
  • 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?: ✅ The 0.48.0 carry-over entry now describes the load-time record and names load_pretrained.
  • Did you get Claude approval on this PR?: ❌ Not yet.

Additional Information

Prerequisite of the HF expert-parallel PTQ (hfep) stack, which is rebased on top of it.

Summary by CodeRabbit

  • Bug Fixes

    • Improved checkpoint handling during model loading and export, including weights omitted from checkpoint indexes.
    • Preserved applicable unplaced weights for more reliable model export.
    • Improved support for quantized and converted checkpoints during loading.
  • New Features

    • Added support for model revisions, access tokens, and cache directories when resolving Hugging Face checkpoints.
    • Added cache-only checkpoint resolution for offline use, with clear errors when checkpoints are unavailable locally.
    • Updated model-loading examples to use the improved checkpoint handling.

@copy-pr-bot

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

Copy link
Copy Markdown
Contributor

Review in 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
📝 Walkthrough

Checkpoint loading now records source tensors that do not map to model parameters or buffers. HF PTQ paths use load_pretrained. Checkpoint resolution forwards Hub options, and export reuses recorded keys or derives them when needed.

Changes: Hugging Face unplaced-weight tracking

Layer / File(s) Summary
Checkpoint inventory and Hub resolution
modelopt/torch/utils/plugins/hf_checkpoint_utils.py, tests/unit/torch/utils/test_hf_checkpoint_utils.py
Checkpoint utilities scan shard headers for tensors absent from the index. ensure_local_checkpoint accepts revision, token, cache-directory, and local-only options.
Conversion-aware key detection and recording
modelopt/torch/utils/plugins/model_load_utils.py, tests/unit/torch/utils/test_unplaced_source_keys.py
load_pretrained loads localized checkpoints and records source keys that do not map to model parameters or buffers. The FSDP2 path uses the shared recording function.
Loader adoption and export carry-over
examples/hf_ptq/*, modelopt/torch/export/..., tests/examples/hf_ptq/*, tests/unit/torch/export/test_unified_export_hf.py, CHANGELOG.rst
HF PTQ paths use load_pretrained. Export returns recorded keys when present and derives and records them when absent.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant HFPTQExample
  participant load_pretrained
  participant ensure_local_checkpoint
  participant AutoModelForCausalLM
  participant unplaced_source_keys
  participant checkpoint_tensor_files
  HFPTQExample->>load_pretrained: pass checkpoint and model arguments
  load_pretrained->>ensure_local_checkpoint: resolve checkpoint
  ensure_local_checkpoint-->>load_pretrained: return local checkpoint
  load_pretrained->>AutoModelForCausalLM: load model
  load_pretrained->>unplaced_source_keys: derive unplaced source keys
  unplaced_source_keys->>checkpoint_tensor_files: inventory checkpoint tensors
  checkpoint_tensor_files-->>unplaced_source_keys: return tensor-to-file mappings
  unplaced_source_keys-->>load_pretrained: return unplaced source keys
  load_pretrained->>load_pretrained: record keys on the model
Loading

Possibly related PRs

Suggested reviewers: kevalmorabia97

Merge Risk: 🔵 Low · up to a3e78

Export now reuses the unplaced checkpoint keys recorded at load time instead of re-deriving them, which avoids carrying unnecessary tensors. One gap remains. A model not loaded through the new loader, in an environment without the optional loader dependencies, can export with no MTP or auxiliary tensors carried. In that case the vLLM fake-quant export guard stays silent. This affects a narrow configuration, but it should be addressed or explicitly accepted before merge.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 65.75% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 73 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and specifically describes the main change: deriving unplaced source keys once during model loading through load_pretrained for reuse during export.
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 No listed security anti-pattern is introduced by the pull request. Added model loading uses trust_remote_code from caller kwargs with a default of False; no hardcoded trust_remote_code=True appe…
Full details: Security Anti-Patterns

Explanation

No listed security anti-pattern is introduced by the pull request. Added model loading uses trust_remote_code from caller kwargs with a default of False; no hardcoded trust_remote_code=True appears. Added code contains no unsafe torch.load, numpy.load(..., allow_pickle=True), eval()/exec() on input, or new # nosec comments. No pyproject.toml or requirements.txt dependency changes are present.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-22 18:27 UTC

@codecov

codecov Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.76543% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 78.98%. Comparing base (f983619) to head (204f98a).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
modelopt/torch/utils/plugins/model_load_utils.py 98.07% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2733      +/-   ##
==========================================
- Coverage   79.66%   78.98%   -0.68%     
==========================================
  Files         659      659              
  Lines       74400    74450      +50     
==========================================
- Hits        59272    58807     -465     
- Misses      15128    15643     +515     
Flag Coverage Δ
examples-diffusers 19.97% <3.70%> (-0.09%) ⬇️
examples-gpt-oss 13.48% <3.70%> (-0.07%) ⬇️
examples-hf_ptq 23.42% <86.41%> (-0.03%) ⬇️
examples-llm_distill 13.55% <3.70%> (-0.07%) ⬇️
examples-llm_eval 17.22% <59.25%> (-0.05%) ⬇️
examples-llm_qat 17.42% <3.70%> (-0.09%) ⬇️
examples-llm_sparsity 16.81% <39.50%> (-0.06%) ⬇️
examples-megatron_bridge 26.33% <6.17%> (-0.31%) ⬇️
examples-specdec_bench 13.26% <3.70%> (-0.06%) ⬇️
examples-speculative_decoding 17.48% <54.32%> (-0.08%) ⬇️
examples-torch_onnx 21.30% <3.70%> (-0.13%) ⬇️
examples-torch_trt 15.19% <3.70%> (-0.08%) ⬇️
examples-vllm_serve 17.43% <37.03%> (-0.07%) ⬇️
gpu 58.73% <81.48%> (-1.42%) ⬇️
regression 15.05% <3.70%> (-0.08%) ⬇️
unit 61.02% <96.29%> (+0.17%) ⬆️

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.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test c6c4454

@shengliangxu shengliangxu changed the title Don't carry source tensors a dequantizing load already folded into the weights [OMNIML-6080] Don't carry source tensors a dequantizing load already folded into the weights Oct 12, 2026
@shengliangxu shengliangxu changed the title [OMNIML-6080] Don't carry source tensors a dequantizing load already folded into the weights [OMNIML-6080] Derive the unplaced source keys once, at load, through a core load_pretrained Oct 13, 2026
@shengliangxu
shengliangxu force-pushed the shengliangx/fix-carry-load-time-conversions branch from c9fa3c0 to 052417a Compare October 13, 2026 01:32
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 052417a

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 052417a

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 7379399

@shengliangxu shengliangxu left a comment

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.

Codex bot review — generated by Codex and posted on behalf of @shengliangxu.

Reviewed revision: 73793998.

Changes

Moves checkpoint preparation, loading, and provenance recording into core load_pretrained. Derives unplaced source tensors from shard headers and the conversions actually used by the load, and lets export reuse that record.

Finding

[P2] Resolve the requested Hub revision before converting the checkpoint ID to a local path. In modelopt/torch/utils/plugins/model_load_utils.py, load_pretrained calls ensure_local_checkpoint(ckpt_path) without the caller’s revision. revision is forwarded only afterward to from_pretrained, whose input is already a local snapshot directory. A request for a pinned revision can therefore load the default revision’s weights.

A resolver-boundary probe confirmed that the loader receives /cache/snapshots/main together with revision="pinned-sha"; this was a wiring reproduction, not a two-revision Hub download test. Pass the revision and relevant cache/auth options into checkpoint resolution before reading the config or weights.

Scope: this PR’s changes within the #2733 → #2754 stack. Local execution used CPU; GPU/NCCL was not run.

@shengliangxu
shengliangxu force-pushed the shengliangx/fix-carry-load-time-conversions branch from a3e782f to ed528c9 Compare October 21, 2026 17:43
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test ed528c9

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 7939be9

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

Two P2 API edge cases reproduced with local synthetic checkpoints; details inline.

model_class=None if auto_class in (AutoModel, AutoModelForCausalLM) else auto_class,
):
model = auto_class.from_pretrained(ckpt_path, **hub_options, **kwargs)
unplaced = record_unplaced_source_keys(model, ckpt_path)

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.

[P2] Record provenance from the selected checkpoint variant

variant reaches from_pretrained through kwargs, but this recording call only receives the directory. checkpoint_tensor_files() then scans the default model.safetensors/index rather than the files actually selected by Transformers.

I reproduced this with a directory containing model.safetensors with default_aux.weight and model.fp16.safetensors with variant_aux.weight. load_pretrained(path, variant="fp16") loads the variant (Transformers reports variant_aux.weight), but records ['default_aux.weight']; read_unplaced_weights() subsequently carries that default tensor instead of the variant's auxiliary tensor. With only variant weights present, the recorded list is empty.

Could we thread the selected variant/files through provenance recording and subsequent source reads, or reject unsupported variants before loading? A regression with both files containing different auxiliary keys would catch this.

@shengliangxu shengliangxu Oct 22, 2026 •

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.

Fixed in 204f98a: load_pretrained now refuses a variant= with a ValueError before anything loads, as it does output_loading_info=True. The load-time record and the export's later source reads both use the checkpoint's default weight files, so refusing is safer than recording the wrong files. test_an_option_it_cannot_honor_is_refused_before_anything_loads[variant] covers it.

ckpt_path = os.path.join(ckpt_path, subfolder)
trust_remote_code = kwargs.get("trust_remote_code", False)
if model_type is None:
model_type = AutoConfig.from_pretrained(

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.

[P2] Honor an explicitly supplied config during model-type detection

The caller's config is forwarded to the actual model load, but this preceding lookup ignores it and requires a config on disk. I reproduced a local weights directory with model.safetensors and generation_config.json, but no config.json: AutoModelForCausalLM.from_pretrained(path, config=config) succeeds, whereas load_pretrained(path, config=config) raises ValueError here before loading.

Could we use the supplied PretrainedConfig object's model_type when available, and read from disk only when it is needed? That also makes the loading hook follow the configuration the model will actually use. Please cover the explicit-config/no-config-file case.

@shengliangxu shengliangxu Oct 22, 2026 •

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.

Fixed in 204f98a: when model_type is omitted, it now comes from the config passed for the load, and the checkpoint's config.json is read only when no config is passed. test_a_config_passed_for_the_load_needs_none_on_disk loads a directory that has generation_config.json but no config.json. Further up the stack, in #2779 (901a06d), the distribution plan is also decided from that config (resolve_distribution_plan(config=...), on a copy). A sharded load then builds from it as its hf_config, so the whole load follows the configuration the model actually uses.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test c27930b

The export carries every source tensor unplaced_source_keys reports, and
that pass replayed only the model's stock conversion mapping. Loading can add
to the mapping, and what it adds consumes tensors the stock mapping never
mentions:

- A dequantizing quantizer. Mxfp4Config(dequantize=True), which
  examples/hf_ptq uses for gpt-oss, folds each expert's *_blocks and *_scales
  into a bf16 gate_up_proj/down_proj; FineGrainedFP8Config(dequantize=True)
  folds every FP8 weight_scale_inv into its weight.
- A patched mapping, such as an on-the-fly decompressor that feeds
  compressed-tensors weight_packed/weight_scale experts in.

Each such tensor read as unplaced, so the export copied it in beside the
weight it had become. A tiny gpt-oss checkpoint loaded the way hf_ptq loads
it reports all four expert block/scale tensors; a tiny FP8-block Llama, all
seven scales. Found on an expert-parallel Kimi-K3 export through such a
decompressor: 494,592 packed expert tensors were carried, the checkpoint grew
from 1.5 TB to 2.8 TB, and rank 0 spent 21 of the run's 37 minutes writing
them.

from_pretrained records the conversions it actually ran on the model
(_weight_conversions, the list transformers' own save path replays), the
additions included. A key now counts as placed when either that record or
the stock mapping resolves it to a parameter: the record keeps only the
conversions some key used, so the stock mapping still answers for weights
one of our own loaders placed.

Signed-off-by: Shengliang Xu <[email protected]>
Reassigning the filtered list kept the type of its first assignment,
list[dict | None], so handing an element to _resolve_target failed type
checking. Filter a tuple of the two candidate plans into a fresh name instead.

Signed-off-by: Shengliang Xu <[email protected]>
Its 2-KV-head Llama had a 64x128 k_proj, which transformers before 5.10.1
cannot dequantize (partial block), so the test failed on CI's minimum
transformers (5.5) before reaching what it tests. Four KV heads make every
projection a whole number of blocks.

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

The export carried the checkpoint tensors a model has no parameter for from two
accountings, unioned at export time: the loader's unexpected_keys, recorded at
load, and a structural pass over the index, run again at export. Each covered a
blind spot of the other -- Transformers' ignore rules drop MTP keys from
unexpected_keys, and the index can omit a tensor a shard holds -- and the union
carried either one's mistakes.

One derivation replaces both, run once when the model loads. Every tensor in the
files the index names (their headers, not just the index) is mapped through the
conversions the load ran, _weight_conversions and the stock mapping, and is
recorded if it lands on no parameter. The export only reads the record; a model
loaded without ModelOpt's loaders gets the same derivation, once, at export.

hf_ptq's recording from_pretrained becomes the core API load_pretrained (local
checkpoint, the model type's loading hook, the record), so a model loaded outside
the example records too. The FSDP2 loader records from the single pass it
already makes.

Signed-off-by: Shengliang Xu <[email protected]>
The init_quantized_weights path called from_pretrained itself, so its unplaced
source keys were only worked out at export. It now loads like every other
hf_ptq path.

Signed-off-by: Shengliang Xu <[email protected]>
load_pretrained made a Hub ID local with ensure_local_checkpoint before
from_pretrained ran, and passed it neither the revision nor the token or
cache_dir: a pinned revision loaded the default branch's weights, and
from_pretrained, handed the local snapshot, ignored all three.

ensure_local_checkpoint now takes revision, token and cache_dir
(keyword-only, unset by default) and passes them to every Hub call, and
load_pretrained hands its own over to it.

Signed-off-by: Shengliang Xu <[email protected]>
load_pretrained made a Hub ID local before from_pretrained ran, and
local_files_only did not reach that step: unless HF_HUB_OFFLINE was set,
ensure_local_checkpoint asked the Hub for the repo and downloaded the
snapshot, and from_pretrained, handed the local snapshot, had nothing
left to honor it for.

ensure_local_checkpoint now takes local_files_only (keyword-only, off by
default) and with it resolves a Hub ID as it does under HF_HUB_OFFLINE:
from the cache alone, with no Hub call, and an error naming the option
when the snapshot is not cached. load_pretrained hands it over with
revision, token and cache_dir.

Signed-off-by: Shengliang Xu <[email protected]>
load_pretrained passed output_loading_info=True through to
from_pretrained, which then returned (model, loading_info): after the
whole checkpoint had loaded, record_unplaced_source_keys failed on the
tuple ('tuple' object has no attribute 'named_parameters').

load_pretrained returns the model alone, with the checkpoint tensors it
has no parameter for recorded on it, so it now refuses
output_loading_info=True with a ValueError before it resolves or loads
the checkpoint.

Signed-off-by: Shengliang Xu <[email protected]>
Three tests imported their transformers classes inside the test body.
Every one of them exists from transformers 5.5, the supported minimum,
so they now join LlamaConfig at module scope, after the importorskip
guards that already skip the module without transformers.

Signed-off-by: Shengliang Xu <[email protected]>
Its stub raised inside unplaced_keys_for's except-Exception, which warns
and returns [], so the test passed even when the export derived the keys
again. Without the stub, deriving again finds the checkpoint's stray
tensor, which the model has no parameter for, and carries it; the test's
assert now catches that.

Signed-off-by: Shengliang Xu <[email protected]>
- test_records_an_empty_list_when_every_tensor_was_placed becomes the
  nothing-stray case of test_records_the_stray_tensors_and_the_checkpoint.
- test_ensure_local_checkpoint_fetches_the_revision_it_is_asked_for folds
  into the per-mode tests: online, unreachable and cache-only now each
  pass a revision, token and cache dir, and check that repo_info and
  snapshot_download got them (the fake HfApi records repo_info's options).
- test_record_unplaced_source_keys_records_an_empty_list_as_an_answer is
  covered by the nothing-stray case and by the export's recorded-empty
  test.
- The examples' clean-checkpoint, auxiliary-tower and sorted-keys tests
  repeat the unit tests on the same loader.

Each removed assert was checked by breaking the code it guards: a
remaining test fails.

Signed-off-by: Shengliang Xu <[email protected]>
load_pretrained passed subfolder to from_pretrained only. The config
lookup read the checkpoint root, so a checkpoint whose config is in the
subfolder alone failed before it loaded. With a root config there, the
unplaced-key record scanned the root's tensors rather than those of the
weights loaded, so the export missed the tensors it should carry. The
subfolder is now joined to the checkpoint path once, for the config, the
loading hook, the load and the record.

Signed-off-by: Shengliang Xu <[email protected]>
load_pretrained handed revision, token, cache_dir and local_files_only to
ensure_local_checkpoint alone. Loading from the local snapshot still
reaches the Hub for custom code an auto_map entry names in another repo,
and without the options local_files_only=True could still make a network
request and private code could fail despite the token. The config and
model loads now take token, cache_dir and local_files_only too; revision
picked the snapshot and applies to the snapshot only.

Signed-off-by: Shengliang Xu <[email protected]>
named_parameters() lists a tied parameter under its first name only. A
checkpoint can store the other name too: Qwen3-0.6B stores lm_head.weight
beside the embedding it is tied to. load_pretrained recorded that name as
a tensor the model has no parameter for, so the export carried the source
tensor over beside the weight it is. The whole-model load now counts
every name of a parameter. The FSDP2 load needs no change: the model it
builds is not tied yet when it lists the names, and the new test covers
both.

Signed-off-by: Shengliang Xu <[email protected]>
Main's test_moe_export_matches set _modelopt_unplaced_source_keys = [] to
stand in for Transformers' unexpected_keys report, which main unions with a
structural pass. Here that attribute is the loader's own record of the
structural pass, and an empty record means nothing to carry, so the
layerwise export dropped the test's MTP weight (KeyError
'mtp.eh_proj.weight' in the GPU run).

Leave both models unrecorded instead: the layerwise exporter then derives
the keys at bind, before it packs the experts, which is what main's
NVBug 6954041 fix protects. On CPU with FP8 both cases pass, and both fail
with the exporter's bind-time snapshot removed.

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

load_pretrained records the checkpoint tensors the model has no parameter
for from the checkpoint's default weight files, and the export carries them
from there. A variant= load reads other files, so the record named the
default files' tensors and the export carried those. Refuse a variant
before anything loads, as output_loading_info is.

The model type that picks the loading hook was read from the checkpoint's
config.json even when the caller passed the config the load uses, so a
directory without one failed before from_pretrained, which loads it. Take
the type from the passed config when there is one.

Signed-off-by: Shengliang Xu <[email protected]>
@shengliangxu
shengliangxu force-pushed the shengliangx/fix-carry-load-time-conversions branch from c27930b to 204f98a Compare October 22, 2026 06:46
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 204f98a

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Prior code concerns are resolved; a manual merge decision remains required because earlier review comments contain embedded agent-directed prompts.

Needs action:

  • 💬 Author reports inspecting the earlier CodeRabbit prompt templates and ignoring their CLI suggestion — confirm the final merge decision manually; this review treated all embedded instructions as untrusted data.

No action needed:

  • ✔️ 9 prior code concerns resolved, including variant rejection and explicit-config loading. Revision/cache options, subfolders, downstream auth/cache options, tuple-return rejection, tied aliases, and module-scope test imports are also verified.
  • The design reasonably replaces unexpected_keys and export-time unioning with existing checkpoint helpers and Transformers conversion metadata; no competing loading framework is introduced.
  • Existing test removals and replacements are justified by the changed accounting contract. Regressions cover ignored MTP keys, omitted index entries, source names, FP8/MXFP4 conversions, and one-time export derivation.
  • The partial-install fallback finding was withdrawn with a technically sound explanation. The new test header matches LICENSE_HEADER.
  • Tests were inspected, not executed.

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

LGTM

@shengliangxu
shengliangxu merged commit db4dc7a into main Oct 22, 2026
56 checks passed
@shengliangxu
shengliangxu deleted the shengliangx/fix-carry-load-time-conversions branch October 22, 2026 18:27
shengliangxu added a commit that referenced this pull request Oct 24, 2026
### What does this PR do?

Type of change: New feature

First of 21 PRs that add expert-parallel (EP) PTQ for Hugging Face MoE
models to `examples/hf_ptq` under `torchrun`. They merge in order:

- [1/21]-[3/21], the building blocks: this all-to-all expert transport,
amax synchronization that holds under data-parallel calibration
([2/21]), and fused-experts quantization under `grouped_mm` ([3/21]).
- [4/21]-[12/21], the distribution plan and the loads it routes to: a
`DistributionPlan` decided once per run, and `load_pretrained` loading
by it, replicated, FSDP2-sharded, or with an MoE's experts sharded.
After [12/21], an MoE whose expert-parallel plan ships with transformers
loads and calibrates expert-parallel.
- [13/21]-[17/21], model specs and export: the specs ([13/21]) make an
MoE expert-parallel when transformers ships no usable plan for it, such
as DeepSeek-V3, and refuse the ones the path cannot handle yet;
[14/21]-[17/21] write a sharded model's Hugging Face checkpoint without
gathering it, expert-parallel included.
- [18/21]-[20/21], models that plug in through their specs:
compressed-tensors experts decompressed as they load, and the Kimi
models.
- [21/21] runs it all from `hf_ptq.py`.

This PR adds the transport.

Calibrating a large MoE has no good option today. Replicating it needs
the whole model on every rank. Sharding it with FSDP2 alone gathers
every expert on every rank for each forward, so the expert weights
dominate both memory and time, while each rank still only sees its own
slice of tokens.

DP=EP instead: dense layers and the router run data-parallel, the routed
experts are sharded across ranks, and tokens go to the rank that owns
their expert by an all-to-all dispatch and come back by the combine.
Each expert sees every token routed to it from all ranks, so its amax is
collected over the global token pool rather than one rank's share. That
is the accuracy point, not just a memory one. The expert matmul stays on
transformers' own `_grouped_linear`, where [3/21] attaches ModelOpt's
per-expert quantizers as in a single process. `register_torch_a2a()`
installs the transport as a transformers experts implementation, lazily
rather than at import.

The transport is plain `all_to_all_single` over NCCL, so it works across
nodes at any rank count. Three things it has to get right:

- **The routing weights stay on the token's rank.** The experts' results
come back unweighted, and the rank that holds each token weights them in
the routing weights' own dtype, as transformers' `grouped_mm` does: a
router that returns fp32 weights (Mixtral's, DeepSeek-V3's) gets an fp32
product. The weights never travel, so no hop carries them, and their
gradient comes from the local product.
- **The combine sums each token's top-k in a fixed order.** A sum whose
order depends on how tokens were distributed, or on the atomics
`index_add_` uses on CUDA, rounds differently from one EP degree or run
to the next, so activation scales would shift and a checkpoint would not
reproduce. The results come back in (token, slot) order, and each
token's top-k rows are weighted and summed with `view(n, top_k,
H).sum(1)`, as transformers' `grouped_mm` does, a slice of tokens at a
time. Each transport buffer is freed as soon as its stage is done: a
whole fp32 copy of the results, beside buffers kept to the end, reached
GiBs at calibration batch sizes.
- **Large transfers.** `all_to_all_single` addresses the flattened
buffer with element offsets, which overflow int32 once rows × hidden
exceeds 2**31. The transport chunks along the hidden dimension, into
slices as wide as the most rows any rank moves allows. Ranks agree on
that row count with one all-reduce per layer; deciding it from local
sizes desyncs the hop count and deadlocks.

A rank that receives more than 4x the most tokens any rank sent (a
collapsed router piling the cluster's tokens onto a few experts) warns
once, before the expert stage allocates for that count. A rank can
receive at most world size times that, so the warning fires only above 4
ranks.

The incidents behind the transport's less obvious code:

| Code | Why | Seen on |
|---|---|---|
| Hops over 2**31 elements go as hidden-column slices |
`all_to_all_single`'s int32 element offsets overflow, and the collective
hangs until the NCCL timeout | Qwen3.5-MoE EP calibration at batch 8 x
seq 4096: rows x hidden = 2.68e9 |
| The host waits for the count exchange before reading the counts | A
read racing the collective's stream sized the dispatch from garbage, and
the next all-to-all crashed | Qwen3.5-MoE EP calibration |
| Each token's top-k is summed in a fixed order | A bf16,
order-dependent combine made exported activation scales EP-dependent |
Qwen3-30B-A3B, top-8: 27% of input scales differed from single-GPU, by
up to 28% |

### Usage

Internal to the expert-parallel loader ([9/21]); nothing to call
directly.

### Testing

- `tests/unit/torch/utils/test_moe_a2a.py`, under gloo on CPU:
- transformers' fused Qwen3-MoE experts split over two ranks: through
the registered `torch_a2a` forward they give the whole module's output
and gradients, for the hidden states, the routing weights and each
rank's own experts (mutation-checked);
- hops split along the hidden dim, each within the per-hop limit, once
that limit is shrunk below the transfer size, with a bit-identical
result;
- the collapse warning, its ratio lowered for two ranks: collapsed
routing warns on the receiving rank only, and unequal batches with even
routing warn nowhere (fails on the previous revision, which compared
with the rank's own count);
- with fp32 routing weights on bf16 experts, at EP=1 the `torch_a2a`
forward gives `grouped_mm`'s result bit for bit (fails on the previous
revision, which rounded the weights to bf16);
- the combine's temporaries stay within one slice of tokens, with the
same result as unsliced (fails on the previous revision, whose fp32
`[tokens, hidden]` accumulator exceeds the slice);
- a rank that sends nothing, its routing slots all `-1` or no tokens at
all, but serves its peer's tokens: its backward still runs the reverse
all-to-all, so both ranks get their input gradients (the test's group
times out in 10 s, so a regression fails instead of hanging);
- experts whose biases the plan left whole (GPT-OSS's, with only the
weights sharded) are refused before any collective.
- `tests/gpu/torch/utils/test_moe_a2a.py`: with fp32 routing weights, at
EP=1 the `torch_a2a` forward gives `grouped_mm`'s result bit for bit on
CUDA. Run on GB200, against the previous revision's `index_add_` combine
and this one (elements that differ from `grouped_mm`, of 4,194,304):

  | Combine | 1 GPU | 4 GPUs, each rank its own one-rank group |
  |---|---|---|
  | Previous (`index_add_`) | 223 | 217 to 232 per rank |
  | This revision | 0 | 0 on every rank |
- Peak memory of one layer's transport, on CPU, at 4096 tokens, hidden
4096, top-k 8, fp32 routing weights:

  | Revision | Peak RSS growth |
  |---|---|
  | Before the bounded combine and the early frees | 2122 MiB |
  | This revision | 706 MiB |
- The two-rank tests run on `cpu_dist_workers`, the two gloo ranks
main's unit tests keep up for the session (`tests/unit/conftest.py`),
since spawning ranks cost each test about 14 s of the linux unit job.
This PR makes those workers reseed after every job, so each job starts
from the seed a freshly spawned rank gets; a job that draws a different
amount of randomness on each rank otherwise leaves the next job's ranks
out of step. Since both ranks then draw the same data, main's
`test_data_parallel` now seeds its calibration data by rank: its
group-MAX check would otherwise hold with or without the data-parallel
amax sync. It fails when that sync is removed. `test_autoquant`'s
data-parallel test seeds its batches by rank for the same reason, and
fails when the score sync is removed.
- The result keeps the dtype it is given: fp32 and fp16 experts through
the transport, in a one-rank group, match a dense reference in their own
dtype. Tokens travel in the model's dtype.
- The test of a hand-written expert function against a dense reference
is dropped: the Qwen3-MoE experts test checks the same forward and
gradients, and the dtype test runs a one-rank group. The drop is checked
by mutation.
- Locally on this revision, the series on main 6cd9ced: pre-commit
(every hook, mypy included) over each PR of the stack against main; the
changed tests in this PR and in [2/21], [3/21] and [8/21], and at the
top of the stack the unit test files that run this transport, on
transformers 5.18 and 5.5. CI runs the full unit lanes and the docs
build.
- The GPU results here were measured on earlier revisions of this
branch; this revision's GPU tests run in CI only.
- On GPUs: `tests/gpu/torch/utils/test_expert_parallel_load.py` ([9/21])
runs a tiny Qwen3-MoE through this transport on every GPU and matches
the unsharded model's logits; the series' model runs exercise it at 4 to
64 ranks (see [21/21]).

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

- Is this change backward compatible?: ✅ Additive; registered only when
the expert-parallel loader asks for it.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
N/A. The feature's entry lands with [21/21].
- Did you get Claude approval on this PR?: ❌ Not yet.

### Additional Information

Part 1 of 21 of expert-parallel PTQ for Hugging Face MoE models. #2733
has merged, so this PR is based on main and merges first; the series
then merges in order, [1/21] through [21/21].

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

## Summary by CodeRabbit

* **New Features**
* Added support for running mixture-of-experts models across multiple
devices, routing tokens to experts and combining their outputs.
* Added support for per-expert biases and split handling of large
transfers, with results accumulated in FP32 before conversion.
* Added a warning when a device receives substantially more tokens than
it sends.

* **Tests**
* Added coverage for distributed outputs, gradients, transfer splitting,
imbalance warnings, and quantization synchronization.
  * Improved consistency by reseeding distributed workers between jobs.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Shengliang Xu <[email protected]>
shengliangxu added a commit that referenced this pull request Nov 2, 2026
…2779)

> [!NOTE]
> **The expert-parallel PTQ series is now a tree instead of one stack**
(re-cut 2026-10-27, from main 1521053bfb0), so PRs that do not depend on
each other can be reviewed and merged in parallel. This PR was [6/21].
Rebased onto main 7c3c8680284 later the same day, after #2739 merged,
and onto main f03651e815c that night.
>
> **[2/2] of a split** (2026-10-30): #3140 ([1/2]), which moved
`fsdp2_wrap` into `modelopt.torch.utils.fsdp2_utils`, merged on
2026-11-01. This PR now targets main.
>
> **Source lines:** 359 against main by the repository's sizing rule
since #3163 (comments, docstrings and blank lines don't count; its
upper-bound command gives 454), under the ~500 guideline.
>
> **Re-cut:** this PR's diff is unchanged; only its base moved. Review
fixes since are listed at the end of Testing.

<details><summary>Series layout</summary>

- `main`
  - #2745 fused experts under grouped_mm (merged)
    - #3074 calibration on grouped_mm
      - #3067 Nemotron-H's experts under grouped_mm
      - #2740 calibration on per-rank data
  - #2739 meta-DCP checkpoint load (merged)
  - #2736 distribution plan, run group, collectives (merged)
    - #2750 keep-fused fold
    - #2751 distributed-writer pieces
      - #2752 no-gather export (on #2751, #2750, #2779 and #2740)
        - #2753 expert-parallel export
    - #2737 plan decision (merged)
      - #3140 fsdp2_wrap move ([1/2])
        - **#2779 load routing (this PR, [2/2])**
        - #2741 expert-parallel loader (on #2779, #3067 and #2740)
          - #2742 dense sharding
            - #2743 block-FP8 dequantization
              - #2780 expert-parallel load routing
                - #2746 expert parallelism in the model specs
                  - #2747 on-the-fly decompression
                    - #2748 Kimi-K2.5 and Kimi-VL adapters
                      - #2749 Kimi-K3 adapter
- #2754 expert-parallel PTQ from hf_ptq.py (on #2746 and #2753)

</details>

### What does this PR do?

Type of change: New feature

`load_pretrained` (#2733) loads a model whole. A distributed load, such
as `parallel_load_and_prepare_fsdp2` (main), is a separate entry point,
and every caller picks one itself, as `hf_ptq.py --use_fsdp2` does. A
caller that picks a loader also gets what that loader skips: a sharded
load cannot run the model type's loading hook, so a Nemotron-H
checkpoint's MTP head is not built and its tensors go to the export
unquantized.

This PR makes `load_pretrained` the one loader, whole or distributed:

- **`distribution` is a `DistributionPlan`**; by default it is the plan
`resolve_distribution_plan` (#2737) decides.
- `dense="fsdp"`: `parallel_load_and_prepare_fsdp2` over the process
group. A single process launched with `torchrun --nproc_per_node=1` has
no group, so the load sets one up, of one rank, once nothing can refuse
the load anymore; a process started without a launcher cannot set one up
and is refused. `distributed_run` (#2736) destroys it with the run. One
rank of a multi-rank launch whose group is not set up yet is refused
too, told to set it up first with `distributed_run()`, rather than shard
over the launch's ranks under a one-rank plan; the plan-size refusal
says the same when that is why the sizes differ.
- Otherwise `from_pretrained`. On a distributed run every rank gets the
whole model, onto its own GPU when it has one and no `device_map` is
passed.
- A plan that shards the routed experts raises here; #2780 adds that
load, once the expert-parallel loader (#2741, #2742 and #2743) is in.
Until then a plan this PR's load decides keeps the EP degree at 1, so an
MoE loads without expert parallelism by default, whole or FSDP2-sharded
as the dense layout says. An EP degree `MODELOPT_EP_DEGREE` asks for, or
a handed plan with `ep_size > 1`, is refused before anything loads, and
the refusal names `MODELOPT_EP_DEGREE=1`.
- `resolve_distribution_plan` takes the class the load builds with
(`auto_class`, which `load_pretrained` passes). With a class the sharded
loads do not build and no knob asking to shard, it plans the whole model
on every rank without a meta-device build, so an encoder-decoder loaded
through `AutoModel`, for example, loads multi-rank as before.
- **The plan is recorded on the model** and every submodule
(`set_distribution_plan`, #2736), where calibration and export read it.
`load_pretrained` records it exactly once, at the end of every load; the
loaders it calls record none. `fsdp2_wrap` records nothing, as on main,
so a caller that wraps or loads a model through it directly records the
plan itself, as the error for a missing plan says. `hf_ptq.py
--use_fsdp2` loads through `parallel_load_and_prepare_fsdp2` directly
and records no plan in this PR. Recording it there lands with #2752, the
first PR whose export reads it on that path, and #2754 moves that load
onto `load_pretrained`.
- **`fsdp2_wrap`** moved into `modelopt.torch.utils.fsdp2_utils`, which
imports no Hugging Face package and which the loaders import it from, in
#3140 ([1/2]), which keeps its old path. This PR makes it refuse a model
that, or any of whose submodules, records a plan, as a model
`load_pretrained` returned does: a plan is recorded once, so a model to
shard yourself is one loaded with `from_pretrained`.
- **Every load** makes a Hub ID local and records the unplaced source
keys (#2733). The FSDP2 load builds its model from the config without
the Hub options, so custom code an `auto_map` names comes with the
environment's Hub settings.
- **Every rank loads the same plan.** Every rank takes rank 0's
distribution, a plan or none, through one broadcast (`broadcast_from`,
#2736) before it branches, and loads a plan rank 0 was handed just as it
would one it decided. Ranks that each loaded the plan they were handed
could build mismatched meshes and hang, and ranks passing different
kinds would wait in each other's collectives. Rank 0 checks what it was
handed before it sends it, a non-plan included, so a distribution it
refuses raises on every rank instead of leaving the others waiting in
the broadcast.
- **Refusals, before anything loads, and on every rank.** Each rank
checks its own arguments and reads the config itself, so each refusal
runs through the failure-carrying `all_reduce` (#2736): a refusal on any
rank raises on every rank, before the checkpoint's fetch for the
arguments, after it for a rank that cannot see the checkpoint rank 0
fetched, and before the sharded load's collectives for what the config
says, instead of leaving the other ranks waiting there.
- A sharded load cannot run the model type's loading hook, so it refuses
a checkpoint the hook would build modules for: the MTP head above.
Main's `hf_ptq.py --use_fsdp2` refuses Nemotron-H MTP on the same loader
(`validate_fsdp2_supported`), and this applies its rule to every caller.
The hook could wrap the FSDP2 load's meta-device build, but the head's
calibration forward inside the root FSDP2 unit and its quantized export
from FSDP2 shards have never run on that path: supporting MTP under
FSDP2 is a change to that loader and to hf_ptq, validated on a real
checkpoint, not part of this routing.
- It refuses `from_pretrained`'s placement arguments (`device_map`,
`max_memory`, ...) and an `auto_class` other than `AutoModelForCausalLM`
(leave it out: the load picks the class), rather than ignore them, and
an explicit `dtype`, saying why it does not apply: the load keeps the
checkpoint's dtype, and FSDP2's `mp_policy` sets the dtype it computes
in. An option passed as `None`, `from_pretrained`'s own default, asks
nothing and is not refused.
- The FSDP2 load refuses a quantized checkpoint, whose tensors it would
read as stored.
- The FSDP2 load builds a text-only VLM it supports (Qwen3.5) through
its image-text class, as hf_ptq's `--use_fsdp2` does, and any other
model through `AutoModelForCausalLM`. It refuses a config `_auto_class`
would not build through that class, as most VLMs (which
`AutoModelForCausalLM` refuses deep in the loader, or builds as the
language model alone), before it sets up a group or reads anything, and
the refusal says how to load the model whole on every rank: its model
class as `auto_class`, with `MODELOPT_FSDP_SIZE=1` (for a plan the load
decided) or a replicated plan.
- A plan made for another world size is refused, and so is anything
other than a plan.
- `hf_config` without the plan it was resolved with is refused. A
sharded load builds the model from it as given, so a plan decided here,
from the checkpoint's own config, would not be the one it came with.
`config=` is for a config the plan should be decided from.
`resolve_distribution_plan`'s docstring says to hand the config it
returns to `load_pretrained` only with a plan that shards the model: a
whole-model load reads the checkpoint's config itself and refuses
`hf_config`.

The FSDP2 route's refusals name their ways out (`MODELOPT_FSDP_SIZE=1`
for a plan the load decided, or a replicated plan), and a config handed
with a plan is copied before the load builds from it. With a plan handed
and no config, the FSDP2 route reads the checkpoint's config once and
hands it to the load, rather than reading it twice. Deciding a plan
builds the meta-device model from a copy of the config, so the config
returned with the plan, which a sharded load builds from, is the same on
every rank: the build writes its dtype and its attention and experts
implementations, and only rank 0 builds.

**Routing details** are in the docs page this PR adds,
`docs/source/guides/_distributed_loading.rst` ("Loading Hugging Face
models across ranks", under the quantization guide), which
`load_pretrained`'s docstring links.

### Usage

```python
# torchrun --nproc_per_node 8 quantize.py
from modelopt.torch.utils.distributed import distributed_run
from modelopt.torch.utils.plugins.model_load_utils import load_pretrained

with distributed_run():
    model = load_pretrained("meta-llama/Llama-3.1-8B")  # a whole copy on every rank's GPU
    # With MODELOPT_FSDP_SIZE=world: FSDP2-sharded over the 8 ranks instead.
```

### Testing

- Tests in `tests/unit/torch/utils/test_model_load_utils.py`, beside the
plan decision's (the module's test file, as CONTRIBUTING asks). They run
on CPU, and stand-in loaders record their calls. They cover:
  - each load: the arguments it gets and the plan it records;
- a decided FSDP2 load, handed the config the plan was decided from
instead of reading it again, and a handed FSDP2 plan's load reading the
checkpoint's config once (that check fails without its fix);
- a single process's FSDP2 load setting up its group of one, and leaving
none behind when the load is refused;
- every refusal, raised before any loader runs, the expert-parallel
plan's included; `test_a_load_refuses_what_it_cannot_load` has a VLM row
(a Llava config), which fails without the refusal;
- on two real gloo ranks (`cpu_dist_workers`), rank 0 handed a
replicated plan and rank 1 an FSDP2 one, or none: both load whole and
record rank 0's plan. A rank that loads the plan it was handed fails at
once, on the placement refusal. Rank 0 handed a non-plan fails both
ranks;
- on two real gloo ranks, rank 1 alone refused, by two configs or a
`dtype` before the checkpoint is fetched or by a quantized `hf_config`
before the FSDP2 load: both ranks raise rank 1's refusal. The fetch and
the load stand in as collectives on a group bounded to 10 s, so without
the change the test fails fast (rank 0 gets a dropped connection)
instead of hanging;
- a caller's own model class: loaded whole on every rank, planned
without building the model, with no sharding knob, and refused by the
sharded load with one.
- With #2737's plan-decision tests: the config returned with the plan is
the one every rank read, unchanged by rank 0's meta-device build (new
`test_the_config_returned_with_the_plan_is_as_every_rank_read_it`, which
fails without its fix).
- A single process's load, placed as `from_pretrained` places it, with
the caller's arguments and a single process's plan: #2733's real CPU
load in `tests/unit/torch/utils/test_unplaced_source_keys.py`, which now
also checks the plan.
- `fsdp2_wrap` leaving the plan to the load, and refusing a model
recorded as replicated: CPU unit tests in
`tests/unit/torch/utils/test_fsdp2_utils.py`. #2733's GPU tests that
wrap or load through it directly (`test_export_carry_over.py`,
`test_model_load_utils.py`) record the plan themselves. Its old path
forwarding every argument: #3140's `test_fsdp2_wrap_keeps_its_old_path`.
- Mutation-checked: 17 mutants, each failing a test. They drop the
rank-GPU default, pin a single process's model, drop the config handoff
or the world-size check, load an expert-parallel or FSDP2 plan whole,
accept a string, let each rank load the plan it was handed, record no
plan in the load or record one in `fsdp2_wrap` too, set no group up for
a single process's FSDP2 load, set one up over a live group, or have the
old `fsdp2_wrap` path drop an argument or the result.
- New tests in `tests/gpu/torch/utils/test_model_load_utils.py` run
`load_pretrained` left to decide, on every GPU of the node:
- a dense model loads whole on each rank, and with
`MODELOPT_FSDP_SIZE=world` FSDP2-sharded;
  - each rank's weights match the checkpoint;
  - the load records its unplaced keys and its plan.
- It needs 2 GPUs, so this PR's GPU CI lane, on one GPU, skips it, and
main's nightly GPU run, on two, runs it. It passed on 2 and 4 GPUs on
2026-10-29 (the GPU check below).
- `tests/examples/hf_ptq/test_example_utils.py`: `get_model`'s stand-in
model is a module now, since `load_pretrained` records its plan on it.
- The load refusals are one parametrized test, and the single-process
load test gives way to #2733's real load. Each drop is checked by
mutation.
- A single process without a launcher is refused an FSDP2 load, without
stubbing the setup, and a handed config is left as the caller passed it.
A rank of a multi-rank launch whose process group is not set up is
refused any load, before anything is fetched. The refusal table has an
explicit `dtype`.
- Locally on this revision, the stack rebased on main c6fa6133cb:
pre-commit over the whole PR against main, at every PR of the stack; and
at the stack's tip the full `tests/unit` on transformers 5.18 and 5.5
and on torch 2.8, and the hf_ptq example tests, each with the same
failures as main in that environment. CI runs the full unit suite.
- Re-cut on 2026-10-27 (see the note at the top): pre-commit, mypy
included, passes at this head over the whole change against main, and
the series' PRs merged together give a tree byte-identical to the former
stack's tip. This PR's own unit tests pass at this head on CPU (torch
2.14, transformers 5.18); CI runs the full unit suite.
- Review fixes, 2026-10-27: a rank of a multi-rank launch without its
process group is refused on every route, before anything is fetched; a
caller's model class with a knob asking to shard is refused before the
model is built; a changelog entry for `fsdp2_wrap`'s move. Each
behaviour fix has a test that fails without it; pre-commit, mypy
included, and this PR's own unit tests pass at this head.
- Rebased on 2026-10-27 onto main 7c3c8680284, after #2739 merged:
pre-commit, mypy included, and this PR's own unit tests pass at this
head, and the series' PRs merged together add no unit-test failure over
main (tests/unit/torch utils, export, quantization and models, on
transformers 5.18 and 5.5.4 and on torch 2.8). #2739's `FSDPModule`
import, now on main, and this PR's `CPUOffloadPolicy, fully_shard` are
one import line, and `fsdp2_wrap` sits ahead of the meta-DCP loader, as
before.
- Review fixes, 2026-10-27 (Claude's review after the rebase): a sharded
load takes `dtype=None` and `torch_dtype` as `from_pretrained` does.
`None` and `"auto"` keep the checkpoint's dtype under either name, and
any other dtype is refused with the dtype message, where `torch_dtype`
got the placement one. The new cases fail without the change.
- Review suggestions, 2026-10-27 evening: a launch whose processes set
no group up (hf_ptq under torchrun without `--use_fsdp2`) loads the
whole model on each process again, refusing there only a plan for
several ranks and a sharded load; a handed plan is checked before the
checkpoint is fetched; an FSDP2 layout decided from rank 0's GPU memory
says so when it refuses placement options; `fsdp2_wrap` imports the
layer detection where it uses it.
- Review fixes, 2026-10-27 night: a launch without its process group
refuses `MODELOPT_EP_DEGREE` above 1 or `MODELOPT_FSDP_SIZE` naming the
world before anything is fetched, and the sharded-load refusal names the
plan to pass. The refusal test's new rows fail without the change.
- Review suggestions, 2026-10-27, last round: on a launch without its
group, a `MODELOPT_EP_DEGREE` that is not an EP degree is refused with
the plan decision's message, and a padded value is read as its number;
`load_pretrained`'s docstring says the automatic layout weighs the model
in the checkpoint's own dtype. The refusal test's new row fails without
the change.
- Review fix, 2026-10-27, last round: a one-rank sharded plan in a
launch without its group is refused before the checkpoint is fetched,
and the advice for a model with no plan names `load_pretrained` again,
which records the plan from this PR on.
- Review fixes, 2026-10-27, last round: `hf_config` with a plan that
loads the model whole is refused before the checkpoint is fetched, with
the no-plan case's message, and the new pre-fetch test row fails without
the change; `fsdp2_wrap`'s docstring says the FSDP2 load wraps with it.
- Review suggestions, 2026-10-28: the refusals that depend only on a
handed plan's arguments (`auto_class`, `dtype`, options the sharded load
does not take) run before the checkpoint is fetched, and the new test
row fails without the change; a test docstring no longer says
`fsdp2_wrap` loads.
- Review suggestions, 2026-10-28, fifth round: the handed-plan test pins
the `auto_class` and `dtype` arms of the pre-fetch refusal, each failing
with its arm left out of the pre-fetch call; the four function-local
imports of `modelopt.torch.utils.distributed` go, now that #2737 imports
it at module top.
- Declined review suggestion, 2026-10-28, fifth round: one helper for
the kwargs view the pre-fetch refusal and `_load_sharded` read; the two
agree, and the handed-plan test pins each pre-fetch arm.
- Rebased on 2026-10-29 onto #2737's current head `2a6290b470a` (main
`2b900c8fa41`). This PR's own diff is unchanged, except that its test
additions follow the module-mirroring test files: the plan-decision test
goes to `test_model_load_utils.py` (#2737 deleted
`test_resolve_distribution_plan.py`), and the `fsdp2_wrap` old-path test
to `test_distributed.py` (main renamed `test_distributed_run.py`). One
test fixture changed: main's `broadcast_from` now picks its sender by
`modelopt.torch.utils.distributed.rank()`, which the load-routing tests'
`process_group` fixture sets to 1 for the FSDP2 load, so `run_as` now
runs the real broadcast with the deciding rank as its sender. No source
change. Pre-commit passes against main; `tests/unit/torch/utils` and the
hf_ptq argument and example-utils tests pass on CPU with transformers
5.18 and 5.5.4.
- 2026-10-29, at `59e83993426`: `tests/unit/torch/export` and
`tests/examples/hf_ptq/test_carry_over_layouts.py` also pass on CPU with
transformers 5.18 and 5.5.4, apart from 7 `test_export_diffusers.py`
cases that fail the same way on #2737's head in this environment; GitHub
runs no unit tests on this PR until it targets main.
- GPU check, 2026-10-29, at `59e83993426`, the first run of this PR's
multi-GPU tests, on GB200 (torch 2.11.0a0 from NGC PyTorch 26.02,
transformers 5.9.0): the new `test_load_pretrained_distribution.py`, the
two files whose tests now record the plan by hand
(`test_model_load_utils.py`, `test_export_carry_over.py`), and
`test_distributed.py`, whose `fsdp2_wrap` tests import it through its
old path:

  | Run at `59e83993426` | 2 GPUs | 4 GPUs |
  |---|---|---|
| `tests/gpu/torch/utils/test_load_pretrained_distribution.py` | 2
passed, 20.9 s | 2 passed, 23.2 s |
| `tests/gpu/torch/utils/test_model_load_utils.py` | 4 passed, 25.6 s |
4 passed, 26.9 s |
| `tests/gpu/torch/export/test_export_carry_over.py` | 2 passed, 22.8 s
| 2 passed, 29.2 s |
| `tests/gpu/torch/utils/test_distributed.py` | 8 passed, 21.9 s | 8
passed, 26.6 s |

- Rebased on 2026-10-29 onto main `70147bcbfa1`, #2737's squash, after
#2737 merged; this PR now targets main. Its own diff is unchanged. The
one conflict was the changelog: main's Transformer Engine 1.x line and
this PR's `fsdp2_wrap` line are both kept. Pre-commit, mypy included,
passes against main; `tests/unit/torch/utils`, `tests/unit/torch/export`
and the hf_ptq tests that load through `load_pretrained` pass on CPU
with transformers 5.18 and 5.5.4, apart from the same 7
`test_export_diffusers.py` cases as above. GitHub now runs the full
unit, GPU, example and regression CI on it.
- Review fixes, 2026-10-29 (cjluo-nv's review): a refusal on any rank
fails every rank, of the arguments before the checkpoint is fetched and
of what the config says before the sharded load (the argument checks now
run after the plan's broadcast; the sharded load's checks moved into
`_sharded_load_kwargs`, run inside the `all_reduce`). The new two-rank
test fails on all three of its cases with the change reverted. The
routing tests moved into the unit and GPU `test_model_load_utils.py`
files, test bodies unchanged; the changelog entry is two sentences; the
MTP refusal's reason is above. Pre-commit, mypy included, passes against
main; `tests/unit/torch/utils`, `tests/unit/torch/export` and the hf_ptq
tests that load through `load_pretrained` pass on CPU with transformers
5.18 and 5.5.4, apart from the same 7 `test_export_diffusers.py` cases
as above.
- Review fix, 2026-10-29, cjluo-nv's second round: a rank that cannot
see the checkpoint rank 0 fetched fails every rank, the fetch running
inside the same `all_reduce` as the other refusals. The two-rank
visibility test
(`test_a_rank_that_cannot_see_the_checkpoint_fails_every_rank`) also
loads by a handed plan, on the test's own gloo group with the error
caught on both ranks, and fails in about 8 s with the change reverted.
Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils`, `tests/unit/torch/export` and the hf_ptq tests
that load through `load_pretrained` pass on CPU with transformers 5.18
and 5.5.4, apart from the same 7 `test_export_diffusers.py` cases.
- Rebased on 2026-10-30 onto main `99c3834f62c` (after #3099 and #2750
merged), without conflicts; this PR's own diff is unchanged. Pre-commit,
mypy included, passes against main.
- Review fix, 2026-10-30 (cjluo-nv): `config=` given as a path, as
`from_pretrained` takes it, is read as the load reads it, and the plan
decision, the loading hook and a sharded load use that config, so a
weights-only checkpoint with its config in another directory loads again
(it had failed on the decision's read of the checkpoint's own
config.json). `test_a_config_passed_for_the_load_needs_none_on_disk` now
also loads one through `LlamaForCausalLM`, with and without
`model_type`; both cases fail without the change. Pre-commit, mypy
included, passes against main; `tests/unit/torch/utils` and the hf_ptq
example tests pass on CPU with transformers 5.18 and 5.5.4.
- Review suggestion, 2026-10-30 (Claude): the `config=` path is read
through the model class's own `config_class`, as `from_pretrained` reads
it, and through `AutoConfig` for the auto classes; a new row loads a
model class of the caller's own whose config class `AutoConfig` cannot
resolve, and fails without the change. Pre-commit passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4.
- Review fix, 2026-10-30 (Claude): a process without a group, or in a
group of one, takes `DistributionPlan()` without deciding or reading a
config, as before plans existed, so a model class of the caller's own
with its `model_type` given loads again whatever `AutoConfig` knows
(`test_a_model_class_of_the_callers_own_reads_its_config_itself`, which
fails without the change); a model class's own config class reads a
`config=` path without `trust_remote_code`. Pre-commit passes against
main; `tests/unit/torch/utils` and the hf_ptq example tests pass on CPU
with transformers 5.18 and 5.5.4.
- Review fix, 2026-10-30 (Claude), the several-rank arm: the plan
decision reads the checkpoint's config as the load does, through the
model class's own `config_class` or, for an auto class, `AutoConfig`, so
a model class of the caller's own loads whole on every rank whatever
`AutoConfig` knows; `test_a_model_class_of_the_callers_own_loads_whole`
has a two-rank row with such a config on disk, which fails without the
change. The other `AutoConfig` reads on the load path (a `model_type`
left to read, which main reads too; the FSDP2 route's, which only auto
classes reach) refuse nothing main loaded. Pre-commit passes against
main; `tests/unit/torch/utils` and the hf_ptq example tests pass on CPU
with transformers 5.18 and 5.5.4.
- Review fixes, 2026-10-30 (Claude): on a plan that loads the model
whole, the options only the FSDP2 load takes (`cpu_offload`,
`mp_policy`, `broadcast_chunk_size`) are refused with the other load
checks, rather than reach `from_pretrained`; `MODELOPT_EP_DEGREE` has
one parse, the plan decision's, which a launch without its group now
uses too and which takes surrounding spaces and refuses a degree below
1. New rows (an FSDP2 option on a replicated plan, a padded auto, a
degree of -2) fail without the change. Source insertions were then 509,
a few over the ~500 budget, for these fixes. Pre-commit passes against
main; `tests/unit/torch/utils` and the hf_ptq example tests pass on CPU
with transformers 5.18 and 5.5.4.
- Review suggestions, 2026-10-30 (Claude's approving review at
`cb7fb1e8495`): a distributed whole-model load defaults each rank's
`device_map` to its GPU only where CUDA is available, so a run without
GPUs (a gloo group on CPU) loads whole again; a model type left to read
is read as the model class reads its config; `MODELOPT_FSDP_SIZE` takes
surrounding spaces as `MODELOPT_EP_DEGREE` does. New rows (two gloo
ranks loading whole without a `device_map`, a caller's model class whose
model type is read, a padded `MODELOPT_FSDP_SIZE`) fail without the
change. Source insertions are 508. Pre-commit passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4.
- 2026-10-30, line budget (cjluo-nv): the routing's comments and
docstrings are tightened, with no change in what a load does or refuses,
bringing source insertions to 488; the automatic layout's placement
refusal reads `MODELOPT_FSDP_SIZE` through its one parse,
`_dense_from_env` (Claude's last suggestion). Pre-commit passes against
main; `tests/unit/torch/utils` and the hf_ptq example tests pass on CPU
with transformers 5.18 and 5.5.4.
- Split on 2026-10-30 (cjluo-nv's review): the `fsdp2_wrap` move, its
old path, its changelog line and its test went to #3140 ([1/2], 54
source lines); this PR is rebased onto it and keeps the rest (434 source
lines). The two merged together give exactly the tree of this PR's
previous head `a51881aa6a8` on main `cb9ab4de069`; the rebase dropped
three commits whose whole change #3140 now carries, and resolved the
commits that had moved or reworded `fsdp2_wrap` to #3140's version.
Pre-commit, mypy included, passes against main at both heads;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4 at both heads.
- 2026-10-30, after #3140's review fixes: rebased onto #3140
`6c44b40df74` (it now also carries `fsdp2_wrap`'s dtype helpers, 114
source lines); this PR's own diff is unchanged. Review suggestions
(Claude's approving review): `load_pretrained`'s docstring says that a
single process, or a group of one, reads no knob and takes the FSDP2
load only from a plan passed as `distribution`, and that a launch
without its group loads with no `device_map` default. Source insertions:
435. Pre-commit passes against main; `tests/unit/torch/utils` and the
hf_ptq example tests pass on CPU with transformers 5.18 and 5.5.4.
- Review fixes, 2026-10-30 (Claude): the whole-model load runs inside
the same failure-carrying `all_reduce` as the refusals, so a rank whose
load fails alone (out of memory on its GPU, say) fails every rank rather
than leave the others in the next collective;
`test_a_whole_load_that_fails_on_one_rank_fails_every_rank` (two gloo
ranks) fails without it. `set_distribution_plan`'s docstring wording.
Source insertions: 439. Pre-commit passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4.
- Rebased on 2026-10-30 onto #3140 `48891f691fb` (its old path's
narrower import error); this PR's own diff is unchanged. Pre-commit
passes against main; `tests/unit/torch/utils` and the hf_ptq example
tests pass on CPU with transformers 5.18 and 5.5.4.
- Review fix, 2026-10-30 (Claude), rebased onto #3140 `26bf59ace7c`: a
model FSDP2-sharded after `load_pretrained` recorded a replicating plan
is refused by `distribution_plan()`, rather than read as replicated by
the export; record-once stays, and the `load_pretrained` and
`fsdp2_wrap` docstrings say to wrap a model loaded with
`from_pretrained` and record its plan after. The two-rank
`test_a_model_with_no_plan_raises_in_a_run_of_several_ranks` covers it
and fails without the change. Source insertions: 453. Pre-commit, mypy
included, passes against main; `tests/unit/torch/utils` and the hf_ptq
example tests pass on CPU with transformers 5.18 and 5.5.4.
- Review fixes, 2026-10-30 (cjluo-nv, Claude), rebased onto #3140
`a4bdab004de`: the FSDP2 load is refused, with the other load checks and
so on every rank, on a rank without a GPU, which in a group the caller
set up used to fail inside the load while the others waited in its
broadcasts (`test_a_load_refused_on_one_rank_fails_every_rank`'s new
two-rank `no-gpu` row, which fails without it); `config`, `variant` or
`hf_config` passed as `None`, their default, is taken as not passed
instead of refused (three new rows of
`test_a_load_it_decides_reads_the_config_once`, which fail without it).
Source insertions: 466. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4.
- Review fixes, 2026-10-30 (Claude), rebased onto #3140 `a627d7d6477`: a
distributed whole-model load defaults a rank's `device_map` only to a
GPU of its own (its local rank below the visible GPU count), so a host
with fewer GPUs than ranks no longer hands a rank a device it lacks, and
the FSDP2 load's refusal asks the same; the CHANGELOG says a model
loaded whole on several ranks goes onto each rank's own GPU; the
two-rank gloo load test masks CUDA, so it no longer depends on the
host's GPUs; a model class given by name is refused by name; an
`ep_size` that is no whole number (`[2]`, `2.9`) is refused rather than
raise a `TypeError` or be truncated. New rows (`no_gpu_of_its_own`,
`fewer-gpus-than-ranks`, the by-name and whole-number tests) fail
without their change. Source insertions: 478. Pre-commit, mypy included,
passes against main; `tests/unit/torch/utils` and the hf_ptq example
tests pass on CPU with transformers 5.18 and 5.5.4, and
`tests/unit/torch/utils` without transformers (339 passed, 35 skipped).
- Review fix, 2026-10-30 (Claude): the check that a model recorded as
replicated was not sharded after its plan was recorded moved from
`distribution_plan()`, where it walked the model on every read of a
replicated plan (the export reads it per weight), to `fsdp2_wrap`, which
now refuses such a model; `distribution_plan()` is an attribute read
again. `test_fsdp2_wrap_refuses_a_model_recorded_as_replicated` fails
without the guard. The single-process FSDP2 load's comment says the
group it sets up outlives the load outside `distributed_run`. Source
insertions: 478. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4, and `tests/unit/torch/utils` without
transformers.
- Review fixes, 2026-10-30 (Claude): a load option outside the sharded
load's own set passed as `None`, from_pretrained's default
(`device_map=None` as hf_ptq passes it, `max_memory`, `offload_folder`,
`quantization_config`), is taken as not passed instead of refused by the
FSDP2 load or the automatic layout (new `placement-none` and `none`
rows, which fail without it); the CHANGELOG files what changes for a
load in a group of several ranks under Backward Breaking Changes, with
`MODELOPT_FSDP_SIZE=1` / `MODELOPT_EP_DEGREE=1` or a replicated plan to
keep it whole; the refusal tests match the option, knob or value a
refusal names rather than its wording (tests only). Source insertions:
487. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4, and `tests/unit/torch/utils` without
transformers.
- Review fixes, 2026-10-30 (Claude): the docstring says a rank's whole
model goes onto its own GPU only when no `device_map` is passed,
`device_map=None` keeping `from_pretrained`'s load on the CPU for the
caller to place (a row now pins it); `mp_policy` or `cpu_offload` passed
as `None` no longer refuses a whole-model load, which made the same call
load or raise by rank 0's GPU memory (new row, which fails without it).
Source insertions: 494. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4, and `tests/unit/torch/utils` without
transformers.
- Rebased on 2026-10-30 onto #3140 `ad004655ca9` (cjluo-nv's review
there: `fsdp2_wrap` lives in `modelopt.torch.utils.fsdp2_utils`, free of
the Hugging Face packages). This PR's own changes to the wrap, its
docstring and its refusal of a model recorded as replicated, moved with
it, and their tests into `tests/unit/torch/utils/test_fsdp2_utils.py`;
the docstrings' references to `fsdp2_wrap` point there. Source
insertions: 496. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4, and `tests/unit/torch/utils` without
transformers (344 passed, 33 skipped).
- Review fix, 2026-10-30 (Claude): the FSDP2 load refuses a VLM whose
language model is quantized, its `quantization_config` under
`text_config` or `llm_config` as Kimi-K2.5 keeps it, rather than only a
top-level one; its remote code builds it as a causal LM, so the load had
read the packed weights as stored. The new `quantized-language-model`
row fails without the change. Source insertions: 498. Pre-commit, mypy
included, passes against main; `tests/unit/torch/utils` and the hf_ptq
example tests pass on CPU with transformers 5.18 and 5.5.4, and
`tests/unit/torch/utils` without transformers.
- Review suggestions taken on the user's decision, 2026-10-30 (Claude):
`fsdp2_wrap` refuses a model that, or any of whose submodules, records
any distribution plan, not only a replicating one, naming the plan; a
rank of a replicated load that has no GPU of its own, and no
`device_map`, warns on that rank (not through `warn_rank_0`) that it
loads where `from_pretrained` places it. New rows (a sharded plan, a
plan on a submodule) and `test_a_rank_without_a_gpu_of_its_own_says_so`
fail without the change, the last also with the warning sent through
`warn_rank_0`. Source insertions: 511, past the budget by the user's
decision. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4, and `tests/unit/torch/utils` without
transformers.
- Review fixes, 2026-10-30 (Claude): the FSDP2 load refuses a checkpoint
only when it would not build the class `_auto_class` names, so a Qwen3.5
VLM, which it builds through its image-text class as hf_ptq's
`--use_fsdp2` does, reaches it
(`test_a_text_only_vlm_the_fsdp2_load_builds_reaches_it`, which fails
without the change); its refusals offer `MODELOPT_FSDP_SIZE=1` only for
a plan the load decided
(`test_a_sharded_load_offers_the_knob_only_for_a_plan_it_decided`); the
changelog files `fsdp2_wrap`'s refusal of a model `load_pretrained`
returned as breaking; the no-GPU warning no longer claims a rank's peers
have GPUs; and `parallel_load_and_prepare_fsdp2`'s docstring says a
direct caller records its own plan. Source insertions: 529. Pre-commit,
mypy included, passes against main; `tests/unit/torch/utils` and the
hf_ptq example tests pass on CPU with transformers 5.18 and 5.5.4, and
`tests/unit/torch/utils` without transformers (346 passed, 33 skipped).
- Review suggestion, 2026-10-30 (Claude's approving review at
`c49fd54f6ee`): `set_distribution_plan` and `fsdp2_wrap` find a recorded
plan with one walk, `distributed._recorded_plan`, and `fsdp2_wrap`
refuses with a `ValueError`, as `set_distribution_plan` does for the
same record, rather than a `RuntimeError`; its test expects the
`ValueError`. Source insertions: 543. Pre-commit, mypy included, passes
against main; `tests/unit/torch/utils` and the hf_ptq example tests pass
on CPU with transformers 5.18 and 5.5.4, and `tests/unit/torch/utils`
without transformers (346 passed, 33 skipped).
- Review suggestions, 2026-10-30 (Claude's approving review at
`4ffccd8088a`): a whole-model load takes `cpu_offload=False`, the FSDP2
load's own default and what hf_ptq passes without `--cpu_offload`, as
asking nothing (new `cpu_offload_at_its_default` row, which fails
without the change); the refusal of placement options under a layout
rank 0's GPU memory chose moved into `_refuse_sharded_load_options`,
which already decides which options place a whole model, and uses
`_whole_instead` for its way out (the refusals are unchanged). Source
insertions: 538. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 and 5.5.4, and `tests/unit/torch/utils` without
transformers (346 passed, 33 skipped).
- Review fixes, 2026-10-30 (Claude): under a layout rank 0's GPU memory
chose, the FSDP2 load's refusals of a quantized checkpoint and of one
carrying an MTP head name the way to load it whole, as its other
refusals do, and the changelog lists them
(`test_a_measured_layout_names_the_way_back_when_it_refuses_a_checkpoint`,
which fails without the change); the docstring says which FSDP2-only
options a whole load takes as asking nothing; the dtype check is written
once. Source insertions: 540. Pre-commit, mypy included, passes against
main; `tests/unit/torch/utils` and the hf_ptq example tests pass on CPU
with transformers 5.18 and 5.5.4, and `tests/unit/torch/utils` without
transformers (346 passed, 33 skipped).
- Fix, 2026-10-30 (found on #3136 by meenchen's review, agreed with that
PR): a rank's own GPU is the one its process is bound to once CUDA is
initialized, as torch's DeviceMesh takes it, else the one its local rank
numbers (`_own_gpu_index()`, with `_has_own_gpu()` over it). A launch
that exposes one GPU to each process, each bound to cuda:0, no longer
reads every rank but the first as GPU-less: the FSDP2 load no longer
refuses it, a whole load no longer leaves it on the CPU with a warning,
and both place onto the bound device
(`test_a_rank_bound_to_its_one_visible_gpu_loads_onto_it`, and the
two-rank `test_one_visible_gpu_per_process_shards_on_every_rank`, both
failing without the change). Source insertions: 556. Pre-commit, mypy
included, passes against main; `tests/unit/torch/utils` and the hf_ptq
example tests pass on CPU with transformers 5.18 and 5.5.4, and
`tests/unit/torch/utils` without transformers (346 passed, 33 skipped).
- Review fixes, 2026-10-30 (Claude): an EP degree left to the plan
decision is decided as 1, so a multi-rank load of an MoE with no knob
set loads without expert parallelism instead of being refused, while a
degree `MODELOPT_EP_DEGREE` asks for is still refused
(`test_a_load_it_decides_keeps_the_experts_whole`, whose left-to-decide
row fails without the change); a whole-model load takes
`broadcast_chunk_size=8`, the FSDP2 load's own default, as asking
nothing (new row). Source insertions: 563. Pre-commit, mypy included,
passes against main; `tests/unit/torch/utils` and the hf_ptq example
tests pass on CPU with transformers 5.18 and 5.5.4, and
`tests/unit/torch/utils` without transformers (346 passed, 33 skipped).
- Rebased on 2026-10-30 onto #3140 `74a636f02c0`, itself on main
`059588b89a5`, without conflicts; this PR's own diff is unchanged.
Pre-commit, mypy included, passes against main; `tests/unit/torch/utils`
and the hf_ptq example tests pass on CPU with transformers 5.18 and
5.5.4, and `tests/unit/torch/utils` without transformers.
- Review suggestions, 2026-10-30 (Claude, at `47ca6d1c422`):
`MODELOPT_EP_DEGREE` or `MODELOPT_FSDP_SIZE` set to whitespace only
reads as unset (`auto`), as an empty one does, instead of being refused:
`env.py` strips both knobs, and the two parses no longer strip their own
(new `exported-blank` rows, which fail without the change). The
docstring says a sharded load builds a text-only VLM through its
image-text class itself and takes no `auto_class` but
`AutoModelForCausalLM`, so leave it out for one. Source insertions: 567.
Pre-commit, mypy included, passes against main; `tests/unit/torch/utils`
and the hf_ptq example tests pass on CPU with transformers 5.18 and
5.5.4, and `tests/unit/torch/utils` without transformers (345 passed, 35
skipped).
- Review suggestions, 2026-10-30 (Claude, at `e78cbe68469`): the
docstring says an option at `from_pretrained`'s own default,
`device_map=None` included, places nothing and does not keep a load
whole. A launch without a group that `MODELOPT_EP_DEGREE` asks to shard
is told to set `MODELOPT_EP_DEGREE=1` as well, since no load here shards
the routed experts. A sharded load's refusal of an `auto_class` names
its way out (leave it out, or load the model whole with it), and both
`auto_class` refusals say which class the load builds. The `ep-knob` and
`model_class` test rows now expect the way out and fail without the
change. Messages and docstring only. Source insertions: 577. Pre-commit,
mypy included, passes against main; `tests/unit/torch/utils` and the
hf_ptq example tests pass on CPU with transformers 5.18 and 5.5.4, and
`tests/unit/torch/utils` without transformers (345 passed, 35 skipped).
- Rebased on 2026-10-30 onto #3140 `b4445d14a8a`, itself on main
`d464d30b120`, without conflicts; this PR's own diff is unchanged.
Pre-commit, mypy included, passes against main; `tests/unit/torch/utils`
and the hf_ptq example tests pass on CPU with transformers 5.18 (778
passed) and 5.5.4 (757 passed, 21 skipped), and `tests/unit/torch/utils`
without transformers (346 passed, 36 skipped).
- Review fixes, 2026-10-31 (cjluo-nv): a load whose plan the load
decides parses `MODELOPT_EP_DEGREE` in the load-arguments check, so a
knob one rank cannot parse fails every rank instead of leaving rank 0 in
the plan decision's collectives
(`test_a_knob_one_rank_cannot_parse_fails_every_rank`, two ranks, which
fails on the group's bound without the change). The unit tests pin the
CUDA state the GPU check reads (`_pin_cuda`), so a host process that set
CUDA up no longer hands them cuda:0; with CUDA set up beforehand, five
of them failed before. `load_pretrained`'s docstring is shortened to the
routes, the record and the refusal guarantees, its extended guidance
moved to Routing details above, and the routing's comments are
tightened, with no change in behaviour: source insertions 483 against
#3140. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 (779 passed) and 5.5.4 (758 passed, 21 skipped), and
`tests/unit/torch/utils` without transformers (346 passed, 36 skipped).
- Review suggestions, 2026-10-31 (Claude, at `54ae57e1cfd`): the refusal
under a layout rank 0's GPU memory chose says the options it refuses do
not apply to a sharded load, rather than that they place a whole model,
as they are any keyword the sharded load does not take (its `placed` row
now matches the new wording and fails without the change). The docstring
says to pass `device_map=None` where the model is placed otherwise, as
under `init_quantized_weights`, which refuses the per-rank `device_map`
a distributed whole-model load defaults to. Source insertions: 484
against #3140. Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils` and the hf_ptq example tests pass on CPU with
transformers 5.18 (779 passed) and 5.5.4 (758 passed, 21 skipped), and
`tests/unit/torch/utils` without transformers (346 passed, 36 skipped).
- Review fixes, 2026-10-31 (cjluo-nv, at `32179e5ad47`): a sharded load
is refused inside `init_quantized_weights`, on every rank and before
anything loads, since the FSDP2 load builds the model with `from_config`
and would skip the quantization and compression the context's
`from_pretrained` applies
(`test_a_sharded_load_is_refused_inside_init_quantized_weights`, with
the automatic layout forced to FSDP2 inside the real context and with a
handed sharded plan, fails without the change). The routing guidance is
published as a docs page, which `load_pretrained`'s docstring links, and
the docstring and the page say a sharded load's `from_config` takes no
Hub options. Source insertions: 494 against #3140. Pre-commit, mypy
included, passes against main; the docs build passes with warnings as
errors; `tests/unit/torch/utils`, the hf_ptq example tests and the
accelerate plugin tests pass on CPU with transformers 5.18 (784 passed)
and 5.5.4 (763 passed, 21 skipped), and `tests/unit/torch/utils` without
transformers (346 passed, 36 skipped).
- Review fix, 2026-10-31 (Claude, at `6ed77327b96`): inside
`init_quantized_weights`, a multi-rank load whose plan the load decides
gives every rank the whole model when nothing asks to shard, without
measuring it, and leaves the device map to the context, which computes
it and refuses one passed; before, it was refused when the layout
sharded and failed on an injected `device_map` when it replicated. A
knob or a handed plan that asks to shard is still refused.
`test_a_load_it_decides_inside_init_quantized_weights_is_whole_and_unplaced`
(rank 0's GPU memory fitting the model or not) fails without the change.
Source insertions: 495 against #3140. Pre-commit, mypy included, passes
against main; `tests/unit/torch/utils`, the hf_ptq example tests and the
accelerate plugin tests pass on CPU with transformers 5.18 (786 passed)
and 5.5.4 (765 passed, 21 skipped), and `tests/unit/torch/utils` without
transformers (346 passed, 36 skipped).
- Rebased on 2026-10-31 onto #3140 `30ab95bdb53`, itself on main
`e352caca3c3`, without conflicts; this PR's own diff is unchanged.
Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils`, the hf_ptq example tests and the accelerate
plugin tests pass on CPU with transformers 5.18 (786 passed) and 5.5.4
(765 passed, 21 skipped), and `tests/unit/torch/utils` without
transformers (346 passed, 36 skipped).
- Review suggestion, 2026-10-31 (Claude, at `c78d2e50ed6`): the
changelog's backward-breaking entry lists what the sharded load refuses,
the class refusal of a layout rank 0's GPU memory chose included, in two
sentences, and the whole load's per-rank GPU placement is its own
bullet. Text only. Source insertions: 496 against #3140. Pre-commit,
mypy included, passes against main.
- Review fix, 2026-10-31 (cjluo-nv, at `0d3d0937c05`): a distributed
whole-model load places the model, and warns on a rank without a GPU of
its own, inside the guard that fails every rank when one fails, so a
rank that raises the warning as an error no longer leaves the others
waiting in the guard's collective
(`test_a_placement_warning_raised_on_one_rank_fails_every_rank`, two
gloo ranks on a bounded group, fails without the change). Source
insertions: 494 against #3140. Pre-commit, mypy included, passes against
main; `tests/unit/torch/utils`, the hf_ptq example tests and the
accelerate plugin tests pass on CPU with transformers 5.18 (787 passed)
and 5.5.4 (766 passed, 21 skipped), and `tests/unit/torch/utils` without
transformers (346 passed, 36 skipped).
- Rebased on 2026-11-01 onto #3140 `db1a28a6f99`, itself on main
`cf38ec30ca4`, without conflicts; this PR's own diff is unchanged.
Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils`, the hf_ptq example tests and the accelerate
plugin tests pass on CPU with transformers 5.18 (787 passed) and 5.5.4
(766 passed, 21 skipped), and `tests/unit/torch/utils` without
transformers (346 passed, 36 skipped).
- Rebased on 2026-11-01 onto main `51645db66dc`, after #3140 merged as
that squash, dropping #3140's own commits; the squash's tree is #3140's
last head's, so this PR's own diff and its tree are unchanged.
Pre-commit, mypy included, passes against main;
`tests/unit/torch/utils`, the hf_ptq example tests and the accelerate
plugin tests pass on CPU with transformers 5.18 (787 passed) and 5.5.4
(766 passed, 21 skipped), and `tests/unit/torch/utils` without
transformers (346 passed, 36 skipped).

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

- Is this change backward compatible?: ❌ Three changes are filed under
Backward Breaking Changes. A multi-rank `load_pretrained` now decides
how to distribute the model rather than load it whole on every rank
(`MODELOPT_FSDP_SIZE=1` and `MODELOPT_EP_DEGREE=1`, or a replicated
plan, keep it whole), and a model it loads whole goes onto each rank's
own GPU unless `device_map` is passed. `load_pretrained` records the
plan on the model it returns, even in a single process, and `fsdp2_wrap`
now refuses a model that records one (wrap a model loaded with
`from_pretrained`). Otherwise a single process loads as before unless a
plan it is handed shards the model, and `distribution` is new.
`fsdp2_wrap`'s old import path still works (#3140).
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅ 0.49.0: Misc, and three Backward Breaking Changes entries.
- Did you get Claude approval on this PR?: ✅ Approved 2026-10-29 at
`1064e3d09ce`, after the fetch fix; its suggestions are answered in
their threads. Approved again at `3160a0fb703` after the config-path
fix; its suggestion is taken in `6c36e2f8a88`; its reviews since are
answered in `f065849c295`, `c53b4863b21` and `cb7fb1e8495`; approved
again at `cb7fb1e8495` and `d9d394b8f55`, their suggestions taken in
`1b308a07425` and `a51881aa6a8`, re-requested.

### Additional Information

Part 6 of 21 of expert-parallel PTQ for Hugging Face MoE models, now
[2/2] after #3140; #2737, below it, merged on 2026-10-29. The
expert-parallel half of this routing is #2780.

Replaces #2774, which carried this routing whole as [19/20]. Moving its
branch down the stack made the branch part of #2774's old base, so
GitHub closed #2774 as merged into that base; nothing reached main.

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

## Summary by CodeRabbit

* **New Features**
* Distributed loading supports replicated or FSDP2-sharded models
through configurable distribution plans, which are recorded on loaded
models. Automatic plan selection and Hub authentication and caching
options are supported.

* **Documentation**
* Added guidance for distributed loading and distribution-plan
recording.
<!-- 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.

4 participants