Skip to content

[OMNIML-6060] [3/3] Refuse an expert-parallel load that would calibrate the experts wrong - #2741

Merged
shengliangxu merged 10 commits into
mainfrom
shengliangx/hfep-6a-ep-loader
Nov 3, 2026
Merged

shengliangxu merged 10 commits into
mainfrom
shengliangx/hfep-6a-ep-loader

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Note

[3/3], split on review (2026-10-30): this PR grew past the 500-line budget, so it is now three PRs, merged in order. #3131 [1/3] holds the loader's helpers, #3136 [2/3] the expert-parallel loader, and this PR, [3/3], the checks it runs once the experts load. #3131 and #3136 have merged. The review history of the whole loader stays here.

Base: main, where #3136 and #2780 have merged (2026-11-03). The diff below is this PR's alone. #2780 merged before this PR after all, so this PR now carries the test fixes the two need together.

Series layout

What does this PR do?

Type of change: New feature

Once the experts load, every rank checks what calibration relies on. It refuses a load that would run without an error but compute or calibrate wrong:

  • No match: a plan whose expert containers match no module of the loaded model, which would seed no expert state;

  • Not named as experts: containers calibration would not take for routed experts by name (model_calib._is_routed_expert). Their weight scales would be merged over ranks holding different experts;

  • Count: a count neither the config nor the experts' weights show divisible by ep_size. transformers keeps the whole count on the DTensors it shards the experts into, from 5.16;

  • Share: a rank holding another share of the experts than ep_size gives it, so the all-to-all transport would send tokens to ranks without their experts. That happens to experts left whole on every rank, or sharded over another mesh (a mesh-builder patch that stopped applying); weights that show no share at all are refused too;

  • Not quantizable on the transport: experts the grouped quantization cannot run on the transport's forward, under any of three conditions:

    • they are stored transposed (GPT-OSS's), which it leaves unquantized;
    • they have a quant wrapper of their own (Llama4's), whose forward drops the transport's process group;
    • their fused-experts wrapper quantizes on the eager forward only (FP8's).

    ModelOpt's generic fused-experts wrapper is no bar.

The checks run inside #3136's _refused_together block around the load, so a rank refusing alone fails every rank, and the share check needs no collective of its own.

The transposed and eager-only rules are quantization's own. They become one helper each in the HF quantization plugin (_transposed_experts, _eager_only_experts), which register_fused_experts_on_the_fly and normalize_experts_impl_on_the_fly now use too, so the load and quantization cannot drift apart. The eager-only rule is the registry lookup alone (#3067): the on-the-fly registration adds only the generic wrapper.

Usage

Automatic: load_and_prepare_ep (#3136) runs these checks after every load.

Testing

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ Additive; the HF plugin refactor keeps quantization's behaviour.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: N/A. The feature's entry lands with [OMNIML-6085] [3/3] Run expert-parallel PTQ from hf_ptq.py #2754.
  • Did you get Claude approval on this PR?: Approved 2026-10-28 on the unsplit PR; re-review requested 2026-10-30 for this slice.

Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models. Merge order: #3131 → #3136 → this PR. #2780, which routes load_pretrained to the loader, has merged.

@copy-pr-bot

copy-pr-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

The change adds an expert-parallel model loader with separate dense and expert meshes. It configures torch_a2a routing, quantization handling, Transformers loading, and distributed state. Unit and GPU tests cover loader behavior, expert sharding, and output comparisons.

Changes: Expert-Parallel Loading

Layer / File(s) Summary
Loader contracts and model selection
modelopt/torch/utils/moe.py, modelopt/torch/utils/plugins/model_load_utils.py, tests/unit/torch/utils/test_resolve_distribution_plan.py
Adds Transformers version and expert-mesh helpers. _auto_class can select AutoModel when a VLM does not require an LM head.
Expert-parallel loading setup
modelopt/torch/utils/plugins/model_load_utils.py
Adds load_and_prepare_ep with plan, process-group, and world-size checks. It builds dense and expert meshes, configures Transformers loading and torch_a2a routing, handles MXFP4 dequantization, records unplaced checkpoint keys, and prepares model and calibration parallel state.
Loader validation and distributed output tests
tests/unit/torch/utils/test_ep_loader.py, tests/unit/torch/conftest.py, tests/unit/torch/utils/test_meta_dcp_load.py, tests/gpu/torch/utils/test_expert_parallel_load.py
Adds unit tests for loader validation, expert wrapper handling, mesh selection, quantization lookup, and mesh-builder restoration. GPU tests verify expert shards, checkpoint metadata, and sharded-model outputs. The one-rank Gloo fixture is shared through conftest.py.

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Loader as load_and_prepare_ep
  participant ProcessGroup
  participant DeviceMesh
  participant Transformers
  Caller->>Loader: Provide checkpoint and expert-parallel plan
  Loader->>ProcessGroup: Check initialization and world size
  Loader->>DeviceMesh: Build dense and expert-parallel meshes
  Loader->>Transformers: Load checkpoint with EP mesh and configuration
  Transformers-->>Loader: Return loaded model
Loading
Merge Risk: Low · previous review cbb1e

Sequential EP and ordinary Llama4 workflows can produce incompletely quantized models. Isolate the EP wrapper exclusion before merging, or accept this bounded risk with a separate-process workaround.

Pre-merge checks: Passed 5
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The PR changes only two modelopt Python files and no examples. The diff adds trust_remote_code with default False and passes that caller value to Transformers; it does not add `trust_remote_…
Title check Passed The title clearly describes the expert-parallel loading safeguard implemented by the changes, including refusal of loads that could calibrate experts incorrectly.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Security Anti-Patterns

Explanation

PASS. The PR changes only two modelopt Python files and no examples. The diff adds trust_remote_code with default False and passes that caller value to Transformers; it does not add trust_remote_code=True. No added torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), external-input eval()/exec(), or # nosec appears. pyproject.toml and requirements.txt are unchanged.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Fix failing CI checks
  • 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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@shengliangxu
shengliangxu added this pull request to stack #2755 October 12, 2026 00:57
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-5-distributed-calibration branch from 7f91f94 to 963e78a Compare October 12, 2026 02:24
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-6a-ep-loader branch from 758dca6 to 5c154cc Compare October 12, 2026 02:24
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-11-03 19:22 UTC

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 5c154cc

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.32%. Comparing base (b002695) to head (01f034c).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2741      +/-   ##
==========================================
+ Coverage   72.18%   80.32%   +8.14%     
==========================================
  Files         677      677              
  Lines       78443    78466      +23     
==========================================
+ Hits        56621    63030    +6409     
+ Misses      21822    15436    -6386     
Flag Coverage Δ
examples-diffusers 19.61% <12.00%> (-0.20%) ⬇️
examples-gpt-oss 13.30% <8.00%> (-0.17%) ⬇️
examples-hf_ptq 23.43% <28.00%> (-0.06%) ⬇️
examples-llm_distill 13.36% <8.00%> (-0.16%) ⬇️
examples-llm_eval 17.28% <16.00%> (-0.09%) ⬇️
examples-llm_qat 17.17% <12.00%> (-0.22%) ⬇️
examples-llm_sparsity 16.64% <12.00%> (-0.09%) ⬇️
examples-megatron_bridge 26.01% <12.00%> (-0.62%) ⬇️
examples-specdec_bench 13.08% <8.00%> (-0.15%) ⬇️
examples-speculative_decoding 17.51% <16.00%> (-0.04%) ⬇️
examples-torch_onnx 20.85% <12.00%> (-0.26%) ⬇️
examples-torch_trt 15.02% <12.00%> (-0.17%) ⬇️
examples-vllm_serve 17.38% <16.00%> (-0.10%) ⬇️
gpu 58.35% <28.00%> (+36.51%) ⬆️
regression 14.80% <8.00%> (-0.17%) ⬇️
unit 63.19% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-6a-ep-loader branch from 5c154cc to e1ef1d1 Compare October 12, 2026 08:39
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test e1ef1d1

@shengliangxu shengliangxu changed the title [6/19] Load an MoE expert-parallel: shard the experts at load time [OMNIML-6060] [6/19] Load an MoE expert-parallel: shard the experts at load time Oct 12, 2026
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-6a-ep-loader branch from e1ef1d1 to fbdcd0c Compare October 13, 2026 00:53
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-5-distributed-calibration branch 2 times, most recently from c3ccb86 to 96159d7 Compare October 13, 2026 01:32
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-6a-ep-loader branch from fbdcd0c to 288db20 Compare October 13, 2026 01:32
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 288db20

@shengliangxu
shengliangxu removed this pull request from stack #2755 October 13, 2026 17:42
@shengliangxu
shengliangxu added this pull request to stack #2775 October 13, 2026 17:43
@shengliangxu shengliangxu changed the title [OMNIML-6060] [6/19] Load an MoE expert-parallel: shard the experts at load time [OMNIML-6060] [6/20] Load an MoE expert-parallel: shard the experts at load time Oct 13, 2026
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-6a-ep-loader branch from 288db20 to ac84840 Compare October 13, 2026 19:38
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-5-distributed-calibration branch from 96159d7 to 540716e Compare October 13, 2026 19:38
@shengliangxu
shengliangxu removed this pull request from stack #2775 October 13, 2026 19:38
@shengliangxu
shengliangxu added this pull request to stack #2781 October 13, 2026 19:40
@shengliangxu shengliangxu changed the title [OMNIML-6060] [6/20] Load an MoE expert-parallel: shard the experts at load time [OMNIML-6060] [7/21] Load an MoE expert-parallel: shard the experts at load time Oct 13, 2026
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test ac84840

@shengliangxu
shengliangxu removed this pull request from stack #2781 October 14, 2026 00:13
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-6a-ep-loader branch from ac84840 to 95781ac Compare October 14, 2026 00:14
@shengliangxu
shengliangxu added this pull request to stack #2786 October 14, 2026 00:14
@shengliangxu shengliangxu changed the title [OMNIML-6060] [7/21] Load an MoE expert-parallel: shard the experts at load time [OMNIML-6060] [8/22] Load an MoE expert-parallel: shard the experts at load time Oct 14, 2026
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-5-distributed-calibration branch from 177c692 to 6e21d0a Compare October 14, 2026 01:47
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test b42e86c

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test caf9b01

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 9f7e896

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 5b3b34b

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test be0727e

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test e497337

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test a098c4b

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 740ba93

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 6e098d5

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 0b56bf9

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

LGTM: every earlier concern is resolved and the five post-load refusals are correct and tested. A human needs to sign off only because an existing test was edited, and the diff justifies that edit.

Needs action:

  • Sign off on the edit to test_a_load_failing_on_one_rank_fails_every_rank in tests/unit/torch/utils/test_model_load_utils.py. num_experts goes from 4 to 8 because the stand-in model holds 4 experts per rank at ep_size=2, and the new share check needs the whole count. The edit also adds a share row and updates the docstring. No assertion is loosened.
  • Optional: add the clause you promised to the _transposed_experts docstring in quantization/plugins/huggingface.py. For a non-gated container only is_transposed is read, so its own wrapper must assert the layout.

No action needed:

  • ✔️ Resolved since the last review: the split into #3131, #3136 and this PR; the one-rank hang (the checks now run inside #3136's _refused_together load block and have a share test row); the module-top imports that bypassed import_plugin (moved back into the functions and covered by a regression test); and reading a one-shot iterable twice (now a tuple).
  • I read load_and_prepare_ep in full at this head. num_experts, ep_degree, plan and DTensor are all in scope. The _transposed_experts and _eager_only_experts extractions keep behaviour unchanged at both call sites, since the wrapper is not None guard is kept.
  • The PR adds about 149 lines of core logic, well under the budget.

@kevalmorabia97 kevalmorabia97 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. Prior review items are addressed; unit tests pass and mutating the new checks fails their tests. Optional: add the promised _transposed_experts docstring clause (non-gated containers read only is_transposed).

@kevalmorabia97 kevalmorabia97 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One required doc fix; no code issues found.

Required

  • modelopt/torch/quantization/plugins/huggingface.py:1699: add the _transposed_experts docstring clause you promised in the earlier thread, that for a non-gated container only is_transposed is read.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test c0059c5

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

@kevalmorabia97 Added in c0059c5. The _transposed_experts docstring now says that a non-gated container (up_proj, as Nemotron-H's) matches no _fused_experts_wrapper, so only its is_transposed is read, and its own wrapper is responsible for the layout. It is a docstring-only change.

@kevalmorabia97 kevalmorabia97 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. The _transposed_experts docstring clause is in; no other changes since my last review.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 01b7fcf

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test df567f8

Quantization decides in two places which fused experts it cannot run on
the grouped forward: experts stored transposed, which it leaves
unquantized, and experts whose wrapper quantizes on the eager forward
only, which keep the forced eager backend. Each rule is now one helper,
_transposed_experts and _eager_only_experts, which
register_fused_experts_on_the_fly and normalize_experts_impl_on_the_fly
use, so the expert-parallel load can refuse exactly what quantization
would get wrong. The eager-only rule is the registry lookup alone: the
on-the-fly registration only adds the generic wrapper, which is not
eager-only. No behaviour changes.

Signed-off-by: Shengliang Xu <[email protected]>
Once the experts load, every rank checks what calibration relies on and
refuses a load that would run without an error but compute or calibrate
wrong:
- a plan whose expert containers match no module of the loaded model;
- containers calibration would not take for routed experts by name;
- a count neither the config nor the experts' weights show divisible by
  ep_size;
- a rank holding another share of the experts than ep_size gives it;
- experts quantization cannot run on the transport's grouped forward:
  stored transposed, or under a wrapper of their own or an eager-only one.

The checks run inside the load's _refused_together block, so a rank
refusing alone fails every rank; the share check no longer needs its own
all_reduce. The quantization rules and _is_routed_expert are imported at
the top of the module.

A two-rank test row has rank 1 alone hold half its share: every rank
raises its refusal, which fails without the block.

Signed-off-by: Shengliang Xu <[email protected]>
The HF quantization plugin loads under import_plugin's guard, so a
transformers it cannot load is a warning and the other loaders keep
working. Importing it at the top of model_load_utils made that a hard
failure for load_pretrained, fsdp2_wrap and record_unplaced_source_keys,
none of which need it. The plugin's two rules are imported inside
_refuse_unquantizable_experts again, and _is_routed_expert next to the
check that uses it, as fsdp2_wrap imports the quantization package where
it needs it. A test imports the module with the plugin unavailable; it
fails with the imports at the top.

Signed-off-by: Shengliang Xu <[email protected]>
entry under it before anything loads, so this test's container-only plan
no longer reached the refusal it checks. Its plan now shards the
container's gate_up_proj through grouped_gemm, as a real plan does.

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

The unquantizable-experts refusal reads its experts twice, once per rule,
so it takes them as a tuple: a one-shot iterable would let the second
rule pass on nothing. The share check's comment says it compares counts,
catching a wrong share rather than a same-size mesh, and its test row is
named for the mesh of another size it builds.

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

It refuses them, and leaves the quant-wrapper registry alone, rather than
keeping them out of ModelOpt's per-expert wrappers.

Signed-off-by: Shengliang Xu <[email protected]>
record_unplaced_source_keys returns a sorted list, which a later check
iterates; these tests' stand-ins returned None.

Signed-off-by: Shengliang Xu <[email protected]>
_transposed_experts finds a transposed gated container by its shapes, but
a non-gated one (up_proj, as Nemotron-H's) matches no
_fused_experts_wrapper, so only its is_transposed flag is read and its own
wrapper is responsible for the layout. The docstring now says so, as
promised in review. Docstring only.

Signed-off-by: Shengliang Xu <[email protected]>
With #2780 in main, load_and_prepare_ep looks up the model spec by
hf_config.model_type before it loads. The stand-in configs of
test_routed_experts_without_experts_in_their_names_are_refused and of
test_an_expert_count_the_config_does_not_name_is_read_off_the_loaded_experts
named none, so all 7 cases raised AttributeError instead of reaching the
refusals they test. They now name _NO_SPEC, as main's other load test
doubles do. Test only.

Signed-off-by: Shengliang Xu <[email protected]>
With #3137 in main, load_and_prepare_ep passes tensor_files= to
record_unplaced_source_keys. The stand-ins of
test_routed_experts_without_experts_in_their_names_are_refused and of
test_an_expert_count_the_config_does_not_name_is_read_off_the_loaded_experts
took positional arguments only, so all 7 cases raised TypeError instead
of reaching the refusals they test. They take keywords too now, as main's
other stand-ins do. Test only.

Signed-off-by: Shengliang Xu <[email protected]>
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 01f034c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants