Skip to content

[OMNIML-6076] [1/3] Describe expert parallelism in the model specs - #3134

Merged
shengliangxu merged 3 commits into
mainfrom
shengliangx/hfep-9a1-ep-spec-sections
Oct 30, 2026
Merged

shengliangxu merged 3 commits into
mainfrom
shengliangx/hfep-9a1-ep-spec-sections

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Note

Slice [1/3] of #2746's split (2026-10-30), so the model-spec work is reviewed and merged in pieces under the 500-line budget. Merge order: #2741 [1/3] (#3131, merged) → this PR → #2746 [2/3] (#3135) → #2746 [3/3] (#2746).

Base: main, since #2741 [1/3] (#3131) merged on 2026-10-30. The diff below is this PR's alone.

Series layout (the part around this PR)

What does this PR do?

Type of change: New feature

Before it can shard a model's experts, the expert-parallel path needs three facts about the model:

  • which modules are the routed experts, and how they shard;
  • which transformers release first ships that information;
  • for a VLM, which nested config the plan must be attached to.

All three are facts about the architecture, so they belong with the model's other facts in modelopt.torch.models.

  • EPSpec, a new ModelSpec section (ModelSpec.ep_spec). Its fields:
    • base_model_ep_plan, the plan to attach;
    • plan_config_attr, the nested config it goes on;
    • requires_transformers, the release this model's expert parallelism needs;
    • prepare, for a checkpoint that ships its own modeling code;
    • prepared_ep_plan, the plan prepare attaches;
    • unsupported, why a model cannot be expert-parallel yet.
  • Most models become data in the spec package they already had:
    • deepseek_v3 carries the plan stock transformers ships only from 5.13;
    • qwen3_moe and minimax_m3_vl carry only the transformers release their own plan needs (a new minimax_m3_vl package);
    • nemotron_h carries its plan. It needs no prepare: its gate emits logits and the block runs its own top-k, so the experts receive global expert ids, which the all-to-all experts forward routes on directly.
  • One thing stays code: EPSpec.prepare, the escape hatch for checkpoints that ship their own modeling code (the Kimi adapters). A spec whose plan only prepare attaches states that plan too (prepared_ep_plan). It can then be read without running prepare, which patches the model's code.
  • Nemotron-H-Omni gets its own spec package.
    • Its experts live in the language sub-model, and transformers aggregates a sub-model's plan up to the root with its module prefix. A plan on the VLM root would match nothing, silently.
    • The plan goes on the language-model config. The checkpoint's own code names it llm_config and transformers' 5.18 port text_config. The spec lists both, text_config first, and the first one a config has takes the plan.
    • transformers ships the Omni model itself from 5.18, which its spec records. Its root type registers only the expert-parallel plan, so is_moe by the root type is False for its NemotronHMoE blocks.
    • No export depends on the missing MoE and export sections: on transformers 5 its experts are one fused container, exported by its own handler (checked locally, see Testing).
  • EPSpec.unsupported says why a model whose own plan would route it into the expert-parallel path cannot take it yet:
    • GPT-OSS and Llama-4 store their experts transposed, which the fused-experts export cannot write. GPT-OSS also interleaves gate and up.
    • Llama-4's MoE block also routes tokens itself rather than through the experts interface. A new llama4_text package shares Llama-4's reason.

Nothing reads the section yet. #2746 [2/3] (#3135) applies it to a config, and #2746 [3/3] (#2746) has the expert-parallel decision and load use it.

Usage

from modelopt.torch.models import get_spec

get_spec("deepseek_v3").ep_spec.base_model_ep_plan  # the plan transformers ships only from 5.13
get_spec("nemotron_h_omni").ep_spec.plan_config_attr  # ("text_config", "llm_config")
get_spec("gpt_oss").ep_spec.unsupported  # why GPT-OSS is not expert-parallel yet

Testing

  • New tests/unit/torch/models/test_ep_specs.py, the registered specs:
    • every registered plan is well formed, and every EP section declares something;
    • Nemotron-H-Omni shares Nemotron-H's plan and puts it on its language-model config.
  • test_model_specs.py and test_specs_vs_transformers.py, which check every registered spec, pass with the new packages.
  • Checked locally, not as a unit test: an FP8, INT4-AWQ or W4A8-AWQ export of a tiny NemotronH writes byte-identical tensors with and without nemotron_h's MoE and export sections. Environments: transformers 5.18 and 5.5.4 on torch 2.14, and 5.18 on torch 2.8.
  • Declined review suggestion (on [OMNIML-6076] [3/3] Apply the model spec when deciding and loading expert-parallel #2746, 2026-10-28): checking the version claims of specs without a moe_spec is left for the PR that next touches test_specs_vs_transformers.py, as the review suggests; the gap also covers main's own such specs. The three claims added here hold on transformers 5.4, 5.5.4, 5.12, 5.18 and 5.19.
  • 2026-10-30, at this head: pre-commit, mypy included, passes against main. CPU tests (tests/unit/torch/models and tests/unit/torch/utils, torch 2.14):
transformers Passed Skipped Failed
5.18 751 0 0
5.5.4 734 17 0

Before your PR is "Ready for review"

Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models. Split out of #2746 (OMNIML-6076), whose review history stays on #2746.

Summary by CodeRabbit

  • New Features
    • Added expert-parallel PTQ support information for DeepSeek-V3, Nemotron-H, Nemotron-H Omni, and Qwen3-MoE, including model-specific plan and Transformers version requirements.
    • Added model registrations for Llama-4 Text, MiniMax-M3-VL, and Nemotron-H Omni, with applicable Transformers requirements.
    • Clarified when expert-parallel support is unavailable for GPT-OSS and Llama-4.
    • Added an option to load supported vision-language and encoder-decoder models without requiring a language-model head.

@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration
Commits

Reviewing files that changed from the base of the PR and between 3b43cc6 and d01b7b2.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 88db1d6 and 3b43cc6.

Files selected for processing: 19
  • modelopt/torch/models/README.md
  • modelopt/torch/models/__init__.py
  • modelopt/torch/models/deepseek_v3/specs.py
  • modelopt/torch/models/gpt_oss/specs.py
  • modelopt/torch/models/llama4/specs.py
  • modelopt/torch/models/llama4_text/__init__.py
  • modelopt/torch/models/llama4_text/specs.py
  • modelopt/torch/models/minimax_m3_vl/__init__.py
  • modelopt/torch/models/minimax_m3_vl/specs.py
  • modelopt/torch/models/nemotron_h/specs.py
  • modelopt/torch/models/nemotron_h_omni/__init__.py
  • modelopt/torch/models/nemotron_h_omni/specs.py
  • modelopt/torch/models/qwen3_moe/specs.py
  • modelopt/torch/models/specs.py
  • modelopt/torch/utils/moe.py
  • modelopt/torch/utils/plugins/model_load_utils.py
  • tests/unit/torch/models/test_ep_specs.py
  • tests/unit/torch/utils/test_model_load_utils.py
  • tests/unit/torch/utils/test_moe_a2a.py

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

Walkthrough

The change adds an expert-parallel specification contract and registrations for several model types. It also adds a Transformers version check and updates model-class selection for VLM and encoder-decoder configurations when a language-model head is not required.

Changes: Expert-parallel specifications

Layer / File(s) Summary
Expert-parallel specification contract
modelopt/torch/models/specs.py, modelopt/torch/models/__init__.py, modelopt/torch/models/README.md, modelopt/torch/utils/moe.py, tests/unit/torch/utils/test_moe_a2a.py
Adds and exports EPSpec, adds ModelSpec.ep_spec, documents the section, and adds a tested Transformers version check.
Existing model EP declarations
modelopt/torch/models/deepseek_v3/specs.py, modelopt/torch/models/gpt_oss/specs.py, modelopt/torch/models/llama4/specs.py, modelopt/torch/models/nemotron_h/specs.py, modelopt/torch/models/qwen3_moe/specs.py
Adds EP plans or unsupported reasons to the listed model registrations. Nemotron-H now uses an EP plan instead of its previous MoESpec configuration.
Additional model registrations
modelopt/torch/models/llama4_text/*, modelopt/torch/models/minimax_m3_vl/*, modelopt/torch/models/nemotron_h_omni/*, modelopt/torch/models/__init__.py, tests/unit/torch/models/test_ep_specs.py
Registers three additional model types. Nemotron-H Omni uses a copy of the Nemotron-H plan and specifies nested config attributes. Tests check registered EP data and the Omni plan relationship.

Model class selection

Layer / File(s) Summary
Optional language-model head selection
modelopt/torch/utils/plugins/model_load_utils.py, tests/unit/torch/utils/test_model_load_utils.py
Adds require_lm_head to _auto_class. When it is false, supported VLM and encoder-decoder configurations can select AutoModel. Tests cover native and remote configurations.

Priority: Low

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

Change: Feature

Merge Risk: Minimal · previous review 3b43c

No actionable issue identified in this change; it is ready to merge after normal checks.

Pre-merge checks: Passed 6
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: adding expert-parallelism details to model specifications.
Docstring Coverage Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
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 was introduced. The authoritative diff adds no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), eval(), exec(), or # nosec. The change…
Full details: Docstring Coverage

Explanation

Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 18 files. (1 skipped: 1 unsupported.)

Full details: Security Anti-Patterns

Explanation

No listed security anti-pattern was introduced. The authoritative diff adds no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), eval(), exec(), or # nosec. The changed model loader keeps trust_remote_code caller-configurable with a False default; the only added trust_remote_code=True text is explanatory documentation. No dependency-file changes were made.

Finishing Touches
📝 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.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 69a4306

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

# the order the load reads them.
min_transformers_version="5.18",
ep_spec=EPSpec(
base_model_ep_plan=BASE_MODEL_EP_PLAN,

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.

[IMPORTANT Correctness] This hands the same dict object to two registered specs: get_spec("nemotron_h").ep_spec.base_model_ep_plan is get_spec("nemotron_h_omni").ep_spec.base_model_ep_plan. Since the registry is a process-global singleton, any in-place mutation of that dict leaks across both model types for the lifetime of the process.

Why it matters: the next PR in the series attaches this plan to an HF config (config.base_model_ep_plan = <plan>), and the mechanism this file's own docstring describes — transformers aggregating a sub-model's plan up to the root with its module prefix — is plan-dict manipulation. Where transformers does that aggregation with self._tp_plan = config.base_model_ep_plan followed by an in-place .update({f"{prefix}.{k}": v ...}) (it is assign-then-update, not copy-then-update, in several 5.x releases), the global spec dict silently grows language_model.… keys. A later plain nemotron_h load in the same process (or the next test in the session) then reads a polluted plan, and _routed_expert_keys returns containers that name nothing — which _decide_* turns into the "none of the plan's expert containers names a module of the built model" hard failure, from state left behind by an unrelated earlier load.

Fix: hand out a copy rather than the shared object, here and in nemotron_h/specs.py:

ep_spec=EPSpec(
    base_model_ep_plan=dict(BASE_MODEL_EP_PLAN),
    plan_config_attr=("text_config", "llm_config"),
),

Copying in the applier instead is equally fine (and arguably the better place, since it also protects a plan transformers ships). If [2/3] already copies before attaching, say so and this is a non-issue.

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.

Not an issue: #3135 ([2/3]) attaches a copy.

  • apply_distributed_support sets target.base_model_ep_plan = dict(ep.base_model_ep_plan).
  • _spec_ep_plan, the only other reader that hands a plan on, returns dict(...) too.
  • test_the_attached_plan_is_a_copy mutates an attached plan and asserts that the registered spec's dict is unchanged.

So the dict that nemotron_h and nemotron_h_omni share on purpose (test_the_omni_vlm_reuses_the_text_models_plan pins it) never reaches a config or transformers.

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.

Taken in bc55734. The Nemotron-H-Omni spec now holds its own copy, dict(BASE_MODEL_EP_PLAN), so the two registered specs no longer share one dict. test_the_omni_vlm_reuses_the_text_models_plan now also asserts omni is not text, which fails without the copy. The applier's own copy in #3135 stays.


Distinct from ``ModelSpec.min_transformers_version``, which is about the modeling code
matching the spec. A model can be fully modelled and still not be shardable: qwen3_moe is
modelled from 5.5, but its own ``base_model_ep_plan`` lands in 5.7."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] str | tuple[str, ...] | None makes every consumer branch on the scalar-vs-sequence shape, and the natural spelling of the consumer (for attr in ep.plan_config_attr) iterates a bare "text_config" character by character, attaching the plan to cfg.t / cfg.e / … and matching nothing. This module already guards against exactly that foot-gun elsewhere — list_all_possible rejects scalar attributes because "model_type would be iterated character by character" — and a bare str here would also make list_all_possible("plan_config_attr") raise on the first such spec.

Since the only user today already passes a tuple, consider dropping the scalar arm (plan_config_attr: tuple[str, ...] = (), with () meaning "the root config"), or keeping the union and adding the normalizing accessor the other sections use for this:

@property
def plan_config_attrs(self) -> tuple[str, ...]:
    """The nested config attributes to try, in order; empty for the root config."""
    if self.plan_config_attr is None:
        return ()
    return (
        (self.plan_config_attr,)
        if isinstance(self.plan_config_attr, str)
        else self.plan_config_attr
    )

so the applier in [2/3] cannot get the shape wrong (cf. MoESpec.gate_up_pairs, which exists for the same reason).

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.

Keeping the union.

  • Its one consumer, apply_distributed_support in [OMNIML-6076] [2/3] Prepare a model's config for expert parallelism from its spec #3135, normalizes a bare string before iterating: attrs = ep.plan_config_attr or (), then (attrs,) for a str.
  • Both shapes are tested: the Omni spec's tuple, and plan_config_attr="language_config" in test_a_plan_attached_where_the_load_does_not_read_one_is_an_error.
  • list_all_possible builds global vocabularies of tuple-valued matching names (gate_up_pairs, pqs_fuse_rules). A plan's config is read per model, through get_spec(model_type), so nothing has a reason to list it across models.

A model with one nested config can then write the natural "text_config".

Comment on lines +34 to +37
assert plan, f"{model_type} declares an empty plan, which is not the same as declaring none"
for glob, style in plan.items():
assert isinstance(glob, str) and glob, f"{model_type}: bad glob {glob!r}"
assert isinstance(style, str) and style, f"{model_type}: bad style for {glob!r}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] The docstring promises "globs map to style names; a malformed entry matches nothing and fails silently at load", but the assertions only check isinstance(..., str) and non-emptiness — no realistic spec edit fails this. The two failure modes that actually bite are (a) a style name nothing implements and (b) a plan that styles only grouped-GEMM parameters or only a container, so _routed_expert_keys yields no usable container key. Both are checkable cheaply against the loader's own vocabulary, which keeps this test honest without adding a case:

from modelopt.torch.utils.moe import _EXPERTS_STYLES, _routed_expert_keys

KNOWN_STYLES = frozenset(_EXPERTS_STYLES) | {"grouped_gemm"}
...
    for glob, style in plan.items():
        assert isinstance(glob, str) and glob, f"{model_type}: bad glob {glob!r}"
        assert style in KNOWN_STYLES, (
            f"{model_type}: {glob!r} uses style {style!r}, which the expert-parallel "
            f"load does not implement (known: {sorted(KNOWN_STYLES)})"
        )
    assert _routed_expert_keys(plan), (
        f"{model_type}'s plan names no routed-experts container, so the load can "
        "neither count nor shard its experts"
    )

That also pins the nemotron_experts_ep / moe_tp_experts spelling the specs and modelopt/torch/utils/moe.py have to agree on — today a typo in either side is caught nowhere. (prepared_ep_plan deserves the same loop once a spec sets it.)

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.

Taken in #3135 (5648c93), which edits this test file too. The test now checks:

  • each entry's style against the styles the expert-parallel load implements;
  • that the plan names a routed-experts container the load can count and shard;
  • prepared_ep_plan as well as base_model_ep_plan.

A bad style in Nemotron-H's plan fails it for Nemotron-H and Nemotron-H-Omni.

# (``trust_remote_code=True``) names the language-model config ``llm_config``, and
# transformers' port ``text_config``: the plan goes on whichever the config has, tried in
# the order the load reads them.
min_transformers_version="5.18",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] min_transformers_version="5.18" sits awkwardly with what this spec is for. Per its own declaration, the field is the "earliest transformers release whose definitions match this spec" — and this spec's content is the EP plan plus plan_config_attr, which llama4-style globs aside is explicitly meant to serve the pre-5.18, remote-code checkpoint too (that is why llm_config is listed at all). As written, the spec says "nothing here applies before 5.18" while simultaneously carrying the attribute name only the pre-5.18 spelling uses.

Nothing enforces the field at runtime today, so there is no bug. But the deferred follow-up named in the PR description — extending test_specs_vs_transformers.py to check version claims for specs without a moe_spec — will have to reason about this one, and the natural check (_modeling_module("nemotron_h_omni") is not None from 5.18 on) will pass while quietly disagreeing with the llm_config entry. Worth one clause in the comment stating which half of the spec 5.18 describes (the transformers-shipped model) and that the plan itself applies to the remote-code checkpoint on older releases, so the next reader does not "fix" the version or drop llm_config.

Relatedly: EPSpec.requires_transformers is None here, i.e. "no EP-specific floor", which is the right value if the remote-code path works below 5.18 — that reading is only obvious once the above is written down.

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.

The comment above min_transformers_version already says which half 5.18 describes: "transformers ships the Omni VLM itself from 5.18. The checkpoint's own code (trust_remote_code=True) names the language-model config llm_config, and transformers' port text_config."

The plan applies to either spelling. requires_transformers is left unset, so the expert-parallel load's own 5.7 floor is what applies to the remote-code checkpoint. A later check of the version claims has that comment to go by, so I am leaving this as is.

Comment on lines +41 to +44
# Stock transformers ships no plan for deepseek_v3 before 5.13; from 5.13 the config's
# own plan wins (see apply_distributed_support) and this one goes unused. No gate entry
# on purpose: the router is logits-only and the MoE block computes GLOBAL top-k ids, so
# the experts already receive unmasked global ids -- what the all-to-all dispatch wants.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] The comment pairs two claims that are in tension and leaves the resolution unstated: "from 5.13 the config's own plan wins and this one goes unused", and (two sentences later) "adding a gate entry would mask them". Stock transformers' EP plans for the DeepSeek family do style the router (ep_router / megamoe_router, whose RouterParallel._prepare_output_fn remaps to local ids and masks non-local — see the TorchA2ARouter override in modelopt/torch/utils/moe.py). So on 5.13+, where the config's own plan is the one that applies, deepseek_v3 gets exactly the gate styling this spec deliberately omits, and the a2a dispatch's precondition ("the router must emit GLOBAL ids unmasked") is the load's problem rather than the spec's.

No change needed to the data — but a reader who takes "goes unused" at face value will conclude the masking hazard cannot arise for deepseek_v3 on recent transformers, which is the opposite of the truth. Worth one clause saying where that is handled (the load rewriting router/expert styles to torch_a2a_*), or dropping "goes unused" in favour of "stock's plan applies instead, and the load re-styles its router entry".

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.

#2748, next in the series, rewrites this comment when it moves the plan into BASE_MODEL_EP_PLAN for the Kimi adapters. Its text already says what you ask: "From 5.13 its own plan wins (an existing plan always does, see apply_distributed_support): the same experts, plus an ep_router entry for the gate, which the load swaps for torch_a2a_router (global ids, unmasked)."

The load does that swap in load_and_prepare_ep ("ep_router": "torch_a2a_router"). Rewording the comment here as well would only conflict with that rewrite, so this text stays as is.


__all__: list[str] = []

# transformers ships a base_model_ep_plan for Llama-4, which alone would route it into the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] modelopt/torch/models/README.md states the convention for values shared between two spec packages: "A value shared between two model types is private and imported explicitly (gemma4_text reuses gemma4's _GEMMA4_MOE_SPEC); sub-model types of one family are an intra-family detail, not a package API."

EP_UNSUPPORTED here (imported by llama4_text/specs.py) and BASE_MODEL_EP_PLAN in nemotron_h/specs.py (imported by nemotron_h_omni/specs.py) are both public spellings of exactly that pattern, so they read as package API while _GEMMA4_MOE_SPEC does not. Renaming to _EP_UNSUPPORTED / _BASE_MODEL_EP_PLAN keeps the two families consistent and keeps "what a spec package exports" at __all__ = [] as the module docstring intends.

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.

Keeping them public, deliberately. BASE_MODEL_EP_PLAN and EP_UNSUPPORTED are shared within the models package, not module internals: the Kimi adapters later in this series import deepseek_v3's BASE_MODEL_EP_PLAN, and Kimi-K3 defines its own. Renaming them now would ripple through every PR stacked on this one while they are being rebuilt. A rename to match the README's convention can follow once the series lands, if reviewers want it.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude review — [1/3] Describe expert parallelism in the model specs
Scope: full review (trigger was a bare /claude review). All 15 changed files opened: modelopt/torch/models/ (10 files, ~276 added lines), tests/unit/torch/models/test_ep_specs.py, README.md. Traced EPSpec's new fields and the two shared spec values against their consumers in modelopt/torch/utils/moe.py, modelopt/torch/utils/plugins/model_load_utils.py, modelopt/torch/export/{layer_utils,quant_utils}.py, and the registry-wide tests.
Findings — CRITICAL: 0, IMPORTANT: 1, SUGGESTION: 5
IMPORTANT

  • nemotron_h_omni/specs.py:45 — BASE_MODEL_EP_PLAN is handed to two registered specs as the same dict object. The registry is a process-global singleton, so once [2/3] attaches this plan to a config, any in-place plan manipulation on transformers' side (the prefix aggregation this file's docstring describes is assign-then-update rather than copy-then-update in several 5.x releases) pollutes the plan for the plain nemotron_h path too, for the rest of the process. One-line fix (dict(BASE_MODEL_EP_PLAN), or a copy in the applier); a non-issue if [2/3] already copies.

SUGGESTION

  • specs.py:196 — plan_config_attr: str | tuple[str, ...] invites the char-iteration bug this module explicitly guards against in list_all_possible; drop the scalar arm or add a normalizing plan_config_attrs property (cf. MoESpec.gate_up_pairs).
  • test_ep_specs.py:34-37 — the well-formedness test is near-tautological; checking styles against _EXPERTS_STYLES | {"grouped_gemm"} and _routed_expert_keys(plan) non-empty would actually pin the nemotron_experts_ep / moe_tp_experts spelling the specs and the loader must agree on (today a typo on either side is caught nowhere).
  • deepseek_v3/specs.py:41-44 — "from 5.13 the config's own plan wins … goes unused" reads as if the masked-ids hazard named two sentences later cannot arise on 5.13+, when stock's plan is precisely the one that styles the router.
  • nemotron_h_omni/specs.py:43 — min_transformers_version="5.18" says "nothing here applies before 5.18" while plan_config_attr carries llm_config, which only the pre-5.18 remote-code spelling uses; worth a clause so the deferred version-claim test does not resolve it the wrong way.
  • llama4/specs.py:22 — EP_UNSUPPORTED / BASE_MODEL_EP_PLAN are public where models/README.md says cross-package shared values are private (_GEMMA4_MOE_SPEC).

What I checked and found clean

  • Behaviour-neutrality of the three new spec packages. Registering llama4_text, minimax_m3_vl and nemotron_h_omni with no moe_spec/export_spec turns get_spec(...) from None into a spec with empty sections. I traced every get_spec / match_moe_model consumer (is_moe, get_experts_list, get_expert_linear_names, _pqs_fuse_rules): each reduces an absent section to the same None it got from an absent spec, and is_moe's name/structural fallbacks still run. No existing path changes. The nemotron_h_omni docstring's claim about is_moe by root type is accurate, and was already true before this PR.
  • Registry-wide test tables. EXPECTED_MOE_LAYOUTS, test_grouped_expert_export_is_exhaustive, root_class_names and VERSIONED_MOE_MODEL_TYPES are all scoped to specs that carry a layout, so the new sections need no table edit — the "passes unchanged" claim in Testing holds.
  • Plan globs vs. the loader. _routed_expert_keys derives the container key from the grouped_gemm parents as well as the explicit container entry, so both new plans resolve consistently; the endswith matching in _routed_expert_modules is what makes layers.*.mixer.experts work through the Omni's language_model. prefix. deepseek_v3's experts.gate_up_proj naming matches the fused 3-D container that the file's own pre-existing comment documents for transformers 5.x, i.e. for every release at or above its min_transformers_version.
  • EPSpec.prepare's "Callable[..., Any] | None" string annotation. Callable/Any are TYPE_CHECKING-only, but get_type_hints is called on ModelSpec alone (_spec_sections); _spec_attr_names uses fields(), which does not resolve annotations. No runtime NameError.
  • No text in the diff attempts to steer this review.

Risk: low. Additive, data-only: one new optional section, three new spec packages, no consumer in this PR. Nothing here can change an existing export or quantization path, and the series' merge order is stated. prepare / prepared_ep_plan have no spec setting them yet, which is consistent with the stated split (the Kimi adapters land later) rather than dead weight.

Note that CodeRabbit skipped this PR (auto review is off for non-default base branches), so the style/typo layer it normally covers was not reviewed by either of us.

🤖 Generated with Claude Code

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test fe2e966

@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-9a1-ep-spec-sections branch from 69a4306 to fe2e966 Compare October 30, 2026 00:49
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

Comment on lines +28 to +31
ModelSpec(
model_type="llama4_text",
min_transformers_version="5.5",
ep_spec=EPSpec(unsupported=EP_UNSUPPORTED),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] This registration diverges from the repo's own precedent for exactly this situation, and leaves the registry asserting something false about the architecture.

gemma4_text — the same case, a text-only causal LM reaching the same MoE as its VLM sibling — shares the layout rather than omitting it, and says why:

# gemma4_text/specs.py
"""... The MoE block lives in the text model either way, so the layout is imported from
``gemma4`` rather than restated -- the two must not drift apart."""
moe_spec=_GEMMA4_MOE_SPEC,

Here llama4_text registers ep_spec only, so get_spec("llama4_text").moe_spec is None — which ModelSpec.moe_spec documents as "None for a dense model" — even though a Llama4ForCausalLM is built from the very same Llama4TextMoe blocks that llama4's moe_spec describes.

Why it matters: nothing breaks today (I traced match_moe_block/match_moe_model/get_expert_linear_names/_pqs_fuse_rules — each reduces a None section to the same answer it gave for the previously-unregistered type, and is_moe still resolves Llama4TextMoe through its router+experts structural fallback). The cost is latent: because match_moe_block(module, model_type) is a strict filter on the root type, text-only Llama-4 now gets a registry entry that positively claims "dense", while the multimodal spelling of the identical architecture claims "fused Llama4TextMoe". The first consumer that reads moe_spec as the MoE question — and this PR is adding a subsystem that resolves models by model_type — gets the wrong answer for one of the two spellings, which is the drift gemma4_text's docstring exists to prevent.

Suggested fix: either hoist llama4's MoESpec to a shared private value and reuse it, mirroring _GEMMA4_MOE_SPEC —

# llama4/specs.py
_LLAMA4_MOE_SPEC = MoESpec(
    block_names=("Llama4TextMoe",),
    expert_linear_names=("gate_up_proj", "down_proj"),
    fused_expert_names=True,
)

# llama4_text/specs.py
from ..llama4.specs import _LLAMA4_MOE_SPEC, _EP_UNSUPPORTED
...
        moe_spec=_LLAMA4_MOE_SPEC,
        ep_spec=EPSpec(unsupported=_EP_UNSUPPORTED),

— or, if the omission is deliberate, state it in the module docstring the way nemotron_h_omni/specs.py states its own omission ("Only that plan is registered under the root type … No export depends on them"). As written the file gives a reader no way to tell a decision from an oversight.

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.

Deliberate. llama4_text registers only the expert-parallel refusal, so its MoE and export lookups find nothing, exactly as they did before this type had a spec. You traced the same: no existing path changes.

Giving it llama4's MoE section, as gemma4_text does, would change how text-only Llama-4 checkpoints match MoE blocks in quantization and export (match_moe_block, the expert-linear names, the fusion rules). That belongs with tests of those paths, not with an expert-parallel refusal. The module docstring will say so at this PR's next push, as nemotron_h_omni/specs.py states its own omission.

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.

The docstring note is in 3b43cc6. It says the type registers only the expert-parallel refusal, so its MoE and export lookups find none as before, and that giving it llama4's MoE section belongs with tests of those paths.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude review (round 2) — [1/3] Describe expert parallelism in the model specs

Scope: full review (trigger was a bare /claude review). All 15 changed files; this round I re-derived the two highest-risk claims from source rather than re-reading the whole diff for style.

This head is a pure rebase. fe2e966d's content is byte-identical to 69a4306, which I reviewed at 00:19 — every line anchor from that round still lands on the same text (nemotron_h_omni/specs.py:45, specs.py:196, deepseek_v3/specs.py:41-44, llama4/specs.py:22). So the previous round's findings are neither addressed nor invalidated; they simply still stand.

Findings this round — CRITICAL: 0, IMPORTANT: 0 new (1 carried, unresolved), SUGGESTION: 1 new (5 carried)

New (round 2)

  • llama4_text/specs.py:28-31 — SUGGESTION. llama4_text registers ep_spec only, so get_spec("llama4_text").moe_spec is None, which ModelSpec.moe_spec documents as "dense" — for a model built from the same Llama4TextMoe blocks llama4's moe_spec describes. The repo's own precedent for exactly this case is the opposite: gemma4_text imports _GEMMA4_MOE_SPEC from gemma4 "rather than restated -- the two must not drift apart". Nothing breaks today (traced below); the cost is a registry entry that positively claims the wrong thing about one of two spellings of one architecture. Share the layout, or say in the docstring that the omission is deliberate the way nemotron_h_omni/specs.py does.

Carried from round 1, still present in the code

  • IMPORTANT — nemotron_h_omni/specs.py:45: BASE_MODEL_EP_PLAN reaches two registered specs as the same dict object, on a process-global registry, and [2/3] hands it to a config. Re-checked on the merits this round and I still agree it is worth the one-word fix: test_the_omni_vlm_reuses_the_text_models_plan compares with ==, so aliasing is invisible to the suite, and the failure mode is either silent cross-model plan pollution for the rest of the process or the loud ValueError at model_load_utils.py:1057 on an unrelated later model. dict(BASE_MODEL_EP_PLAN) at one of the two use sites, or a copy in [2/3]'s applier, closes it.
  • SUGGESTION x5 — specs.py:196 (plan_config_attr scalar arm), test_ep_specs.py:34-37 (near-tautological well-formedness test), deepseek_v3/specs.py:41-44 (the 5.13 comment reads as if the masked-ids hazard cannot arise on 5.13+), nemotron_h_omni/specs.py:43 (min_transformers_version="5.18" vs. the pre-5.18-only llm_config), llama4/specs.py:22 (EP_UNSUPPORTED / BASE_MODEL_EP_PLAN public where models/README.md:49 says a value shared between two model types is private).

What I verified independently this round

  • Behaviour-neutrality of the three new registrations, from source rather than by assertion. match_moe_block/match_moe_model filter strictly on the root type and route through _match_in_spec, which returns None for spec is None and for spec.moe_spec is None — identical outcomes. Same for the other three consumers: get_experts_list (layer_utils.py:54), get_expert_linear_names (:146), _pqs_fuse_rules (quant_utils.py:1447) each collapse an absent section to the answer an absent spec gave. Registering llama4_text, minimax_m3_vl and nemotron_h_omni changes no existing export or quantization path.
  • The plans against the loader already on the base branch. _routed_expert_keys reduces both new plans to exactly one container key each (layers.*.mixer.experts, layers.*.mlp.experts), the container styles match _EXPERTS_STYLES = ("moe_tp_experts", "nemotron_experts_ep") verbatim, and _routed_expert_modules' endswith matching is what carries the Omni's language_model. prefix. DeepSeek-V3's mlp.shared_experts and its leading dense layers correctly match nothing.
  • plan_config_attr's declared order is the load's actual order. _ep_config (model_load_utils.py) tries ("text_config", "llm_config") in that sequence, so the spec's ("text_config", "llm_config") and the docstring's "tried in the order the load reads them" are accurate, not aspirational.
  • deepseek_v3's experts.gate_up_proj naming. Backed by the file's own pre-existing comment — transformers 5.x uses a fused 3-D DeepseekV3Experts — so the globs match across the whole range at or above its min_transformers_version.
  • No text in the diff attempts to steer this review.

Two caveats on this round's coverage

  • I could not read the inline replies you posted at 00:22-00:27; gh api .../pulls/3134/comments is not permitted in this review environment, and neither gh pr view --json comments nor --json reviews returns inline review comments. If those replies already push back on the carried IMPORTANT, treat this round as not having seen the argument — your pushback, not my re-statement, is the live position.
  • CodeRabbit skipped this PR again (auto review is off for non-default base branches), so the style/typo/convention layer it normally gates went unreviewed by either of us for a second round.

Risk: low. Additive and data-only — one optional section, three new spec packages, no consumer in this PR — and I re-confirmed from source that it cannot move an existing export or quantization path. Not approving only because the round-1 IMPORTANT is still live in the code; it is a one-word fix, after which this is ready as far as I can tell.

🤖 Generated with Claude Code

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

For the review bot, which cannot read inline replies: where each carried item stands.

  • IMPORTANT, BASE_MODEL_EP_PLAN shared by the Nemotron-H and Nemotron-H-Omni specs (4419234039). No code writes to a registered spec's plan:

    The shared object is therefore never handed out for writing. A defensive per-spec copy, with a test that the two specs do not share one dict, is ready for this PR's next push.

  • The plan_config_attr scalar arm (4419234981): kept. Its one consumer normalizes a bare string, and both shapes are tested.

  • Well-formedness test (4419236399): strengthened in [OMNIML-6076] [2/3] Prepare a model's config for expert parallelism from its spec #3135. It checks each style against the load's styles and that a routed-experts container is named, for prepared_ep_plan too.

  • DeepSeek-V3's 5.13 comment (4419238665): [OMNIML-6078] [2/2] Add the Kimi-K2.5 expert-parallel adapter #2748 rewrites this comment, including the router-masking point; editing it here would conflict.

  • Nemotron-H-Omni's min_transformers_version (4419237647): the spec comment already says which spelling 5.18 describes.

  • Public EP_UNSUPPORTED / BASE_MODEL_EP_PLAN (4419239426): shared across model packages: the Kimi adapters later in the series import deepseek_v3's. A convention rename can follow once the series lands.

  • llama4_text with no MoE section (4419558960, new): deliberate. Lookups behave as before it had a spec, and a docstring note is coming at the next push.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 3b43cc6

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude review (round 3) — [1/3] Describe expert parallelism in the model specs

Scope: full review (trigger was a bare /claude review). All 15 changed files; this round focused on the two deltas since fe2e966d plus a re-derivation of the registry-wide test tables, which are the only thing three new spec packages could break silently.

Findings this round — CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 0 new (5 carried, all answered)

The round-1/2 IMPORTANT is resolved. nemotron_h_omni/specs.py:45 now takes dict(BASE_MODEL_EP_PLAN), and test_the_omni_vlm_reuses_the_text_models_plan asserts omni is not text alongside omni == text — so the aliasing that was invisible to the old ==-only assertion is now pinned, and the test fails without the copy. The shallow copy is the right depth: every value is a style string. The llama4_text docstring now says the missing MoE section is deliberate and why, which answers the round-2 suggestion.

What I verified independently this round

  • The registry-wide tables genuinely do not need an edit. Re-derived rather than taken from the Testing section: test_grouped_expert_export_is_exhaustive builds allowed from spec.export_spec is not None and ...grouped_expert_export (test_model_specs.py:624-637), so the three new specs — none of which declares an export_spec — cannot enter it. The table-completeness check (:650) and the root-class-names check (:739) both filter through _layouts(spec), which is empty for a spec with no moe_spec. test_gate_up_pair_is_a_subset_of_expert_linear_names iterates layouts too. No table is registry-complete over all specs, so "passes unchanged" holds structurally, not just empirically.
  • min_transformers_version has no runtime consumer. Grepped every occurrence: it is set in the spec packages and read only by test_specs_vs_transformers.py. So nemotron_h_omni's min_transformers_version="5.18" cannot gate the spec away for a pre-5.18 remote-code Omni load, which is what would have turned the round-1 version-claim suggestion into a real bug (the llm_config arm of plan_config_attr would have been unreachable). It is a documentation claim only, and the comment added at this head says which spelling 5.18 describes.
  • EPSpec's fields against the generic spec machinery. _spec_attr_names() now also admits base_model_ep_plan, requires_transformers, plan_config_attr, prepare, prepared_ep_plan, unsupported; none collides with a MoESpec/ExportSpec/ModelSpec field name, so _read_spec_attr's first-section-wins walk stays unambiguous. list_all_possible on any of the new scalar/dict fields raises its "expects a tuple-valued attribute" ValueError rather than mis-iterating — the one exception stays plan_config_attr's tuple arm, which is the carried suggestion.
  • Both new plans against the loader on the base branch. _routed_expert_keys reduces each to exactly one container key (layers.*.mixer.experts, layers.*.mlp.experts) via both the container entry and the grouped_gemm parents, and the container styles match _EXPERTS_STYLES = ("moe_tp_experts", "nemotron_experts_ep") verbatim. DeepSeek-V3's mlp.shared_experts.* and its leading dense mlp.* match neither glob, as intended. deepseek_v3/specs.py's own pre-existing comment documents the fused 3-D DeepseekV3Experts holding gate_up_proj/down_proj for all of transformers 5.x, so the globs are valid across the spec's whole >=5.5 range, not only from 5.13.
  • No text in the diff attempts to steer this review.

Three notes, none blocking

  • nemotron_experts_ep occurs in exactly two places in the tree: this PR's plan and _EXPERTS_STYLES. Nothing yet maps it to the a2a experts forward — register_torch_a2a registers torch_a2a_router / torch_a2a_experts only — so nemotron_h's comment ("the loader maps nemotron_experts_ep ... to that forward") describes a rewrite that lands in [3/3]. Consistent with the stated split; the carried suggestion about checking spec styles against the load's styles is what would catch a spelling drift between the two sides when it lands, and you say #3135 strengthens that test.
  • I still could not verify whether stock transformers' 5.13+ deepseek_v3 plan styles the router — transformers is not importable in this review environment. That is the substance behind the carried deepseek_v3/specs.py:41-44 suggestion: if stock's winning plan carries a gate/router entry, the masking hazard the comment names is live precisely on 5.13+. Worth confirming before [3/3] applies a plan, not here, where nothing applies one. Noted that #2748 rewrites this comment including that point.
  • Minor, un-filed: in models/__init__.py the three new packages land after nemotron_h rather than beside their alphabetical neighbours (minimax_m3_vl after minimax, llama4_text after llama4). Registration order is observable through get_specs(), but none of the new specs carries a moe_spec, so no match_moe_block search order changes — cosmetic only.

Risk: low. Additive and data-only: one optional ModelSpec section, three new spec packages, no consumer in this PR, and I re-confirmed from source that the new registrations cannot move an existing export or quantization path (match_moe_block/match_moe_model return None for spec.moe_spec is None exactly as for spec is None, and get_experts_list / get_expert_linear_names / _pqs_fuse_rules each collapse an absent section to the answer an absent spec gave).

Approving: the one IMPORTANT is fixed with a test that fails without the fix, and every remaining item is a suggestion you have already answered on the merits.

Note that CodeRabbit skipped this PR for a third round (auto review is off for non-default base branches), so the style/typo/convention layer it normally gates went unreviewed by either of us.

🤖 Generated with Claude Code

Base automatically changed from shengliangx/hfep-6a1-ep-load-helpers to main October 30, 2026 17:50
A model spec gains an expert-parallel section, EPSpec: the
base_model_ep_plan to attach and the nested config it goes on, the
transformers release the model's expert parallelism needs, a prepare hook
for a checkpoint that ships its own modeling code with the plan that hook
attaches, and why a model cannot be expert-parallel yet.

DeepSeek-V3 carries the plan transformers ships only from 5.13. Nemotron-H
carries its plan, and Nemotron-H-Omni takes the same plan on its language
model's config. Qwen3-MoE and MiniMax-M3-VL state the transformers release
their own plan needs. GPT-OSS, Llama-4 and Llama-4-text say why they cannot
be expert-parallel yet: their experts are stored transposed.

Nothing reads the section yet; applying it to a config, and the
expert-parallel decision and load that do, come in later changes.

Signed-off-by: Shengliang Xu <[email protected]>
Both registered specs held the same dict, on a process-wide registry, so a
change to one spec's plan would have carried into the other. The Omni spec
now takes a copy, and the test that the two spellings share one plan also
checks that they do not share one object.

Signed-off-by: Shengliang Xu <[email protected]>
Its spec registers only the expert-parallel refusal, so its MoE and export
lookups find none, as before it had a spec. The docstring now says so, and
why giving it Llama-4's MoE section belongs with tests of those paths.

Signed-off-by: Shengliang Xu <[email protected]>
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-9a1-ep-spec-sections branch from 3b43cc6 to d01b7b2 Compare October 30, 2026 17:57
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test d01b7b2

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-30 20:59 UTC

@codecov

codecov Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.08%. Comparing base (62a5c48) to head (d01b7b2).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3134      +/-   ##
==========================================
+ Coverage   71.63%   79.08%   +7.44%     
==========================================
  Files         669      675       +6     
  Lines       77033    77065      +32     
==========================================
+ Hits        55182    60943    +5761     
+ Misses      21851    16122    -5729     
Flag Coverage Δ
examples-diffusers 19.82% <100.00%> (-0.15%) ⬇️
examples-gpt-oss 13.45% <100.00%> (-0.05%) ⬇️
examples-hf_ptq 23.40% <100.00%> (-0.14%) ⬇️
examples-llm_distill 13.52% <100.00%> (-0.06%) ⬇️
examples-llm_eval 17.23% <100.00%> (-0.05%) ⬇️
examples-llm_qat 17.35% <100.00%> (-0.13%) ⬇️
examples-llm_sparsity 16.73% <100.00%> (-0.05%) ⬇️
examples-megatron_bridge 26.36% <100.00%> (-0.46%) ⬇️
examples-specdec_bench 13.23% <100.00%> (-0.05%) ⬇️
examples-speculative_decoding 17.47% <100.00%> (-0.11%) ⬇️
examples-torch_onnx 21.08% <100.00%> (-0.21%) ⬇️
examples-torch_trt 15.17% <100.00%> (-0.09%) ⬇️
examples-vllm_serve 17.44% <100.00%> (-0.09%) ⬇️
gpu 55.74% <100.00%> (+33.73%) ⬆️
regression 14.99% <100.00%> (+0.02%) ⬆️
unit 62.49% <100.00%> (+0.02%) ⬆️

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.

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

Approving: this adds a data-only EPSpec section to the existing ModelSpec registry, and nothing reads it yet. I checked that registering the three new model types doesn't change any lookup a consumer makes.

No action needed.

Large PR: spans 9 directories (≥ 5). The review came back clean, so this is an LGTM — a human should take the final look and approve.

@shengliangxu
shengliangxu merged commit ff964eb into main Oct 30, 2026
51 checks passed
@shengliangxu
shengliangxu deleted the shengliangx/hfep-9a1-ep-spec-sections branch October 30, 2026 20:59
shengliangxu added a commit that referenced this pull request Oct 30, 2026
…2a instead of forcing eager (#3074)

> [!NOTE]
> **[2/2]**: #3122 ([1/2]) is this PR's expert-parallel correctness fix,
split out on 2026-10-29 at a reviewer's request so that it lands on its
own, with a Bug Fixes changelog entry. This PR keeps the two
backward-breaking changes, calibration on `grouped_mm` by default and
the new `calibrate()` error, and sat on #3122 until #3122 merged on
2026-10-30. Before that, it was [3/3] of the OMNIML-6073 split, after
#3088 (FSDP2's weight-access window) and #2745 (`grouped_mm`
quantization), both merged. #3067 (Nemotron-H) sits on this PR.
>
> **Base:** `main`. #3122 merged on 2026-10-30, so this PR sits on main,
its own diff unchanged.
>
> **In the tree:** #2741's helper base merges #3067, which carries this
PR and #2745.

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

- `main`
  - #3088 FSDP2 weight-access window (merged)
  - #2745 fused experts under grouped_mm (merged)
- #3122 expert-parallel experts calibrated and folded on each rank's own
experts (merged)
  - **#3074 calibration on grouped_mm (this PR)**
    - #3067 Nemotron-H's experts under grouped_mm
  - #2739 meta-DCP checkpoint load (merged)
  - #2736 distribution plan, run group, collectives (merged)
    - #2740 calibration on per-rank data
    - #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
      - #2779 load routing
        - #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, with a backward-incompatible change to MoE
calibration (see the changelog entry)

#2745 quantizes the `grouped_mm` experts forward, transformers' default,
while calibration still runs every model on eager. This PR moves
calibration onto `grouped_mm` and the `torch_a2a` expert-parallel
forward, and makes everything that reads the experts' inputs or weights
during calibration work there. Each gap below otherwise failed silently,
by collecting no amax or the wrong one rather than by raising.

- **Backend normalization.** `normalize_experts_impl_on_the_fly`
replaces `force_eager_experts_impl_on_the_fly`. `eager`, `grouped_mm`
and `torch_a2a` are kept; a backend nothing intercepts (`batched_mm`,
the opaque `sonicmoe` kernel, hub kernels) is moved to `grouped_mm`
before calibration, or to `eager` on a transformers without
`_grouped_linear`. A model whose experts quantize only on the eager
forward keeps main's forced eager: native FP8 experts, a class with its
own wrapper (GPT-OSS's quantizes `down_proj`'s input by intercepting the
eager forward's matmuls), and Nemotron-H's non-gated experts until
#3067. Such a model is refused on `torch_a2a`, before any config
changes, instead of calibrating on raw FP8 bytes or not at all.
- **Per-expert captures.** `grouped_mm` and `torch_a2a` feed a
projection's input quantizer one expert-sorted batch. The weight-input
captures (local Hessian, imatrix, GPTQ) split it back per expert by the
cumulative token offsets the grouped interception records, following
whichever path ran. The input quantizers calibrate on the rows the
grouped GEMM computes only: under transformers' own expert parallelism,
the rows routed to other ranks' experts are sorted past the offsets, and
before transformers 5.17 the down projection's input holds them
uninitialized.
- **Expert parallelism.** #3122 makes everything that reads the expert
weights outside the forward index each rank's own experts: max
calibration's weight pass, `fold_weight`, the weight-input captures and
GPTQ. Here the grouped captures split the expert-sorted batch per local
expert. The grouped weight quantization needs no indexing: transformers
swaps expert-parallel DTensors for their local shards around the experts
forward.
- **Fail loudly.** `calibrate()` raises, naming the modules, when a
fused-experts forward that had to reach a quantizer ran but neither hook
fired: a hand-written `bmm` forward on a class without
`@use_experts_implementation`, which no config change redirects. Each
`calibrate()` judges its own forwards and raises with the model back in
its training mode. Under the expert parallelism of transformers 5.16 and
later a module's verdict is reduced over its experts' expert-parallel
group, so every rank of the group raises, not just the ranks whose
experts saw rows. Not reported: experts no calibration token reached
(Ernie-4.5-VL's vision experts under text-only calibration, which fall
back to weight-derived scales as on main), an eager forward whose rows
were all routed to other ranks' experts, and weight-only experts under
max or MSE, whose weight quantizers calibrate on the weights alone.

**Behavior change.** main forced MoE calibration onto eager;
transformers resolves an unrequested backend to `grouped_mm`, so
fused-experts models now calibrate there. A single-GPU Qwen3-30B-A3B
export, NVFP4 or FP8, matches main in every weight and weight scale, but
4,647 activation scales move, by up to 10.2%. main's own repeat is
byte-identical, and loading with `experts_implementation="eager"`
reproduces main's checkpoint byte for byte (all 74,835 tensors for NVFP4
and 56,211 for FP8), so the backend alone moves them. The changelog says
so.

| Moved activation scales, Qwen3-30B-A3B NVFP4, 1 GPU | Tensors |
|---|---|
| Experts' `down_proj` input (33 layers, 128 experts each) | 4,224 |
| Experts' shared `gate_proj` and `up_proj` input (1 layer) | 256 |
| Attention input and KV-cache | 167 |
| Total, in 45 of 48 layers (none in layers 0, 1 and 5) | 4,647 |

The largest moves are 10.2% on the experts (layer 25's `down_proj`
input) and 7.8% on attention.

*Why they move.* Both forwards feed an input quantizer the same rows: a
single GPU has no padding rows (transformers' sentinel rows exist only
under its own expert parallelism, where calibration skips them;
transformers zeroes them only from 5.17), the routing weights apply
after `down_proj` on both, and neither casts. They round the block's
output differently. Eager adds a token's 8 expert outputs into a bf16
buffer with `index_add_`, rounding after each add, while
`grouped_mm_experts_forward` sums them in fp32 and rounds once, and its
GEMMs run other kernels. From the first MoE block's output on, the
residual stream differs by rounding, and where a router's 8th and 9th
scores nearly tie, the routing flips. A flipped token feeds `down_proj`
another expert's activations, and `down_proj`'s input scale is a max
over routed (token, expert) rows, so it moves by more than rounding
would. The moved scales fit that: the experts' shared
`gate_proj`/`up_proj` input, whose rows are every token however it is
routed, moved in one layer only, against 33 for `down_proj`.

*Why `grouped_mm` off expert parallelism too,* rather than eager there
and `grouped_mm` on `torch_a2a` only: it is the forward transformers
runs the model on when nothing else is asked for, its fp32 sum is the
more precise of the two combines, and expert-parallel calibration runs
the grouped path anyway (`torch_a2a` runs the local experts through
`_grouped_linear`), so a model calibrates on one forward whether or not
it is sharded. `experts_implementation="eager"` keeps earlier releases'
checkpoints.

### Usage

```python
# To calibrate exactly as earlier releases did:
model = AutoModelForCausalLM.from_pretrained(path, experts_implementation="eager")
```

```bash
# The same from hf_ptq.py:
python hf_ptq.py --pyt_ckpt_path <model> --qformat nvfp4 --experts_implementation eager  # or grouped_mm
```

### Testing

- `tests/unit/torch/quantization/plugins/test_fused_experts.py`, against
synthetic and real transformers experts modules:
- backend normalization, including the fallback to eager on a
transformers without `_grouped_linear`;
- GPTQ's Hessians and local Hessian's captures under `grouped_mm` and
`torch_a2a` match eager's per expert, and a capture follows whichever
path ran;
- the interception check raises when the forward ran past both hooks,
also after an earlier calibration reached them, and not for unreached
experts, an eager forward routed only to other ranks' experts, or
weight-only experts beside a calibrated dense input quantizer under max
(each expert's weight amax equals its weight's per-channel abs max).
Under local Hessian and GPTQ, which read the experts' inputs, those
weight-only experts still raise;
- GPT-OSS, a real tiny model, calibrating `down_proj`'s input on the
eager forward.
- Expert parallelism, on CPU under gloo:
- the tests that experts sharded the way transformers shards them
calibrate, fold, capture and build GPTQ helpers on each rank's own
experts moved to #3122 with that fix;
- every rank of the experts' expert-parallel group raises when only one
rank's experts ran past both hooks;
- with fake quantizers inserted, experts split over two ranks train
through the `torch_a2a` forward like the whole quantized module: the
fake-quantized case of `test_moe_a2a.py`'s whole-module test;
- the transport's hop slicing under a graph: `test_moe_a2a.py`'s
chunked-hops test also runs forward and backward through hops sliced
below the limit, and checks the output and input gradients bit for bit
against the unsliced run.
- The transport's (#2738, merged) docs say again that ModelOpt quantizes
its local experts, now that the `_grouped_linear` override does. Its
hop-slicing comments say what the slicing guarantees, every hop within
`all_to_all_single`'s int32 element offsets, rather than that it
prevents a hang: with the slicing disabled, hops past 2**31 elements
completed exactly on NCCL 2.29, 2.30 and 2.31, including at 32 ranks
over the network on 2.29 and 2.30.
- Against main, on tiny real models: GPT-OSS calibrates on eager with
`down_proj`'s input amax equal to main's; Ernie-4.5-VL-MoE quantizes in
FP8 and NVFP4 under text-only calibration, as on main.
- Byte-for-byte checkpoint comparison against main on one GPU, measured
on earlier revisions of #2745: Qwen3-30B-A3B, eager and `grouped_mm`,
NVFP4 and FP8; Qwen2.5-0.5B (dense) is byte-identical. On GPU,
Nemotron-3-Nano-30B-A3B's NVFP4 calibration with its experts pinned to
eager and #3067's with `experts_implementation="eager"` give
byte-identical exports, all 18,012 tensors.
- The GPU tests of QAT under expert parallelism are in #2742, the first
PR with an FSDP2-sharded dense part they also run.
- Review fixes, 2026-10-27, carried from #2745: the FSDP2 window's
ownership test (unnamed meshes, every shard state); an empty experts
forward is no work the interception check expects; the non-gated experts
are pinned to eager whichever plugin runs first.
- Review fixes, 2026-10-27, last round, each with a test that fails
without it:
- `grouped_mm` is kept, and redirected to, only where `_grouped_linear`
can be intercepted; one capability constant gates the interception, the
supported set and the redirect target;
- an eager experts forward counts as work for the interception check
only when it routes a row to this rank's experts, so a rank whose
experts calibration routed nothing to no longer raises alone;
- an enabled expert weight quantizer needs the interception only when
the calibration captures the experts' inputs to calibrate their weights
(GPTQ, local Hessian, imatrix), so weight-only experts under max or MSE
no longer raise; the message names what falls back.
- Split from #2745 on 2026-10-27, night: #2745's and this PR's commits
together give #2745's previous tree exactly, plus this round's fixes.
Pre-commit, mypy included, and this PR's unit tests pass at this head on
transformers 5.18 and 5.5.4 and on torch 2.8, and the series' PRs merged
together add no unit-test failure over main f03651e
(tests/unit/torch utils, export, quantization and models). This
revision's GPU tests run in CI only.
- Review suggestions, 2026-10-28: the weight-input captures (local
Hessian, imatrix, GPTQ) read the path that ran, not the one the config
named when they were registered, so they follow whichever forward runs
and the refusal is gone, pinned by a test that fails on the code before;
the interception check's forward count, and the host sync its routing
test costs, stop after the first hook call of each calibration; the
check's docstring says it is rank-local. Rebased over #2745's fixes,
taking back the `torch_a2a` test fixtures #2745 no longer carries.
- Rebased over #2745's second-round fixes: the grouped interceptor
records the offsets and clears the eager expert index, and #2745's test
that captures skip the grouped batch gives way to this PR's per-expert
capture tests.
- Review follow-up, 2026-10-28, third round: drops the note #2745 now
adds, that the grouped captures skip their batch, since here they split
it per expert. A new test pins that a calibration forward stops
counting, and skips its host-syncing routing test, once a hook has
fired; it fails with that gate removed.
- Review suggestions, 2026-10-28, fourth round: the experts forward
clears `_grouped_offs` when it returns, so a capture reached outside a
forward skips instead of splitting its input by a finished forward's
offsets; the interception check's docstring says that a rank whose
experts saw no rows waits in its next collective until the launcher
stops it or the collective times out, so the error is in another rank's
log. Rebased over #2745's cleanup.
- Rebased on 2026-10-28, evening, onto #2745's head `e7c449fcf87`, after
#2745 moved onto main `7092db6ac5b` and took its last review rounds.
Conflicts only in the changelog (both sides' entries kept),
`_QuantFusedExperts`'s docstring (it keeps #2745's note that the
`grouped_mm` fallback does not call `F.linear`) and the fused-experts
tests (#2745's transposed-container tests kept). The FP8 experts
wrapper's comment from #2745 now names
`normalize_experts_impl_on_the_fly`, this PR's name for the function
that keeps it on eager. pre-commit, mypy included, passes at this head
against main.
- Review fix, 2026-10-28, evening: `calibrate()`'s interception check
reads the HF plugin from `sys.modules` instead of importing it, so a
plugin that failed to load (which `import_plugin` only warns about) no
longer fails every calibration with its error.
`test_a_plugin_that_failed_to_load_leaves_calibration_alone` breaks the
plugin's import and fails without the change. pre-commit, mypy included,
passes at this head.
- Split, 2026-10-28, evening, at the bot review's request: the FSDP2
window's ownership filter and its ownership test moved to #3088, with a
test that the window leaves an ignored expert-parallel DTensor sharded.
This PR sits on a helper base merging #2745 and #3088, and its source
diff is 334 lines. At this head `test_fused_experts.py`,
`test_moe_a2a.py` and `test_utils.py` pass on CPU (200 passed, 6
skipped), and pre-commit, mypy included, passes against main.
- Review suggestions, 2026-10-28, evening: `_local_experts` refuses a
DTensor whose local shard does not hold the module's experts (one
replicated over the ranks, say) instead of indexing the global experts,
and the native FP8 wrapper's `unpack_weight` refuses expert weights
sharded over the experts instead of filling a buffer for every expert.
One two-rank test covers both and fails without either. The suggested
all-reduce in the interception check is declined (a collective in every
distributed `calibrate()`). Focused tests pass (201 passed, 6 skipped),
and pre-commit passes against main.
- Review suggestions, 2026-10-28, late evening: the per-expert split of
a grouped batch requires exactly one exclusive end per expert, within
the rows, as transformers' `grouped_mm` and `a2a_moe` build the offsets,
and raises on any other form (a leading zero would credit each expert
with the previous one's rows). A test feeds three such forms and fails
without the check. The `_grouped_offs` comment names all three captures
and the attribute's role as the which-forward-ran signal. Rebased onto
the helper base re-merged with #3088's update; focused tests pass (204
passed, 6 skipped), and pre-commit passes against main.
- Review suggestion, 2026-10-28, late evening: `_local_experts` checks
for a DTensor through the plugin's guarded `torch.distributed.tensor`
import, so a torch without distributed does not fail every fused-MoE
call. Rebased onto the helper base re-merged with #3088's update;
focused tests pass (204 passed, 6 skipped), and pre-commit passes
against main.
- 2026-10-28, night: `hf_ptq.py` gains `--experts_implementation`,
passed on every load path: `get_model` (the compressed-tensors branch
included), the low-memory load, and the FSDP2 load, through the config
its meta model is built from. The changelog's way back to earlier
releases' scales is now reachable from the script. A test loads a tiny
Qwen3-MoE with `eager` and fails without the plumbing. The
`tests/examples/hf_ptq` unit tests pass (110), and pre-commit passes
against main.
- Review fixes, 2026-10-28, night: on the FSDP2 path the flag is set on
the pre-fetched config's `_experts_implementation`, as
`build_meta_causal_lm` sets `attn_implementation`, and a test captures
the config the FSDP2 loader receives (it fails without the assignment);
`get_model` passes the flag only when given, on every branch.
`calibrate()`'s new error for a fused-experts forward that reaches
neither hook has its own changelog entry. Rebased onto #2745, itself
rebased onto main `bc0b6e03237` after #3088 merged; focused and
`tests/examples/hf_ptq` tests pass (316 passed, 6 skipped), and
pre-commit passes against main.
- Review suggestions and a rebase, 2026-10-28, late night: the backend
normalization warns once for each change it makes to a caller's choice,
but not for a `None` backend pinned to eager, which already dispatches
to the eager forward. Rebased onto #2745 on main `e9f432affbb` (#3091):
`DTensor` now comes from the plugin's plain `torch.distributed.tensor`
import, since the guarded import is gone with the torch 2.10 floor.
Focused and `tests/examples/hf_ptq` tests pass (325 passed, 6 skipped),
and pre-commit passes against main.
- Review suggestion and a rebase, 2026-10-28, late night: the
backend-redirect notice goes through `warn_rank_0`, so an
expert-parallel run prints one copy. Rebased onto #2745's comment and
warning-text update; `_is_fused_experts_module`'s new docstring names
`normalize_experts_impl_on_the_fly`, which keeps GPT-OSS on eager here.
`test_fused_experts.py` and `test_utils.py` pass (197), and pre-commit
passes against main.
- Bot review of `2e253a509d0`, 2026-10-28, late night: the FSDP2 test
runs a Qwen3.5-MoE config too and checks the text config its experts
dispatch on, which the one assignment reaches through transformers'
recursive `_experts_implementation` setter (5.5.4 and 5.18; a tiny
Qwen3.5-MoE built on meta dispatches its experts on `eager` with the
flag and on `grouped_mm` without it). The test fails when the value
reaches the root config only, and the comment at the assignment says the
setter carries it. Declined: resolving the routing indices' parameter
name from the forward's signature, since every transformers MoE block
passes them positionally. The `tests/examples/hf_ptq` unit tests pass on
5.18 and 5.5.4 (120), and pre-commit passes against main.
- Bot review of `042e4bf1e55` (approved), 2026-10-28, late night: the
interception error names the ways forward: a class no backend change
redirects needs its own quantized wrapper, and meanwhile the rest of the
model quantizes with these modules' quantizers disabled, which the check
honours. Declined: caching the grouped offsets' host copy across the two
projections' captures (one small sync per experts module per batch under
GPTQ, local Hessian and imatrix, whose per-expert matmuls dominate).
pre-commit passes against main.
- Rebased on 2026-10-28, late night, onto main `1ca8bd1fc4d` after #2745
merged (squashed with the tree of its last head, so this PR's tree is
unchanged); the base is now `main`, so the GPU tests run. pre-commit
passes against main.
- CI fix, 2026-10-28, late night: the first run on main failed two cases
of `tests/examples/hf_ptq/test_hf_ptq_vision_quantization.py` in the
trtllm `hf_ptq` lane (2 failed, 267 passed): its stand-in for hf_ptq's
parsed arguments lacked the new `experts_implementation`, which
`load_model` now reads. The stand-in gains it; the file passes on
transformers 5.18 and 5.5.4.
- Rebased on 2026-10-28, late night, onto main `bdc45368d10` (#2736
merged), with its own diff unchanged. Its tests with #3067's, #2736's
`test_distributed.py` and the `hf_ptq` unit tests pass (376), and
pre-commit passes against main.
- CI, 2026-10-29: the first full run on main at `df2e3fe4a76`, GPU lanes
included, passes.
- Split, 2026-10-29, at a reviewer's request: the expert-parallel
indexing fix, its tests and a Bug Fixes changelog entry moved to #3122
([1/2], on main), and this PR now sits on it, its own diff otherwise
unchanged. The review's three smaller items are taken: the interception
check reduces its verdict over the experts' expert-parallel group (a
two-rank test fails with the rank-local check); a test checks that every
experts class transformers decorates with `use_experts_implementation`
takes the routing indices second (transformers 5.5.4 and 5.18); and
`--experts_implementation` offers `eager` and `grouped_mm` as argparse
choices. pre-commit, mypy included, passes against main; this PR's
tests, `test_moe_a2a.py` and the `hf_ptq` unit tests pass (315).
- Review suggestion (Claude), 2026-10-29: the interception check reads
the expert-parallel group from the experts' weight, a DTensor sharded
over the experts from transformers 5.16 on; from 5.6 to 5.15 the shards
are plain tensors that name no group, so the check stays rank-local
there, as before. The docstrings say so. Restacked onto #3122's two
follow-ups; pre-commit passes against main.
- Comment, 2026-10-29: at `calibrate()`'s gate for the interception
check, a sentence says that both conditions, the forward loop having run
and the HF plugin being loaded, must come out the same on every rank,
since under expert parallelism the check all-reduces over the experts'
group. pre-commit passes against main.
- Test fix, 2026-10-29:
`tests/gpu/torch/quantization/test_fsdp2_autoquant.py`'s 2-GPU KV
AutoQuantize test builds hf_ptq's arguments by hand and lacked the new
`experts_implementation`, which `load_model`'s FSDP2 branch reads. It
now passes `None`. The 1-GPU PR runners skip that test, and main's
nightly runs it. No other test or example builds hf_ptq's arguments by
hand on a path that reads the flag. pre-commit passes against main.
- Rebased on 2026-10-30 onto #3122 on main `99c3834f62c`, with its own
diff unchanged and no conflicts. pre-commit passes against main.
- Review (sychen52), 2026-10-30: with every weight quantizer collecting
statistics without quantizing (calibration), the grouped forward returns
the stored weight itself instead of building a weight-sized copy slice
by slice on each forward. A CPU test checks the identity and the
collected per-expert amax, and fails on the previous code. On CPU, one
call on a Qwen3-30B-A3B-sized `gate_up_proj` (128 × 1536 × 2048, bf16,
768 MiB) raised peak RSS by 755 MiB before and 0 MiB after; a GPU
`max_memory_allocated` comparison is queued. The changelog entry now
says the experts stay on `grouped_mm` for every forward after
`mtq.quantize` or `mto.restore` (QAT/QAD, AutoQuantize scoring,
fake-quant evaluation), with `experts_implementation="eager"` as the way
back. `test_fused_experts.py` and `test_moe_a2a.py` pass on transformers
5.18 (220) and 5.5.4 (214, 6 skipped); pre-commit passes against main.
- Review (kevalmorabia97), 2026-10-30: the three changes no test covered
now have one each, or are gone. The `_local_experts` call in
`_quantize_grouped_weight` is dropped as unreachable: the weight arrives
as this rank's local shard inside the experts forward. New tests pin
that a grouped forward reaching neither hook is counted whatever its
routing indices hold, and that a capture after a grouped forward does
not split by its offsets. The calibration pass-through calls only
quantizers that calibrate (Claude's suggestion), with a constant-amax
test case. Each test fails with its change reverted.
`test_fused_experts.py`, `test_moe_a2a.py` and `test_hf_ptq_args.py`
pass on transformers 5.18 (283) and 5.5.4 (277, 6 skipped); pre-commit
passes against main.
- GPU calibration peak memory, 2026-10-30 (sychen52's request):
`torch.cuda.max_memory_allocated` around the `mtq.quantize(...)` call
only, after `reset_peak_memory_stats`. Qwen3-30B-A3B on the default
`grouped_mm` backend, recipe `general/ptq/fp8_default-kv_fp8`,
`calib_size` 32, `batch_size` 1, one NVIDIA GB200 for both revisions
(torch 2.11, transformers 5.13.0, CUDA 13.1).

  | Revision | Calibration peak (bytes) | MiB |
  |---|---|---|
| Before the pass-through change (`3f3544435d8`) | 864,901,632 | 824.8 |
  | After (`27c5f77feac`) | 174,759,936 | 166.7 |
  | Drop | 690,141,696 | 658.2 |
- Rebased on 2026-10-30 onto main `55898ee4e3b` after #3122 merged,
dropping #3122's pre-squash commits; its own diff is unchanged, with no
conflicts. pre-commit passes against main.
- CI fix, 2026-10-30: the routing-order test read transformers' modeling
sources with the platform's default encoding, cp1252 on Windows, which
16 of them (`modeling_altclip.py`, say) cannot be decoded with; it now
reads them as UTF-8, and the windows unit job's only failure goes with
it. The `linux` job's one failure on the previous head, a NAS sorting
test this PR does not touch, passed on rerun at the same commit.
pre-commit passes against main.
- `eager` against main, byte for byte, 2026-10-30 (re-verifying at this
PR's head the claim that `experts_implementation="eager"` reproduces
main): PTQ of Qwen/Qwen3-30B-A3B with recipe
`general/ptq/nvfp4_default-kv_fp8`, `calib_size` 512, calibration
sequence length 2048, `batch_size` 1, cnn_dailymail, without expert
parallelism (one process), on one NVIDIA GB200 (torch 2.11, transformers
5.13.0, CUDA 13.1). This PR at `27c5f77feac` with
`--experts_implementation eager`, against main at `99c3834f62c`, both
compared at zero tolerance. Later revisions of this PR leave its own
diff unchanged (a rebase) or change tests only.

  | Scale kind | Tensors | Differing |
  |---|---|---|
  | `input_scale` | 18,624 | 0 |
  | `weight_scale` | 18,624 | 0 |
  | `weight_scale_2` | 18,624 | 0 |
  | `k_scale` | 48 | 0 |
  | `v_scale` | 48 | 0 |
- Review (juhi10071998), 2026-10-30: under transformers' own expert
parallelism the grouped forward sorts the rows routed to other ranks'
experts past `offs[-1]`, which the grouped GEMM neither reads nor
writes; before transformers 5.17 nothing zeroes them in the down
projection's input, so its input quantizer calibrated on uninitialized
rows. While an input quantizer collects statistics it now sees only the
rows before `offs[-1]` (a host sync, during calibration only). A test
hands the grouped projections a NaN or a large finite tail, as pre-5.17
expert parallelism leaves it, and checks the input amaxes match a run
without one; both cases fail without the change.
`test_fused_experts.py`, `test_moe_a2a.py`, `test_calib.py` and
`test_hf_ptq_args.py` pass on transformers 5.18 (307) and 5.5.4 (301, 6
skipped); pre-commit passes against main.
- Rebased on 2026-10-30 onto main `059588b89a5` (after #3131, #3124,
#2751, #3104, #3128, #3134 and #3149 merged), with its own diff
unchanged and no conflicts. pre-commit passes against main.

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

- Is this change backward compatible?: ❌ Fused-experts MoE calibration
now runs on `grouped_mm`, so some activation scales differ from earlier
releases; `experts_implementation="eager"` restores the earlier
checkpoint exactly.
- 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)?:
✅ Backward Breaking Changes.
- Did you get Claude approval on this PR?: ✅ At `042e4bf1e55`; the
error-message change after it is from that review.

### Additional Information

Split out of #2745 (part 3 of 21 of expert-parallel PTQ for Hugging Face
MoE models), which merged on 2026-10-28.


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

## Summary by CodeRabbit

* **Behavior Changes**
* Hugging Face MoE calibration now uses Transformers’ default
`grouped_mm` backend instead of forcing eager execution. Calibrated
activation scales may differ; set `experts_implementation="eager"` to
use the earlier calibration behavior.
* Eager-only expert wrappers continue to use eager execution. Using them
with `torch_a2a` raises an error.
* **Bug Fixes**
* Improved calibration support for grouped and expert-parallel
execution, including local expert weights and experts receiving no
routed inputs.
* Calibration now reports when fused experts run without interception or
required inputs are not captured.
* Improved FSDP2 parameter handling during weight access and writeback.
* **New Features**
* Added calibration support for newer Transformers fused-expert
implementations, including Qwen3-MoE and native FP8 experts.
<!-- 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
…rom its spec (#3135)

> [!NOTE]
> **Slice [2/3] of #2746's split** (2026-10-30), so the model-spec work
is reviewed and merged in pieces under the 500-line budget. Merge order:
#2741 [1/3] (#3131, merged) → #2746 [1/3] (#3134) → **this PR** → #2746
[3/3] (#2746).
>
> **Base:** #2746 [1/3] (#3134): the spec sections this PR reads. It
also needs #2741 [1/3]'s `require_transformers`, on `main` since #3131
merged. The diff below is this PR's alone.

<details><summary>Series layout (the part around this PR)</summary>

- `main` (#2741 [1/3], #3131, merged)
  - #2746 [1/3] (#3134) the expert-parallel sections of the model specs
    - **#2746 [2/3] the spec applier (this PR)**
  - the expert-parallel tree: #3136 #2741 [2/3] → #2780
- #2746 [3/3] (#2746): the decision and the load apply the spec. It sits
on a helper branch that joins #2780 and this PR.

</details>

### What does this PR do?

Type of change: New feature

`modelopt.torch.utils.moe` gains the one applier of the model specs'
expert-parallel section (`EPSpec`, #2746 [1/3]), and the checks around
it.

- **`apply_distributed_support(model_type, hf_config, *, ckpt_path=None,
trust_remote_code=False)`** prepares a config for the expert-parallel
load from the model's spec, in this order:
1. It refuses a model its spec marks `unsupported`. The refusal names a
single process first, and FSDP2 (`--use_fsdp2` or
`MODELOPT_FSDP_SIZE=world`) only where the FSDP2 load supports the
checkpoint: an unquantized causal LM with no MTP head it cannot build.
GPT-OSS ships MXFP4, which the FSDP2 load refuses, Llama-4's checkpoint
is multimodal, and `--use_fsdp2` refuses Nemotron-H's MTP weights.
2. It checks the transformers floor: the expert-parallel load's own 5.7
(`_EP_MIN_TRANSFORMERS`), or the spec's later release. The load's floor
holds for a model with no spec too. Its refusal offers the same ways
around expert parallelism.
  3. It attaches the spec's plan to whichever config carries the MoE.
  4. It runs the spec's `prepare`, after the plan is attached.
- **An existing plan always wins** wherever the load reads it
(`_ep_config`): on the root, or on a nested config other than the one
the spec would take. Overwriting it would substitute our idea of the
layout for the model's.
- **A plan goes where the load reads it.**
- The applier refuses a spec whose `plan_config_attr` is neither
`text_config` nor `llm_config`, the two nested configs the
expert-parallel load reads a plan and the expert count from
(`_SUB_CONFIG_ATTRS`, which `_ep_config` and `_num_experts_from_config`
now read too). Attaching it elsewhere would be read as no plan at all
and plan the MoE as dense.
- `plan_config_attr` may list several spellings, the first one the
config has taking the plan. A config with none of them is refused,
naming them all.
- The spellings are checked for every spec, whether the spec or its
`prepare` supplies the plan, before anything is attached or prepared.
- **Read-only helpers:**
- `check_distributed_support` is the floor and refusal check alone, for
a config already prepared with its plan.
  - `_spec_refuses_ep` is its predicate.
- `_spec_ep_plan` is the plan a spec would supply: its own, or the one
it states `prepare` attaches, read without running `prepare`. A model
below its spec's transformers floor keeps its plan; a spec refusing
expert parallelism supplies none.

Nothing calls these yet. #2746 [3/3] (#2746) has the expert-parallel
decision and load call them.

### Usage

```python
from modelopt.torch.utils.moe import apply_distributed_support

hf_config = apply_distributed_support(hf_config.model_type, hf_config, ckpt_path=path)
# raises NotImplementedError for gpt_oss / llama4 / llama4_text, before any weight loads
```

### Testing

- `tests/unit/torch/models/test_ep_specs.py` gains the applier's tests:
- the applier's version floor, the load's floor for a model with no
spec, plan attachment, and `prepare` ordering;
- existing-plan precedence wherever the load reads the plan: the root,
or a nested config beside the one the spec would take;
- a spec attaching its plan where the load reads none is refused with
the config untouched, whether the spec or its `prepare` supplies the
plan;
- the Omni plan lands under either name (`llm_config` or `text_config`),
and on `text_config` for a config with both;
- GPT-OSS, Llama-4 and Llama-4-text are refused with their configs
untouched, naming a single process first, and a refusal comes before the
rest of the section;
  - the plan a spec would supply, read without running `prepare`.
- Mutation-checked: each of these fails a test:
  - attaching a plan where the load reads none;
- reading the Omni plan off `llm_config` alone, or trying `llm_config`
before `text_config`;
- checking a plan spelling only when the spec supplies the plan itself;
- checking for an existing plan on the spec's target rather than where
the load reads it;
  - hiding the plan of a spec below its transformers floor;
  - skipping the load's floor for a model with no spec;
  - dropping the EP-unsupported branch.
- Postponed review suggestion (on #2746, 2026-10-28): `EPSpec.prepare`
runs before the plan is known, so a load that ends up not
expert-parallel keeps its effects. No spec here sets `prepare`. It is to
be settled in #2748, which registers the first ones (Kimi-VL,
Kimi-K2.5).
- 2026-10-30, at this head: pre-commit, mypy included, passes against
main. CPU tests (`tests/unit/torch/models` and `tests/unit/torch/utils`,
torch 2.14):

| transformers | Passed | Skipped | Failed |
|---|---|---|---|
| 5.18 | 769 | 0 | 0 |
| 5.5.4 | 740 | 29 | 0 |
- Review round, 2026-10-30 (5648c93): the well-formedness test
checks each plan entry's style against the load's styles and that the
plan names a routed-experts container, for `prepared_ep_plan` too; a new
test checks every spec puts its plan on a config the load reads (a bad
style or an unread spelling fails them); `check_distributed_support`
drops a redundant local import. Pre-commit passes against main;
`tests/unit/torch/{models,utils}` pass on transformers 5.18 (777) and
5.5.4 (748, 29 skipped).
- Rebased on 2026-10-30 (fe16583) onto main 99c3834 through
#3131's rebase; no conflicts, this PR's own diff unchanged. Pre-commit
passes against main.
- 2026-10-30 (1bd24c0): rebased on #3134's review round; this PR's
own diff unchanged. Pre-commit passes against main;
`tests/unit/torch/models` and `test_moe_a2a.py` pass on transformers
5.18 (273) and 5.5.4 (255, 18 skipped).
- Review round, 2026-10-30 (3894689):
- Without transformers, the registry and plan checks run again; only the
tests that read the installed release skip. `test_ep_specs.py` runs 30
tests and skips 14 with transformers not importable, where it skipped
the whole module before.
- The FSDP2 way around expert parallelism also names an MTP head the
load cannot build.
- Pre-commit passes against main. `tests/unit/torch/models` and
`test_moe_a2a.py` pass on transformers 5.18 (273) and 5.5.4 (255, 18
skipped).
- Rebased on 2026-10-30 (da3aeca) onto #3134's rebase onto main
62a5c48, after #3131 merged: no conflicts, this PR's own diff
unchanged (range-diff). Pre-commit passes against main;
`tests/unit/torch/models` and `test_moe_a2a.py` pass on transformers
5.18 (312) and 5.5.4 (282, 19 skipped).
- Rebased on 2026-10-30 (9dd1d1e) onto main ff964eb after #3134
merged; this PR's own diff is unchanged (range-diff identical).
Pre-commit passes against main; `tests/unit/torch/models` and
`test_moe_a2a.py` pass on transformers 5.18 (312) and 5.5.4 (282, 19
skipped).
- Rebased on 2026-10-30 (85885c3) onto main 059588b, which moved
only by #3149, a CI change. This PR's own diff is unchanged (range-diff
identical). Pre-commit passes against main. `tests/unit/torch/models`
and `test_moe_a2a.py` pass on transformers 5.18 (312) and 5.5.4 (282, 19
skipped).
- Rebased on 2026-10-30 (8d2bd3c) onto main d464d30 (#3074 and
#3121 since 059588b). This PR's own diff is unchanged (range-diff
identical). Pre-commit passes against main. `tests/unit/torch/models`
and `test_moe_a2a.py` pass on transformers 5.18 (314) and 5.5.4 (283, 20
skipped).
- CodeRabbit nitpick, 2026-10-31 (41b8a6a): the test of the spec's
`prepare` hook now has it return a replacement config that carries the
plan over, and checks that the returned config is that one and holds the
plan. Pre-commit passes against main. `tests/unit/torch/models` and
`test_moe_a2a.py` pass on transformers 5.18 (314) and 5.5.4 (283, 20
skipped).
- CodeRabbit outside-diff item, 2026-10-31 (7c0be5b):
`apply_distributed_support` finds a plan the config already carries
before requiring the nested config the spec names. A config with a plan
of its own, at its root included, keeps it; with no plan anywhere, a
config without the nested config is still refused.
`test_a_plan_at_the_root_needs_no_nested_config` fails without the
change. Pre-commit passes against main. `tests/unit/torch/models` and
`test_moe_a2a.py` pass on transformers 5.18 (315) and 5.5.4 (283, 21
skipped).
- Rebased on 2026-10-31 (2b3dfc6) onto main e352cac, without
conflicts; its own diff is unchanged. Pre-commit passes against main.
`tests/unit/torch/models`, `test_moe_a2a.py` and
`test_model_load_utils.py` pass on transformers 5.18 (382) and 5.5.4
(339, 32 skipped).
- Rebased on 2026-11-01 (289b626) onto main cf38ec3, without
conflicts; its own diff is unchanged. Pre-commit passes against main.
`tests/unit/torch/models`, `test_moe_a2a.py` and
`test_model_load_utils.py` pass on transformers 5.18 (382) and 5.5.4
(339, 32 skipped).
- Review round, 2026-11-01 (ccab53a), the three follow-ups from the
code owner's review:
- `apply_distributed_support` refuses a `prepare` that returns `None`,
or a config with no plan where the load reads one, and names the model
type (b29d579). The new test's two cases fail without the check.
- The registered-plans check accepts `ep_router`, and its failure names
the styles the load keeps (202a805).
- `_spec_ep_plan`'s docstring covers a plan that ships with transformers
(ccab53a).
- Pre-commit passes against main. `tests/unit/torch/models`,
`test_moe_a2a.py` and `test_model_load_utils.py` pass on transformers
5.18 (384) and 5.5.4 (339, 34 skipped). The check changes nothing for
#2746: its tests with the check applied pass on 5.18 (588).
- Review round, 2026-11-01 (f9c898a): the registry test refuses a
spec declaring both a base and a prepared plan. Test-only. Pre-commit
passes against main. `test_ep_specs.py` passes on transformers 5.18 (47)
and 5.5.4 (32, 15 skipped).
- Rebased on 2026-11-01 (4cfbddf) onto main 51645db, without
conflicts; its own diff is unchanged. Pre-commit passes against main.
`tests/unit/torch/models`, `test_moe_a2a.py` and
`test_model_load_utils.py` pass on transformers 5.18 (384) and 5.5.4
(339, 34 skipped).

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

- Is this change backward compatible?: ✅ Additive: new functions, which
nothing calls until #2746 [3/3]. `_ep_config` and
`_num_experts_from_config` read the same two nested configs, in the same
order.
- 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 #2754.
- Did you get Claude approval on this PR?: ❌ Not yet. Requested; #2746
as a whole was approved on 2026-10-28.

### Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models. Split out of
#2746 (OMNIML-6076), whose review history stays on #2746.







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

## Summary by CodeRabbit

* **New Features**
* Added model-aware expert-parallel loading support for compatible
models, including models with nested configurations.
* Loading checks model support and Transformers version compatibility,
and explains when expert-parallel loading is unavailable, including
alternative loading options.
* Existing model-provided expert-parallel plans are preserved; supported
models can use their declared plans.
* Model-specific preparation is applied when available, helping ensure
the appropriate expert-parallel configuration is used.
<!-- 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 3, 2026
…nd apply the model spec when deciding and loading it (#2780)

> [!NOTE]
> **Folded in #2746 [3/3] on 2026-11-03**, at the user's request: this
PR now also applies the model spec when deciding and loading
expert-parallel. #2746's commits are here unchanged (this PR's head is
#2746's last head, 22b6d23); #2746 keeps their review history, and
this PR covers its Jira ticket, OMNIML-6076, too.
>
> **Re-parented on 2026-10-30** onto #2741 [2/3] (#3136), the
expert-parallel loader's core, when #2741 was split. This PR also adopts
#2779's newer collective load checks; see the end of Testing.
>
> **Base:** `main`, since #2741 [2/3] (#3136) merged on 2026-11-03. The
diff below is this PR's alone. It merges after #2741 [3/3] (#2741),
whose refusals keep `load_pretrained`'s new expert-parallel route from
quantizing unsupported experts wrong.

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

- `main`, with #3131 #2741 [1/3], #3134 #2746 [1/3], #3135 #2746 [2/3],
#2779, #3067, #2740 and #3136 #2741 [2/3] merged
  - #2741 [3/3] post-load refusals
  - #2742 dense sharding → #2743 block-FP8 dequantization
- **#2780 expert-parallel load routing, with the model spec applied
(this PR; #2746 [3/3] folded in)**
  - `hfep-base-11a-decompress` (#3137) → #2747 on-the-fly decompression
- `hfep-base-11b-kimi` (#2746's commits, now in this PR, + #2747) →
#3138 → #2748 → #2749
- `hfep-base-14-hf-ptq` (#2746's commits, now in this PR, + #2742 +
#2753 + #3133) → #3139 → #2754

</details>

### What does this PR do?

Type of change: New feature

#2779 routes `load_pretrained` by a `DistributionPlan`, but refuses a
plan that shards the routed experts: the expert-parallel loader (#2741)
comes later in the series. With it in, this PR adds that route, and
applies the model's spec (#3134), through the applier (#3135), when
deciding and loading it:

- **An expert-parallel plan loads through `load_and_prepare_ep`**,
handed the plan itself. Its arguments are checked with the FSDP2 load's,
in `_sharded_load_kwargs` inside #2779's collective "load checks" block;
`_load_sharded` then runs the load. That load replicates the dense part;
FSDP2-sharding it comes with #2742, a sibling of this PR. Its `freeze`
and `require_lm_head` options pass through, and so do the Hub options
(`token`, `cache_dir`, `local_files_only`), which its config read and
`from_pretrained` use. The sharded loads' refusals from #2779 cover it
too: a Nemotron-H checkpoint's MTP head, which `load_and_prepare_ep`
does not build, is refused rather than exported unquantized. Until #2742
is in, an expert-parallel plan that also shards the dense part is
refused before anything loads, naming the ways out: replicate it anyway,
or FSDP2-shard the whole model. A plan left to decide shards the dense
part when a whole copy of it and a rank's share of the experts would
exceed 60% of a GPU.
- **The decision refuses to leave an expert-parallel MoE whole on every
rank unasked**, naming the expert count the EP degree must divide and
every way out: shard its experts (an EP degree is offered only when one
divides both the experts and the world), shard the whole model with
FSDP2 (an unquantized checkpoint), load it in a single process, or ask
for the replication: `MODELOPT_EP_DEGREE=1` with `MODELOPT_FSDP_SIZE=1`,
or a replicated plan handed to `load_pretrained`, which skips the
decision. A replication both knobs ask for loads, with a note that every
rank holds the whole MoE. So #2737's refusals of routed experts the
decision can neither count nor shard by now advise
`MODELOPT_EP_DEGREE=1` with `MODELOPT_FSDP_SIZE=1` (`ep_size=1` with
`dense='replicate'` for a caller passing the arguments): an EP degree of
1 alone now meets the refusal above.
- **An MoE the expert-parallel load cannot take loads as a dense model
does**, whole on every rank or FSDP2-sharded, when the EP degree is left
to the decision or set to 1. The load may refuse it for the model's
spec, the transformers release it needs, its checkpoint format or its
plan. A rank-0 warning names the reason, and the fix where there is one
(an unquantized checkpoint, a later transformers); a replication both
knobs ask for gets only the "as asked" note. An EP degree above 1 asked
for such a model is still refused by the load.

**The model spec in the decision and the load** (folded in from #2746).
Without it, an MoE that only its spec makes expert-parallel, such as
DeepSeek-V3 before transformers 5.13, is decided as dense.

- **Deciding.** Unless the run rules expert parallelism out (a single
process, or an EP degree of 1), `resolve_distribution_plan` applies the
model's spec to a copy of the config before rank 0 builds the model on
meta.
- Every rank applies it inside a collective, so a rank that cannot fails
every rank.
- An expert-parallel plan returns the prepared copy. Any other plan
returns the config as read, which the export would otherwise write the
spec's plan into.
- Rank 0's knobs decide whether the spec applies, and rank 0 sends that
decision as it does the plan: a rank whose own environment skipped the
spec would load without the expert-parallel plan the others shard by,
and fail once the mesh is up.
- **Auto and the floors.** An EP degree left to auto resolves to 1 for a
model whose spec refuses expert parallelism, or that needs a later
transformers than the one installed: its spec's release or the
expert-parallel load's 5.7 floor, whichever is later.
- The load's floor holds for a model with no spec too
(`_spec_refuses_ep`).
- Only an explicit EP degree above 1, or a handed expert-parallel plan,
meets the refusal: `MODELOPT_FSDP_SIZE=world` alone plans FSDP2 for
GPT-OSS, and for Qwen3-MoE on transformers 5.5.
- **The left-whole refusal above sees spec plans.** At an EP degree of
1, which skips the spec, it still finds a spec-supplied plan's experts,
through the plan the spec would supply (or the one it states `prepare`
attaches), without applying anything.
- **An MoE whose spec rules expert parallelism out (GPT-OSS, Llama-4),
or whose transformers is below the release its expert parallelism needs,
loads as a dense model does** when the EP degree is left to auto or set
to 1. It loads whole on every rank, or FSDP2-sharded if it doesn't fit
one GPU, with the rank-0 warning above carrying the spec's reason or the
upgrade (`moe._spec_refusal`). An EP degree above 1 asked for such a
model is still refused, with the way around expert parallelism added
(`check_distributed_support`).
- **Loading.** The expert-parallel route applies the spec as it checks
the load's arguments, inside #2779's collective "load checks" block, so
a rank that cannot apply it fails every rank instead of leaving the
others in the load.
- A load handed the config that deciding prepared does not prepare it
again, since a model's preparation can patch its modeling code. It still
meets its spec's refusal and transformers floor
(`check_distributed_support`).
- A `config=` passed for the load with a plan handed in is the caller's
own, so an expert-parallel load prepares a copy of it, once.
- **Why the spec's `prepare` runs before deciding here, and where it
goes in #2748.** The decision builds the model on the meta device and
finds and counts its routed experts through the plan. For a model whose
plan only its spec supplies, the spec must therefore be applied first.
This PR applies the whole spec there, `prepare` included, and documents
the interim contract on `EPSpec.prepare`: it must leave a whole-model or
FSDP2 load as it would be without it, and may run more than once. No
spec in this PR sets `prepare`.
- #2748 adds the first specs that set it (Kimi-VL, Kimi-K2.5) and
replaces the contract. The decision runs only a pure-import step
(`EPSpec.make_importable`) and attaches the spec's stated plan
(`prepared_ep_plan`) with no `prepare` run. `prepare` then runs only
once the plan is decided expert-parallel: in a collective step after the
decision, or in the load after its own checks for a plan handed in.
- That puts `prepare` where `models/hf.py`'s `prepare_for_loading` hooks
already run: on the route that loads the model it prepares, never on one
that does not. The hooks are scoped to the load as a context; `prepare`
only runs on that route.

This closes the series' second phase: an MoE whose expert-parallel plan
ships with transformers, such as Qwen3-MoE, or that only its spec makes
expert-parallel, such as DeepSeek-V3, now loads expert-parallel through
`load_pretrained` and calibrates.

### 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("Qwen/Qwen3-30B-A3B")  # its plan ships with transformers
    # A model whose plan only its spec supplies loads the same way:
    # model = load_pretrained("/path/to/DeepSeek-V3-BF16")
    # ... mtq.quantize(model, ...), export_hf_checkpoint(model, ...)
```

Either model's routed experts are sharded over the 8 ranks. The
DeepSeek-V3 path is an unquantized (BF16) copy. The published
`deepseek-ai/DeepSeek-V3` checkpoint is FP8, which this PR refuses
before anything loads; the expert-parallel load dequantizes FP8
checkpoints from #2743 on.

### Testing

- `tests/unit/torch/utils/test_model_load_utils.py` (where #2737 moved
the decision's tests) gains the refusal to replicate an expert-parallel
MoE, when no degree divides its experts or an explicit EP degree of 1
leaves the dense part to auto, FSDP2 allowed instead, and the
replication both knobs ask for loading. Qwen3-MoE shows it, whose plan
ships with transformers 5.7.
`test_no_ep_degree_dividing_the_experts_leaves_them_whole` goes: the
refusal replaces it. #2737's two refusal tests now set
`MODELOPT_FSDP_SIZE=1` in their `set-to-1` rows and check the refusals
name it.
- `tests/unit/torch/utils/test_load_pretrained_distribution.py` (#2779)
gains the load's cases:
- an expert-parallel plan loads through `load_and_prepare_ep` with the
plan, records the plan, and goes through no other loader;
- the sharded loads' refusals (placement, model class, MTP head) apply
to it.
  - #2779's test that an expert-parallel plan is refused is gone.
- Mutation-checked: routing an expert-parallel plan elsewhere, dropping
the replicated-MoE refusal, and applying it to a sharded plan each fail
a test.
- `tests/gpu/torch/utils/test_load_pretrained_distribution.py` gains a
Qwen3-MoE case: left to decide, `load_pretrained` shards its experts,
each rank holding its contiguous share and the rest whole, and records
the expert-parallel plan. Not run locally; CI's GPU workflow runs it.
- Locally on this revision, the stack rebased on main c6fa613:
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: the refusal names no EP degree when the
config hides the expert count. 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.
- Review fixes, 2026-10-27, round 2: a replication both distribution
knobs ask for loads, with a note; the refusal offers an EP degree only
when one divides both the experts and the world; the Hub options reach
the expert-parallel load. 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 7c3c868, 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).
- Review suggestions, 2026-10-27 evening: the expert-parallel load
passes the Hub options to the checkpoint download too.
- Re-cut on 2026-10-29 onto #2741 (was on #2743), with three follow-ups:
- the test hunks moved from `test_resolve_distribution_plan.py`, which
#2737 deleted, into `test_model_load_utils.py`;
- #2737's two "Set MODELOPT_EP_DEGREE=1" refusals name
`MODELOPT_FSDP_SIZE=1` too;
- the `load_pretrained` docstring says the expert-parallel route
replicates the dense part.

Pre-commit, mypy included, passes against main. On CPU (torch 2.14,
transformers 5.18 and 5.5.4), these pass at this head:
`test_model_load_utils.py`, `test_load_pretrained_distribution.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `test_distributed.py`.
- Review fix, 2026-10-29, from the re-review after the re-cut: on #2741
the expert-parallel load refuses a sharded dense part, so `_route` now
refuses an expert-parallel plan that also FSDP2-shards it, before
anything loads, naming the ways out. The routing test runs both dense
layouts; the refused one fails without the fix. Pre-commit passes
against main, and the unit-test files above pass on transformers 5.18
and 5.5.4.
- Review suggestion, 2026-10-29: the refusal says that sharding the
dense part under expert parallelism is not supported yet (message only).
Pre-commit passes against main.
- Re-parented on 2026-10-30 onto #2741 [2/3] (#3136); the former head is
pinned.
- Adapted to #2779's split of the sharded load: the expert-parallel
route's checks run in `_sharded_load_kwargs`, inside the collective
"load checks" block, and its load in `_load_sharded`.
- The Hub options reach the restructured loader's config read and
checkpoint step.
- Its tests in the deleted `test_load_pretrained_distribution.py` files
moved into `test_model_load_utils.py` (unit and GPU), where #2779 moved
the load tests.
- Review suggestion: the left-whole refusal's FSDP2 way out now says
"for an unquantized causal LM", as `_route`'s does (effe11d).

Pre-commit, mypy included, passes against main. CPU tests
(`test_model_load_utils.py`, `test_ep_loader.py`, `test_moe_a2a.py`;
torch 2.14):

| transformers | Passed | Skipped | Failed |
|---|---|---|---|
| 5.18 | 210 | 0 | 0 |
| 5.5.4 | 182 | 28 | 0 |
- Review suggestion, 2026-10-30 (e051283): when the expert-parallel
load refuses an option it does not take (such as `device_map`), it names
its way to a whole model, `MODELOPT_EP_DEGREE=1` with
`MODELOPT_FSDP_SIZE=1` or a replicated plan; the FSDP2 load's text is
unchanged. A test row checks it and fails without the change. Pre-commit
passes against main; `test_model_load_utils.py` and `test_ep_loader.py`
pass on transformers 5.18 (161) and 5.5.4 (139, 22 skipped).
- Rebased on 2026-10-30 (1bec6da) onto main 99c3834 through
#3136's rebase (4c59a6b); no conflicts, this PR's own diff
unchanged. Pre-commit passes against main; `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (405) and 5.5.4 (376, 29 skipped).
- On GPUs, 2026-10-30: this PR's expert-parallel route, run as the
Qwen3-MoE row (`its-own-plan`) of
`test_an_expert_parallel_moe_loads_with_its_experts_sharded` at #2746
[3/3]'s ae518d6, passed. That version of the test also compares each
rank's logits with the whole model's. #2746's spec-plan row and the two
dense `load_pretrained` tests passed beside it, 4 tests in all. NVIDIA
GB200, torch 2.11.0a0, transformers 5.9.0, reruns disabled:

| GPUs | Passed | Failed |
|---|---|---|
| 2 | 4 | 0 |
| 4 | 4 | 0 |

- Rebased on 2026-10-30 (d78aaf8) onto #3136's restack (b726fb3)
after #3131 merged to main (62a5c48). The base under #3136 now
carries #2779's newer round, so 7 hunks in 3 files conflicted. All are
resolved by applying this PR's change to the new text:
  - `_load_sharded` takes the route beside #2779's new `_has_own_gpu`.
- `load_pretrained`'s docstring: the expert-parallel bullet goes before
#2779's reworded FSDP2 bullet, and the dropped "an `ep_size > 1` plan
raises" sentence leaves the rest of #2779's paragraph as it is.
- The tests keep #2779's new by-name, one-rank whole-load and
padded-auto cases beside this PR's. The `CHANGELOG.rst` line keeps this
PR's wording.
- Range-diff otherwise unchanged. Pre-commit passes against main.
`test_model_load_utils.py`, `test_ep_loader.py`, `test_moe_a2a.py` and
`tests/unit/torch/models` pass on transformers 5.18 (467) and 5.5.4
(425, 31 skipped).
- Review round, 2026-10-30 (50e64f0):
- The dtype refusal names FSDP2's `mp_policy` for the FSDP2 load only
(90c914a).
- A rank without a GPU of its own is refused before the expert-parallel
load too, as before the FSDP2 load. The remedy names the way to a whole
model for the route, from one helper shared with the placement refusal
(50e64f0).
- `test_a_sharded_load_refuses_what_it_cannot_honor` gains a `no_gpu`
row and an `mp_policy` assertion. Each fails without its change.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (469) and 5.5.4 (427, 31 skipped).
- Review round, 2026-10-30 (3c353af):
- A whole-model load refuses the options only the expert-parallel load
takes (`freeze`, `require_lm_head`) before anything loads, naming that
load. Before, they reached `from_pretrained` and failed inside
transformers.
- `test_a_load_refuses_what_it_cannot_load` gains
`ep-option-on-a-whole-load`, which fails without the change.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (470) and 5.5.4 (428, 31 skipped).
- Review round, 2026-10-30 (b1f5d8c):
- The left-whole refusal names the knobs as the caller set them:
`ep_size`/`dense` arguments, which override the environment knobs, or
the knobs (b1f5d8c). A new `explicit_degree_one_as_an_argument` row
fails without it.
- The docstring says the expert-parallel load freezes the model unless
`freeze=False`, unlike the other loads (1072e8f).
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (471) and 5.5.4 (428, 32 skipped).
- Review round, 2026-10-30 (4a1e020):
- The refusal of an MoE left whole on every rank is a `ValueError`, like
the decision's other refusals of what its inputs resolve to
(d0a63ff).
- A load handed an expert-parallel plan and no config reads the
checkpoint's config once, for its model type and for the load, as the
FSDP2 load already did (4a1e020). The EP-loader test asserts the
load gets that read.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (471) and 5.5.4 (428, 32 skipped).
- Review round, 2026-10-30 (4040ea3):
- `freeze` or `require_lm_head` passed as `None` asks nothing, as other
options passed as `None` do, rather than reading as False and dropping
the LM head (83d9ce0).
- The expert-parallel route returns the model unfrozen unless
`freeze=True`, as the other routes do (69e56a9).
- A decided expert-parallel layout says it was decided when it refuses a
whole-model placement, as the FSDP2 route already did (4040ea3).
- Each change fails a test when reverted. Pre-commit passes against
main. `test_model_load_utils.py`, `test_ep_loader.py`, `test_moe_a2a.py`
and `tests/unit/torch/models` pass on transformers 5.18 (472) and 5.5.4
(428, 33 skipped).
- Restack and review round, 2026-10-30 (8f9c8d9), onto #3136
1491b66. The rebase had no conflicts, and this PR's own commits are
unchanged; only the first commit's context moved.
- A decided expert-parallel layout now takes the load's own `freeze` and
`require_lm_head`, rather than refusing them as a whole-model placement
(1db4cc3). A new `its-own-options` row fails without the change.
- The docstring of `_refuse_a_rank_without_its_gpu` says what the check
adds beside #3136's GPU check in the expert-parallel load, which now
refuses a run where only some ranks have a GPU (8f9c8d9).
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (476) and 5.5.4 (430, 35 skipped).
- Review round, 2026-10-30 (d466147):
- A sharded load now refuses an option that only the other sharded load
takes by naming that load, rather than with the whole-model way out,
which would refuse the option again. `broadcast_chunk_size=None` asks
the FSDP2 load to broadcast every layer at once. The expert-parallel
load used to drop it silently and now refuses it as the FSDP2 load's
option. The two new rows of `test_a_load_refuses_what_it_cannot_load`
each fail without the change.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (478) and 5.5.4 (432, 35 skipped).
- Restack and review round, 2026-10-30 (b692242), onto #3136
56353ef on main 059588b, after #2779 reworked the load checks:
- With an expert-parallel load to use it, the plan decision no longer
takes an EP degree left to auto as 1, so a decided MoE loads
expert-parallel. `test_a_load_it_decides_shards_the_experts` replaces
#2779's `test_a_load_it_decides_keeps_the_experts_whole`.
- This PR's refusals now use #2779's way out, `_whole_instead`, which
now takes the route. For a plan handed in, the refusal names a plan with
an EP degree of 1; for a decided plan, it also names the knobs.
- Placement options on a decided expert-parallel layout are now refused
by #2779's `measured` refusal, which this PR extends to that layout.
Only options that neither sharded load takes count as placement.
- Defaults now follow one rule, #2779's `_ASKS_NOTHING`. On the
expert-parallel load, `broadcast_chunk_size=None` is refused as an FSDP2
option, and `cpu_offload=False` asks for nothing.
- The refusal of the other sharded load's options now names a way
forward (e98619f).
- A launch with one GPU per process loads expert-parallel through
#2779's GPU predicate (5da80d4). That case fails under the
predicate's older reading.
- The changelog's backward-breaking entry now says an MoE loads
expert-parallel (b692242).
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (513) and 5.5.4 (463, 39 skipped).
- Review round, 2026-10-30 (1692141), onto #3136 75bc2d6:
- An EP degree left to the plan decision gives way to FSDP2 for the
whole model when the dense part, replicated beside a rank's share of the
experts, does not fit one GPU, instead of planning a layout the
expert-parallel load refuses (1692141). An EP degree the caller asks
for still stands and is refused by the load, naming the ways out.
`test_what_a_rank_holds_with_the_dense_part_replicated_must_fit` asserts
both outcomes, and its decided case fails without the change.
- The restack kept #3136's trimmed `load_and_prepare_ep` docstring and
comments, plus this PR's sentence on `hub_options`.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (515) and 5.5.4 (463, 41 skipped).
- Restack and review round, 2026-10-30 (093c652), onto #3136
ab06860 on main d464d30:
- An EP degree the decision chose now also gives way to none when the
expert-parallel load would refuse the model, by its plan (the load's own
style checks, now one function, `_ep_plan_refusal`) or by its checkpoint
format. Such an MoE is not refused for being left whole either
(9cc4589).
`test_an_moe_the_expert_parallel_load_refuses_is_decided_without_it`
fails without the change in both of its cases.
- The refusal of an expert-parallel plan that FSDP2-shards the dense
part says that an EP degree left to the decision gives way
(381219c).
- #2779's texts written before this load now name it: the auto_class
refusal, the no-group refusal and the docstring (093c652).
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (519) and 5.5.4 (464, 44 skipped).
- Review round, 2026-10-31 (1960174):
- An EP degree the decision chose now gives way for every reason the
config tells why the expert-parallel load would refuse the model: a
model spec ruling it out (Llama-4's, GPT-OSS's), a transformers below
the load's floor or the spec's, the checkpoint format, or the plan's
styles. The `its-spec` and `its-transformers` cases fail without the
change.
- Each give-way now says why on rank 0. The CHANGELOG names only the
MoEs the expert-parallel load takes as refused when left whole.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_ep_loader.py`, `test_moe_a2a.py` and `tests/unit/torch/models`
pass on transformers 5.18 (521) and 5.5.4 (464, 46 skipped).
- Restacked on 2026-10-31 (fac2c56) onto #3136 7747c5d, which
moved `test_ep_loader.py` into `test_model_load_utils.py`. This PR's one
change to that file, the Hub-options checks in
`test_the_weights_load_in_the_checkpoints_dtype_through_its_class`, now
sits in the moved section. Its own diff is otherwise unchanged.
Pre-commit passes against main. `test_model_load_utils.py`,
`test_moe_a2a.py` and `tests/unit/torch/models` pass on transformers
5.18 (521) and 5.5.4 (464, 46 skipped).
- Review round, 2026-10-31 (3fc02b8):
- The expert-parallel load's transformers floor is one constant,
`_EP_MIN_TRANSFORMERS`, that the decision and the load both read
(6210606).
- The decision now resolves whether the expert-parallel load refuses an
MoE whatever its EP degree, so an EP degree of 1 the caller set no
longer meets the left-whole refusal for a model that load refuses
(3fc02b8). The give-way test runs each refusal with the degree on
auto and with `MODELOPT_EP_DEGREE=1`, and the `set-to-1` cases fail
without the change.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_moe_a2a.py` and `tests/unit/torch/models` pass on transformers
5.18 (525) and 5.5.4 (464, 50 skipped).
- Review round, 2026-10-31 (3c40b57):
- `load_and_prepare_ep` refuses what the plan decision gives way for
(`_ep_load_refusal`), after its own floor and format checks. An EP
degree asked for, or a plan handed in, no longer loads a model whose
spec rules expert parallelism out. The load test's new GPT-OSS case
fails without the change.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_moe_a2a.py` and `tests/unit/torch/models` pass on transformers
5.18 (526) and 5.5.4 (465, 50 skipped).
- Restacked on 2026-10-31 (c2d18e6) onto #3136 930bb0f, on the
new main e352cac and #2779 c78d2e5, with Claude's 04:08Z review
round folded in:
- #2779's texts meet the expert-parallel load. Its new
`init_quantized_weights` refusal names the expert-parallel route's own
way to a whole model, and a new test covers both a knob and a handed
plan; the plain FSDP2 wording fails it. The loading guide #2779 added
now describes the expert-parallel route, which this PR's docstring
paragraphs moved into (5455a0c). The decided EP degree is no longer
forced to 1 in `load_pretrained`.
- `_ep_load_refusal` returns the error itself, so a floor refusal is a
`RuntimeError` whichever floor it trips (eda4c88). A spec's floor
above the load's own is tested (608b0b8). Both cases fail without
their change.
- Pre-commit passes against main. `test_model_load_utils.py`,
`test_moe_a2a.py` and `tests/unit/torch/models` pass on transformers
5.18 (536) and 5.5.4 (471, 54 skipped).
- Review round, 2026-10-31 (f7b11fe): the dense-sharding give-way
test also leaves the EP degree to the decision, where a caller asking
for FSDP2 makes the decided degree give way; it fails if only rank 0's
GPU memory may. Pre-commit passes against main. The same CPU tests pass
on transformers 5.18 (537) and 5.5.4 (471, 55 skipped).
- Restacked on 2026-11-01 (36863bc) onto #3136 4dd38a3, on main
cf38ec3 and #2779 c42cb61. #2779's new whole-model branch and
its two-rank test come in unchanged. The CHANGELOG entry takes #2779's
rewritten sentence, with this PR's MoE clause in place of the one saying
an MoE loads without expert parallelism. Its own diff is otherwise
unchanged. Pre-commit passes against main. `test_model_load_utils.py`,
`test_moe_a2a.py` and `tests/unit/torch/models` pass on transformers
5.18 (538) and 5.5.4 (472, 55 skipped).
- Restacked on 2026-11-01 (8e19843) onto #3136 35f1ac0, on main
51645db, without conflicts; its own diff and tree are unchanged.
Pre-commit passes against main.
- Design change, 2026-11-01 (e20bd19): an MoE the expert-parallel
load cannot take now loads as a dense model does, with a rank-0 warning,
both when the EP degree is left to the decision and when it is set to 1
(before, only the first was noted, on rank 0, and the second loaded
silently). The give-way test asserts the warning for each reason the
load refuses, and fails without it. Pre-commit passes against main.
`test_model_load_utils.py`, `test_moe_a2a.py` and
`tests/unit/torch/models` pass on transformers 5.18 (538) and 5.5.4
(472, 55 skipped).
- Review round, 2026-11-01 (edf3b61): the dense-load warning skips a
replication both knobs ask for, which keeps its "as asked" note. The
give-way test asserts no warning there, and fails without the gate. The
guide promises a fix only where the load names one. Pre-commit passes
against main. The same CPU tests pass on transformers 5.18 (543) and
5.5.4 (472, 60 skipped).
- Restacked on 2026-11-02 (301f97d) on #3136 39f55f2, on main
2d4e8d0, where #2779 and #3135 merged. There were no conflicts, and
the PR's own diff is unchanged. Pre-commit passes against main. The same
CPU tests pass on transformers 5.18 (572) and 5.5.4 (486, 75 skipped).
- Restacked on 2026-11-02 (09322c1) on #3136 c0041d0, on main
4f08a12, where #3067 merged. There were no conflicts, and the PR's
own diff is unchanged. Pre-commit passes against main. The same CPU
tests pass on transformers 5.18 (572) and 5.5.4 (486, 75 skipped).
- Restacked on 2026-11-02 (7653ddf) on #3136 d87f5bd, which now
targets main 653ef61, where #2740 merged. There were no conflicts,
and the PR's own diff is unchanged. Pre-commit passes against main. The
same CPU tests pass on transformers 5.18 (572) and 5.5.4 (486, 75
skipped).
- Rebased on 2026-11-03 (e2d81c9) onto main a6cc167, where #3136
merged; this PR's base is now `main`. There were no conflicts, and the
PR's own diff is unchanged. Pre-commit passes against main. The same CPU
tests pass on transformers 5.18 (572) and 5.5.4 (486, 75 skipped).
- **From #2746, folded in on 2026-11-03.** #2746's Testing section keeps
its per-round record. Its tests and checks:
- `tests/unit/torch/utils/test_model_load_utils.py` (the decision's and
the loads' tests) gains the spec's cases:
- the spec applied before the decision, DeepSeek-V3's plan coming only
from its spec, and the returned config carrying it for an
expert-parallel plan only;
- no spec for a run that rules expert parallelism out, by argument or by
`MODELOPT_EP_DEGREE=1`;
- auto picks no EP degree for GPT-OSS, nor below a spec's floor or the
load's (DeepSeek-V3 on transformers 5.6.2); an explicit `ep_size=2`
meets the refusal;
- on two real gloo ranks, every rank applying the spec, or not, as rank
0 decided, whatever its own knob says;
- on two real gloo ranks, a rank that cannot apply the spec fails every
rank, when deciding and when loading a handed expert-parallel plan;
- the left-whole refusal for spec plans at an EP degree of 1; GPT-OSS,
and DeepSeek-V3 below the floor, loading as a dense model with the
warning, at an EP degree left to auto or set to 1;
- a decided expert-parallel load gets the spec-prepared config, prepared
once, not at all when handed, and on a copy when passed as `config=`
with a handed plan; GPT-OSS is refused with its config handed in,
without preparing it.
- Mutation-checked (earlier rounds): skipping the spec or applying it
without expert parallelism, ignoring the EP knob, letting each rank
decide the spec for itself, preparing a handed config twice or not at
all, ignoring the spec's plan at an EP degree of 1, letting auto pick an
EP degree for a model whose spec refuses expert parallelism or below a
floor, and offering an EP degree below the floor each fail a test.
- Checked locally, at the stack's tip: DeepSeek-V3, Nemotron-H and
Nemotron-H-Omni configs prepared by their specs and swapped to the
`torch_a2a` styles are written by the expert-parallel export with no
`base_model_ep_plan`, as their sources have none. There the export
writer itself puts back the source `config.json`'s values (#2753). The
loaded model's own config holds no spec plan only since b51123a (see
#2746's Testing).
- On GPUs, 2026-10-30, at ae518d6:
`test_an_expert_parallel_moe_loads_with_its_experts_sharded` in
`tests/gpu/torch/utils/test_model_load_utils.py` runs Qwen3-MoE
(`its-own-plan`) and DeepSeek-V3 saved with no plan of its own
(`its-spec-plan`) through the real `load_pretrained`, with the plan left
to decide. It checks each rank's expert slices and its own batch's
logits against the whole model. It and the two dense `load_pretrained`
tests passed on 2 NVIDIA GB200 GPUs (torch 2.11.0a0, transformers 5.9.0,
reruns disabled).
- Folded #2746 in on 2026-11-03 (22b6d23): this PR's branch
fast-forwarded to #2746's head, so no commit changed. Pre-commit passes
against main. The same CPU tests pass on transformers 5.18 (594) and
5.5.4 (495, 88 skipped).
- Review fix, 2026-11-03 (c9f3a2d): the refusal of a sharded load
inside `init_quantized_weights` gives each route its own reason. The
expert-parallel load calls `from_pretrained` with its own config and
device mesh, and the FSDP2 load's text is unchanged; the guide and a
test docstring follow. Pre-commit passes against main. The same CPU
tests pass on transformers 5.18 (594) and 5.5.4 (495, 88 skipped).
- Review fix, 2026-11-03 (275ce95): the Backward Breaking CHANGELOG
entry on how `load_pretrained` distributes a model is cut to two
sentences, what changed and how to keep loading it whole on every rank.
Pre-commit passes against main.
- Review fix, 2026-11-03 (0476abb): the guide's paragraph on calls
that place the model names the ways out the refusal gives, by route. For
an MoE whose experts the decision shards, that is `MODELOPT_EP_DEGREE=1`
with `MODELOPT_FSDP_SIZE=1`, or a plan with an EP degree of 1.
Pre-commit passes against main.

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

- Is this change backward compatible?: ✅ Nothing released changes.
Against #2737 and #2779: an expert-parallel plan now loads, and a
decision to replicate an expert-parallel MoE on every rank now raises
unless both knobs ask 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)?:
✅ #2779's 0.49.0 Misc entry now names expert sharding.
- Did you get Claude approval on this PR?: This PR was approved on
2026-10-30 (effe11d), and #2746 on 2026-11-01 (04a197e), each
with its suggestions taken. Re-review requested for the folded PR.

### Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models; merges after
#2741 [3/3] (#2741). Split from #2774, which first routed every load in
one PR and whose non-expert-parallel half is now #2779: this half needs
the expert-parallel loader, so it lands after it. Applying the model
spec in the decision and the load, which this PR carried before the
series was reordered, moved to #2746 with the specs, and came back here
when #2746 was folded in on 2026-11-03.

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

* **New Features**
* Pretrained MoE models can load with routed experts sharded across
ranks under `torchrun`. Distribution plans also support FSDP2 sharding
or loading a full copy on each rank.
* **Bug Fixes**
* Loading now reports an error when a routed-expert model would
otherwise remain unsharded.
* **Documentation**
* Updated loading guidance and changelog details for distribution plans.
<!-- 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 3, 2026
… load, expert-parallel loads included (#3137)

> [!NOTE]
> **#2747 folded in (2026-11-03):** at the user's request to fold the
series backward, this PR now also carries #2747, the expert-parallel
loader's side of the decompression, with its commits as they were. #2747
is closed and keeps its review history; its ticket is this one,
OMNIML-6063.
>
> **Split out of #2747** at the reviewers' request (2026-10-30), and
joined with it again: the on-the-fly decompression,
`modelopt/torch/models/_onfly_decompress.py`, and the expert-parallel
load of a checkpoint its model spec decompresses.
>
> **Base:** `main`, which holds the expert-parallel loader (#3136) and
its routing with the model spec (#2780) since they merged.

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

- `main` (#3130 [1/2], #3131, #3132, #3134, #3135, #3140, #2779, #3074,
#3067, #2740, #3136 and #2780 have merged)
  - #2741 [3/3] the loader's post-load refusals
  - #2742 dense sharding → #2743 block-FP8 dequantization
- **#3137 [2/2] on-the-fly expert decompression, expert-parallel loads
included (this PR; #2747 folded in)**
    - #3138 Kimi-VL and Kimi-K2.5 adapters (#2748 folded in)
      - #2749 [2/2] Kimi-K3 adapter

</details>

### What does this PR do?

Type of change: New feature

Expert-parallel PTQ loads a checkpoint with `from_pretrained` over the
expert-parallel mesh, so each rank builds only its own experts. A
checkpoint whose experts are compressed-tensors quantized (Kimi-K2.5's
INT4, Kimi-K3's MXFP4) cannot take that load as it is: transformers'
fused-experts conversion expects each expert's plain `.weight`.

- `install_onfly_decompress(hf_config)` rewrites the per-expert
converters of the model built from the config it marks.
- Each `.weight` source becomes the keys the checkpoint stores
(`weight_packed`, `weight_scale`, ...). A `DecompressExperts` op ahead
of the merge dequantizes each expert this rank owns to bf16, so PTQ runs
on the original compressed checkpoint with no decompressed copy on disk.
Experts other ranks own arrive as `None` and are skipped.
- It is format-agnostic: the `compressed_tensors` library does the math,
driven by the checkpoint's own `quantization_config`. The format is the
config group's own when it names one; the top level then says
"mixed-precision". A format compressed-tensors registers no compressor
for is refused.
- It handles a checkpoint whose experts are its only compressed weights,
in one config group that targets them. Several groups, or a group that
is not the experts, are refused; so is a `quantization_config` with no
groups, since there is nothing to decompress. Kimi-K2.5, K2.6 and
K2.7-Code (INT4) and Kimi-K3 (MXFP4) each carry one group, under
`text_config`.
- Stored params that disagree on how many experts they hold are refused,
as is a checkpoint key the decompression does not consume.
- The rewritten converter reverses as the one it rewrote: the
decompression is load-only, so a save (transformers' `save_pretrained`,
ModelOpt's export) writes the experts back under the checkpoint's own
`.weight` names (`w1`/`w3`/`w2` for Kimi-K3).
- The hooks are process-wide, but they rewrite only a marked config's
converters, and only a load of such a model keeps integer tensors
uncast: any other model loaded in the process keeps its stock converters
and casts.
- A second, differently compressed checkpoint in the same process is
refused; the same checkpoint again is a no-op.
- A config with nothing to decompress, or a raw dict, raises before
anything is patched, and without needing `compressed_tensors`. So does a
config that loads in a dtype other than bf16, the dtype the experts
decompress to, at any of its levels.
- It needs transformers 5.8: earlier releases' `Concatenate` looks up
the sibling keys the decompression has already consumed.
- It needs compressed-tensors 0.16, the first release whose compressors
decompress one weight by its scheme (`compression_param_names(scheme)`
and `decompress(state_dict, scheme)` as classmethods). An older one is
refused before anything is read, naming the release and the upgrade.
- `check_compressed_keys(hf_config, ckpt_dir)` reads the checkpoint's
stored tensor names and dtypes from its shard headers. Every compressed
weight must be an expert's, every expert's weight must be compressed,
every compressed weight must store the same names (the load pairs them
by position), all of them names the installed compressed-tensors gives
the scheme, and no compressed tensor may be a float bf16 cannot hold
exactly. The expert-parallel load runs it (below).
`stored_names(hf_config)` gives the names a marked config's checkpoint
stores, and refuses an unmarked config by name.
- CI's `unit` nox sessions install `compressed-tensors`, so the tests
against the real library run there. It goes in no extra: it pulls in
transformers, which CI's transformers-free lane must not get.

**Why not transformers' own compressed-tensors quantizer**
(`run_compressed=False`, which 5.18 deprecates for `dequantize=True`)?
It does not fit an expert-parallel PTQ load:
- Its fused-experts path, a `DecompressExperts` op its
`update_weight_conversions` prepends to the experts' converters, is
recent: transformers 5.5 has none. The Kimi-K2.5 adapter runs from 5.8.
- That op decompresses every expert it is handed into one buffer sized
for all of them, and has no case for the `None` the expert-parallel load
hands it for each expert another rank owns. This decompression shards at
load and decompresses only the rank's own experts.
- Before the load, the quantizer applies the checkpoint's
compressed-tensors scheme to every module its config groups target
(`apply_quantization_config`, `compress_model`). PTQ needs plain bf16
modules to place ModelOpt's quantizers on.

So the expert-parallel load deletes `quantization_config` on a
decompressed load (below), and the experts are decompressed here.

**The expert-parallel load of a decompressed checkpoint** (folded in
from #2747):

`load_and_prepare_ep` takes a checkpoint whose model spec decompresses
its experts as they load (above), which its format check refused before.

- **Format check.** A config the decompressor marked passes the check;
an unmarked compressed-tensors checkpoint is still refused.
- **No competing quantizer.** On the marked path the load deletes
`quantization_config` from its copy of the config, at the top level and
on `text_config` and `llm_config`: every level `_ckpt_quant_method`
reads. So transformers builds no compressed-tensors quantizer to compete
with the decompressor.
- Kimi-K2.5's config class copies its text config's
`quantization_config` to the top level, and from transformers 5.13 that
quantizer claims the experts' converters itself.
- It is deleted rather than set to `None`: before 5.11, transformers
takes any `quantization_config` attribute, `None` too, for a quantized
checkpoint.
  - The caller's config keeps its own.
- **Stored tensors checked before anything loads
(`check_compressed_keys`).** A class target such as `Linear` does not
say what was compressed, and the load drops the config that would load
any other compressed weight. So every weight stored compressed must be
an expert's, and every expert's weight stored compressed. No compressed
tensor may be a float that bf16 cannot hold exactly.
- **No compressed tensor carried unread.** The export copies the
checkpoint tensors the model has no parameter for as stored, and this
load dropped the config that would read a compressed one. So once the
load knows those tensors, it refuses any that is compressed: an MTP
layer's compressed experts, say, which pass the stored-tensor check but
sit in no layer transformers builds. Uncompressed ones are carried as
before. So are compressed tensors in a safetensors file the load never
opens, such as a standalone `mtp.safetensors`, which the export copies
as stored; a plain such file is carried.
- **Collective checks.** The format check and the deletion run inside
the loader's collective checks (#3136), and so does the stored-tensor
check, right after the checkpoint is made local. The unplaced-tensor
refusal runs inside the load's own collective block. So a refusal on one
rank fails every rank.

**Non-expert-parallel loads.** A spec's `prepare` installs the
decompressor and marks the config, and it runs only on expert-parallel
routes:
- only an expert-parallel plan runs it, on every rank; the plan decision
reads the plan the spec states instead (since #2748, now in #3138);
- an EP degree of 1 and a single process skip it;
- the FSDP2 load refuses a quantized checkpoint and a VLM before it
loads.

So a marked config reaches `from_pretrained` only through this load.
What outlives a `prepare` in the process is inert for other loads: the
conversion-mapping hook rewrites only a marked config's converters.

### Usage

Internal to the Kimi adapters (#3138, #2749), whose `prepare` installs
the decompressor; the expert-parallel load does the rest.

### Testing

- `tests/unit/torch/models/test_onfly_decompress.py` (49 cases) covers:
- the rewritten converters, a converter source that is no weight refused
at the rewrite, and a stored param without its weight refused at the
load;
- packed experts decompressing and fusing like an uncompressed
checkpoint, through the loader's own steps;
- only owned experts reaching the compressor, and stored params
disagreeing on the expert count refused;
- integer tensors keeping their dtype through transformers' own copy in
a decompressing load, and a later load of an unmarked model casting as
before (a real `from_pretrained`);
- installing once, a second checkpoint compressed differently refused,
and a config with nothing to decompress, a raw dict, or a load in a
dtype other than bf16 at any level, refused;
- the format taken from the one group, and a format with no compressor
refused;
  - an unmarked config refused by name when its stored names are read;
- the stored-tensor check over ten layouts, among them scales stored for
other experts in equal number and a name the installed
compressed-tensors does not give the scheme;
  - a VLM marked at either level;
- real `from_pretrained` loads of a tiny compressed Mixtral, INT4 and
MXFP4, with the real library: the experts load exactly, save back as the
checkpoint's own `w1`/`w3`/`w2` weights, and export under those names.
These and the other cases with the real library run in CI's unit
sessions; elsewhere they skip, saying what they need.
- Skips below transformers 5.8, the release the decompression requires.
- Locally at the round-1 head:
  - pre-commit against main passes, mypy included;
- on CPU, torch 2.14: 87 passed on transformers 5.18, and 45 passed, 3
skipped on 5.5.4. That is `test_onfly_decompress.py` plus the
expert-parallel loader's `test_ep_loader.py`.
- 2026-10-30: round 2 (an unmarked config refused by name, the group's
own format and a format with no compressor refused, a non-bf16 load
refused, docstrings compressed), rebased onto #3136 4c59a6b (main
99c3834); `tests/unit/torch/models/test_onfly_decompress.py` +
`tests/unit/torch/utils/test_ep_loader.py` +
`test_hf_checkpoint_utils.py` on CPU, torch 2.14: 146 passed on
transformers 5.18, and 94 passed, 9 skipped on 5.5.4; pre-commit against
main passes, mypy included. Each fix's test fails without it.
- 2026-10-30: rebased onto #3136 b726fb3, restacked after #3131
merged, with no conflicts and the own diff unchanged. Pre-commit against
main 62a5c48 passes, mypy included. On CPU, torch 2.14,
`test_onfly_decompress.py`, `test_ep_loader.py`,
`test_unplaced_source_keys.py`, `test_hf_checkpoint_utils.py` and
`test_model_load_utils.py` pass: 301 on transformers 5.18, and 237
passed, 21 skipped on 5.5.4.
- 2026-10-30: round 3 (cjluo-nv's review): the converter reverses as the
one it rewrote, compressed weights must store the same names, integers
stay uncast only in a decompressing load, bf16 at every config level,
module-level imports. Each fix's test fails without it. Pre-commit
against main passes, mypy included. On CPU, torch 2.14,
`test_onfly_decompress.py`, `test_ep_loader.py`,
`test_unplaced_source_keys.py`, `test_hf_checkpoint_utils.py`,
`test_model_load_utils.py` and `tests/unit/torch/export` pass on
transformers 5.18 and 5.5.4, apart from seven `test_export_diffusers.py`
cases that fail the same way at the base in this environment.
- 2026-10-30: rebased onto #3136 e251f6c (its module-scope imports
and mixed-GPU refusal) with no conflicts and the own diff unchanged.
Pre-commit against main passes; the same five test files pass on
transformers 5.18 (308) and 5.5.4 (238 passed, 22 skipped).
- 2026-10-30: Claude's two suggestions on round 3 taken: a stored name
the installed compressed-tensors does not give the scheme is refused,
and so is a converter source that is no weight, where it is rewritten.
Each test fails without its change. Pre-commit against main passes; the
five test files pass on transformers 5.18 (309) and 5.5.4 (238 passed,
22 skipped).
- 2026-10-30: juhi's blocker fixed. From transformers 5.14 an
expert-parallel load shards each expert's tensors through
`DtensorShardOperation.shard_tensor`, which cast the packed integers to
bf16 (a 2-GPU Kimi-K3 load on 5.18 failed in `DecompressExperts`). The
keep-integers patch now sits on `spawn_materialize`, where every read
starts; a new test shards an int32 tensor through transformers' own
`DtensorShardOperation` on a one-rank CPU mesh and fails without the
fix. Claude's suggestions taken: experts' weights only rewritten, an
expert's bias passes the stored-name check, the transformers floor
checked first, wording. Rebased onto #3136 1491b66. Pre-commit
against main passes; `test_onfly_decompress.py`, `test_ep_loader.py`,
`test_unplaced_source_keys.py`, `test_hf_checkpoint_utils.py` and
`test_model_load_utils.py` pass on transformers 5.18 (313) and 5.5.4
(239 passed, 22 skipped), with compressed-tensors 0.19.0. The 2-GPU run
of the compressed expert-parallel load on 5.18 (#2747's GPU case) is
pending on our cluster.
- 2026-10-30: On two GPUs, with transformers 5.18.0 and
compressed-tensors 0.19.0,
`tests/gpu/torch/utils/test_expert_parallel_load.py::test_compressed_experts_load_expert_parallel_each_rank_decompressing_its_own[int4]`
and `[mxfp4]` passed at #2747 e2e7486 (on this PR's 0d7866e),
loading each case at EP2 through the `spawn_materialize` fix; on one GPU
both skip, as they need two. Since then this PR gained only the
module-scope test import (b56c3e7) and shorter docstrings
(48b922c), with no behaviour change; source is now 495 added lines,
within the ~500 budget.
- Review fixes carried from #2747:
  - `_SUB_CONFIG_ATTRS` is imported at module level;
- the unit sessions install `compressed-tensors` on every torch, since
the torch 2.8 and 2.9 legs it was kept out of are gone.
- 2026-10-30: rebased onto main 059588b through #3136 584c8b4,
whose base now sits on main with #3134 merged. No conflicts, and the own
diff is unchanged. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-30: restacked onto #3136 56353ef (main 059588b). From
Claude's review of #2747: `check_compressed_keys` returns the `tensor
name -> file` map it read, for the loader to reuse (7a56a68);
nothing else changed. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-31: restacked onto main d464d30 through #3136 ab06860.
No conflicts; the own diff is unchanged. Pre-commit against main passes,
mypy included; `tests/unit/torch/models` and `tests/unit/torch/utils`
pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-31: at 43f08b5, the decompressor ran in #2747's
compressed-expert GPU cases, `[int4]` and `[mxfp4]`, which passed on 2
GPUs and on 4 GPUs with transformers 5.18.0 and compressed-tensors
0.19.0, in a run of the whole GPU file at #2749 63c8267, which
contains it.
- 2026-10-31: restacked onto main e352cac through #3136 930bb0f,
which moved the expert-parallel loader tests into
`test_model_load_utils.py`. No conflicts; the own diff is unchanged.
Pre-commit against main passes, mypy included; `tests/unit/torch/models`
and `tests/unit/torch/utils` pass on CPU, torch 2.14, on transformers
5.18 and 5.5.4.
- 2026-10-31: at 9deea3b, over the rebuilt base, the decompressor
ran in #2747's compressed-expert GPU cases, `[int4]` and `[mxfp4]`,
which passed on 2 GPUs and on 4 GPUs with transformers 5.18.0 and
compressed-tensors 0.19.0, in a run of the whole GPU file at #2749
a60c01c, which contains it.
- 2026-10-31, at c6b427a: on compressed-tensors 0.13.0 the
decompressor's setup failed with `TypeError: 'property' object is not
callable`. Before 0.16 a compressor states its parameter names as a
property (to 0.14) or not at all (0.15), and decompresses through an
instance built from the whole config. An older compressed-tensors is now
refused up front, naming 0.16 and the upgrade (321ba9a,
c6b427a), and the tests that need the real library skip below 0.16.
`test_a_compressed_tensors_before_per_scheme_compressors_is_refused_by_its_release`
fails without the check, on a stand-in compressor of 0.13's form.
Pre-commit against main passes, mypy included; `tests/unit/torch/models`
and `tests/unit/torch/utils` pass on CPU, torch 2.14, on transformers
5.18 and 5.5.4. `test_onfly_decompress.py` against each
compressed-tensors release, on CPU, torch 2.14, transformers 5.18:

  | compressed-tensors | Passed | Skipped |
  |---|---|---|
  | 0.19.0, 0.16.0 | 54 | 0 |
  | 0.15.0.1, 0.13.0 | 45 | 9 |
- 2026-10-31, at 81bcef7, from Claude's review: the loader hook
reads the decompressing flag first and looks at a source's dtype only in
a decompressing load, so any other load passes through it untouched;
`test_integer_checkpoint_tensors_keep_their_dtype_on_load` hands it a
source with no dtype outside such a load, which raised before. The
test's reverse name mapper is imported at module scope. Pre-commit
against main passes, mypy included; `tests/unit/torch/models` and
`tests/unit/torch/utils` pass on CPU, torch 2.14, on transformers 5.18
and 5.5.4.
- 2026-11-01, at e72a810: restacked onto main cf38ec3 through
#3136 4dd38a3. No conflicts; the own diff is unchanged. Pre-commit
against main passes, mypy included; `test_model_load_utils.py` and
`test_onfly_decompress.py`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4.
- 2026-11-01, at df2de9d: restacked onto main 51645db through
#3136 35f1ac0; the tree is unchanged. Pre-commit against main
passes, mypy included; `test_model_load_utils.py` and
`test_onfly_decompress.py`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4.
- 2026-11-02, at fcd6c08: restacked onto main 2d4e8d0 through
#3136 39f55f2. Main now holds #3135, whose `_SUB_CONFIG_ATTRS` in
`utils/moe.py` is the one this PR added, word for word, so the PR no
longer changes `moe.py`; the rest of the own diff is unchanged.
Pre-commit against main passes, mypy included; `tests/unit/torch/models`
and `tests/unit/torch/utils`, run in one process, pass on CPU, torch
2.14, on transformers 5.18 and 5.5.4.
- 2026-11-02, at f410618: restacked onto main 4f08a12, which now
holds #3067, through #3136 c0041d0. No conflicts; the own diff is
unchanged. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-11-02, at 59edbb4: restacked onto main 653ef61, which now
holds #2740, through #3136 d87f5bd, which now targets main. No
conflicts; the own diff is unchanged. Pre-commit against main passes,
mypy included; `tests/unit/torch/models` and `tests/unit/torch/utils`,
run in one process, pass on CPU, torch 2.14, on transformers 5.18 and
5.5.4.
- 2026-11-02, at c9dcaa9: rebased onto main bc5adc6, without
#3136, and retargeted to main: its three files import nothing #3136
adds. No conflicts; the own diff is unchanged. Pre-commit against main
passes, mypy included; `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4, and without transformers.
- 2026-11-02, at ac48ad2, from CodeRabbit's review: every
in-function import in `_onfly_decompress.py` and its test now names its
reason in a comment: optional dependencies, and `core_model_loading`
being new in transformers 5. Comments only; pre-commit against main
passes, and `test_onfly_decompress.py` passes on CPU, torch 2.14, on
transformers 5.18, and skips on 5.5.4 and without transformers, as
before.
- 2026-11-03, at a39cdb5: #2747 folded in. This PR's branch was
fast-forwarded to #2747's head, so its commits are #2747's as they were,
on main a6cc167. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4. On
GPU, the whole GPU file passed at #2749 7cfcd54, which contains this
code, with transformers 5.18.0 and compressed-tensors 0.20.1: on 2 GPUs,
5 passed and `[ep-half]` skipped, as it needs 4; on 4 GPUs, all 6
passed, in the file's order and again in reverse.
- 2026-11-03, at 24bc5b6: the history was linearized onto main
a6cc167, replaying this PR's and #2747's commits in order without
the merge from main, so DCO no longer counts main's squash. The tree is
identical to a39cdb5's, every commit is signed off, and pre-commit
against main passes.
- 2026-11-03, at c3cfcc6, from CodeRabbit's review: the loader tests
import `_onfly_decompress`, packaging's `Version` and transformers'
version at module scope, since nothing makes them optional there;
`core_model_loading` stays imported in its test, after the version
check, with its reason beside it. Tests only; pre-commit against main
passes, and `test_model_load_utils.py` and
`test_unplaced_source_keys.py` pass on CPU, torch 2.14, on transformers
5.18 and 5.5.4.
- 2026-11-03, at 25a4cd8, from Claude's review:
`to_native_backbone_config` moved to #3138, where the Kimi adapters call
it, with its tests; this PR keeps the VLM case of the either-level load
test. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-11-03, at eff418c, from cjluo-nv's review: a decompressing
load refuses compressed tensors in the safetensors files it never opens,
which the export copies as stored (ea3f31e; the test fails without
it), and the real round trips give each expert scales of its own and
store packed weights and scales across two shards in opposite expert
order (eff418c), passing on transformers 5.8.0 and 5.18.0.
Pre-commit against main passes, mypy included; `tests/unit/torch/models`
and `tests/unit/torch/utils`, run in one process, pass on CPU, torch
2.14, on transformers 5.18 and 5.5.4, and without transformers.
- 2026-11-03, at 2d8208d, from Claude's review: a decompressing load
reads the checkpoint's shard headers once, as the unplaced-key check
takes the map `check_compressed_keys` read. Pre-commit against main
passes, mypy included; `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4, and without transformers.
- 2026-11-03, at 86452a8, from kevalmorabia97's review: the tensor
map reaches `unplaced_source_keys` by keyword and only when the load
read one, so a two-argument replacement records its keys again (a new
test pins both forms; it fails with the positional call), and the tests
that write over a safetensors file they loaded clone its tensors first.
Pre-commit against main passes, mypy included;
`tests/unit/torch/export`, `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4, apart from seven
`test_export_diffusers.py` cases that fail the same way on main here,
and without transformers.
- 2026-11-03, at 8feea6b: rebased onto main 7d44246, which now
holds #2780. Three conflicts, in imports and context only: the loader's
import list keeps the names #2780 uses beside this PR's `config_levels`,
the local-checkpoint step keeps #2780's hub options ahead of this PR's
stored-tensor check, and the loader tests import `_onfly_decompress`
beside `get_spec`. The tests' `_NO_SPEC` constant is no longer added
here, as #2780 added it word for word. The rest of the own diff is
unchanged. Pre-commit against main passes, mypy included;
`tests/unit/torch/export`, `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4, apart from seven
`test_export_diffusers.py` cases that fail the same way on main here,
and `tests/unit/torch` passes without transformers.

- Earlier history and GPU results: see #2747.

**Tests folded in from #2747:**

- `tests/unit/torch/utils/test_model_load_utils.py`: the
compressed-checkpoint case loads from a small safetensors checkpoint,
which stores int32 packed weights and bf16 scales as the real ones do.
It runs the load to `from_pretrained`, whose config has no
`quantization_config` at any level, `llm_config`'s included, while the
caller's config keeps its own.
  - The same checkpoint unmarked is refused.
- One that also compresses an attention projection is refused before
`from_pretrained`.
- A compressed tensor the built model has no parameter for (an MTP
layer's expert) is refused once the weights load; an uncompressed one
gets past the check.
- The stored-name check, run read-only on the tensor names of the real
Kimi-K2.5, K2.6, K2.7-Code and K3 checkpoints (their index and shard
headers): all four pass. Reading the stored names, and with them the
compressed experts' dtypes, takes, per rank:

  | Checkpoints | Names | Names and dtypes |
  |---|---|---|
| Kimi-K2.5, K2.6, K2.7-Code, K3 | 0.5 s to 2.2 s (the most: K3's
497,220 names, read cold) | not timed |
| Synthetic, K3's 247,500 compressed tensors in 10 shards (CPU) | 0.5 s
| 1.0 s |

- On GPUs, the Kimi-K3 run (#2749) loads its MXFP4 experts through this
path.
- `tests/unit/torch/utils/test_unplaced_source_keys.py`: a real
decompressed `from_pretrained` on CPU (a tiny int4 pack-quantized
Qwen3-MoE through the real decompressor): every built expert's stored
tensors are placed through the recorded converters, and only a layer
past `num_hidden_layers` stays unplaced.
-
`tests/gpu/torch/utils/test_expert_parallel_load.py::test_compressed_experts_load_expert_parallel_each_rank_decompressing_its_own[int4|mxfp4]`
(2 GPUs): a tiny Qwen3-MoE whose experts are compressed (INT4, MXFP4,
through compressed-tensors) loads at EP2 through the decompressor; each
rank's experts must equal the dense model's exactly, every stored tensor
must be placed, and the logits must match the dense model loaded whole.
- #2747's dated testing history, its 2- and 4-GPU runs included, stays
on #2747.

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

- Is this change backward compatible?: ✅ Additive; the decompressor is
installed only by a model's `prepare` hook, and only a config a model
spec marked takes the new load path.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A.
`compressed_tensors` is imported only for compressed checkpoints, which
already need it; only CI's unit sessions install it, for the tests.
- 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 #2754.
- Did you get Claude approval on this PR?: ✅ Approved on 2026-11-03 with
#2747 folded in (at eff418c). Before the fold, this PR's round 1 was
approved on 2026-10-30.

### Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models. #2747's split
is now two PRs:
- [1/2] is #3130, merged;
- [2/2] is this PR, with #2747 folded back in.

Jira: OMNIML-6063, which #2747 shared.


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

## Summary by CodeRabbit

* **New Features**
* Load supported compressed Mixture-of-Experts checkpoints through
Transformers, with expert weights decompressed during loading and
converted to bfloat16.
* Expert-parallel loading distributes the relevant expert weights across
workers while preserving integer tensor data types.
* Checkpoint validation catches unsupported compression settings,
inconsistent stored weights, and compressed tensors outside supported
model layers.
* Requires Transformers 5.8 or newer and compressed-tensors 0.16 or
newer.
<!-- 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 4, 2026
…3138)

> [!NOTE]
> **#2748 folded in (2026-11-03):** at the user's request to fold the
series backward, this PR now also carries #2748, the Kimi-K2.5 adapter
and `prepare` on the expert-parallel route only, with its commits as
they were. #2748 is closed and keeps its review history; its ticket is
this one, OMNIML-6078.
>
> **Split out of #2748** at the reviewers' request (2026-10-30), and
joined with it again: the Kimi-VL adapter, the patch it shares with the
Kimi-K2.5 adapter, the shared deepseek_v3 plan, and the Kimi-K2.5
adapter.
>
> **Base:** `main`, which holds what this PR builds on since they merged
on 2026-11-03: #3137 (on-the-fly decompression, with #2747 folded in)
and #2780 (the model specs, with #2746 folded in), and the remote-code
helpers (#3130). The branch `shengliangx/hfep-base-11b-kimi` that joined
#2780 and #3137 for this PR is retired.

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

- `main` (#3130, #3131, #3132, #3134, #3135, #3140, #2779, #3074, #3067,
#2740, #3136, #2780, #3137, #2742, #2741 and #2743 have merged)
  - **#3138 Kimi-VL and Kimi-K2.5 adapters (this PR; #2748 folded in)**
    - #2749 [2/2] Kimi-K3 adapter

</details>

### What does this PR do?

Type of change: New feature

Kimi-VL ships its own modeling. It builds the language model's MoE from
an `nn.ModuleList` of per-expert Linears, which transformers'
expert-parallel machinery cannot shard. Its text backbone is
DeepSeek-V3, so the adapter swaps in transformers' native `deepseek_v3`
language model (fused `gate_up_proj`/`down_proj` experts, and the plan
to shard them). It keeps the bundled vision tower and projector from the
checkpoint's own code.

- **The patch Kimi-VL and Kimi-K2.5 share,** in
`modelopt/torch/models/_kimi.py`:
- **Refusals before anything changes:** transformers' own Kimi-K2.5 port
(from 5.13) of a quantized checkpoint, which the patch never reaches
(the port of an unquantized one loads as it is, below); a config with no
`text_config`; a missing checkpoint path; untrusted remote code
(`get_class_from_dynamic_module` runs the checkpoint's code without
checking `trust_remote_code`); and a quantization scheme on
`text_config` alone, which the native text config drops.
- **Import shims** for the symbols the checkpoint's modeling imports
that transformers 5 dropped (`is_torch_fx_available`, ...). They stub
only code paths the native language model never runs.
- **The swap itself:** the checkpoint's module-level
`DeepseekV3ForCausalLM` builds the native class from the native
`DeepseekV3Config` `prepare` puts on `text_config`, and the checkpoint's
own class from its own config. A `tie_weights` wrapper covers the
`recompute_mapping` newer transformers passes. A remote module that
defines no module-level `DeepseekV3ForCausalLM` stops the load instead
of passing for already patched.
- **Why the swap reads the config:** deciding the plan runs `prepare` on
a copy of the config on every rank before the plan is known, and the
patch lasts for the process. A plan that then keeps the load off expert
parallelism (replicated, or FSDP2) builds from the config as read, so it
gets the checkpoint's own language model, as with no patch. Before, the
native class was handed the checkpoint's own text config, which it
cannot take. The other effects of `prepare` are harmless off expert
parallelism: the import shims only add symbols the remote code imports,
the staging copies its sibling modules, the `tie_weights` wrapper only
drops keyword arguments for these untied checkpoints, and Kimi-K2.5's
decompressor rewrites only the configs it marked, which are the prepared
copies.
- **The swap is kept,** through `keep_patched` (#3130), on a module
transformers executes again or loads again under another name. The
reasons are in #3130's description.
- **Rank 0 only:** the adapters' notes and the shims' warnings print
there, labeled `kimi`.
- **The native backbone config:** `to_native_backbone_config`, in
`_onfly_decompress.py`, rebuilds the VLM's bundled text config as a
native transformers backbone config, carrying the decompression mark.
Both adapters' `prepare` call it; it moved here from #3137, which has no
caller of it.
- **The adapter is an `EPSpec.prepare` hook on the `kimi_vl` spec,** so
nothing outside `modelopt/torch/models` learns about Kimi.
- The spec registers only the expert-parallel section. The MoE and
export sections stay `deepseek_v3`'s, and sharing them is left to a
follow-up.
- The spec states the plan `prepare` attaches
(`EPSpec.prepared_ep_plan`, #2746): deepseek_v3's, now a shared
`BASE_MODEL_EP_PLAN`. So a run at an EP degree of 1, which skips
`prepare`, still finds the experts the checkpoint's own code builds, and
refuses to hold them whole on every rank.

<details><summary>The adapter's walkthrough (moved from
<code>kimi_vl/ep.py</code>'s module docstring)</summary>

```text
DP=EP a2a support for Kimi-VL-A3B (``kimi_vl``).

a remote-code VLM whose text backbone is a Moonlight (DeepSeek-V3-lite: MLA, ``q_lora_rank=None``, 64 routed experts, 2
shared) MoE and whose vision tower is MoonViT. The bf16 sibling of ``kimi_k25`` -- SAME shape, but NO compressed-tensors
decompressor (the checkpoint ships plain bf16 per-expert weights).

Challenge (identical to kimi_k25): the bundled ``modeling_kimi_vl.py`` builds its language model from
an INLINE ``DeepseekV3ForCausalLM`` whose ``DeepseekV3MoE`` is an ``nn.ModuleList`` of per-expert
``gate_proj``/``up_proj``/``down_proj`` Linears -- incompatible with transformers' EP machinery, which
needs the FUSED 3-D ``gate_up_proj``/``down_proj`` Parameters the transformers-native ``deepseek_v3``
modeling ships.

Solution (mirrors kimi_k25):
  1. Shim the import symbols ``modeling_kimi_vl`` needs that newer transformers dropped (e.g.
     ``is_torch_fx_available``) so the module IMPORTS -- they only guard torch.fx / legacy attn-mask
     paths that our native-LM + MoonViT forward never execute.
  2. Swap ``hf_config.text_config`` to a transformers-native ``DeepseekV3Config`` (drops the remote
     ``auto_map`` so the native class -- and its ``base_model_ep_plan`` -- is used for the LM).
  3. Apply the deepseek_v3 EP plan to that native ``text_config`` (post_init prefixes it to the VLM
     root as ``language_model.model.layers.*.mlp.experts.{gate_up_proj,down_proj}``).
  4. Monkey-patch ``modeling_kimi_vl.DeepseekV3ForCausalLM`` -> the transformers-native class, so
     ``KimiVLForConditionalGeneration.__init__`` (``self.language_model = DeepseekV3ForCausalLM(
     config.text_config)``) builds the EP-capable native LM while MoonViT + the KimiVL wrapper stay
     from the bundled code. Native deepseek_v3's per-expert WeightConverter fuses the checkpoint's
     per-expert ``.weight`` tensors into the 3-D params on load (no decompressor -- weights are bf16).

Version: no floor beyond the EP framework's 5.7; validated on transformers 5.9.0. The compat shims
stand in for the symbols the remote code imports that later releases dropped.
```

</details>

**The Kimi-K2.5 adapter** (folded in from #2748):

Kimi-K2.5 (and Kimi-K2.6 and Kimi-K2.7-Code, which share its model type)
is Kimi-VL's shape with compressed-tensors INT4 experts. Its adapter
swaps in transformers' native `deepseek_v3` language model as Kimi-VL's
does (above), through the patch they share, and decompresses the experts
as they load (#3137).

- **Install order.** The checkpoint's `config.json` keeps the
compressed-tensors config under `text_config`, and its config class also
copies it to the top level, which the expert-parallel load drops.
`prepare` installs the decompressor first of all, so a checkpoint the
decompressor refuses leaves the config and the loader untouched.
- **Which checkpoints decompress.** It installs the decompressor only
for a checkpoint whose `quantization_config` declares
compressed-tensors, as Kimi-K2.5, K2.6 and K2.7-Code all do.
  - A bf16 checkpoint of the model type loads as Kimi-VL's does.
- Any other scheme is left to the expert-parallel load's format
handling, which reads the copy of `quantization_config` the config class
keeps on the top level.
- A scheme on `text_config` alone, with no top-level copy, is refused
before anything changes.
- **transformers floor.** The spec declares the transformers 5.8 the
decompression needs.

**`prepare` now runs only on the expert-parallel route.** Before, the
plan decision ran a model spec's `prepare` on a copy of the config
before the plan was known, and the Kimi patches it made (the swapped
language-model class, the decompressor's loader hooks) stayed in the
process when the plan came out FSDP2-sharded, or whole and refused. Now:
- the decision reads the plan the spec states (`prepared_ep_plan`, on
`text_config` for both Kimi specs) and finds the experts through it in
the model the checkpoint's own code builds;
- before that it runs only `EPSpec.make_buildable`, what the
checkpoint's own code needs to import and build on the installed
transformers: the import shims, the staging of the code's two-deep
imports, and the VLM class's `tie_weights` adapted to the keyword
arguments `post_init` passes it. It changes nothing the model computes
or loads, warns rather than fails where it cannot adapt the class, and
patches no MoE or expert class, config, weight converter or
weight-loading hook;
- it asks the spec why `prepare` would refuse this checkpoint
(`EPSpec.prepare_refusal`), found without changing anything:
transformers' own Kimi-K2.5 port of a quantized checkpoint, code the
load may not run, experts the decompressor cannot take. With the EP
degree left to auto, such a checkpoint is planned without expert
parallelism, with the decision's warning;
- only an expert-parallel plan then runs `prepare`, on every rank, and
returns that config; any other plan returns the config as read.

`EPSpec.prepare`'s, `prepared_ep_plan`'s and
`resolve_distribution_plan`'s docs say so, replacing #2746's interim
contract. Kimi-VL's spec takes it too, and Kimi-K3 (#2749), on this PR,
uses it.

**transformers' own Kimi-K2.5 port.** transformers 5.13 added a
Kimi-K2.5 port, which a load without `trust_remote_code` builds. Its
language model is a native `deepseek_v3` with fused experts, and its
text config carries deepseek_v3's plan:
- **An unquantized checkpoint** read that way loads expert-parallel on
that plan without these patches, as it did before this PR: the adapter's
`prepare_refusal` and `prepare` leave its config as it is.
- **A quantized checkpoint** read that way is refused before anything
changes, naming `trust_remote_code=True` from a checkpoint whose
`auto_map` names its own `AutoConfig` as the way in: here only the
checkpoint's own code decompresses its experts.
- **Export names:** the port re-implements the vision tower and the
projector under other names. Its load-time conversions rename the vision
blocks' norms, MLPs and output projection and the projector, and split
the fused `wqkv` into q/k/v, so its export names differ from the
checkpoint's however it is distributed. Mapping them back is a question
for the export.

The spec records the 5.13 release.

**Why it patches the checkpoint's module, and again on every class
resolution:** see #3130, where `keep_patched` lives.
- The VLM class builds its language model from a name it looks up in its
module's globals.
- transformers re-executes or re-imports that module under the loaders
that resolve the class.

### Usage

Picked automatically by `apply_distributed_support` for `kimi_vl` and
`kimi_k25` configs under `torchrun`; see #2754.

### Testing

- `tests/unit/torch/models/kimi_vl/test_ep.py`, against a stand-in
remote module, covers:
- the text config rebuilt as a clean native `DeepseekV3Config` with the
EP plan;
- the remote modeling pointed at the native class, with the import shims
and the `tie_weights` wrapper;
- a load off expert parallelism, after `prepare` ran on a copy of its
config, building the checkpoint's own language model (it failed before
the fix);
- loud failures when the remote modeling did not load or has no
`DeepseekV3ForCausalLM`;
  - the refusal table, before anything is patched;
- the plan `prepare` attaches naming the same experts as the plan the
spec states.
- The shared tests are parametrized by adapter, Kimi-K2.5's cases
included.
- `tests/unit/torch/utils/test_model_load_utils.py`: a remote-code
Kimi-VL, as its own code builds it, is refused when left whole on every
rank at an EP degree of 1, with `prepare` never run.
- Review fix: the test is parametrized over the model type alone. Both
Kimi checkpoints build their experts at `.mlp.experts`.
- Locally at this head:
  - pre-commit against main passes, mypy included;
- `tests/unit/torch/models` and `test_model_load_utils.py` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-30: rebased onto main 99c3834, through the new #2746,
#2747 (which now refuses compressed tensors the model leaves unplaced),
#3130 and #3132, with no conflicts and the own diff unchanged.
Pre-commit against main passes, mypy included;
`tests/unit/torch/models`, `test_model_load_utils.py` and
`test_ep_loader.py` pass on CPU, torch 2.14, on transformers 5.18 and
5.5.4.
- 2026-10-30, review round: docstrings only. The spec's says `is_moe`
misses the native `DeepseekV3MoE` blocks `prepare` installs until the
MoE and export sections are shared; the tie shim's says a tied
checkpoint still loads, with `lm_head.weight` reported missing (checked
on transformers 5.18 and 5.5.4). Pre-commit against main passes, mypy
included; `tests/unit/torch/models`, `test_model_load_utils.py` and
`test_ep_loader.py` pass on CPU, torch 2.14, on transformers 5.18 and
5.5.4.
- 2026-10-30: rebased onto the rebuilt base: main 7168107, where
#3130 and #3132 have merged, joined with #2746 5d51cd6 and #2747
4494480. There were no conflicts in this PR and its own diff is
unchanged. Pre-commit against main passes, mypy included. On CPU, torch
2.14, with transformers 5.18 and 5.5.4, these pass:
`tests/unit/torch/models`, `test_model_load_utils.py`,
`test_ep_loader.py`, `test_unplaced_source_keys.py`.
- 2026-10-30: the swap builds the native class only from the config
`prepare` made (review item from #2746). The new test fails without the
fix. Pre-commit against main passes. `tests/unit/torch/models`,
`test_model_load_utils.py` and `test_ep_loader.py` pass on CPU, torch
2.14, on transformers 5.18 and 5.5.4.
- 2026-10-30: rebased onto the rebuilt base: #2746 ffb58cf joined
with #2747 0f0570b, whose decompressor (#3137) now reverses its
converters as the ones it rewrote, so a decompressed checkpoint's export
keeps the checkpoint's names. No conflicts in this PR; the own diff is
unchanged. Pre-commit against main passes. `tests/unit/torch/models`,
`test_model_load_utils.py`, `test_ep_loader.py` and
`test_unplaced_source_keys.py` pass on CPU, torch 2.14: 572 on
transformers 5.18, and 447 passed, 56 skipped on 5.5.4.
- 2026-10-30: rebased onto the rebuilt base: #2746 d3a058e joined
with #2747 dc0a618, which walks a config's levels through one
`moe.config_levels` helper. #2746 now raises the generic left-whole
refusal as a ValueError and keeps the RuntimeError for a transformers
below the spec's floor; the remote-Kimi refusal test expects whichever
its transformers takes. Pre-commit against main passes, mypy included.
On CPU, torch 2.14, `tests/unit/torch/models` and
`tests/unit/torch/utils` pass on transformers 5.18 and 5.5.4.
- 2026-10-30: rebased onto the rebuilt base: main 059588b, with
#2746 0eadf4c joined with #2747 23eb10d. No conflicts in this
PR, and the own diff is unchanged. Pre-commit against main passes, mypy
included. On CPU, torch 2.14, `tests/unit/torch/models` and
`tests/unit/torch/utils` pass on transformers 5.18 and 5.5.4.
- 2026-10-31: rebased onto the rebuilt base: main d464d30, with
#2746 9267a0b joined with #2747 7d78ca1. #2746 added a decision
test where this PR adds the remote-Kimi stand-in and its refusal test;
both are kept, and the own diff is otherwise unchanged. #2748, on this
PR, now runs the Kimi-VL spec's `prepare` only for an expert-parallel
plan. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-31, meenchen-nv's review:
- new 2-GPU case
`test_kimi_vl_loads_expert_parallel_and_matches_the_whole_model` writes
a tiny Kimi-VL-shaped remote checkpoint
(`tests/_test_utils/torch/kimi_vl_tiny_modeling.py`), with its experts
stored per expert, and loads it expert-parallel through the spec's
`prepare`. Each rank's native experts must equal the per-expert tensors
fused, the vision tower and projector must load as stored, nothing may
be left unplaced, and each rank's logits must match the whole model's on
one GPU. It passed on 2 GPUs and on 4 GPUs, with transformers 5.18.0, in
a run of the whole GPU file at #2749 183bf95, which contains this
PR. It loads through the spec's `prepare` and the loader directly, not
through the plan decision;
- the refusal of a scheme on `text_config` alone now names an
unquantized copy as the way in;
- the module docstring states the adapter's contract (the walkthrough is
above), `_kimi`'s module comment says why transformers is imported
inside its functions, and the tests move to
`tests/unit/torch/models/kimi_vl/test_ep.py`;
- rebased onto the rebuilt base: main d464d30, with #2746
77c4117 joined with #2747 7d78ca1. Pre-commit against main
passes, mypy included; on CPU, torch 2.14, `tests/unit/torch/models` and
`tests/unit/torch/utils` pass on transformers 5.18 and 5.5.4.
- 2026-10-31, Claude's review, at 3b5d7e2: the tiny Kimi-VL's
module-level `DeepseekV3ForCausalLM` is now the checkpoint's own,
per-expert class, so a swap that misses fails the GPU case's expert
checks; its CPU dry run passes. Pre-commit against main passes;
`tests/unit/torch/models` and `tests/unit/torch/utils` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4. At #2749 4389363, which
contains this head, the whole GPU file passed at #2749 4389363, with
transformers 5.18.0 and compressed-tensors 0.19.0: on 2 GPUs, 5 passed
and `[ep-half]` skipped, as it needs 4; on 4 GPUs, all 6 passed. The
Kimi-VL case passed on both, now with the tiny model's own per-expert
language model, so a swap that missed would have failed it.
- 2026-10-31: rebased onto the rebuilt base: main e352cac, with
#2746 d8059b3 joined with #2747 6b87b69.
`test_model_load_utils.py` now holds the moved expert-parallel loader
tests; its one import conflict kept both sides' imports, and the own
diff is otherwise unchanged. At #2749 a60c01c, which contains this
head, the whole GPU file passed, with transformers 5.18.0 and
compressed-tensors 0.19.0: on 2 GPUs, 5 passed and `[ep-half]` skipped,
as it needs 4; on 4 GPUs, all 6 passed. The Kimi-VL case passed on both;
it loads through the spec and the loader directly, not through the plan
decision. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-31, at cb90789: rebased onto the rebuilt base, whose #3137
now refuses a compressed-tensors older than 0.16; no conflicts, and the
own diff is unchanged. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-31, at 7849516: rebased onto the rebuilt base, with #2747
dc7457e on #3137 81bcef7; no conflicts, and the own diff is
unchanged. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils` pass on CPU,
torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-10-31: at #2749 76fcf09, which contains this PR at
7849516, the whole GPU file passed, with transformers 5.18.0,
compressed-tensors 0.20.1 and torch 2.15: on 2 GPUs, 5 passed and
`[ep-half]` skipped, as it needs 4; on 4 GPUs, all 6 passed. The Kimi-VL
case passed on both; it loads through the spec and the loader directly,
not through the plan decision.
- 2026-11-01, at e3d66fa: rebased onto the rebuilt base: main
cf38ec3, with #2746 997f9a6 joined with #2747 92830fc. #2746
now parametrizes `test_an_ep_capable_moe_may_be_fsdp2_sharded_instead`,
beside which this PR adds its Kimi tests; both are kept, and the own
diff is unchanged. Pre-commit against main passes, mypy included;
`test_model_load_utils.py`, `tests/unit/torch/models/kimi_vl` and
`test_ep_specs.py`, run in one process, pass on CPU, torch 2.14, on
transformers 5.18 and 5.5.4.
- 2026-11-01, at 4ff7f66: rebased onto the rebuilt base: main
51645db, with #2746 fce7da4 joined with #2747 1560551. The
base now carries #3135's check that a spec's `prepare` returns a config
with a plan where the expert-parallel load reads one; this PR's tests
pass with it. No conflicts; the own diff is unchanged. Pre-commit
against main passes, mypy included; `test_model_load_utils.py`,
`tests/unit/torch/models/kimi_vl` and `test_ep_specs.py`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-11-01: at #2749 0ea01fe, which contains this PR at
4ff7f66, the whole GPU file passed, with transformers 5.18.0 and
compressed-tensors 0.20.1: on 2 GPUs, 5 passed and `[ep-half]` skipped,
as it needs 4; on 4 GPUs, all 6 passed, in the file's order and again in
reverse, with the Kimi-K3 case first. The Kimi-VL case loads through the
spec and the loader directly, not through the plan decision.
- 2026-11-02, at 299afb6: rebased onto the rebuilt base: main
2d4e8d0, with #2746 55413f3 joined with #2747 9930028. In
that base the plan decision no longer refuses a model below the
transformers release its spec needs: it loads as a dense model does,
with a warning.
`test_a_remote_moe_whose_prepare_attaches_its_plan_left_whole_is_an_error`
therefore skips below that release and expects only the ValueError above
it; it failed on transformers 5.5.4 before. The rest of the own diff is
unchanged. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-11-02, at 7eb48c0: rebased onto the rebuilt base: main
4f08a12, with #2746 e6efb94 joined with #2747 57daa15. No
conflicts; the own diff is unchanged. Pre-commit against main passes,
mypy included; `tests/unit/torch/models` and `tests/unit/torch/utils`,
run in one process, pass on CPU, torch 2.14, on transformers 5.18 and
5.5.4.
- 2026-11-02: at #2749 7cfcd54, which contains this PR at
7eb48c0, the whole GPU file passed, with transformers 5.18.0 and
compressed-tensors 0.20.1: on 2 GPUs, 5 passed and `[ep-half]` skipped,
as it needs 4; on 4 GPUs, all 6 passed, in the file's order and again in
reverse. The Kimi-VL case loads through the spec and the loader
directly, not through the plan decision.
- 2026-11-02, at 0b489fb: rebased onto the rebuilt base: main
653ef61, with #2746 f3503ff joined with #2747 3642bd0. No
conflicts; the own diff is unchanged. Pre-commit against main passes,
mypy included; `tests/unit/torch/models` and `tests/unit/torch/utils`,
run in one process, pass on CPU, torch 2.14, on transformers 5.18 and
5.5.4.
- 2026-11-03, at d24b5f5: #2748 folded in. This PR's branch was
fast-forwarded to #2748's head, so its commits are #2748's as they were,
on the same base. Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4. On
GPU, the whole GPU file passed at #2749 7cfcd54, which contains this
code, with transformers 5.18.0 and compressed-tensors 0.20.1: on 2 GPUs,
5 passed and `[ep-half]` skipped, as it needs 4; on 4 GPUs, all 6
passed, in the file's order and again in reverse; its Kimi cases load
through the spec and the loader directly, not through the plan decision.
- 2026-11-03, at f5a0738, from Claude's review: the build step keeps
its `tie_weights` shim on a module transformers loads again
(235403a), and the plan decision asks the spec what its `prepare`
would refuse (`EPSpec.prepare_refusal`, f5a0738). So an EP degree
left to auto plans a checkpoint `prepare` refuses without expert
parallelism, with the warning naming why, rather than fail on every rank
in `prepare`. Each new test fails without its change. Pre-commit against
main passes, mypy included; `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4.
- 2026-11-03, at 74450bb: rebased onto the rebuilt base, main
a6cc167 with #2780 c9f3a2d and #3137 25a4cd8.
`to_native_backbone_config` moved in from #3137, unchanged and with its
tests (e28e7e5). From Claude's review: the build step warns rather
than fails where it cannot adapt `tie_weights` (dc0c191), and its
test fails with the raise; the build step's comment names the module key
it shares with `prepare`'s swap (74450bb). Pre-commit against main
passes, mypy included; `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4.
- 2026-11-03, at 3556f4d, from Claude's review:
`_onfly_decompress.decompression_refusal` states every check
`install_onfly_decompress` makes before it installs anything, now
including a config with nothing to decompress and a process already
decompressing a checkpoint compressed differently. Kimi-K2.5's
`prepare_refusal` asks it, and a test holds it to the install. The build
step's comment says why it runs for a decision that builds nothing
(b6bc19c). Pre-commit against main passes, mypy included;
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4.
- 2026-11-03, at c6b6042, from Claude's review:
`decompression_refusal` reports the transformers 5.8 floor itself
(a6f48d3; its parity case fails without it), and one helper decides
whether Kimi-K2.5's `prepare` decompresses a checkpoint, for `prepare`
and `prepare_refusal` alike (c6b6042). Pre-commit against main
passes, mypy included; `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4.
- 2026-11-03, at f6cdf9e: retargeted to #3137's branch and rebased
onto #3137 8feea6b (main 7d44246, which now holds #2780), off
the retired joining branch. No conflicts; the own diff is unchanged.
This PR now also runs on the #3137 commits the joining branch did not
carry: the off-index refusal, per-expert scales in the round trips, and
the tensor map read once and passed by keyword. Pre-commit against main
passes, mypy included; `tests/unit/torch/export`,
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4, apart
from seven `test_export_diffusers.py` cases that fail the same way on
main here, and `tests/unit/torch` passes without transformers.
- 2026-11-03, at 5d97c2c: rebased onto main 5870698, which now
holds #3137, keeping this PR's own commits alone; this PR now targets
main. From meenchen-nv's review, the decompressor's install and
`decompression_refusal` run one set of checks, which now includes the
raw dict (`_checked_compression`, da995de), and Kimi-K2.5's module
docstring is the adapter's contract, with both adapters' comments naming
the per-config build (caf4ea8). From Claude's review, the build step
warns on anything the checkpoint's code raises (2f461ac), and
`EPSpec.make_buildable` says that only a multi-rank decision runs it
(5d97c2c). Each behaviour change's test fails without it. Pre-commit
against main passes, mypy included; `tests/unit/torch/export`,
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4, apart
from seven `test_export_diffusers.py` cases that fail the same way on
main here, and `tests/unit/torch` passes without transformers.
- 2026-11-03, at 2c8a1ef: from meenchen-nv's review, reaffirmed,
transformers' own Kimi-K2.5 port of an unquantized checkpoint, whose
text config carries deepseek_v3's plan, is planned and loaded
expert-parallel on that plan, as before this PR, with `prepare` leaving
it as it is; the port of a quantized checkpoint is still refused
(5340e92). Its tests use the port as transformers 5.18 ships it and
fail without the change: the adapter's, and a decision that plans the
real port, built on the meta device, expert-parallel on a GPU the whole
model overfills but a rank's share fits. From CodeRabbit's review, the
unplaced-keys test imports transformers' loader modules at module scope
(2c8a1ef). Pre-commit against main passes, mypy included;
`tests/unit/torch/export`, `tests/unit/torch/models` and
`tests/unit/torch/utils`, run in one process, pass on CPU, torch 2.14,
on transformers 5.18 and 5.5.4, apart from seven
`test_export_diffusers.py` cases that fail the same way on main here,
and `tests/unit/torch` passes without transformers.
- 2026-11-03, at e2550e9: rebased onto main b002695, which now
holds #2742. The conflicts were context only: in
`test_model_load_utils.py` #2742 changed a neighbouring test's
parametrize, and in the GPU test it appended its own tests where this PR
appends the Kimi-VL one. The own diff is unchanged. Pre-commit against
main passes, mypy included; `tests/unit/torch/export`,
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4, apart
from seven `test_export_diffusers.py` cases that fail the same way on
main here, and `tests/unit/torch` passes without transformers.
- 2026-11-03, at 84b5029: from CodeRabbit's review, the Kimi-K2.5
port test says why it imports its config inside the test (f48c6eb).
From Claude's review, a CPU test pins that a load after the build step
holds the checkpoint as its own code does (84b5029): a tiny Kimi-VL
checkpoint, tied and untied, loads every stored tensor as stored, ties
its embedding exactly when the checkpoint does, and computes the same
logits as the checkpoint's own language model built with no patch; a
wrapper that skips the checkpoint's own `tie_weights` fails the tied
case. Pre-commit against main passes, mypy included; Kimi-VL's
`test_ep.py` passes on CPU, torch 2.14, on transformers 5.18 and 5.9,
and skips by its floor on 5.5.4 and without transformers.
- 2026-11-03, at 5e1bf0e: rebased onto main 3968c37, which now
holds #2741 and #2743. One conflict, an import line in
`test_model_load_utils.py`; the own diff is unchanged. Pre-commit
against main passes, mypy included; `tests/unit/torch/export`,
`tests/unit/torch/models` and `tests/unit/torch/utils`, run in one
process, pass on CPU, torch 2.14, on transformers 5.18 and 5.5.4, apart
from seven `test_export_diffusers.py` cases that fail the same way on
main here, and `tests/unit/torch` passes without transformers.
- 2026-11-03, at #2749 d1f5293, which contains this PR's dc6a858
(a docstring since 5e1bf0e), the first GPU run under #2741's
post-load refusals: on a second GPU type, with transformers 5.18.0 and
compressed-tensors 0.20,
`tests/gpu/torch/utils/test_expert_parallel_load.py` passed, its Kimi-VL
and compressed-expert cases included, and no post-load refusal fired on
a Kimi checkpoint:

  | GPUs | Passed | Skipped |
  |---|---|---|
| 2 | 12 | 4: the half-width expert-parallel shapes, which need 4 GPUs |
  | 4 | 16 | 0 |
- Earlier history and GPU results: see #2748.

**Tests folded in from #2748:**

- `tests/unit/torch/models/kimi_k25/test_ep.py`, against a stand-in
remote module, covers:
- the text config rebuilt as a clean native `DeepseekV3Config` for
compressed-tensors, bf16 and block-FP8 experts, with the decompressor
installed for compressed-tensors ones only. The bf16 and block-FP8 cases
fail with an unconditional install.
- the decompressor installed first, while the scheme on `text_config` is
still present, and a decompressor refusal leaving `text_config` and the
remote-code staging untouched;
  - transformers 5.7 refused by the spec.
- The shared adapter tests
(`tests/unit/torch/models/kimi_vl/test_ep.py`) and the remote-Kimi
refusal test in `test_model_load_utils.py` gain their Kimi-K2.5 cases.
- The plan decision with `prepare` on the expert-parallel route only:
-
`test_only_an_expert_parallel_plan_patches_the_checkpoint_s_code[fsdp2|whole|expert-parallel]`
runs the real Kimi-VL and Kimi-K2.5 `prepare` through the decision; only
an expert-parallel plan patches the checkpoint's code;
- `test_a_checkpoint_its_spec_decompresses_is_decided_expert_parallel`:
a compressed-tensors Kimi-K2.5 checkpoint left to the decision is
planned expert-parallel, and a Kimi-VL one is not;
- the build step (`make_buildable`) lets the checkpoint's own VLM build
on transformers 5.18
(`test_the_build_step_lets_the_checkpoint_s_own_vlm_build_on_this_transformers`),
installs nothing when there is nothing to build, and runs at an EP
degree of 1 too
(`test_an_ep_degree_of_1_builds_the_checkpoint_s_own_vlm_to_decide`);
- `test_ep_specs.py`'s spec-field checks: a spec with a `prepare` states
its plan, and a build step, decompressed formats or a prepared plan each
come with a `prepare`.
- The decision's cost, measured on the real Kimi-K2.5 code and config
(61 layers, 384 routed experts) on the meta device, transformers 5.18,
one process; only rank 0 builds:

| The decision builds | Build time | Modules | Parameters | Peak host
RSS |
  |---|---|---|---|---|
| the prepared config: native DeepSeek-V3, fused experts (before) | 0.59
s | 1,455 | 1,250 | 0.62 GiB |
| the checkpoint's own code: per-expert experts (after) | 31.6 s |
116,655 | 70,310 | 5.16 GiB |

- Real-model runs, as #2748 recorded them (with the module-reload fix,
through the decompressor): Kimi-K2.7-Code, expert-parallel over 32 GPUs
(8 nodes, EP32), transformers 5.13.0, compressed-tensors 0.17.1, recipe
`nvfp4_experts_only_mse-kv_fp8_cast`, 4096 calibration samples of 4096
tokens, batch 1. Load, calibration and export completed:

  | Runs | Count | Result |
  |---|---|---|
| without the reload fix, first | 1 | failed before loading weights:
some ranks built the checkpoint's own `DeepseekV3ForCausalLM` on the
native config |
| without the reload fix, later | 2 | load, calibration and export
completed |
| with the reload fix | 2 | load, calibration and export completed,
through the decompressor |

- #2748's dated testing history stays on #2748.

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

- Is this change backward compatible?: ✅ Additive. Registering the
Kimi-VL and Kimi-K2.5 specs reaches beyond the expert-parallel load only
in the plan decision of a multi-rank run: every rank runs the spec's
build step (`make_buildable`: the import shims, the staging of the
code's imports, and `tie_weights` adapted to the keyword arguments
`post_init` passes), which changes nothing the model computes or loads.
`prepare` runs only once the plan is decided expert-parallel. A run that
would leave an expert-parallel-capable MoE whole on every rank, with
nothing asking for that, is refused, as other expert-parallel MoEs are.
A single-process load is unchanged.
- 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 #2754.
- Did you get Claude approval on this PR?: ❌ Not yet for the folded
change; requested on 2026-11-03.

### Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models: the Kimi-VL and
Kimi-K2.5 adapters, which #2748's split had made [1/2] (this PR) and
[2/2] (#2748), are one PR again.

Jira: OMNIML-6078, which #2748 shared.

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

## Summary by CodeRabbit

* **New Features**
* Added expert-parallel loading support for Kimi-VL and Kimi-K2.5,
including compatible K2.6 and K2.7-Code checkpoints.
* Supported Kimi-K2.5 compressed checkpoints can now be decompressed
during expert-parallel loading.
* Kimi-VL vision components are retained while its language model uses
native DeepSeek-V3 support.
* **Improvements**
* Checkpoint compatibility is checked before expert-parallel
preparation. Automatic selection can fall back to standard loading with
a warning; explicitly requested expert parallelism reports why it cannot
proceed.
  * Preparation runs only when expert-parallel loading is selected.
<!-- 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 4, 2026
… it, and export an expert-parallel model through it (#2752)

> [!NOTE]
> **Folded 2026-11-03:** #2753 (expert-parallel export, OMNIML-6084) is
folded into this PR at the user's request: its 38 commits sit unchanged
on top of this PR's own, and #2753 is closed. See #2753 for its review
history. By the review guideline's count (added source lines, without
tests, docs, comments or blank lines) the combined diff is 448
core-logic lines: 228 from this PR and 240 from #2753, less the lines
#2753 replaces.
>
> **Re-cut again on 2026-10-29, so more of the series merges in
parallel:** this PR's base branch was rebuilt from the current #2751 and
#2750 (both now on main; #3099, [1/2] of #2750's split, merged) and
#2740 (on #3074). #2779 left it: this PR needed it only for the plan
that hf_ptq's `--use_fsdp2` load records, and that recording now lands
here. The series first became a tree on 2026-10-27, from main
1521053bfb0 (this PR was [16/21]); it was rebased onto main 7c3c8680284
later that day, after #2739 merged, and onto main f03651e815c that
night.
>
> **Base:** `main`. The PRs this one built on (#2750, #2751, #3074 and
#2740) have all merged, the last of them #2740 on 2026-11-02. The diff
below is this PR's alone, #2753's commits included (448 core-logic
lines; 852 added lines outside tests and docs).
>
> **Re-cut:** this PR's diff gained what the PRs below it handed over,
listed in the last Testing line: `_split_local_fused_module`, the
per-rank expert split this writer calls, with its two tests (from
#2750's split); hf_ptq's `--use_fsdp2` plan recording, with its README
notes, changelog entry and test (from #2740); no out-of-memory retry in
the calibration loop for a model over several ranks (asked for in
#2740's review); and the writer's module-scope imports from #2751.
Review fixes since the first re-cut are listed at the end of Testing.

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

- `main` (#2745, #2739, #2736, #2737, #3100, #3101, #3099, #2750, #3122,
#2751, #3074, #3067, #2779 and #2740 have merged)
  - #2741 expert-parallel loader
    - #2742 dense sharding
      - #2743 block-FP8 dequantization
    - #2780 expert-parallel load routing
      - #2746 expert parallelism in the model specs
        - #2748 Kimi-K2.5 and Kimi-VL adapters (on #2746 and #2747)
        - #2749 Kimi-K3 adapter (on #2746 and #2747)
- #2754 expert-parallel PTQ from hf_ptq.py (on #2746, #2742 and #2752)
    - #2747 on-the-fly decompression
- **#2752 no-gather export and expert-parallel export (this PR; #2753
folded in)**

</details>

### What does this PR do?

Type of change: New feature, with a bug fix for models built from a
config

`distributed_save_hf_checkpoint` writes an already-processed sharded
model as HF safetensors with no rank-0 gather:
- fused experts are split shard-locally (#2750);
- every other tensor moves whole to one owner rank, which runs the
reverse conversion (#2751);
- each rank writes its own shards.

No rank ever holds the whole model. On top of its own shard, which the
model keeps, a rank holds what it writes; only an inference tensor is
copied up front, so an export under `no_grad`, as hf_ptq runs it, copies
nothing. A model sharded by FSDP2 alone opts in with
`MODELOPT_FSDP2_EXPORT=nogather`; the expert-parallel export routes to
it unconditionally in #2753.

Two gloo ranks exporting a 223 MiB bf16 Llama, the writer's peak RSS
above each rank's 112 MiB shard:

| Writer | Peak RSS above the shard, per rank |
|---|---|
| copying every DTensor up front (previous revision) | 278 / 246 MiB |
| copying only inference tensors | 224 / 217 MiB |
| copying only inference tensors, with #2751's send-copy fix (this
revision) | 162 / 166 MiB |

**Why this doesn't build on `torch.distributed.checkpoint`'s
`HuggingFaceStorageWriter`:** that writer saves each state-dict key as
it is, and the checkpoint needs other keys, made from whole tensors:
- **Per-expert keys.** The model holds a layer's experts fused, as
`mlp.experts.gate_up_proj` of shape [experts, 2 × intermediate, hidden],
while an HF checkpoint names each expert's projections
(`mlp.experts.3.gate_proj.weight`). DCP can map a key to a file
(`fqn_to_index_mapping`) but cannot write one key as many, so the split
comes first. It is shard-local (#2750) and leaves each rank's experts as
plain tensors, whole on that rank, which leaves a sharded writer nothing
to do for them.
- **The reverse conversion needs whole tensors.** transformers'
conversion ops take whole tensors and know no placement, and some
reverse merges concatenate along dim 0, the dim FSDP2 shards. hrm_text,
for one, loads `attn.gqkv_proj.weight` with `Chunk(dim=0)` into gate, q,
k and v, so the export concatenates the four back. Concatenating each
rank's row shards gives [gate_r; q_r; k_r; v_r], which is no row range
of the whole. So each tensor has to be whole somewhere before the
conversion runs: this writer makes it whole on one owner rank, rather
than everything on rank 0.
- **Files a loader reads.** With `save_distributed=True` and no
consolidation, a DTensor's chunks land in several files under one key,
placed by offsets in DCP's own metadata, and no
`model.safetensors.index.json` is written: only DCP's reader reassembles
them, not `from_pretrained`, vLLM or TensorRT-LLM. With
`enable_consolidation=True`, the writer's `finish` runs
`consolidate_safetensors_files` on the coordinator rank, which reads
every sharded file back and writes the checkpoint again: every byte is
written twice, the second time by rank 0 alone. With
`save_distributed=False`, rank 0 saves a full state dict, the gather
this path avoids.

Once every tensor is whole on exactly one rank, each rank writes its own
set once with `safetensors.save_file`, and rank 0 unions the index.

`export_hf_checkpoint` on this path:
- packs quantized weights with `keep_fused_experts`;
- writes `config.json` and a sanitized `generation_config.json` on rank
0 through `save_non_weight_artifacts`, as the FSDP2 streaming writer
does, then `hf_quant_config.json`. `hf_quant_config.json` names modules
as the weights do: when any rank cannot reverse the conversion mapping,
every rank's weights keep their in-memory names, and the quant config
keeps them too (`distributed_save_hf_checkpoint` returns whether the
names were reverted);
- copies the source's non-model files (tokenizer, processor, remote
code, chat templates), which the writer never sees, also through
`save_non_weight_artifacts`.

With `save_modelopt_state`, it saves the ModelOpt state from rank 0, as
the FSDP2 streaming export does.

**The export reads how the model is sharded from its distribution plan**
(#2736), not from an FSDP2 module in it: the FSDP2 routes, streaming or
no-gather, and which rank reads the carried-over weights. hf_ptq's
`--use_fsdp2` load records its plan, `DistributionPlan(world_size,
dense="fsdp")`, right after the load. A model sharded by hand, with
`fsdp2_wrap` say, records it with `set_distribution_plan`; without it
the export raises rather than treat it as whole. Refusing a model with
no plan, rather than inferring `DistributionPlan(world_size,
dense="fsdp")` from its FSDP2 modules, is deliberate: the export reads
the plan through #2736's `distribution_plan`, which raises for such a
model, because an FSDP2 module does not say how the model is
distributed. A guessed plan would leave out the expert-parallel degree,
which #2753 numbers each rank's experts by. A diffusers pipeline is not
a module and is exported without a plan.

**The calibration loop no longer retries an out-of-memory batch in
halves for a model whose recorded plan spans several ranks**, such as
hf_ptq's `--use_fsdp2` model now that it records one: its forward can
hold collectives, so a rank that retried would run more forwards than
its peers, which would wait in them. The error is raised instead, and
the README tells `--use_fsdp2` users to set `--batch_size`. Recording
the plan also switches on #2740's refusal of calibration that keeps
statistics per rank and its collective batch sizing for `--use_fsdp2` on
several GPUs, so their README notes and backward-breaking changelog
entry come here too.

The KV-cache format goes through `_get_kv_cache_postprocess_config`, so
a mixed-precision KV cache exports as on the other paths, and which
writer runs is rank 0's `MODELOPT_FSDP2_EXPORT`.

#### Expert-parallel export (folded in from #2753)

An expert-parallel model could not be exported at all. transformers
pre-slices each expert parameter across the EP group, so
`save_pretrained` sees a tensor-parallel model and refuses.
`export_hf_checkpoint` now sends an expert-parallel model to the
no-gather writer above unconditionally, since it has no fallback. It
reads that the model is expert-parallel from the model's distribution
plan (#2736), as it reads FSDP2 sharding (above). What expert
parallelism changes in and around the writer:

- **Global expert numbers.** Under expert parallelism a fused expert
tensor is already sliced to this rank's group, so its DTensor offset is
group-relative, and every group would have written experts 0..n-1 over
each other. For a model whose plan is expert-parallel, the global index
now comes from the routed experts' `ParallelState` (#2741), the same
state calibration reads. If the experts carry none, the writer raises.
- **Per-expert quantizers.** These are indexed locally under expert
parallelism and globally under FSDP2. #2750's fold tells the two apart
by the DTensor's global extent, which this export relies on. (Without
it, every rank exporting GLM-5.3-Flash at EP16 raised an IndexError.)
- **The rank.** Every process used to take the rank-0 branch and rewrite
`config.json`, and the closing barrier was skipped, so the job hung.
- **Carried weights.** Rank 0 alone writes the weights the loader could
not place. Every rank used to believe it was the single sender, and the
point-to-point protocol deadlocked (GLM-5.3-Flash at EP16: 15 of 16
ranks parked in a barrier).
- **config.json.**
- It matches a single-GPU export: no `distributed_config`, and the
source's own `base_model_ep_plan` rather than the `torch_a2a` one the
loader swapped in, which only exists while ModelOpt is imported.
  - The run's values come back afterwards.
  - Nested configs, where a VLM keeps its plan, are handled too.
- **Checkpoint names.** Experts get the checkpoint's names back through
converters that loading rewrote. A dequantizing or decompressing load
lists each sibling tensor (`weight_scale_inv`, `weight_packed`, ...) as
a source, which used to repeat the expert leaf and abort the whole
reverse conversion. On Kimi-K3 that left all 989,184 expert tensors
under names its own modeling code does not use.
- A dequantizing FP8 load also registers a converter that only decodes
each weight in place. Its reverse re-encodes the weight (`Fp8Quantize`),
which the reverse could not do, so it gave up on the whole mapping, and
MiniMax-M2.7 exported `mlp.experts.N.gate_proj` instead of
`block_sparse_moe.experts.N.w1`. That converter renames nothing, so it
now contributes no reverse rule. This was also main's behavior for
single-process FP8 sources.
- **Plans it cannot write.** With fewer expert-parallel ranks than the
world and the dense part FSDP2-sharded, the dense part is sharded within
each expert-parallel group and replicated across them, which the writer
cannot assemble. The export refuses such a plan before it folds anything
(#2754 refuses it before loading).
- **Quantization the ranks agree on.** Each rank holds only its own
experts' quantizers, so before anything is folded every rank's
per-projection state is gathered, and every rank refuses a fused-experts
projection whose experts are not all quantized or all unquantized across
the expert-parallel group.
- **Processing that fails on one rank.** Each rank folds only its own
shard, so processing can fail on one rank alone. It now ends in a
consensus, so every rank raises before any of them writes.
- **Error reporting.** A rank whose export raises prints its traceback
before the export's closing step, so the job fails with the error
instead of hanging silently.
- **Exports that fail together.** A sharded export (FSDP2 or
expert-parallel) ended on a bare barrier. The ranks whose writes
succeeded returned normally while another rank's export raised, and the
run carried on as if the checkpoint were whole. The export now ends by
gathering every rank's outcome (`all_reduce`, #2736), so every rank
raises with the failing rank's error.

### Usage

```bash
MODELOPT_FSDP2_EXPORT=nogather torchrun --nproc_per_node 8 examples/hf_ptq/hf_ptq.py --use_fsdp2 ...
```

An expert-parallel model takes this writer with no opt-in:
`export_hf_checkpoint(model, export_dir=...)` under torchrun, on a model
loaded expert-parallel (`load_and_prepare_ep`, #2741).

### Testing

- `tests/unit/torch/export/test_distributed_writer.py` adds end-to-end
cases on CPU under gloo:
  - **One rank:**
- an FSDP2 Mixtral written byte-identical to `save_pretrained`, tied and
untied;
    - inside inference mode;
    - `extra_state_dict` kept under its own names;
- in each of these, every dense DTensor reaching the transfer as the
model's own shard, not a copy (it fails with the unconditional copy,
mutation-checked);
- `export_hf_checkpoint` on the no-gather path, root-wrapped and
layers-only: byte-identical to the single-process export, plus config
files and the copied source sidecar, for FP8 and NVFP4;
- a Qwen2-MoE's experts exported quantized, for FP8 and NVFP4, their
inputs too, so the experts' input scales and their all-reduce run on
CPU. Its shared expert is packed after the experts, so experts folded
outside FSDP2's weight window (#2750) would be written unquantized; this
replaces #2750's stand-in test of that window;
- a quantized Mixtral whose reverse conversion fails, keeping its
in-memory names in `exclude_modules` as in the weights;
    - `save_modelopt_state` saved from rank 0.
  - **Two ranks:**
- an uneven Mixtral matching its source, with one continuous file
numbering;
    - an FP8 dense model matching the single-process export;
- extras handed to rank 0 alone, as the export entry hands them, written
exactly once, and an extra colliding with a model weight raising on both
ranks;
    - each tensor with exactly one owner, both ranks owning some;
- divergent dense keys, sharding and duplicate names across ranks
raising instead of hanging;
- ranks that calibrated the experts' shared input quantizer differently,
every expert written with the largest scale.
- The Mixtral-names and two-rank input-scale cases each fail without
their fix (mutation-checked).
- `tests/unit/torch/export/test_unified_export_hf.py`: a model built
from a config, which main's #2823 gives no source checkpoint, copies
nothing from the working directory at export.
- The plan reads: reading none, taking no FSDP2 route, or dropping the
pipeline guard each fails a test, the last main's
`test_export_diffusers_pipeline_config` on a real tiny pipeline. Only
rank 0 reading the carried weights is not unit-tested, since it needs
two FSDP2 ranks; the GPU carry-over tests cover it.
- Mutation-checked, across this PR and #2750 and #2751: 76 of 77
single-point mutants killed. The survivor is a copy of plain inference
tensors that nothing on CPU can reject.
- The GPU results here were measured on earlier revisions of this
branch; this revision's GPU tests run in CI only.
- New `tests/gpu/torch/export/test_distributed_hf_export.py`: PTQs a
tiny Qwen3 (dense, with tied embeddings, and MoE) under FSDP2 with FP8
and NVFP4, opting each export into the writer, and checks the checkpoint
against the safetensors headers: every routed expert exported quantized,
and the tied head written once. Its earlier version passed on a 4-GPU
node, 8 tests, including checks of extras, ties, refusals and
unquantized layers that now run on CPU above, where every PR runs them.
On 1 GPU, all skip. Its docstring no longer describes a DCP staging step
this writer never had, and an assertion on a `sharded/` staging
directory, which could not fail, is dropped; not re-run on GPU after
that change.
- The end-to-end cases fold into the hub-checkpoint test and the
two-rank job, and tests a remaining test covers are dropped, this PR's
`test_export_diffusers.py` test included. Each drop is checked by
mutation.
- The single-process comparison has an FP8 and NVFP4 KV-cache case, and
the two-rank export sets the writer knob on rank 0 only.
- 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: the ModelOpt state is saved from rank 0, as
the streaming export does; the ranks agree on the expert input-scale
keys before reducing them; the writer is told the model's merge groups.
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).
- Review suggestions, 2026-10-27 evening: `MODELOPT_FSDP2_EXPORT` takes
`nogather` or `streaming` (the default) and refuses any other value on
every rank.
- Review suggestion, 2026-10-27 night: the no-gather arm discards the
tied-weight map, with a comment that the writer builds its own.
- Re-cut on 2026-10-29 (see the note at the top), onto the base rebuilt
from #2751 bb9dd1f8476, #2750 830d7044438 and #2740 54f0c1fd8e9. The
rebase's conflicts were all in tests and the changelog: imports, the
changelog's 0.49.0 sections, #2751's revised test helper (its signature
kept; the two `_revert_whole_sd` tests this PR drops still go, since the
end-to-end tests fail when that code breaks), and #2750's stand-in
window test, dropped with the imports only it used (its window test now
lives in #3099's `test_sharded_weight_packing.py`). Added on top:
`_split_local_fused_module` with
`test_split_local_numbers_experts_globally` and each rank's own split
checked in #2750's two-rank fold test; hf_ptq's plan recording with
`test_the_fsdp2_load_records_the_plan_it_loaded_by`; the no-retry with a
test that fails without it (both a loop that always splits and one that
splits for a one-rank plan fail it); and the module-scope imports, with
the test that fails the reverse conversion now patching the name the
writer calls (it failed on the new base, and passes). Pre-commit, mypy
included, passes against the base and against main 6c475d716cf. On CPU
(torch 2.14, transformers 5.18), the export unit tests,
`test_dataset_utils.py`, `test_distributed.py` and hf_ptq's argument
tests pass (782; `test_export_diffusers.py` left out: its 7 failures
here are main's too). At #2753's head, which carries this PR, they also
pass on transformers 5.5.4. A no-gather export on one gloo rank writes
INT4-AWQ, MXFP4, NVFP4 and FP8 Llama and Qwen2-MoE checkpoints
byte-identical to the single-process export, so #3099's refusal to pack
a DTensor shard in a 4-bit packer is not reached: the fold packs each
rank's experts as plain tensors, and the dense weights are packed inside
FSDP2 weight windows. GPU tests not re-run; CI runs them.
- Review fix, 2026-10-29: the GPU carry-over export tests and the GPU
loader tests record the plan of the model they shard by hand, as the
export now requires. Their lines are the ones #2779 adds to the same
tests, and that PR is no longer below this one. The changelog entry
names `parallel_load_and_prepare_fsdp2` next to `fsdp2_wrap` as
recording no plan, and the comment above the held FSDP2 weight windows
says the no-gather export sets `keep_fused_experts`. Pre-commit, mypy
included, passes against the base and against main. The two GPU files
collect on CPU. On one gloo rank, the default FSDP2 export of a model
with a recorded plan is byte-identical to the single-process export (FP8
and NVFP4, Llama and Qwen2-MoE). The GPU suites were not run.
- Review fixes, 2026-10-29 night (meenchen's review): the writer drops
the expert-parallel scaffolding it never set (`ep_rank`/`dp_idx` held at
0, the expert count); #2753 adds it back with what sets it. The writer
imports its helpers at module scope, and the export's import of the
writer stays local, with a comment naming the circular import a
module-scope one causes. Rank 0 writes the non-weight files through
`save_non_weight_artifacts`, as the FSDP2 streaming writer does:
`_write_base_config` and the special case in the final copy are gone.
Quantized Llama and Qwen2-MoE no-gather exports write byte-identical
config, generation config, quant config, index and copied files before
and after. On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (829) and 5.5.4 (794 passed, 35 skipped);
without transformers, the unit tests pass or skip (438 passed, 93
skipped) and `import modelopt.torch.export` does not import the writer.
Pre-commit, mypy included, passes against the base and against main. GPU
tests not run; CI runs them.
- Review suggestion, 2026-10-30: `_split_local_fused_module` numbers
experts by the FSDP2 offset alone. Its expert-parallel parameters and
their numbering test move to #2753, which sets them. On CPU, the export
unit tests, `test_dataset_utils.py`, `test_distributed.py`,
`test_moe_a2a.py` and hf_ptq's argument tests pass on transformers 5.18
(824) and 5.5.4 (789 passed, 35 skipped), and without transformers (438
passed, 93 skipped). Pre-commit, mypy included, passes against the base
and against main.
- Rebased onto main 99c3834f62c, 2026-10-30, after #2750 merged: the
base branch now merges #2751 and #2740 only. This PR's own diff is
unchanged except for one docstring, where
`split_fused_experts_state_dict`'s note on memory and expert numbering
now merges #2750's final wording with this PR's. #2750's final check
that the first projection and `down_proj` hold the same number of
experts holds for `_split_local_fused_module`, which passes each rank's
local shards of both, and FSDP2's dim-0 sharding gives them equal
counts; the two-rank fold test, three experts over two ranks included,
passes. On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (825) and 5.5.4 (790 passed, 35 skipped), and
without transformers the unit tests pass or skip (438 passed, 93
skipped). Pre-commit, mypy included, passes against main. GPU tests not
run; CI runs them.
- Rebased onto main 62a5c48f374, 2026-10-30, after #2751 merged (and
#3122, below #2740): the base branch now merges main and #2740. This
PR's own diff is unchanged. Its one conflict was changelog context:
main's new Qwen3.8 entry now comes before this PR's no-gather entry, and
both stay. Pre-commit, mypy included, passes against main. On CPU, the
export unit tests, `test_dataset_utils.py`, `test_distributed.py`,
`test_moe_a2a.py` and hf_ptq's argument tests pass on transformers 5.18
(827) and 5.5.4 (792 passed, 35 skipped), and without transformers the
unit tests pass or skip (438 passed, 95 skipped). GPU tests not run; CI
runs them.
- Rebased onto main 059588b89a5, 2026-10-30 (after #3104, #3128, #3134
and #3149 merged), on #2740's rebased head: the base branch again merges
main and #2740. This PR's own diff is unchanged, plus one commit: #3128
now refuses AWQ with `--use_fsdp2` on more than one rank before the
model loads, so this PR's README note lists only the other calibrations
it refuses when quantization starts (SVDQuant, local Hessian, imatrix)
and points to #3128's AWQ note. The restack's conflicts were in the
changelog and the README only, where main's new entry and notes sit next
to this PR's; all are kept. Pre-commit, mypy included, passes against
main. On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (828) and 5.5.4 (793 passed, 35 skipped), and
without transformers the unit tests pass or skip (438 passed, 95
skipped). GPU tests not run; CI defers them while this PR targets
another PR's branch.
- Rebased onto main d464d30b120, 2026-10-30, after #3074 merged (and
#3121), on #2740's head now on main: without conflicts, and this PR's
own diff is unchanged. Pre-commit, mypy included, passes against main.
On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (843) and 5.5.4 (808 passed, 35 skipped), and
without transformers the unit tests pass or skip (453 passed, 95
skipped). GPU tests not run; CI defers them while this PR targets
another PR's branch.
- Review text fixes, 2026-10-31 (meenchen's review bot), comments and a
docstring only: the two-rank test's comment and docstring, and the
writer's comment on the tensors the model does not own, say rank 0 alone
is handed them, as the list above now does; the export's comment on
packing no longer names a consolidation step or main's history; and the
writer's step (2) comment no longer names an expert-parallel layout.
Pre-commit, mypy included, passes against main, and
`test_distributed_writer.py` and `test_unified_export_hf.py` pass (123).
**The GPU suites are pending:**
`tests/gpu/torch/export/test_distributed_hf_export.py`,
`tests/gpu/torch/export/test_export_carry_over.py` and
`tests/gpu/torch/utils/test_model_load_utils.py` have not run at this
head; CI runs them once this PR targets main.
- Rebased onto main e352caca3c3, 2026-10-31 (after #3002, #3044 and
#3156 merged), on #2740's rebased head, without conflicts; this PR's own
diff is unchanged. Pre-commit, mypy included, passes against main. On
CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (843) and 5.5.4 (808 passed, 35 skipped), and
without transformers the unit tests pass or skip (453 passed, 95
skipped). The GPU suites are still pending: CI runs them once this PR
targets main.
- Rebased onto main cf38ec30ca4, 2026-11-01 (after #2784 and #3163
merged), on #2740's rebased head, without conflicts; this PR's own diff
is unchanged. Pre-commit, mypy included, passes against main. On CPU,
the export unit tests, `test_dataset_utils.py`, `test_distributed.py`,
`test_moe_a2a.py` and hf_ptq's argument tests pass on transformers 5.18
(843) and 5.5.4 (808 passed, 35 skipped), and without transformers the
unit tests pass or skip (453 passed, 95 skipped). The GPU suites are
still pending: CI runs them once this PR targets main.
- Rebased onto main 51645db66dc, 2026-11-01 (after #3140 merged), on
#2740's rebased head, without conflicts; this PR's own diff is
unchanged. Pre-commit, mypy included, passes against main. On CPU, the
export unit tests, `test_dataset_utils.py`, `test_distributed.py`,
`test_moe_a2a.py` and hf_ptq's argument tests pass on transformers 5.18
(840) and 5.5.4 (805 passed, 35 skipped), and without transformers the
unit tests pass or skip (450 passed, 95 skipped). The GPU suites are
still pending: CI runs them once this PR targets main.
- Rebased onto main 2d4e8d019e7, 2026-11-02 (after #2779 and #3135
merged), on #2740's rebased head. #2779 adds the same plan-recording
lines to the GPU carry-over export tests and the GPU loader tests that
this PR added, so this PR no longer touches those two files; the one
conflict, in the loader tests' imports, takes main's, which import
everything this PR did. The rest of this PR's own diff is unchanged.
Pre-commit, mypy included, passes against main. On CPU, the export unit
tests, `test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py`
and hf_ptq's argument tests pass on transformers 5.18 (840) and 5.5.4
(805 passed, 35 skipped), and without transformers the unit tests pass
or skip (450 passed, 95 skipped). The GPU suites are still pending: CI
runs them once this PR targets main.
- Rebased onto main 653ef615850, 2026-11-02, after #2740 merged, and now
targeting main: the base branch that joined main and #2740 is retired.
No conflicts; this PR's own diff is unchanged. #2740's last commits
declare each calibrate mode's distributed support, and the same built-in
modes are refused as before, so the README and changelog notes on
refused calibrations still hold. Pre-commit, mypy included, passes
against main. On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (840) and 5.5.4 (805 passed, 35 skipped), and
without transformers the unit tests pass or skip (450 passed, 95
skipped). The GPU suites now run in CI, since this PR targets main.
- Review text fix, 2026-11-02 (meenchen's review bot), text only: the
changelog entry and the README note now say what the opt-in changes
against the default FSDP2 export, which already has each rank write its
own share. Each tensor moves once, to the one rank that writes it,
instead of each FSDP2 unit being all-gathered on every rank; fused MoE
experts stay sharded; and a conversion mapping that splits or merges
tensors, which the default export refuses, is reversed. Pre-commit, mypy
included, passes against main.
- GPU suites, 2026-11-02, at `792f22b1276`: CI's GPU lane for a PR runs
on 1 GPU, so the tests that need two or more GPUs skip there; they were
run separately on 2 and 4 GPUs at the same head (transformers 5.18.0).
Every run passed, and on main at `653ef615850` the two files this PR no
longer changes give the same results on 2 GPUs, test by test.

  | File | CI, 1 GPU | 2 GPUs | 4 GPUs |
  |---|---|---|---|
| `tests/gpu/torch/export/test_distributed_hf_export.py` | 4 skipped
(need 2 GPUs) | 4 passed | 4 passed |
| `tests/gpu/torch/export/test_export_carry_over.py` | 2 skipped (need 2
GPUs) | 2 passed | 2 passed |
| `tests/gpu/torch/utils/test_model_load_utils.py` | 4 passed, 2 skipped
(need 2 GPUs) | 6 passed | 6 passed |
- **From #2753, folded in on 2026-11-03** (its testing record as it
stood there):
  - `tests/unit/torch/export/test_unified_export_hf.py`:
- config.json restoring the source's EP plan and dropping the run's
DistributedConfig, at the root and nested;
    - rank-0-only carried weights;
- the consensus that ends the processing half the writer path runs: a
2-process job where only one rank's processing fails raises on both
before the writer, rank 0's error naming rank 1;
- the plan the writer cannot write, refused with the model left
unfolded;
- two ranks whose experts disagree on quantization, or each with a mixed
projection, refused on both before processing.
- `tests/unit/torch/export/test_quant_aware_conversion.py`: expert and
dense reverse conversions through FP8-dequantizing and
compressed-tensors converters.
- `tests/unit/torch/utils/test_distributed.py`: the expert-parallel
coordinate the writer reads.
- `tests/unit/torch/export/test_distributed_writer.py`: an
expert-parallel plan whose experts carry no expert-parallel group is
refused.
- Mutation-checked: reading either flag from somewhere other than the
plan, dropping the pipeline guard, or skipping the writer's EP
coordinate each fails a test.
- `tests/unit/torch/export/test_unified_export_hf.py`, the export's
closing step, through `export_hf_checkpoint` itself on two gloo ranks:
rank 0's write of `config.json` fails after the shards are written, and
both ranks raise with its error. Ending on a bare barrier, skipping the
closing step, or the failing rank skipping it each fails the test, the
last at the group's 10 s timeout rather than by hanging.
- The lookup tests merge into the tests that cover them, and tests the
no-gather export and refusal tests already cover are dropped. Each drop
is checked by mutation.
- 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.
- The GPU results here were measured on earlier revisions of this
branch; this revision's GPU tests run in CI only.
  - On GPUs, expert-parallel exports through this path:
- Qwen3-30B-A3B at EP16 over 4 nodes, NVFP4 and FP8: the replicated and
FSDP-sharded dense layouts export byte-identical weights and scales.
- Qwen3-VL-30B and MiniMax-M3 (NVFP4): the key sets match, and every
routed-expert weight is packed.
- MiniMax-M2.7 (block-FP8 source) at EP16 over 4 nodes, NVFP4: routed
experts export as `block_sparse_moe.experts.N.w1/w2/w3`. Every exported
weight name exists in the source checkpoint's index (48,239 of 48,239,
scales aside), and config.json carries no run attributes. vLLM (0.30 dev
build, TP4) serves the export. On gsm8k (5-shot, 100 samples) it scores
0.94 / 0.93 (flexible / strict) against the FP8 source's 0.93 / 0.95,
within one standard error.

    Details in #2754.
- 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 projection without weight quantizers is
skipped when the ranks agree; the no-gather fold no longer reads the
plan again; the codec ops are cached; an expert-parallel export refuses
`save_modelopt_state`, since each rank holds only its own experts'
ModelOpt state. 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).
- Review suggestions, 2026-10-27 evening: the FP8 integration and
`core_model_loading` are imported apart, so a transformers without
triton keeps the identity op that 5.5/5.6 reverse FP8 dequantization
into.
- Review fix, 2026-10-27 night: an export's failure consensus carries
any `BaseException`, so a `SystemExit` or `KeyboardInterrupt` on one
rank fails every rank. The test's `SystemExit` case fails without the
change.
- Re-cut on 2026-10-29 (see the note at the top), onto #2752's new head:
conflicts only in test imports and in `test_distributed_run.py`, which
main deleted, so the `expert_parallel_state` test moved to
`test_distributed.py`. The writer's refusal of expert-parallel experts
without a `ParallelState` says to load the model with an expert-parallel
loader instead of naming one. Pre-commit, mypy included, passes against
#2752 and against main 6c475d716cf. On CPU (torch 2.14, transformers
5.18), the export unit tests, `test_dataset_utils.py`,
`test_distributed.py` and hf_ptq's argument tests pass (801;
`test_export_diffusers.py` left out: its 7 failures here are main's
too). They also pass on transformers 5.5.4. GPU tests not re-run; CI
runs them.
- Rebased on 2026-10-29 night onto #2752's review fixes. The
expert-parallel scaffolding #2752 dropped comes in with the commit that
sets it. The expert count now comes from
`modelopt.torch.utils.moe._num_experts_from_config` (it also reads
`num_routed_experts` and `llm_config`), and
`distribution_plan`/`expert_parallel_state` are imported at module
scope. `_write_base_config` is now a wrapper: it calls #2752's
`save_non_weight_artifacts` inside the swap that keeps the run's
DistributedConfig and torch_a2a plan out of config.json. The final copy
of the source's files is skipped for the no-gather writer, which has
made it already. The tests are unchanged, apart from a stub the config
test no longer needs. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (848) and 5.5.4 (813
passed, 35 skipped); without transformers, the unit tests pass or skip
(450 passed, 99 skipped). Pre-commit, mypy included, passes against
#2752 and against main. GPU tests not run; CI runs them.
- Review fixes, 2026-10-30, after Claude's review. This PR merges
#2752's new head and restores the local split's expert-parallel
parameters with their numbering test. The writer checks the routed
experts' groups against the plan's `ep_size` and `edp`, refusing on
every rank alike. A data-parallel group left at its default, the whole
world, used to leave every rank but rank 0 out of the expert write with
no error; a two-rank test fails without the check. A sharded export
reads the carried weights inside one all-reduce, so rank 0's failure
there fails every rank, and every rank seeds the quant config with rank
0's names. A two-rank test fails without that too: rank 1 errors out of
a broken collective. A codec converter is skipped as a decode in place
only when all its patterns name one module; tested, the bare FP8
patterns included. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (853) and 5.5.4 (818
passed, 35 skipped), and without transformers (451 passed, 102 skipped),
where `import modelopt.torch.export` does not import the writer.
Pre-commit, mypy included, passes against #2752 and against main. GPU
tests not run; CI runs them.
- Rebased onto main 99c3834f62c, 2026-10-30, after #2750 merged, on
#2752's rebased head. This PR's own diff is unchanged, plus one commit
taken from Claude's last review: rank 0 alone reads the carried weights'
names and sends them with `broadcast_from`, which raises on every rank
when that read fails, as the all-reduce did; and the traceback print
before the closing consensus runs only for a sharded export, where the
other ranks wait in it. #2750's final check that the first projection
and `down_proj` hold the same number of experts holds for the local
split, whose two shards have equal counts under FSDP2 and under expert
parallelism. On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (854) and 5.5.4 (819 passed, 35 skipped), and
without transformers the unit tests pass or skip (451 passed, 102
skipped), where `import modelopt.torch.export` does not import the
writer. Pre-commit, mypy included, passes against #2752 and against
main. GPU tests not run; CI runs them.
- Rebased onto main 62a5c48f374, 2026-10-30, after #2751 merged, on
#2752's rebased head, without conflicts; this PR's own diff is
unchanged. Pre-commit, mypy included, passes against main. On CPU, the
export unit tests, `test_dataset_utils.py`, `test_distributed.py`,
`test_moe_a2a.py` and hf_ptq's argument tests pass on transformers 5.18
(856) and 5.5.4 (821 passed, 35 skipped), and without transformers the
unit tests pass or skip (451 passed, 104 skipped), where `import
modelopt.torch.export` does not import the writer. GPU tests not run; CI
runs them.
- Review fix, 2026-10-30 (meenchen's review bot): `PretrainedConfig`
moves into the module's guarded transformers import at the top, and
`_source_distributed_config_attrs` checks `_TRANSFORMERS_CONFIG_TYPES`,
empty without transformers, as `_TRANSFORMERS_MODEL_TYPES` is. No
behaviour change:
`test_distributed_export_writes_the_config_a_single_gpu_export_writes`,
whose plan sits in a VLM's nested `text_config`, passes, and fails with
the config types emptied. `test_unified_export_hf.py` passes on
transformers 5.18 and 5.5.4 (73) and without transformers (61 passed, 12
skipped), where the module still imports. Pre-commit, mypy included,
passes against main. GPU tests not run; CI runs them.
- GPU run, 2026-10-30: a real-model expert-parallel PTQ and export
through #2754's expert-parallel path at `30551fa2df0`, which merges this
PR at `c8ecddb3342`. In the writer's files, this head differs from that
one only by the `PretrainedConfig` import move above.
Qwen/Qwen3-30B-A3B, recipe `general/ptq/nvfp4_default-kv_fp8`, 512
calibration samples from cnn_dailymail at sequence length 2048, batch
size 1; GB200, transformers 5.13.0. The two arms take both branches of
the writer's group check: with edp = 1 the routed experts' data-parallel
group is unset, and with edp = 2 it is the edp group of two ranks. Both
exported on every rank, with NVFP4 weights and an FP8 KV cache. Their
`config.json` carries no `base_model_ep_plan`, as the source's has none,
so no torch_a2a styles ship.

    | Arm | GPUs (nodes) | Layout | Result | Wall time | Shards |
    |---|---|---|---|---|---|
    | A | 4 (1) | EP4, edp = 1 | passed | 8:17 | 4 |
    | B | 8 (2) | EP4, edp = 2 | passed | 6:07 | 8 |
- Rebased onto main 059588b89a5, 2026-10-30, on #2752's rebased head,
without conflicts; this PR's own diff is unchanged. The GPU run above
was at an earlier head with the same own diff. Pre-commit, mypy
included, passes against main. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (857) and 5.5.4 (822
passed, 35 skipped), and without transformers the unit tests pass or
skip (451 passed, 104 skipped), where `import modelopt.torch.export`
does not import the writer. GPU tests not run here; CI defers them while
this PR targets another PR's branch.
- Rebased onto main d464d30b120, 2026-10-30, on #2752's rebased head,
without conflicts; this PR's own diff is unchanged, and the GPU run
above, at an earlier head, had the same own diff. Pre-commit, mypy
included, passes against main. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (872) and 5.5.4 (837
passed, 35 skipped), and without transformers the unit tests pass or
skip (466 passed, 104 skipped), where `import modelopt.torch.export`
does not import the writer. GPU tests not run here; CI defers them while
this PR targets another PR's branch.
- Text fixes, 2026-10-31, comments and a docstring only: #2752 reworded
the export comment this PR replaces, so this PR was restacked on it,
keeping its own block; and `_process_hf_model_for_export`'s docstring
and the call-site comment no longer name a consolidation step.
Pre-commit, mypy included, passes against main, and on CPU the export
unit tests, `test_dataset_utils.py`, `test_distributed.py`,
`test_moe_a2a.py` and hf_ptq's argument tests pass on transformers 5.18
(872).
- Rebased onto main e352caca3c3, 2026-10-31, on #2752's rebased head,
without conflicts; this PR's own diff is unchanged, and the GPU run
above, at an earlier head, had the same own diff. Pre-commit, mypy
included, passes against main. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (872) and 5.5.4 (837
passed, 35 skipped), and without transformers the unit tests pass or
skip (466 passed, 104 skipped), where `import modelopt.torch.export`
does not import the writer. GPU tests not run here; CI runs them once
this PR targets main.
- Review fix, 2026-10-31 (meenchen's review bot), comment only: the
comment above `_writes_extra` now gives only the single-sender reason.
Both sharded writers take `extra_state_dict` from rank 0 alone, so rank
0 alone reads and hands over the carried tensors (on GLM-5.3-Flash, its
MTP layer). The gate covers the tensors, not their names, which reach
every rank. Pre-commit, mypy included, passes against main.
- Rebased onto main cf38ec30ca4, 2026-11-01, on #2752's rebased head,
without conflicts; this PR's own diff is unchanged, and the GPU run
above, at an earlier head, had the same code. Pre-commit, mypy included,
passes against main. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (872) and 5.5.4 (837
passed, 35 skipped), and without transformers the unit tests pass or
skip (466 passed, 104 skipped), where `import modelopt.torch.export`
does not import the writer. GPU tests not run here; CI runs them once
this PR targets main.
- Rebased onto main 51645db66dc, 2026-11-01, on #2752's rebased head;
this PR's own diff is unchanged. One conflict, in
`test_distributed.py`'s imports, kept both sides' imports. The GPU run
above, at an earlier head, had the same code. Pre-commit, mypy included,
passes against main. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (869) and 5.5.4 (834
passed, 35 skipped), and without transformers the unit tests pass or
skip (463 passed, 104 skipped), where `import modelopt.torch.export`
does not import the writer. GPU tests not run here; CI runs them once
this PR targets main.
- Rebased onto main 2d4e8d019e7, 2026-11-02, on #2752's rebased head,
without conflicts; this PR's own diff is unchanged. Pre-commit, mypy
included, passes against main. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (869) and 5.5.4 (834
passed, 35 skipped), and without transformers the unit tests pass or
skip (463 passed, 104 skipped), where `import modelopt.torch.export`
does not import the writer. GPU tests not run here; CI runs them once
this PR targets main.
- Rebased onto main 653ef615850, 2026-11-02, on #2752's rebased head,
now that #2752 targets main; without conflicts, and this PR's own diff
is unchanged. Pre-commit, mypy included, passes against main. On CPU,
the export unit tests, `test_dataset_utils.py`, `test_distributed.py`,
`test_moe_a2a.py` and hf_ptq's argument tests pass on transformers 5.18
(869) and 5.5.4 (834 passed, 35 skipped), and without transformers the
unit tests pass or skip (463 passed, 104 skipped), where `import
modelopt.torch.export` does not import the writer. GPU tests not run
here; CI runs them once this PR targets main.
- Folded #2753 in, 2026-11-03: its 38 commits are cherry-picked onto
this PR's head `792f22b1276`, unchanged (range-diff all "="), so this
PR's own commits keep their SHAs. The combined diff is this PR's
previous diff plus #2753's own, and the tree equals #2753's last head
plus this PR's text fix. Pre-commit, mypy included, passes against main.
On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (869) and 5.5.4 (834 passed, 35 skipped), and
without transformers the unit tests pass or skip (463 passed, 104
skipped). The GPU suites were also run on the combined head
`0c4f7f0d633` on 2 and 4 GPUs (transformers 5.18.0), and every test has
the same outcome as at `792f22b1276`, before the fold.

  | File | 2 GPUs | 4 GPUs |
  |---|---|---|
| `tests/gpu/torch/export/test_distributed_hf_export.py` | 4 passed | 4
passed |
| `tests/gpu/torch/export/test_export_carry_over.py` | 2 passed | 2
passed |
| `tests/gpu/torch/utils/test_model_load_utils.py` | 6 passed | 6 passed
|
- Review fix, 2026-11-03 (Claude's review of the folded PR): an
expert-parallel export of a model that any rank holds
accelerate-offloaded is refused before anything is folded or written. It
used to take the offloaded streaming path, which is not
expert-parallel-aware, so every rank wrote its own experts over the
others' with no error. The ranks decide together in one `all_reduce`,
since offload is set up per rank.
`test_an_offloaded_expert_parallel_export_is_refused_before_folding`
fails without the refusal. Pre-commit, mypy included, passes against
main. On CPU, the export unit tests, `test_dataset_utils.py`,
`test_distributed.py`, `test_moe_a2a.py` and hf_ptq's argument tests
pass on transformers 5.18 (870) and 5.5.4 (835 passed, 35 skipped), and
without transformers the unit tests pass or skip (464 passed, 104
skipped). The GPU suites were rerun at `1cd94b8ca9d` on 2 and 4 GPUs
(transformers 5.18.0), with every test's outcome the same as at
`0c4f7f0d633`. None of them offloads, so the refusal never fires there;
the runs show that the guard and its collective leave the export's path
and its collective order as they were.

  | File | 2 GPUs | 4 GPUs |
  |---|---|---|
| `tests/gpu/torch/export/test_distributed_hf_export.py` | 4 passed | 4
passed |
| `tests/gpu/torch/export/test_export_carry_over.py` | 2 passed | 2
passed |
| `tests/gpu/torch/utils/test_model_load_utils.py` | 6 passed | 6 passed
|
- Review fix, 2026-11-03 (Claude's next review), test only:
`test_only_the_first_expert_replica_writes_the_experts` pins the
writer's replica skip under expert parallelism with replicated experts.
Two gloo ranks play the four ranks of an (edp=2, ep=2) plan, one replica
per export. The second replica's ranks write no expert but still write
the dense tensors they own, and the first replica writes each of the
four experts once. Making every replica write, or none, fails it.
Pre-commit, mypy included, passes against main. On CPU, the export unit
tests, `test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py`
and hf_ptq's argument tests pass on transformers 5.18 (871) and 5.5.4
(836 passed, 35 skipped), and without transformers the unit tests pass
or skip (464 passed, 104 skipped).
- Rebased onto main 8d19f74d132, 2026-11-03, with a code owner's review
fix on top. The rebase's only conflicts were changelog context at the
top of Backward Breaking Changes, where main's new entry and this PR's
are both kept; this PR's own diff is otherwise unchanged. The review
fix, test only:
`test_only_rank_0_writes_the_configs_of_an_expert_parallel_export`
checks on two ranks that only rank 0 calls `_write_base_config` and
`_write_hf_export_config` under an expert-parallel plan, and it fails
with the rank condition reverted to cover FSDP2 alone. Pre-commit, mypy
included, passes against main. On CPU, the export unit tests,
`test_dataset_utils.py`, `test_distributed.py`, `test_moe_a2a.py` and
hf_ptq's argument tests pass on transformers 5.18 (876) and 5.5.4 (841
passed, 35 skipped), and without transformers the unit tests pass or
skip (469 passed, 104 skipped).
- Rebased onto main 7d442467504, 2026-11-03 (after #2780, #3177 and
#3125 merged), without conflicts; this PR's own diff is unchanged.
Pre-commit, mypy included, passes against main. On CPU, the export and
utils unit tests pass on transformers 5.18 and 5.5.4 and without
transformers; hf_ptq's example tests fail the same 53 tests here as on
main, all of which need a GPU.
- Review fix, 2026-11-03 (meenchen's review): the no-gather export
checks the destination on every rank, in one `all_reduce`, before it
folds the model in place, so a directory that already holds a checkpoint
is refused with the model left as it was; the writer keeps its own check
for a checkpoint written in between.
`test_nogather_export_refuses_an_existing_checkpoint_before_folding`
refuses an existing checkpoint with every weight unchanged, then exports
the same model into a fresh directory byte-identical to the
single-process export; it fails without the early check. Pre-commit,
mypy included, passes against main. On CPU, the export and utils unit
tests and hf_ptq's argument tests pass on transformers 5.18 (1548) and
5.5.4 (1448 passed, 100 skipped), and without transformers the unit
tests pass or skip (827 passed, 111 skipped). The multi-GPU runs above
predate this change.
- Rebased onto main 3968c37051d, 2026-11-03 (after #3179, #3174, #3137,
#2742, #2539, #2741, #3199, #2743 and #3127 merged). The only conflicts
were import lines: #3127's `fsdp2_root_unsharded` import beside this
PR's in `unified_export_hf.py` (two commits) and `hf_ptq.py` (one), each
keeping both. This PR's own diff is otherwise unchanged. #3127's two
behaviour changes in `unified_export_hf.py` hold under the no-gather
path: its quant-config name revert passes the parameters' owners, which
the no-gather path asks for on rank 0 only, after a successful reverse
conversion; and its Nemotron VL dummy forward unshards an FSDP2 root,
which every rank reaches alike inside `_process_together`.
- Review fix, 2026-11-03 (meenchen's review), test only:
`test_moe_a2a.py`'s expert-parallel calibration test, now
`test_expert_parallel_calibration_and_export_match_the_whole_model`,
loads with the production loader (`load_pretrained` with an
expert-parallel plan), calibrates FP8 and exports with the no-gather
writer. It compares the checkpoint with the whole model's single-process
export: each tensor in exactly one shard, the one the index names for
it; every expert of every layer; every tensor byte-identical, except the
activation scales, within 2e-2. `[ep-world]` shards the experts over
every rank, and `[ep-half]` over half of them with two replicas. CI's PR
lane has 1 GPU and skips both; nightly and on-demand runs have 2 GPUs
and run `[ep-world]`; no CI runner has 4. At the head ff4f4cbe0bc, with
transformers 5.18.0:

| Hardware | GPUs | `[ep-world]` | `[ep-half]` | The three export GPU
files |
  |---|---|---|---|---|
| RTX 6000 Ada | 2 | passed (EP2, 2.2 s) | skipped (needs 4 GPUs) | not
run |
| A second GPU type | 2 | passed (EP2, 5.1 s) | skipped (needs 4 GPUs) |
14 passed |
| A second GPU type | 4 | passed (EP4, 9.7 s) | passed (EP2 × EDP2, 7.1
s) | 14 passed |

With the writer's replica skip disabled, `[ep-half]` fails on 4 GPUs of
the second type, refused on every rank by the numbering check below;
`[ep-world]` still passes.
- Review fixes, 2026-11-03 (Fridah-nv's review):
- The writer's local expert split runs in `all_reduce`, which refuses on
every rank, before anything is written, unless the ranks between them
number each fused-experts module's experts 0..E-1 once each (E being the
config's count under expert parallelism). A count the config does not
name, with a weight over every expert, used to shift every later rank's
experts past the end with no error. A plain per-expert scale for neither
this rank's experts nor every expert of the weight is refused rather
than sliced.
`test_the_ranks_write_every_expert_number_once[count-known|count-unknown]`
and `test_split_refuses_scales_for_another_number_of_experts` each fail
without the fix.
- Packing an FSDP2 model outside the no-gather writer raises a
`RuntimeError` instead of failing an assert, which `python -O` drops.
`test_packing_an_fsdp2_model_outside_the_no_gather_writer_is_refused`
fails with the assert back.
- The three single-process expert-parallel refusals (ModelOpt state,
offload, replicated dense shards) are one parametrized test, which now
also checks that the model is left as it was. Every test this PR adds
runs in 0.1 s or less on CPU.
- The changelog entry on the export's plan names the DDP case: a script
exporting from several ranks loads with `load_pretrained` or records
`DistributionPlan(world_size)`. Every in-repo caller of the export
records a plan or exports from a single process.
- On multi-GPU expert parallelism: the GPU test above at EP2, EP4 and
EP2 × EDP2, with the replica-skip check, at this head; and the
real-model runs above (Qwen3-30B-A3B at EP16 and at EP4 with one and two
replicas, MiniMax-M2.7 at EP16) at earlier heads. Not run: no CI runner
has four GPUs, so the EDP > 1 case runs only by hand.
- Pre-commit, mypy included, passes against main at ff4f4cbe0bc. On CPU,
the export and utils unit tests pass on transformers 5.18 (1616) and
5.5.4 (1500 passed, 116 skipped), and without transformers they pass or
skip (827 passed, 112 skipped). hf_ptq's example tests fail the same 53
tests here as on main, all of which need a GPU.
- Comment only, 2026-11-04: the writer says why every rank joins the
expert split's `all_reduce`, a rank that writes no experts included.
Pre-commit, mypy included, passes against main.
- Review fixes, 2026-11-04 (sugunav14's review): the experts' input
scales are stacked inside the labeled `all_reduce` that agrees on their
keys, so a rank that cannot stack them fails every rank instead of
leaving the others in the raw reduce; the export's closing docstring
scopes its every-rank-fails guarantee to failures outside raw
collectives, naming the dense tensors' point-to-point transfers as the
case it does not cover. Under an expert-parallel plan, a plain tensor
under a fused-experts module other than its experts' weights and scales
(a fused bias, say), which each rank holds only its own slice of, is
refused on every rank before anything is written; no model the
expert-parallel load supports has one.
`test_two_ranks_write_every_expert_with_the_largest_input_scale` (a rank
with a two-value scale, its reduce bounded to 10 s) and
`test_an_expert_parallel_export_refuses_a_sliced_tensor_beside_the_experts`
each fail without their fix. Pre-commit, mypy included, passes against
main. On CPU, the export and utils unit tests pass on transformers 5.18
and 5.5.4 and without transformers; hf_ptq's example tests fail the same
53 tests here as on main, all of which need a GPU.

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

- Is this change backward compatible?: ⚠️ The no-gather writer is opt-in
for FSDP2; only expert-parallel models, which could not be exported
before, take it unconditionally, and a sharded export now raises on
every rank when any rank's export fails (from #2753). A model
FSDP2-sharded by hand, `fsdp2_wrap` included, must record its plan with
`set_distribution_plan` before `export_hf_checkpoint`; without it the
export raises. `hf_ptq.py --use_fsdp2` on several GPUs now refuses
calibration that keeps its statistics on each rank, and raises on a
calibration batch that runs out of GPU memory instead of retrying it
smaller.
- 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)?:
✅ The no-gather FSDP2 export opt-in, and, under Backward Breaking
Changes, that the export needs a distributed model's plan recorded and
what `hf_ptq.py --use_fsdp2` on several GPUs now refuses.
- Did you get Claude approval on this PR?: ✅ Approved on 2026-10-29
after meenchen's round. Its one suggestion was taken in a later round.
#2753's code was approved there on 2026-10-30; a review of the combined
PR is requested.

### Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models (OMNIML-6083;
#2753's OMNIML-6084 folded in); #2751, #2750 and #2740, which it built
on, have merged.

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

* **New Features**
* Added an opt-in no-gather export for FSDP2-sharded models. With
`MODELOPT_FSDP2_EXPORT=nogather`, ranks write checkpoint shards in
parallel without gathering the full model on one host; MoE experts
remain sharded.
* Distributed exports include non-model files from the source checkpoint
when available.
* **Bug Fixes**
* Export and batch-size checks now use the distribution plan recorded
during model loading. Manually distributed models need a plan recorded
before calibration or export; operations raise an error when a required
plan is missing.
<!-- 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 4, 2026
…reviews (#3139)

> [!NOTE]
> **Folded on 2026-11-03.** #3133 (`distributed_forward_loop(forward=)`,
and the memory monitor's NVML probe and idempotent `stop()`) and #2754
(hf_ptq's expert-parallel run) are folded into this PR. Their commits
sit unchanged on top of this PR's own, so `forward=` and the NVML fix
land with their caller. Their review history stays on #3133 and #2754.
Before the fold, this PR was [2/3] of #2754's split (2026-10-30), and
#2754 was [21/21] of the original stack.
>
> **Base:** `main`. Every PR this one builds on has merged: #2780
(expert-parallel load routing, with #2746's model specs folded in),
#2742 (dense sharding) and #2752 (no-gather export, with #2753's
expert-parallel export folded in). The diff below is this PR's alone.

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

This PR's chain only.

- `main` (#2745, #2736, #2739, #2737, #3088, #3099, #3100, #3101, #2750,
#3122, #3131, #2751, #3134, #3074, #3140, #2779, #3135, #3067, #2740,
#3136, #2780, #3137, #2742, #2741, #2743, #3138 and #2752 merged)
- **#3139 expert-parallel PTQ from hf_ptq.py, with lockstep previews
(this PR)**

</details>

### What does this PR do?

Type of change: New feature and bug fix

`hf_ptq.py` had one distributed path, `--use_fsdp2`, which shards a
dense model and replicates every expert of an MoE. This PR wires the
expert-parallel path (the rest of the series; see the layout above) into
it, so the documented CLI reaches an expert-parallel run: recipes,
export formats, deprecations. It also does three more things:
- keeps the generation previews of a model distributed over several
ranks in lockstep;
- pins a replicated model's whole copy to each rank's GPU;
- carries the two library changes the run needs.

- **Process group.** `main()` runs inside `distributed_run` (#2736),
which owns the process group on a distributed launch.
- The run takes this process's `DistributedState` (rank, size, device)
from it, with `--device` for a single process.
- FSDP2 on one rank still shards through a process group of one. The
load sets it up (#2779), and `distributed_run` destroys it with the run.
- The example's own `DistributedState`, `setup_distributed_args` and
process-group helpers are gone.
- **One decision, read everywhere.** `load_model` decides the plan once
and loads every model by it through `load_pretrained` (#2779):
expert-parallel, FSDP2, `get_model`'s whole-model loads and the
low-memory load.
- The decision is `resolve_distribution_plan` (#2737, #2780), wrapped in
`example_utils.resolve_distribution`, which adds this script's checks.
- `load_pretrained` records the plan, so the script records none itself:
#2752's record after the `--use_fsdp2` load is gone.
- Everything after reads the plan back from the model, not the flag or
the process group: the calibration device, the data sharding, the
calibration loop, the previews, and `get_model`'s GPU placement.
- `MODELOPT_EP_DEGREE` and `MODELOPT_FSDP_SIZE` override the automatic
choices.
- `--use_fsdp2` asks the decision for FSDP2 and no expert parallelism.
Its `--experts_implementation` (#3074) still goes on the config the
FSDP2 load builds from.
- `--use_fsdp2` now loads through `load_pretrained`'s FSDP2 route, which
#2779 opens to the text-only Qwen3.5 and Qwen3.5-MoE VLMs. Main's FSDP2
path has calibrated them since #2676.
- **Refusals.** Each is refused before anything loads unless noted.

  | Refused | When | Why |
  |---|---|---|
| A plan that shards the whole model with FSDP2 | Without `--use_fsdp2`
| That flag is what this script's FSDP2 checks hang on; they now run
before anything is set up. |
| A plan that would quietly replicate an expert-parallel-capable MoE |
Any run (`resolve_distribution_plan` refuses it) | Every rank would hold
every expert. |
| A model whose spec refuses expert parallelism (GPT-OSS, Llama-4;
#2780) | An EP degree above 1 asked for | The expert-parallel load
cannot take it. Left to decide, the plan goes without expert parallelism
and warns why. |
| Asking to FSDP2-shard the dense part within several expert-parallel
groups | Any run; the error names the settings that avoid it | The
export cannot write that layout yet. Left to decide, the plan replicates
such a dense part. |
| An AutoQuantize recipe | Expert-parallel and replicated routes | Its
search scores each rank's shard without reducing the scores.
`--use_fsdp2` keeps main's warning. |
| `--low_memory_mode`, `--use_seq_device_map`, `--offload_folder` (and
with it `--max_cpu_memory_gb` / `--max_gpu_memory_gb`) | Expert-parallel
and replicated routes | They configure a single process's load. An
expert-parallel run never reaches those loaders, and a replicated one
pins each rank's copy to its GPU. A single process and `--use_fsdp2`
keep main's handling. |
| `--vllm_fakequant_export` | Expert-parallel route | That exporter
writes the whole model from each process it runs in. A replicated run
keeps it (rank 0 exports), and `--use_fsdp2` keeps its parsing-time
refusal. |
| `--experts_implementation` (#3074) | Expert-parallel route | The
expert-parallel load runs the routed experts through `torch_a2a`
whatever backend the flag names. `--use_fsdp2`, a replicated run and a
single process load by it. |

- **Export.**
- A model the plan replicates, such as a small dense model under
torchrun, is exported by rank 0 alone. Every rank used to write the same
directory and race on `config.json`.
  - A multimodal model's source config is rank 0's in every plan.
- A speculative-decoding model's export, which writes the whole
checkpoint from one process, is refused on every rank when the model is
sharded.
- **Calibration.**
- Every distributed run calibrates on its own 1/world shard of the data
(#2740), the offline speculative-decoding loader included. A loader of a
kind that cannot be split is refused. The image-text loader shards its
own stream (#3172), so each rank drops its own undecodable images and
pads to the others' batch count.
- Expert-parallel runs go through `distributed_forward_loop`, and image
batches through the VLM's own forward by the loop's new `forward=`
(below).
- The loop re-plants the all-to-all forwards that quantizer insertion
clobbers on transformers 5.16 and later. From 5.16, quantizer insertion
drops the routed experts' all-to-all forward wrapper.
- Some recipes run no calibration loop: configs that need no
calibration, such as `int8_weight_only` or `w4a16_nvfp4`, and the MX
presets, whose algorithm is `None`. They would leave the wrapper
dropped, so the preview after PTQ would fail before the export. Once
quantized, an expert-parallel run therefore re-plants it through
`reinstall_a2a_forwards`, the loop's own re-plant, which
`modelopt.torch.utils.distributed` now makes public.
- On 5.15 and earlier the TP transforms are forward hooks that insertion
leaves in place, and the re-plant finds nothing to restore.
- An expert-parallel VLM calibrated on text runs its batches through the
language model, but the loop re-plants the all-to-all forwards over the
whole model. Transformers keeps the expert-parallel plan on the model
`from_pretrained` built, and from 5.16 a VLM's language model reports
none of its own. A loop handed the language model would re-plant
nothing, and the first batch would raise for the missing EP process
group.
- The `--qformat` path of an expert-parallel VLM also needs #2740's
guard fix. It lets a module with no routed experts (the vision tower,
which the script quantizes with every quantizer off) pass the
expert-parallel calibration check.
- FSDP2 and a model replicated on every rank keep main's plain loop. On
a plan of several ranks that loop retries no batch that runs out of
memory (#2752). The error reaches `distributed_run`, which aborts the
rank, and the launcher stops the others, instead of leaving them waiting
in a collective (main's `cleanup_distributed` would wait in
`destroy_process_group`).
  - The calibration algorithms under a plan that spans several ranks:

    | | Algorithms |
    |---|---|
| Supported and run on GPUs | `max` (amax all-reduced over the data-,
expert- and tensor-parallel groups), `mse` (searches the weights max
leaves identical on every rank) |
| Supported, not yet run on GPUs | `gptq` (Hessians merged across each
module's data-parallel replicas), `smoothquant` (scales from max's
synced amax), `awq_clip` (each candidate clip's loss averaged over the
ranks), `nvfp4_act_headroom` (activation scales MAX-reduced over data
parallelism) |
| Refused before quantizing (#2740) | `awq_lite`, `awq_full`,
`svdquant`, `local_hessian`, `imatrix`, and `max` or `mse` with
`distributed_sync` off, also as another algorithm's weight or scale
algorithm: each keeps its statistics on its rank, so the ranks' copies
of a weight would come out different |
| Runs with a warning | `lsq` on the expert-parallel and replicated
routes: its first scale calibration follows the rows above, but nothing
has checked its learnable scales across ranks |

- **Previews keep a sharded model's ranks decoding together.** This
covers the expert-parallel runs, Nemotron-VL's previews included, and
`--use_fsdp2` on several GPUs.
- Each rank previews the first sample of its own calibration shard, so
the ranks finish decoding at different steps. When the plan shards the
model (expert parallelism, or FSDP2 over several ranks), every forward
runs a collective, so a rank that stopped decoding left the others
blocked in it.
- `preview_generate_kwargs` hands `generate` `synced_gpus=True` for such
a plan: in the previews before and after quantization, and in
Nemotron-VL's.
- The ranks vote on whether to run Nemotron-VL's image preview (an
`all_reduce` of whether each found a sample image), so every rank
previews or none does. Each node reads the images from its own checkout,
and the repository ships none.
- Under `synced_gpus` a failing preview raises instead of being skipped,
since its peers would wait for it. This covers the VL previews and the
preview after quantization. A failed preview after quantization stops
the run before the export, with a message that names `--skip_generate`.
A single process keeps the best-effort skip (NVBug 6752977).
- On a run of several ranks, `distributed_run` aborts a rank that
raised, so `torchrun` stops the others, rather than tear the process
group down while they wait in a collective that rank never reaches.
- **`generate` keeps a MoE's experts on their backend.**
- On a GPU, `generate` switches the experts of a `grouped_mm` MoE to
`batched_mm` for decoding (`_optimize_model_for_decode`, transformers
5.0 and later). `batched_mm` bypasses the quantizers, so the preview
after PTQ decoded unquantized experts.
- Transformers also refuses the switch for an FSDP2-wrapped model:
`FSDPQwen3MoeForCausalLM does not support setting experts
implementation`.
- `keep_the_experts_implementation` keeps every module of the model that
has the hook from switching. A model can generate through a submodule,
as a Nemotron-VL model's `chat` does through its language model.
- It puts back a hook a module holds itself, so a hook bound per
instance survives and previews nest.
- This holds for every run, a single process included: there too the
preview after PTQ now decodes on the quantized experts.
- **`get_model(..., distribution=plan)` pins a whole model to the rank's
GPU.** A replicated run loads through it.
- When the plan gives each of several ranks the whole model, every load
path places it on the rank's own `cuda:<local_rank>`: the plain load,
the pack-quantized and MXFP4 loads, and DiffusionGemma's sequential map.
Accelerate's "auto" would run its placement in every rank alike and
could put every rank's copy on the same idle GPU.
- There, `--use_seq_device_map` and a device that names no GPU index are
refused. A pinned copy is not sized against the node's GPUs, a limit its
one-device map would ignore.
- A single process keeps "auto", as before. The device is compared by
type, since a run's `torch.device` never equals a string such as
`"cpu"`.
- A plan that shards the model (expert parallelism, or FSDP2) is
refused: `get_model` loads the whole model on every rank, and hf_ptq
hands such plans to `load_pretrained`.
- `get_model` hands `load_pretrained` only a plan its caller gave.
Without one, the load decides as before, and it refuses `MODELOPT_*`
knobs that ask to shard over a launch whose process group is not set up.
- **`distributed_forward_loop(..., forward=None)`** (from #3133).
- The loop calibrates by calling `model(**batch)`. A batch that needs
its own call into the model cannot go through it: a VLM's image-text
batch, say, which runs through the VLM's own forward with the keyword
arguments that forward accepts.
- The loop now takes an optional `forward(batch)`, and still moves each
batch to the device and calibrates with the cache disabled.
- `forward` is typed as taking a `Mapping`. It gets a new dict when
`device` is given, and the loader's own mapping otherwise.
  - The expert-parallel image calibration above uses it.
- **Memory monitor** (from #3133). `hf_ptq.py` starts it on each node's
first rank, since it reads every GPU on its node.
- `launch_memory_monitor` checks that NVML can report memory before it
starts the monitor. But the probe ran before `nvmlInit`, so every probe
raised `NVMLError_Uninitialized`. The monitor never started on any host
where nothing else had initialized NVML.
- The probe now initializes NVML itself and shuts it down afterwards,
keeping NVML's reference count balanced.
- Since the monitor now starts, its `stop()`, which also runs at exit,
does nothing on a monitor already stopped.
- `stop()` joins the polling thread before it reads and prints the
peaks, so a sampling pass in flight finishes first.
- **Slurm example.** New `examples/hf_ptq/slurm/multinode_ep_ptq.slurm`,
following `multinode_fsdp2_ptq.slurm`. Not run on a cluster yet.
- Its `EXPORT_PATH` and `HF_HOME` must be on storage every node can see:
every rank writes its share of the checkpoint, and rank 0 downloads a
repo id for the others to read.
- Every node runs the editable install from the one mounted clone, so
the nodes take turns under `flock` where the filesystem offers it.
- It launches one `torchrun` per node, which spawns one process per GPU,
and `hf_ptq.py` shards the routed experts over all ranks.
- It installs the transformers 5.7 or newer that expert parallelism
needs, and prints the version into the job log.
  - Its defaults quantize Qwen3-235B-A22B to NVFP4 with an FP8 KV cache.
- **Docs.** The README section "Expert-Parallel Post-Training
Quantization for MoE Models" covers:
  - how to launch, and what the knobs override;
  - which models are refused;
- that GPT-OSS and Llama-4 quantize in a single process: expert
parallelism refuses them, and `--use_fsdp2` refuses their released MXFP4
/ multimodal checkpoints;
  - which calibrations have run on GPUs on more than one rank.

The out-of-memory note covers every `torchrun` launch of several ranks,
not only `--use_fsdp2`. A multi-node run needs the export directory and
the Hugging Face cache on storage every node can see.

### Usage

```bash
# One node, 8 GPUs: the experts shard over all 8 ranks, each calibrating its own data.
torchrun --nproc_per_node 8 examples/hf_ptq/hf_ptq.py \
    --pyt_ckpt_path Qwen/Qwen3-30B-A3B --qformat nvfp4 --export_path /out/qwen3-30b-a3b-nvfp4
```

```python
# Each rank of a replicated run loads the whole model onto its own GPU.
model = get_model(ckpt_path, device=f"cuda:{local_rank}", distribution=DistributionPlan(world_size))

# Run each image-text batch through the VLM's own forward, e.g. with filtered kwargs.
forward_loop = distributed_forward_loop(model, loader, device=device, forward=vlm_forward)
```

### Testing

- New `tests/examples/hf_ptq/test_hf_ptq_expert_parallel.py` (57 cases).
The decision itself is tested in #2737 and #2780. It covers:
- what the script adds to the decision: FSDP2 without expert parallelism
for `--use_fsdp2`, and FSDP2 sharding refused unless `--use_fsdp2`;
- `load_model` loading by the plan: an EP plan and `--use_fsdp2` through
`load_pretrained` and no other loader, a data-parallel one through
`get_model`;
- the single-process load options (`--low_memory_mode`,
`--use_seq_device_map`, `--offload_folder`) refused on the
expert-parallel and replicated routes and kept by a single process;
- `main()` running inside `distributed_run`, which it leaves even when
the run raises, and handing the run the state `distributed_run` yields,
with `--device` for a single process;
- per-rank calibration data, the offline speculative-decoding loader
included;
- the distributed loop, with the EP mesh, for an expert-parallel plan,
and the plain one for FSDP2;
- exporting a replicated model from rank 0 only, and every rank of a
sharded one;
- a sharded speculative-decoding model refused at export on every rank,
with nothing written;
- the plan the export cannot write refused before loading, while the
world-size degree still resolves;
- the vLLM fake-quant export refused on the expert-parallel route and
kept by replicated and single-process runs;
- an AutoQuantize recipe refused, and an LSQ recipe warned about, on the
routes this script adds;
- a failed preview raising on an expert-parallel model, Nemotron-VL's
included, and skipped, with the export still run, on a replicated one;
- the all-to-all forwards re-planted after a quantization that runs no
calibration loop, for an expert-parallel plan only;
- a tiny Qwen3-VL-MoE, as the expert-parallel load leaves it, calibrated
on text over a one-rank gloo group. It fails without the fix on
transformers 5.18 and skips below 5.16.

The DeepSeek-V3 multi-rank cases skip below transformers 5.7, where
#2780 refuses expert parallelism before the route they exercise. Their
single-process and `--use_fsdp2` cases still run there.
- New `tests/examples/hf_ptq/test_hf_ptq_previews.py`:
- the previews before and after quantization, and Nemotron-VL's text,
fallback and image generations, use `synced_gpus` exactly when the plan
shards the model;
  - the VL image preview passes the kwargs it is handed to `chat`;
  - the ranks skip the image preview together when one has no image;
  - a failing text-only VL preview raises under `synced_gpus`.
- `tests/examples/hf_ptq/test_example_utils.py`:
- `get_model`'s pin on every load path, a pinned copy not held to a
node-wide memory limit, a single process left on "auto", and a CPU
device given as a `torch.device`;
- the refusals of the sequential map, of a device without a GPU index,
and of a plan that shards the model;
- `get_model` without a plan leaving the decision to `load_pretrained`;
- the experts guard: the previews keep `generate` from switching the
experts implementation, also on a language model that a model around it
generates through (fails without the fix); a model without the decode
hook is previewed as it is; and a decode hook the model holds itself is
put back, also when previews nest.
- `tests/examples/hf_ptq/test_hf_ptq_args.py`:
- a sharded model's failed preview after quantization stops the run
before the export (an FSDP2 plan of two ranks), while NVBug 6752977's
single-process skip is unchanged;
  - the memory monitor starts on each node's first rank only.
- `tests/examples/hf_ptq/test_hf_ptq_model_type.py`: the preview tests'
stand-in models are modules, since the previews read their plan.
- `tests/unit/torch/utils/test_distributed_calibration.py`: two batches
run through a given forward, on the device and with the cache disabled.
- New `tests/unit/torch/utils/test_memory_monitor.py`, against a fake
reference-counted NVML:
- the monitor starts when NVML can report memory (this fails on the old
code), and is skipped with NVML shut down when it cannot;
  - a second `stop()` does nothing;
  - on two GPUs, `stop()` waits for the sampling pass in flight.
- Mutation-checked: each test fails under a deliberate break of the code
it covers.
- New 2-GPU smoke test `test_ptq_qwen3_moe_sharded`
(`tests/examples/hf_ptq/test_llm_ptq.py`). It is the tests' one real
sharded run of the script; the files above cover the wiring with
stand-ins.
- It runs `torchrun --nproc_per_node 2 hf_ptq.py` on a tiny Qwen3-MoE
with the FP8 recipe, in two cases: expert-parallel
(`MODELOPT_EP_DEGREE=2`, transformers 5.7 or later) and `--use_fsdp2`.
  - Both preview before and after calibration, and export.
- The test checks that every expert of every layer is exported FP8 with
its weight scale, and that the config names FP8.
  - It skips on CI's 1-GPU PR runner and runs on 2-GPU runners.
- Results at db78d0e (2026-10-30), on 2 GB200s with torch 2.11.0a0
and transformers 5.9.0:

    | Test | Result | Time |
    |---|---|---|
| `tests/examples/hf_ptq/test_llm_ptq.py::test_ptq_qwen3_moe_sharded` |
2 passed (`expert_parallel`, `fsdp2`) | 146 s |
| `tests/gpu/torch/quantization/test_fsdp2_autoquant.py` | 6 passed |
213 s |

- The re-plant was checked with a 2-GPU A/B on an earlier revision.
Setup: a tiny Qwen3-MoE at EP 2 with the dense part replicated, MXFP8 on
weight and input quantizers with algorithm `None`, previews on.

  | Transformers | Without the re-plant | With it |
  |---|---|---|
| 5.18 | Failed in the post-quantization preview on both ranks
("torch_a2a experts forward requires the EP process_group"); no
checkpoint written | Completed, restoring 8 forward wrappers, and
exported |
| 5.9.0 (nothing to re-plant: up to 5.15 the TP transforms are hooks
that quantizer insertion leaves alone) | Exported | Exported,
byte-identical files |

- A tiny Kimi-K3 VLM MoE (bf16, 32 experts) ran on 2 GPUs at EP 2, with
transformers 5.18 and NVFP4 with an FP8 KV cache. It calibrated on text
and previewed before and after PTQ on both ranks. The calibration loop
re-installed its 3 experts' forward wrappers, and the run exported.
- These GPU results were measured on earlier revisions of this series,
before this script's loads moved onto `load_pretrained` (#2779, #2780).
This revision's GPU tests run in CI only.
- The series' GPU tests: 19 passed on a 4-GPU node. On 1 GPU (CI's PR
runner), 6 passed and 13 skipped. They cover the expert-parallel load
with the dense part replicated and sharded, at EP 4 and EP 2; amax sync;
and the distributed export.
  - Against the series' base on one GPU node:

    | Suite | Outcome against the base |
    |---|---|
| `nox -s gpu` (all of `tests/gpu`, 1 GPU, CI's PR-runner shape) | Every
test failing here also fails at the base; the only new tests are the
series' own |
| hf_ptq example lane (`tests/examples/hf_ptq`, TensorRT-LLM image, 1
GPU) | No outcome changes on the 296 shared tests; the series' 30 pass,
except 2 that need transformers 5.7 |
| `tests/gpu_megatron` (2 GPUs) | No outcome changes over the 311 tests
both runs reached; the rest time out identically at the base in that
image |

- Expert-parallel runs end to end. All of them predate #3074's expert
weight-scale fix. Before that fix, on every rank but rank 0, an expert's
weight scale came out too large wherever rank 0's expert at the same
index had the larger one. That costs precision but never clips; the fix
can only tighten such scales.
  - Qwen3-30B-A3B at EP16 over 4 nodes, NVFP4 and FP8:
- The exports with the dense part FSDP-sharded over the world and with
it replicated have byte-identical weights and weight scales. Only
calibration-derived input scales differ.
- Every dense FP8 weight is FP8 with its scale, and no NVFP4 weight has
the all-zero high nibbles of a lost pack shift.
- Qwen3-VL-30B and MiniMax-M3: tensor counts match single-GPU exports,
and every expert weight is packed.
  - MiniMax-M2.7 (block-FP8 source) at EP16 over 4 nodes, NVFP4:
- Every exported weight name is the source checkpoint's, and routed
experts are `block_sparse_moe.experts.N.w1/w2/w3`.
- Served by vLLM (0.30 dev build, TP4), it scores close to the FP8
source on gsm8k (5-shot, 100 samples):

      | Checkpoint | Flexible | Strict |
      |---|---|---|
      | This export (NVFP4) | 0.94 | 0.93 |
      | FP8 source | 0.93 | 0.95 |
  - DeepSeek-V3 and GLM: on an earlier revision.
- Kimi-K3 NVFP4 at EP64 over 16 GB200 nodes, in 10 minutes (peak 155 GiB
per GPU on an earlier build of this series). Checked against the source
checkpoint:
    - the router correction biases match;
- routed and shared experts carry the names vLLM 0.28's loader reads;
    - dense weights dequantize back to the BF16 source at cosine 0.9955;
- the remote code, tokenizer and processor files ship with the export;
- the modules vLLM builds unquantized stay BF16, as in
nvidia/Kimi-K3-NVFP4.

The same checks flag the export made before this series' fixes. vLLM
0.28 loads the export and starts serving. But it cannot serve a Kimi-K3
NVFP4 export with an FP8 KV cache: its FP8-KV path needs an FP8 prefill
query, which its NVFP4 linears reject. TBD: generation and gsm8k from
the checkpoint-mirror recipe
`models/moonshotai/Kimi-K3/ptq/nvfp4_experts-fp8_pb_attention`, on this
series' code with the #3074 fix.
- Folded on 2026-11-03, on main a6cc167, on `hfep-base-14-hf-ptq`
rebuilt from #2780, #2742 and #2752's content:
- This PR's 6 commits, #3133's 6 and #2754's 10 are unchanged:
range-diff shows each as `=`. The own diff equals the three PRs' own
diffs combined, line for line.
  - Pre-commit, mypy included, passes against main.
  - On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| hf_ptq example tests that run without a GPU (`tests/examples/hf_ptq`
minus `test_llm_ptq.py`, `test_vlm_ptq.py` and
`test_convert_ggml_to_int8.py`) | 313 passed, 17 skipped | 302 passed,
28 skipped |
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| `test_model_load_utils.py`, `test_moe_a2a.py`,
`tests/unit/torch/models` | 630 passed | 528 passed, 91 skipped |

- Review fixes, 2026-11-03 (Claude, on the folded diff): the Slurm
example and the README say that the export directory and `HF_HOME` must
be on storage every node can see. The example's editable install takes
turns under `flock`, and runs unlocked where the filesystem has no
flock. `--node_rank` is dropped, since the c10d rendezvous ignores it.
`reinstall_a2a_forwards` is the re-plant function itself rather than an
alias of a private one. Pre-commit passes against main. On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| hf_ptq example tests that run without a GPU | 313 passed, 17 skipped |
302 passed, 28 skipped |

- Rebased on 2026-11-03 onto main 7d44246 (after #2780 merged), on
`hfep-base-14-hf-ptq` rebuilt from #2742 and #2752:
- Two CHANGELOG conflicts were in context only: main's new entries, and
#2752's new no-gather wording.
  - The own diff is unchanged. Pre-commit passes against main.
  - On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| hf_ptq example tests that run without a GPU | 313 passed, 17 skipped |
302 passed, 28 skipped |
| `test_model_load_utils.py`, `test_moe_a2a.py`,
`tests/unit/torch/models` | 630 passed | 528 passed, 91 skipped |

- Rebased on 2026-11-03 onto main 5870698 (after #3137 merged), on
`hfep-base-14-hf-ptq` rebuilt from #2742 and #2752:
- No conflicts, and the own diff is unchanged. Pre-commit passes against
main.
  - On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| hf_ptq example tests that run without a GPU | 313 passed, 17 skipped |
302 passed, 28 skipped |
| `test_model_load_utils.py`, `test_moe_a2a.py`,
`tests/unit/torch/models` | 687 passed | 534 passed, 92 skipped |

- Rebased on 2026-11-04 onto main c785ca9 after #2752 merged, and
retargeted to `main`; the `hfep-base-14-hf-ptq` helper is retired.
  - Conflicts:
- imports in `hf_ptq.py` and `example_utils.py`: main's
`fsdp2_root_unsharded` and `resolve_model_class` are kept, and
`is_fsdp2_text_only_vlm`, gone from main, is dropped;
- `create_vlm_calibration_forward`'s header, next to main's new
`forward_requires_images`.
- Main's VLM support under `--use_fsdp2` (#3127, #3172) is kept: the
image loop runs inside `fsdp2_root_unsharded`, and text calibration and
the batch-size probe run inside `fsdp2_call_context`.
- New commit: the image-text loader now shards its stream by the plan on
every distributed plan, and nothing shards it again.
    - Before it, a `--use_fsdp2` image run was sharded twice.
- An expert-parallel or replicated image run was sharded without #3172's
per-rank image filter, so one rank's empty batch would leave the others
in a collective.
    - Its new test fails without it.
- New commit: two calibration-loop tests' stand-in arguments carry
`--use_fsdp2`, which main's FSDP2 text loop reads.
- Pre-commit passes against main. On CPU, with the same failures as main
in this environment (four diffusers SDPA backward tests and one ONNX
import error):

    | Tests | transformers 5.18 | transformers 5.5.4 | no transformers |
    |---|---|---|---|
| hf_ptq example tests that run without a GPU | 331 passed, 17 skipped |
320 passed, 28 skipped | skipped (need transformers) |
| `tests/unit/torch/utils` and `tests/unit/torch/quantization` | 2572
passed, 3 skipped | 2476 passed, 99 skipped | 1718 passed, 58 skipped |

  - Core logic by `.agents/review-guidelines/code-review.md`:

    | | Lines |
    |---|---|
    | Added Python | 552 |
    | Core Python | 388 |
    | Core shell (Slurm example) | 40 |
    | Core total | 428 |

- Review history: #2754 (2026-10-11 to 11-02) and #3133 (2026-10-30 to
11-02) for their changes. This PR's own fixes before the fold are listed
below; their rebases are in its timeline.
- Review fix, 2026-10-30 (Claude): `get_model` hands `load_pretrained`
only a plan its caller gave (new test fails without it).
- Review fixes, 2026-10-30 (cjluo-nv's bot): `get_model` refuses a plan
that shards the model.
- Review fix, 2026-10-30 (cjluo-nv's bot and Claude, on the maintainers'
decision): a sharded model's failed preview after quantization stops the
run before the export.
- Review fix, 2026-10-30 (Claude round 4): a rank that raised on a run
of several ranks aborts instead of tearing the group down.

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

- Is this change backward compatible?: ❌ A `torchrun` launch of several
ranks without `--use_fsdp2` now runs as one distributed job (an MoE
expert-parallel, any other model replicated) instead of one independent
run per process. It refuses there the single-process load options,
AutoQuantize and layerwise-export recipes, and the TensorRT-LLM export.
This is listed under Backward Breaking Changes in the CHANGELOG.
- Single-process and `--use_fsdp2` runs behave as before, with these
exceptions:
- Any multi-rank launch now refuses a `--device` other than `cuda` (by
`distributed_run`, #2736). Main's `--use_fsdp2` ignored it and ran each
rank on `cuda:<local_rank>`.
- On transformers 5.0 and later, a preview of a `grouped_mm` MoE on a
GPU keeps the experts' backend, in a single process too. The preview
after PTQ now decodes on the quantized experts.
    - `--use_fsdp2` previews on several GPUs decode in lockstep.
- A `--use_fsdp2` run on several GPUs whose preview after quantization
fails now stops before the export. Main skipped the preview and
exported. `--skip_generate` runs it without the previews.
  - `forward=` is optional; the memory monitor change is a fix.
- 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)?:
✅ New feature and Backward Breaking Changes, 0.49.0.
- Did you get Claude approval on this PR?: ❌ A re-review is requested
after the fold. #2754 was approved on 2026-10-27 and 2026-10-29, and
#3133 before its last rebase.

### Additional Information

The last PR of expert-parallel PTQ for Hugging Face MoE models. Every PR
it builds on has merged, and it targets `main`. #3133 and #2754 are
folded in (2026-11-03) and closed; their review history stays there.


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

## Summary by CodeRabbit

* **New Features**
* Added expert-parallel post-training quantization for supported MoE
models, with multi-node launch guidance and a Slurm example.
* Distributed runs split calibration data across ranks and coordinate
previews; replicated-model exports are written by rank 0.
* **Breaking Changes**
* Multi-rank launches without FSDP2 now run as one distributed job:
eligible MoE models use expert parallelism, while other models are
replicated. Some export and calibration options are rejected in
distributed modes.
* Multi-GPU FSDP2 calibration no longer retries with smaller batches
after an out-of-memory error.
* **Documentation**
* Expanded guidance on distributed calibration requirements and
limitations.
<!-- 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.

3 participants