Skip to content

[OMNIML-6082] [2/3] Move each tensor of a sharded model whole to one owner rank - #3101

Merged
shengliangxu merged 6 commits into
mainfrom
shengliangx/hfep-12b2-writer-transport
Oct 29, 2026
Merged

shengliangxu merged 6 commits into
mainfrom
shengliangx/hfep-12b2-writer-transport

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Note

[2/3] of #2751's split (2026-10-29), at its review's request: [1/3] #3100 (the reverse conversion's hook), [2/3] this PR (ownership and transport), and [3/3] #2751 (reverse conversion and shard writing). Merge in that order.

Base: main. [1/3] #3100 merged on 2026-10-29 (8ab63386152), and this PR was rebased onto it with its own diff unchanged.

What does this PR do?

Type of change: New feature (part of the no-gather distributed export)

This is the first part of a checkpoint writer for sharded models (FSDP2 and expert parallelism) in which every tensor moves once, whole, to one owner rank and is written from there (modelopt/torch/export/distributed_writer.py).

Main's FSDP2 export already writes each rank's share, but each FSDP2 unit is first unsharded in turn, an all-gather of that unit to every rank. It also refuses conversion mappings that merge or split tensors, since one unit at a time cannot regroup them, and it does not handle expert-parallel shards. Here no rank all-gathers anything, and the tensors a merge needs end up together, so the reverse conversion in [3/3] can run.

_materialize_owned:

  • Owner assignment: gives each dense tensor one owner, largest first onto the lightest rank, seeded with each rank's expert bytes. Each group a merge needs (together) goes to one owner as a unit.

  • Transport:

    • dim-0 shards travel once, to their owner, over batched point-to-point sends bucketed by (peer, dtype), so the operation count is O(world × dtypes), not O(keys × peers). Both sides build the buckets from the same sorted keys and owner map, so every send meets a receive of its length. Rounds of at most 4096 keys bound how many keys one transfer carries;
    • replicated and plain tensors are unwrapped by their owner and dropped elsewhere;
    • an empty tensor is created by its owner.

    The send buffers are freed before a rank assembles what it owns: the ops and their requests hold them, and they are dropped inside _run_to_completion. On top of the shards it is handed, which the model keeps, a rank therefore holds in each round copies of its shards of keys other ranks own plus the shards it receives, and then those received shards plus the tensors assembled from them. With balanced shards that is about twice its owned set; a layout that puts most rows on one rank (four one-row tensors over four ranks) makes that rank's outgoing copies the larger part. The mesh check is memoized per mesh: FSDP2 gives every parameter the same mesh, so a few hundred keys would otherwise each redo it.

  • NCCL initialization: before the first transfer, every rank runs a one-element all-reduce on the transport's device. A batched P2P that is NCCL's first call on a group needs every rank of the group, and on the cpu:gloo,cuda:nccl group the setup creates, the metadata collective runs on Gloo, so a transfer only some ranks take part in could otherwise be that first call.

  • Refusals: an unsupported placement, shards that do not tile their global shape, an expert still a DTensor, dim-0 shards on more than one device type (a CPU-offloaded shard beside one on the accelerator), and ranks that disagree on keys, on a shard's dtype or device, on a whole tensor's dtype or shape, or on groups are all refused. Every refusal is decided from one gathered metadata collective, so it is the same on every rank.

Also here, the one-rank gloo world the meta-DCP load tests used moves to the shared tests/unit/torch/conftest.py, in the same text #3099 adds.

Usage

Internal to the no-gather export (#2752).

Testing

  • tests/unit/torch/export/test_distributed_writer.py, on CPU under gloo:

    • sizes and the placement check;
    • every tensor whole and plain after ownership;
    • each unsupported layout refused, on every rank;
    • two ranks moving uneven and empty shards of two dtypes, with what a rank sent freed before it assembles.
  • tests/gpu/torch/export/test_distributed_writer_gpu.py runs on every visible GPU, from two. It moves BF16, FP8 and packed-NVFP4 uint8 shards of uneven and empty extent, a tensor with no rows, a replicated and a plain tensor over NCCL, and checks each ends whole, byte for byte, on exactly one rank. The same logic passes on two gloo ranks locally; GPU runs are requested.

  • These tests come from [OMNIML-6082] [3/3] Write a sharded model's HF checkpoint shards from each tensor's owner rank #2751's reviewed suite, moved here with their code. 43 pass locally, and pre-commit passes against main.

  • GPU runs on GB200 of test_distributed_writer_gpu.py, ran at b4baa594bdf (the transport code is unchanged since; only docstrings and tests changed):

    GPUs Result Time
    1 skipped (needs two GPUs) 0.5 s
    2 passed 21.1 s
    4 passed 23.2 s
  • Transport measured on GB200 with a synthetic sharded state dict: 600 keys of shape (8741, 4096), 360 BF16, 150 FP8 e4m3 and 90 uint8, 32.0 GiB in total. 8741 rows divide by neither 4 nor 8, so the dim-0 shards are uneven. _materialize_owned(sd, set(), rank, world) ran at [OMNIML-6082] [3/3] Write a sharded model's HF checkpoint shards from each tensor's owner rank #2751's f577fc05af0, whose transport is this PR's. Rank 0 is shown; all ranks were near-identical.

    GPUs Input per rank Owned per rank Transport Peak device memory above the input
    4 (one node) 8.01 GiB 8.00 GiB 6.22 s 12.01 GiB
    8 (two nodes × 4) 4.00 GiB 4.00 GiB 14.15 s 7.01 GiB

    The peak is torch.cuda.max_memory_allocated() after reset_peak_memory_stats, minus the allocation before the transport. During the transfer a rank holds a send buffer and a receive buffer per (peer, dtype):

    • the send buffers copy its shards of the tensors other ranks own, (w-1)/w of its input;
    • the receive buffers hold the other ranks' shards of the tensors it owns, (w-1)/w of its owned set.

    Their sum is the measured peak at both sizes. In this run the state dict held the only reference to each input shard, so a rank freed its inputs as it assembled. The 8 GPUs span two nodes, so that time includes cross-node traffic and does not scale like-for-like against the one-node run.

  • Re-measured at [OMNIML-6082] [3/3] Write a sharded model's HF checkpoint shards from each tensor's owner rank #2751's 239260c7d8d (same transport code) with the input DTensors kept alive, as the model keeps its parameters in a real export. Same state dict and hardware:

    GPUs Owned per rank Transport Peak device memory above the input (transport, and the write that follows)
    4 (one node) 8.00 GiB 6.83 s 14.01 GiB
    8 (two nodes × 4) 4.00 GiB 14.76 s 7.51 GiB

    The peak now comes from the assembly: the receive buffers, (w-1)/w of the owned set, plus the assembled owned tensors. Their sum is the measured peak at both sizes, within the docstring's bound of about twice the owned set.

  • Review round, 2026-10-29 (46e42e10a74, rebased onto [OMNIML-6082] [1/3] Let a reverse conversion record a merge rule no key matched #3100's b9fbb242300): the two-rank test checks that two merge groups sharing a key end on one owner, where byte balancing alone would split them; a _StridedShard on dim 0 is pinned as refused (in torch>=2.10 it is not a Shard, so it was already refused); the docstrings keep the constraints, and the cost derivations moved here. Pre-commit passes against main; test_distributed_writer.py passes (16).

  • Review round 2, 2026-10-29 (055b57bd7cf, cjluo-nv's review bot):

    • Dim-0 shards on more than one device type are refused on every rank before anything moves; so is a key whose ranks disagree on its dtype or device. A round's transfers are one batch, which cannot mix devices.
    • Every dense tensor's dtype and shape are compared across ranks, not only its byte count.
    • Each round of transfers runs in a helper, so its receive buffers are freed before the next round starts.
    • The refusal test gains a shard on another device on one rank, shards on two device types, and three whole-tensor disagreements at equal byte counts (dtype, shape, empty shapes). The transfer test runs rounds of two keys and checks that no earlier round's receive buffer is alive when the next starts. Each fails without its change.
    • test_distributed_writer.py passes (21), and pre-commit passes against main. The transport's GPU test was re-run at this round's head; see below.
  • GPU run, 2026-10-29, ran at 055b57bd7cf (the same code as the rebased head ba9f1c5773b). GB200, torch 2.11.0a0 (NGC 26.02), transformers 5.9.0:

    tests/gpu/torch/export/test_distributed_writer_gpu.py (1 test) 1 GPU 2 GPUs 4 GPUs
    Result skipped (needs 2 or more) passed, 22.3 s passed, 24.0 s
  • Rebased on 2026-10-29 onto main 2b900c8fa41 (the [hf] floor bump and the QAT Diffusers-attention fix), own diff unchanged.

  • Review round 3, 2026-10-29 (bb80474fe8f, b73c052e45f; cjluo-nv's review bot):

    • Every rank initializes NCCL with a one-element all-reduce on the transport's device before the first transfer. A new GPU test, test_a_first_transfer_most_ranks_sit_out_finishes_on_a_fresh_group, spawns a fresh cpu:gloo,cuda:nccl group on 3 or more GPUs, runs no collective on it first, and transfers a two-row tensor that only ranks 0 and 1 hold. A rank stuck in NCCL's initialization exits through a watchdog, so the test fails instead of hanging. Its logic passes on three gloo CPU ranks; its GPU run is below.
    • The docstring's memory bound names a rank's outgoing shard copies as well as what it receives and assembles; with skewed dim-0 shards, the outgoing copies can exceed the owned set.
    • Pre-commit passes against main; test_distributed_writer.py passes (21).
  • GPU runs, 2026-10-29, at b73c052e45f (cjluo-nv's review bot asked for the fresh-group test with and without the NCCL initialization). GB200, torch 2.11.0a0 (NGC 26.02), CUDA 13.1, NCCL 2.29.2, transformers 5.9.0.

    test_a_first_transfer_most_ranks_sit_out_finishes_on_a_fresh_group, on 4 GPUs:

    Arm Result
    With the NCCL initialization (b73c052e45f) passed, 23.2 s
    Same head with only the initialization removed (84548cd6d4c) failed, 75.8 s: a rank exited non-zero through the 60 s watchdog

    The file's pool-based tests:

    test_distributed_writer_gpu.py 2 GPUs 4 GPUs
    Result 1 passed, 1 skipped (the fresh-group test needs 3 or more), 21.5 s 2 passed, 44.0 s
  • Review (juhi10071998), 2026-10-29 (764036cd64e): the docstring says ranks are weighed by bytes, not free device memory, so a large embedding or lm_head must fit on its owner. Docstring only; pre-commit passes against main.

Before your PR is "Ready for review"

Additional Information

Split out of #2751, part of the expert-parallel PTQ series for Hugging Face MoE models.

Summary by CodeRabbit

  • New Features
    • Distributed checkpoint materialization can assemble supported sharded tensors into full tensors without gathering all data onto one rank.
    • Dense tensors are assigned to a single rank, while replicated and ordinary tensors are handled locally. Supported dimension-0 shards, including uneven and empty shards, are combined in rank order.
    • Expert tensors remain on their existing ranks, and assembled tensors are retained by their assigned owner.
  • Bug Fixes
    • Unsupported layouts and inconsistent tensor metadata now produce errors instead of being assembled incorrectly.

@shengliangxu
shengliangxu requested review from a team as code owners October 29, 2026 00:14
@shengliangxu
shengliangxu requested review from sugunav14 and removed request for a team October 29, 2026 00:14
@coderabbitai

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 b73c052 and 764036c.

Files selected for processing: 1
  • modelopt/torch/export/distributed_writer.py
Files skipped from review as they are similar to previous changes: 1
  • modelopt/torch/export/distributed_writer.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 pull request adds a distributed checkpoint materializer. It validates tensor metadata across ranks, assigns dense tensors and merge groups to owners, and transfers supported dimension-0 shards in bounded rounds. Unit and GPU tests cover materialization, ownership, transfer behavior, and invalid inputs.

Changes: Distributed tensor materialization

Layer / File(s) Summary
Classification and collective validation
modelopt/torch/export/distributed_writer.py, tests/unit/torch/export/test_distributed_writer.py, tests/unit/torch/conftest.py, tests/unit/torch/utils/test_meta_dcp_load.py
The writer adds tensor and mesh helpers and checks rank agreement on keys, layouts, devices, shapes, dtypes, and merge groups. Unit tests cover helper behavior and invalid inputs. The one-rank Gloo fixture is defined in shared torch test configuration and removed from the meta DCP test module.
Dense ownership and local materialization
modelopt/torch/export/distributed_writer.py, tests/unit/torch/export/test_distributed_writer.py
The writer assigns dense units to ranks by size and current load, including expert bytes in the initial load. Owners retain plain tensors, unwrap replicated tensors, or create empty tensors; other ranks drop their copies.
Shard transfer and assembly
modelopt/torch/export/distributed_writer.py, tests/unit/torch/export/test_distributed_writer.py, tests/gpu/torch/export/test_distributed_writer_gpu.py
The writer transfers supported dimension-0 shards in batched flat buffers and concatenates them on owners in rank order. Unit and GPU tests check assembled values, unique ownership, sparse transfers, and buffer release.

Priority: Normal

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

Change: Feature

Possibly related issues

Merge Risk: Minimal · up to 76403

No actionable risk introduced by this PR remains. The existing export paths do not expose the previously reported companion-scale scenario.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: moving each tensor of a sharded model whole to a single owner rank. It matches the distributed writer ownership and transport work described in the summary and objecti…
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 adds one modelopt Python file and test-only Python changes. The added modelopt code contains no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), hardcoded trust_re…
Full details: Title check

Explanation

The title names the main change: moving each tensor of a sharded model whole to a single owner rank. It matches the distributed writer ownership and transport work described in the summary and objectives. It also carries the [OMNIML-6082] [2/3] tracking prefix, which is acceptable. The title is a single, specific sentence and does not use vague terms.

Full details: Security Anti-Patterns

Explanation

PASS. The PR adds one modelopt Python file and test-only Python changes. The added modelopt code contains no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), hardcoded trust_remote_code=True, eval(), exec(), or # nosec. The diff adds no pyproject.toml or requirements.txt dependencies.

Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. 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 16 functions across 4 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

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

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

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test b4baa59

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

pending.append((srcr, ks, buf))
ops.append(dist.P2POp(dist.irecv, buf, srcr))

_run_to_completion(ops)

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 Performance] Non-owned local shards stay alive through the transfer, so the peak is higher than the docstring claims

torch.cat(...) at line 121 already copies every shard this rank owes a peer into the send buffer, so from that point the source local_sd[k] entries for owner[k] != rank are dead weight — but they are only dropped in the assembly loop at line 143, after the recv buffers are allocated and the transfer has run.

Peak therefore holds, concurrently: all local shards of the chunk (L), the send copies (≈ L·(world-1)/world), and the recv buffers (R). The docstring at line 169 says "A rank holds at most about twice its owned set: the shards it receives and the tensors assembled from them", which accounts for R + O but not the L + sends that coexist with R. Since L and the owned set are both ≈ model/world, the real peak is closer to 3× the per-rank share than 2×. For a feature whose whole value is the memory bound, I'd either correct the docstring or tighten the actual peak.

Tightening is cheap — after the send ops are built and before the recv buffers are allocated, nothing in the chunk needs the non-owned sources any more:

        # Packed into the send ops above, so the sources are dead: drop them before the recv
        # buffers are allocated, rather than after the transfer.
        for k in part:
            if owner[k] != rank:
                del local_sd[k]

        for srcr, dt in sorted(recv_groups, key=lambda kd: (kd[0], str(kd[1]))):
            ...

with the if owner[k] != rank: del local_sd[k]; continue at lines 142-145 then reducing to if owner[k] != rank: continue. Note the recv-buffer device at line 127 is taken from local_sd[ks[0]], which is a key this rank owns, so it is unaffected by the earlier deletion.

The existing two-rank test already measures live send storages at each assembled store; extending it to assert the non-owned sources are gone before assembly would pin the tighter bound.

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.

I'm not changing the transport here.

The values _materialize_owned receives are views of the model's own parameters: #2752 takes them from get_model_state_dict, and the model keeps them. Deleting them from the dict earlier therefore frees nothing in the export. The docstring's bound counts what the transport holds on top of those shards, and 46e42e1 makes the docstring say so.

Measured on GB200 with a 32 GiB synthetic sharded state dict:

  • 600 keys of shape (8741, 4096): BF16, FP8 and uint8.
  • Uneven dim-0 shards.
  • Timed _materialize_owned at the head before this round. The transport code is unchanged since.
GPUs Owned per rank Transport Peak device memory above the input
4 (one node) 8.0 GiB 6.2 s 12.0 GiB
8 (two nodes) 4.0 GiB 14.2 s 7.0 GiB

During the transfer, a rank holds one send buffer and one receive buffer per (peer, dtype):

  • The send buffers copy its shards of the tensors other ranks own, which is (w-1)/w of its input.
  • The receive buffers hold the other ranks' shards of the tensors it owns, which is (w-1)/w of its owned set.

That is 6 + 6 GiB at 4 GPUs and 3.5 + 3.5 GiB at 8, as measured, and within the docstring's bound.

) -> None:
"""Make every tensor in ``local_sd`` whole and owned by exactly one rank, in place.

Experts are already whole, plain and disjoint per rank; one still a DTensor is refused. Each

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] Expert disjointness is assumed but, unlike every other cross-rank precondition here, not refused

The docstring states experts are "whole, plain and disjoint per rank", and the function does check two of those three from the metadata collective: still-a-DTensor is refused (m[6], line 232), and wholeness follows from plainness. Disjointness is the one that is only asserted in prose.

It is violable in a configuration this series targets. In an EP × FSDP hybrid with EP group size < world size — world 8, EP 4, FSDP 2 — each expert tensor lives on two ranks. _materialize_owned leaves every expert exactly where it is on every rank, so both ranks would carry that key into the write, and [3/3] would emit the same tensor into two shard files with one index.json entry. That is a silently duplicated/ambiguous checkpoint, in a function whose stated design is to refuse anything it cannot handle from the single gathered metadata rather than risk a bad write.

I am filing this as a suggestion rather than a blocker because nothing calls this yet and the caller arrives in [3/3] — a global key→file index built there has to gather every key anyway and would surface the duplicate. Two reasonable resolutions:

  • Cheapest: reword the docstring from a description into an explicit precondition on the caller ("the caller must guarantee expert_key_set members are held by exactly one rank; not checked here"), and note where it is enforced.
  • Or check it: the gather already carries sum(_nbytes(...)) over experts (m[1]). Adding a per-rank expert key count plus a stable digest of the sorted expert key list lets you refuse when the summed counts exceed the union — without paying the O(world × experts) string payload that gathering the full expert key sets would cost on a 128-expert MoE.

Either way the reader learns whether this is guarded or delegated; right now the sentence reads as a guarantee the code does not make.

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 now states this as the caller's precondition (46e42e1): experts must come whole, plain and disjoint per rank, as the caller splits them.

The refusal does exist, in [3/3] (#2751). _write_even_shards gathers every rank's key list in its first collective and refuses a name held by more than one rank before any file is written. A duplicated expert fails there, on every rank, at no extra cost. That is the global key check you describe, and it covers dense keys as well.

@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 — [2/3] Move each tensor of a sharded model whole to one owner rank

Findings: CRITICAL 0 · IMPORTANT 1 · SUGGESTION 4

Scope. Full review (trigger comment carried no scoping instructions). 5 files / +695 −9; I read all of them — modelopt/torch/export/distributed_writer.py in full, plus both new test files and the two test-infra moves. No prior Claude review on this PR to dedupe against; CodeRabbit auto-review is disabled on this non-default base branch, so nothing was skipped as already-covered.

Most impactful finding

is_shard(0) accepts _StridedShard (line 45) — IMPORTANT. _StridedShard subclasses Shard, so is_shard(0) is true for it, and a strided placement on a 1-D full-world mesh passes the gate into shard0. Its chunks interleave by split_factor rather than sitting contiguously at rank offsets, but the tiling check only verifies the dim-0 extents sum to the global dim 0 — a strided layout tiles just as well. So assembling with torch.cat(pieces, dim=0) in rank order yields a silently row-permuted tensor, which is the one outcome the module's own docstring says it refuses to risk. Reachability is narrow (the 2-D-mesh and full-world-mesh checks already catch FSDP2+TP and FSDP sub-meshes), but the failure mode is unrecoverable corruption rather than an error, and the fix is to make the check exact instead of subclass-tolerant.

The four suggestions: the real memory peak is ~3× the per-rank share rather than the ~2× the docstring claims, and dropping non-owned sources right after torch.cat packs them would actually buy the tighter bound; together's happy path is untested (only its disagreement refusal is); expert disjointness is asserted in prose but, unlike the other preconditions, not refused; and a third of the file is prose, some of it cost derivations that CONTRIBUTING.md places in the PR description.

What I checked and found correct

The cross-rank reasoning is the risky part of this change and it holds up:

  • Every refusal is symmetric. For the key-set, dim-0-classification, size and grouping checks, each rank compares the gathered values against its own. If the values are not all equal then every rank necessarily finds a differing peer, so all of them raise — no rank is left in a collective its peer never joins. The cpu_dist_workers suite covers this on both the agreeing and the disagreeing rank for all seven cases.
  • Send/recv buckets pair exactly. Sender (owner[k], dtype) groups and the owner's (src, dtype) groups are built from the same sorted key list, the same owner map and the same all_shapes emptiness test, both sorted by (peer, str(dtype)). Element counts match by construction (sum(_numel(all_shapes[sender][k])) on both sides), the dtype equality the buffer sizing depends on is refused up front, and the (peer, dtype) bucket is one op per side so in-order p2p matching per pair is preserved even with two dtypes between the same ranks.
  • Chunk boundaries are aligned. shard0 is derived from sorted dense_keys and its membership is verified across ranks, so the chunk = 4096 rounds are identical everywhere — no rank runs a transfer round its peer skipped.
  • Assembly order is shard order. _is_full_world_shard0 pins mesh.mesh == range(world), so global-rank order is mesh order and the torch.cat reproduces what full_tensor() would have built. The padded-chunk hazard is caught by the tiling check (short-circuits correctly when ranks disagree on the global shape, so a multi-element gshapes cannot produce a false pass), and empty shards are skipped symmetrically on both sides rather than concatenated.
  • Owner assignment is deterministic. The unit sort (-bytes, u) and the min key (loads[i], i) both break ties explicitly, over inputs (dense_sizes, expert_bytes, merged_units) that are all verified identical — so no tensor can be dropped everywhere or claimed twice.
  • The together union pass is transitively correct. The new unit is the union of every member's old unit and all of its members are rewritten, so [A,B], [C,D], [B,C] collapses to one unit regardless of group order.
  • No host syncs on the metadata path. _nbytes, numel() == 0 and placements are all metadata; the one tensor read (mesh.mesh.tolist()) is CPU and memoized. Freeing the send buffers right after req.wait() is safe under NCCL because ProcessGroupNCCL::pointToPoint calls recordStream on them, so the caching allocator defers reuse.
  • torch.distributed.tensor is fine against the declared torch>=2.10; the module is intentionally absent from export/__init__.py's star imports (all-private, no caller yet), and the gloo_world_of_one move to tests/unit/torch/conftest.py is a clean lift that keeps the meta-DCP tests working while adding the CPU mesh the new tests need.

Risk

Low-to-moderate. Additive and unreferenced, so nothing regresses today; the GPU test covers BF16/FP8/packed-uint8, uneven and empty shards, a no-row tensor, replicated and plain over NCCL, and the CPU suite covers the refusals on every rank. The residual risk is concentrated in the one placement gate above — this code's contract is "refuse anything not exactly Shard(0) on a full-world 1-D mesh", and that gate is currently one subclass wider than the contract. Worth closing before [3/3] starts depending on the transport.

🤖 Generated with Claude Code

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 46e42e1

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

Thanks. Here is what each item became; it is pushed as 46e42e1, rebased onto #3100's b9fbb24.

  • IMPORTANT, _StridedShard: already refused. In torch>=2.10, _StridedShard is bound on Placement, not on Shard, and is_shard(0) is False for it. The case you suggested is now in the refusal test. Details are in the thread.
  • Memory peak: the transport is unchanged. Its inputs are views of the model's parameters, so dropping them earlier frees nothing in the export. The docstring now says its bound is on top of those shards. A GB200 measurement is in the thread and the description.
  • together's happy path: now tested in the two-rank job, and mutation-checked.
  • Expert disjointness: the docstring now states it as the caller's precondition. [3/3] refuses a key held by two ranks before writing.
  • Docstring length: trimmed. The cost derivations moved to the description.

@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 — [2/3] Move each tensor of a sharded model whole to one owner rank

Claude review passed — no blocking issues found. LGTM.

Findings: CRITICAL 0 · IMPORTANT 0 · SUGGESTION 2

Scope. Full review (the trigger comment carried no scoping instructions). 5 files / +705 −9; I read all of them — modelopt/torch/export/distributed_writer.py in full, both new test files, and the two test-infra moves. CodeRabbit's auto-review is disabled on this non-default base branch, so nothing was skipped as already-covered.

Since the previous round (b4baa59 → 46e42e1)

The prior review's five findings, re-checked against the current code:

Prior finding Status now
IMPORTANT — is_shard(0) accepts _StridedShard Addressed by test, downgraded. A strided-shard0 refusal case was added. The gate itself is unchanged, so the refusal still rests on torch's internal class hierarchy rather than on an explicit check — re-raised as a SUGGESTION, not a blocker, since CI decides whether the refusal fires.
SUGGESTION — together's happy path untested Addressed. The two-rank test's third layout drives [["x","y"],["y","z"]], with sizes chosen so per-key balancing alone would split the group, and asserts all three land on one rank.
SUGGESTION — memory peak is ~3× not ~2× Withdrawn — the docstring was right. _run_to_completion clears ops before the caller assembles, so the send copies are freed before the torch.cats allocate. Peak extra is max(send + recv, recv + assembled), and both terms are ~1× the owned set. No change needed here.
SUGGESTION — expert disjointness asserted in prose, not refused Still open; non-blocking.
SUGGESTION — prose volume / cost derivations belong in the PR body Still open; non-blocking.

This round's findings

  1. [SUGGESTION] distributed_writer.py:42 — make the placement gate exact (type(p) is Shard) instead of relying on is_shard(0) excluding _StridedShard. The new test passes only under that torch-internal behaviour; stating the contract in code makes the refusal version-independent and turns the test into documentation of an intent.
  2. [SUGGESTION] test_distributed_writer.py:33-34 — drop the safetensors/transformers importorskips. The module under test imports neither, so on a torch-only install they silently skip the seven cross-rank refusal cases, which reads as green.

What I checked and found correct

The cross-rank reasoning is the risky part of this change, and it holds up:

  • Every refusal is symmetric. For the key-set, dim-0-classification, size, dtype, global-shape and grouping checks, each rank compares the gathered values against its own. If the values are not all equal, every rank necessarily finds a differing peer, so all of them raise — no rank is left in a collective its peer never joins. gshape = next(iter(gshapes)) being computed before the len(gshapes) != 1 test is harmless: the or short-circuits, so the arbitrarily-chosen element is never compared. The cpu_dist_workers suite covers all seven cases on both the agreeing and the disagreeing rank, under bounded_collectives() so a hang fails fast rather than stalling CI.
  • Send/recv buckets pair exactly. Sender (owner[k], dtype) groups and the owner's (src, dtype) groups are built from the same sorted key list, the same owner map and the same all_shapes emptiness test, both sorted by (peer, str(dtype)). Element counts match by construction, the dtype equality the buffer sizing depends on is refused up front, and one op per (peer, dtype) per side preserves in-order p2p matching per pair even with two dtypes between the same ranks. chunk = 4096 rounds are derived from the verified-identical sorted shard0 list, so no rank runs a round its peer skipped.
  • Assembly reproduces full_tensor(). _is_full_world_shard0 pins mesh.mesh == range(world), so global-rank order is mesh order; torch.chunk is what Shard._split_tensor uses, so the GPU test's hand-built shards match FSDP2's cut. Padded chunks are caught by the tiling check, and empty shards are skipped symmetrically on both sides rather than concatenated.
  • Owner assignment is deterministic and total. The unit sort (-bytes, u) and the min key (loads[i], i) both break ties explicitly, over inputs (dense_sizes, expert_bytes, merged_units) that are all verified identical, and unit_of covers every dense key — so no tensor can be dropped everywhere or claimed twice. Asymmetric expert sets are fine by design: expert_bytes is read from the gathered metadata, not computed locally.
  • The together union pass is transitively correct. Each new unit is the union of every member's current unit and all of its members are rewritten, so unit_of stays a valid partition regardless of group order — [A,B], [C,D], [B,C] collapses to one unit either way round.
  • empty0 cannot desynchronize. DTensor.numel() is global, so ranks agree; a global shape disagreement surfaces as a shard0/empty0 classification split, which the all_shapes key-set check names.
  • No host syncs on the metadata path. _nbytes, numel() == 0 and placements are all metadata; the one tensor read (mesh.mesh.tolist()) is CPU and memoized, and id(mesh) cannot collide because local_sd pins every mesh alive through the classification loop. Freeing the send buffers right after req.wait() is safe under NCCL because ProcessGroupNCCL::pointToPoint calls recordStream on them, so the caching allocator defers reuse — and the two-rank test proves the free actually happens, via StorageWeakRefs sampled at each assembled store.
  • The module is intentionally absent from export/__init__.py (all-private, no caller yet — grep confirms nothing in modelopt/ references it), torch.distributed.tensor is fine against the declared torch>=2.10, and the gloo_world_of_one lift to tests/unit/torch/conftest.py keeps the meta-DCP tests working while adding the CPU mesh the new tests need, now with try/finally teardown.

Risk

Low. Additive and unreferenced, so nothing regresses today. The GPU test covers BF16/FP8/packed-uint8, uneven and empty shards, a no-row tensor, replicated and plain over NCCL; the CPU suite covers the refusals on every rank plus the merge-group and send-buffer-lifetime properties. Both suggestions are robustness and test hygiene, not behaviour. Fine to merge ahead of [3/3] once the strided gate is either made explicit or confirmed green in CI.

🤖 Generated with Claude Code

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

Thanks for the approval. On the items the review lists as still open, and the two new ones:

  • Expert disjointness: _materialize_owned's docstring now states it as the caller's precondition ("experts must come whole, plain and disjoint per rank, as the caller splits them"). [3/3]'s _write_even_shards refuses, on every rank, a name held by more than one rank before it writes anything; this is in 46e42e1.
  • Prose volume: the three places you listed are trimmed in 46e42e1, and the cost derivations are in the description now.
  • Exact placement gate: kept as is_shard(0). In torch>=2.10, is_shard is itself the exact check (a C++ typeid comparison), and type(p) is Shard would refuse a Shard built on the C++ side. Details are in the thread.
  • The importorskips: kept, because [3/3]'s tests in this file import transformers at module level. Details are in the thread.

@cjluo-nv cjluo-nv left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Changes requested: mixed-device shards can fail before their peers complete transport.

Needs action:

  • Fix device-aware packing in distributed_writer.py:90–121; add a mixed CPU-offloaded/CUDA shard test, or refuse that layout collectively before mutation.
  • Validate every dense tensor’s dtype and global shape in distributed_writer.py:197–206; test disagreements that preserve byte counts, including empty tensors.
  • Release round-local receive-buffer references in distributed_writer.py:126–147; extend the lifetime regression across the 4096-key boundary.
  • Confirm NCCL first-use works when some ranks have no P2P operations; add a cold-group sparse-participation test.

No action needed:

  • Standard headers match LICENSE_HEADER; the fixture relocation preserves existing assertions.
  • sdk-gpt61-20261029T014604Z/PR-3101: static review only; pinned SHAs and reported test runs could not be independently verified.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 055b57b

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

Thanks. The first three items are done in 055b57b, with details in their threads; the fourth needs no change.

  • Mixed devices: dim-0 shards on more than one device type, or a key whose ranks disagree on its dtype or device, are now refused on every rank before anything moves.
  • Whole-tensor metadata: every dense tensor's dtype and shape are compared across ranks, not just its byte count.
  • Round-local buffers: each round runs in a helper, and the transfer test checks across a round boundary.
  • NCCL first use with sparse participation: the batched transfer is never the group's first collective. _materialize_owned runs dist.all_gather_object(meta, my_meta) on the default group (distributed_writer.py:217) before it calls _gather_shard0_to_owners (line 356). Every rank reaches that collective, and the P2P ops use the same default group, so the communicator exists before any rank skips a send. The GPU test ran over NCCL on 2 and 4 GB200 GPUs, with uneven and empty shards, and passed.

shengliangxu added a commit that referenced this pull request Oct 29, 2026
…ey matched (#3100)

> [!NOTE]
> **[1/3] of #2751's split** (2026-10-29), at its review's request:
[1/3] this PR (the reverse conversion's hook), [2/3] #3101, the
ownership and transport of the distributed checkpoint writer (stacked on
this PR), and [3/3] #2751, the reverse conversion and shard writing
(stacked on [2/3]). Merge in that order.
>
> **Base:** `main`.

### What does this PR do?

Type of change: New feature (part of the no-gather distributed export)

`revert_weight_conversion_quant_aware` refuses a merge rule that matches
no key of the state dict, so that a later rename cannot leave a
checkpoint that mixes the two namings.

The distributed checkpoint writer reverts each rank's own share of the
model. A rank can hold none of a merge rule's keys while another rank
holds them all, so the conversion now takes an `unmatched_merges` list:
- given one, a rule's refusal is recorded there instead of raised, and
the rest of the conversion still applies;
- the caller ([3/3]) refuses a rule that no rank matched;
- without it, nothing changes.

### Usage

Internal: `revert_weight_conversion_quant_aware(model, state_dict,
unmatched_merges=[])`, called by the distributed writer ([3/3]).

### Testing

- `test_quant_aware_conversion.py` gains
`test_radio_merge_that_matches_no_keys_is_recorded_for_one_ranks_share`
next to the existing raise case: the refusal is recorded instead of
raised, and a matching merge rule after it still applies, its fused
output checked, with the unrelated key kept.
- The conversion tests pass (79), and pre-commit passes against main.
- Review round, 2026-10-29 (`b9fbb242300`): `apply_reverse_rules`'s
docstring says what `unmatched_merges` does. The recorded-refusal test
now has a matching merge rule after the unmatched one and checks its
fused output; it fails if the reverse stops after recording the refusal.
A merge group split across ranks cannot reach this hook: [2/3] keeps
each group on one owner, and [3/3] runs the reverse inside a collective
that carries any rank's refusal to every rank. Pre-commit passes against
main; the conversion tests pass (79 on transformers 5.18; on 5.5.4 the
scoped-merge cases skip, as before).

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

- Is this change backward compatible?: ✅ The new argument is
keyword-only and defaults to the old 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](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
N/A. The no-gather export's entry lands with #2752.
- Did you get Claude approval on this PR?: ❌ Not yet; its code was
reviewed inside #2751.

### Additional Information

Split out of #2751, part of the expert-parallel PTQ series for Hugging
Face MoE models.


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

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Unmatched merge rules can now be recorded for later handling instead
of immediately raising an error when an optional collection is provided.
  * Without that option, unmatched rules continue to raise an error.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Shengliang Xu <[email protected]>
Base automatically changed from shengliangx/hfep-12b1-conversion-hooks to main October 29, 2026 07:03
@juhi10071998

Copy link
Copy Markdown
Contributor

Reviewed distributed_writer.py: I found no blocking bug.

What I checked: I ran _materialize_owned on 2, 3 and 4 gloo ranks (torch 2.10, CPU) with:

  • uneven dim-0 shards (7 rows), and fewer rows than ranks (empty shards)
  • uint8, bf16, and fp8 viewed as uint8, side by side
  • replicated and plain tensors, plus per-rank expert tensors
  • overlapping merge groups chained transitively ((a, d), (d, g))

In every case each tensor ended up whole on exactly one rank, byte-equal to the original, with no duplicates, and each merge group landed on a single owner. Send and receive grouping are built from the same gathered metadata, and every refusal is decided from the single all_gather_object, so all ranks agree and none is left hanging.

Non-blocking:

A rank's share is balanced by the bytes it owns, so a large embedding or
lm_head lands whole on one owner whatever its free memory, and must fit
there. The docstring says so (a review's note).

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

Copy link
Copy Markdown
Collaborator Author

/ok to test 764036c

@shengliangxu

shengliangxu commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

@juhi10071998, thank you for the multi-rank checks. Running _materialize_owned on 2, 3 and 4 ranks, with empty shards, mixed dtypes and chained merge groups, covers layouts the unit tests take one at a time.

  • Owners balanced by bytes, not free memory: documented in 764036c. _materialize_owned's docstring now says ranks are weighed by bytes, not by free device memory, so a large embedding or lm_head must fit on its owner. I did not build a memory-aware bound. It would need each rank's free memory gathered in the metadata collective, and that number changes as the export runs.
  • The duplicate gloo_world_of_one fixture: agreed. [OMNIML-6081] [1/2] Pack sharded weights in FSDP2 weight-update windows, and NVFP4 DTensor shards #3099 and this PR add it in byte-identical text, so whichever merges second will be rebased onto main and drop its copy. That happens once one of them merges.

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

The owner assignment and the batched send/receive pairing are consistent across ranks, the earlier cold-group NCCL finding is fixed, and the unit tests pass here (49 passed). Two description lines are stale: the Testing note that the transport is unchanged since the GB200 run at b4baa594, and the "Claude approval: not yet" checklist line.

@shengliangxu
shengliangxu merged commit 4bef852 into main Oct 29, 2026
50 checks passed
@shengliangxu
shengliangxu deleted the shengliangx/hfep-12b2-writer-transport branch October 29, 2026 19:02
shengliangxu added a commit that referenced this pull request Oct 29, 2026
[3/3] of #2751's split, on [2/3]'s transport (#3101): the reverse
conversion on each rank's whole tensors, with each merge group and its
quantization state kept on one owner (_merge_groups, _revert_whole_sd),
and the shards' writing: even files numbered into one global range,
staged as .tmp files and renamed into place once every rank has written,
the index last (_even_bins, _write_even_shards). Every step a rank can
fail alone runs in the failure-carrying all_reduce.

This collects the branch's history from before the split, when it held
the whole writer; the commits after the split follow on their own.

Signed-off-by: Shengliang Xu <[email protected]>
shengliangxu added a commit that referenced this pull request Oct 29, 2026
…ws, and NVFP4 DTensor shards (#3099)

> [!NOTE]
> **[1/2] of #2750's split** (2026-10-28), made at its review's request
because #2750 was over the 500-line budget. This PR packs weights that
are still sharded, which the keep-fused fold needs. #2750, now [2/2] and
stacked on this PR, keeps the fold.
>
> **Base:** `main`, now that #2736 has merged (2026-10-28). #2750 merges
after this PR.

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

- `main`, with #2736 (distribution plan, run group, collectives) merged
  - #3074 calibration on grouped_mm
    - #3067 Nemotron-H's experts under grouped_mm
  - #2740 calibration on per-rank data
  - **this PR: sharded-weight packing, [1/2] of #2750's split**
    - #2750 keep-fused fold, [2/2]
  - #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 and the rest of the loader chain

</details>

### What does this PR do?

Type of change: New feature (part of the no-gather distributed export)

The no-gather export (#2752) packs quantized weights while the model is
still sharded across ranks: no rank gathers the whole model, though each
FSDP2 unit is still all-gathered once, inside its weight-update window,
while its weights are packed. This PR covers the two parts of that which
do not depend on the fused-experts fold.

- **NVFP4 packs DTensor shards.** Three steps broke on a DTensor:
- The block scales' zero fill used a boolean-mask assignment. That
lowers to `index_put_`, which DTensor cannot dispatch. It now uses
`torch.where`.
- The fp4 cast mixed the DTensor with plain constants ("got mixed
torch.Tensor and DTensor"). It now runs on the local shard and rewraps
it with the global shape and stride, so an uneven shard keeps its real
size. `from_local` would infer local x world rows, which for 96 rows
over 64 ranks gives each rank a different global shape, and the writer
then fails far from the cause.
- The nibble pack's `<<` is a silent no-op on a DTensor (torch 2.8 to
2.14), so it packed unrelated codes. It now uses
`torch.bitwise_left_shift`.

  Plain tensors pack exactly as before.
- **The other 4-bit packers refuse a DTensor shard.** INT4, NF4 and
MXFP4, and the export's INT4 packer (`pack_int4_in_uint8`), shift with
`torch.bitwise_left_shift` too, which gives the same bytes on a plain
tensor. None of them packs a shard: each combines its input with plain
tensors, which DTensor refuses deep inside, or, on INT4's CPU fallback,
gathers it whole and then dropped the shift. So each now refuses a
DTensor up front, and NVFP4 refuses one that comes with a plain
per-block scale, such as a static quantizer's. On this PR's path the
packers see plain tensors; the refusals keep a shard that reaches them
from being packed wrong.
- **FSDP2-owned weights pack inside weight-update windows.**
`ExportContext.keep_fused_experts` marks the no-gather path.
- On that path, a quantized linear whose dense part FSDP2 shards is
packed inside its unit's `fsdp2_aware_weight_update` window, which hands
FSDP2 the packed weights. Packed outside one, the unit's next reshard
puts FSDP2's unquantized shard back, and the checkpoint is written
unquantized.
- Under `held_fsdp2_weight_windows`, a unit's window stays open from one
module to the next, so a decoder layer is gathered once, not once per
linear. A module joins the window once, however many of its weights it
packs. `_process_quantized_modules` enters it around its dispatch loop,
but no window opens there until the no-gather export (#2752) sets
`keep_fused_experts` on that loop's context and lets a sharded model
through.
- Where expert parallelism leaves the root unwrapped, the window opens
on the layer's own unit.
- A unit that owns a weight directly, as a linear that is a unit of its
own under an unwrapped root does, keys that weight by its bare name in
the window's FSDPParam mapping (`core_utils._param_key`).
`get_prefixed_param_names` used to name it after the weight itself, so
the window skipped the packed weight and the reshard put the float shard
back. A module the name map does not know keeps a key no parameter has,
so the window skips it rather than take it for the root.
- The unit is found by walking up the module's name through name maps
built once per export (`ExportContext.module_names`), instead of
scanning the model per module. Time to open the window around each of 10
linears per FSDP2 unit, in a synthetic model of about 1,000 modules per
unit (CPU, one gloo rank, torch 2.14), measured before the split:

    | Units | Scanning the model per module | Walking up the name |
    |---|---|---|
    | 48 | 22.5 s | 4.8 s |
    | 96 | 79.8 s | 9.5 s |
- **Test fixture:** the one-rank gloo fixture `gloo_world_of_one` moves
into `tests/unit/torch/conftest.py`, in the same text #3101 adds.

### Usage

Internal to the export: the no-gather writer (#2752) sets
`keep_fused_experts`. Nothing changes for a single-process or gather
export.

### Testing

- `tests/unit/torch/export/test_sharded_weight_packing.py` (new) runs on
a one-rank gloo world. It checks that:
- NVFP4 packs a DTensor shard into the same codes and scales as the
plain weight, an all-zero block included;
  - the fp4 cast keeps an uneven shard's global shape;
- the quantized-linear handlers pack an FSDP2 unit in one held window,
or in a window per module outside held windows, with the root sharded or
not, and the sharded state dict carries the packed weights byte for
byte.
- `test_nvfp4_tensor.py`: an all-zero block gets a scale of 1 on both
the dynamic and the static path.
- These tests come from #2750's reviewed suite, moved here with their
code.
- Pre-commit passes against main.
- `tests/unit/torch/export`, `test_nvfp4_tensor.py`,
`test_meta_dcp_load.py` and `quantization/test_utils.py` pass (530), on
transformers 5.18 and torch 2.14. The exceptions are 7
`test_export_diffusers.py` cases, which fail the same way in that
environment without this change.
- Review round, 2026-10-29: a module that asks for its unit's held
window once per weight now joins it once; listed twice, it was
re-registered with FSDP2 from its own shard, which FSDP2 rejects. The
new `test_a_module_joins_its_units_held_window_once` fails without the
fix. Comments are cut to their constraint, `DTensor` and
`init_device_mesh` are imported at module scope, and
`ExportContext.fsdp2_window` is typed. Pre-commit passes against main;
`test_sharded_weight_packing.py`, `test_nvfp4_tensor.py`,
`test_meta_dcp_load.py` and `test_export_registry.py` pass (66) on torch
2.14.
- Review round 2, 2026-10-29 (`54f8632c78b`, cjluo-nv's review bot):
- A linear that is an FSDP2 unit of its own under an unwrapped root now
keeps its packed weight. It used to export as float32, reproduced on one
gloo rank. The handler test gains that layout, which fails without the
fix.
- A two-rank job on the `cpu_dist_workers` pool packs an uneven NVFP4
shard (three rows over two ranks) into the plain pack's codes and
scales. It also runs the handlers over two FSDP2 units, a 17-row weight
among them, against an unsharded export. Dropping the global shape from
`_cast_fp4`'s rewrap fails it.
- `test_sharded_weight_packing.py` and `test_param_index.py` pass (17)
on torch 2.14, and pre-commit passes against main.
- GPU runs over NCCL:
`tests/gpu/torch/export/test_sharded_weight_packing_gpu.py`
(`51f187fb029`) runs the two-rank checks on every visible GPU and skips
below two. Results are below.
- GPU run, 2026-10-29, at `51f187fb029` (cjluo-nv's review bot asked for
CUDA/NCCL validation). GB200, torch 2.11.0a0 (NGC 26.02), CUDA 13.1,
transformers 5.9.0:

|
`test_sharded_weight_packing_gpu.py::test_sharded_packing_matches_the_unsharded_bytes_over_nccl`
| 1 GPU | 2 GPUs | 4 GPUs |
  |---|---|---|---|
| Result | skipped (needs 2 or more) | passed, 23.2 s | passed, 24.1 s |
- GPU run, 2026-10-29, ran at `54f8632c78b`: main's
`tests/gpu/torch/export/test_fsdp2_export.py`, which goes through
`fsdp2_aware_weight_update` and so the parameter-key change in
`core_utils`, on more GPUs than CI's one. GB200, torch 2.11.0a0 (NGC
26.02), transformers 5.9.0:

  | `tests/gpu/torch/export/test_fsdp2_export.py` | 2 GPUs | 4 GPUs |
  |---|---|---|
  | Result | 39 passed, 116.7 s | 39 passed, 85.3 s |
- Review round 3, 2026-10-29 (`d568dacad39`, `6033bb8e2a8`;
juhi10071998's review and Claude's):
- The INT4, NF4 and MXFP4 packers and the export's INT4 packer shift
with `torch.bitwise_left_shift` and refuse a DTensor shard, and NVFP4
refuses one with a static quantizer's plain per-block scale.
`test_a_packer_that_packs_only_whole_tensors_refuses_a_shard` covers the
five; each case fails without its refusal. On one and two gloo ranks,
before the change, the INT4 export packer, NF4 and MXFP4 raised "mixed
torch.Tensor and DTensor" deep inside, and `INT4QTensor`'s CPU fallback
returned wrong codes.
- A module the window's name map does not know no longer takes the key
of a parameter the root owns.
`test_a_module_the_window_cannot_name_never_takes_the_roots_own_weight`
fails without the fix.
  - `keep_fused_experts` is documented in a docstring.
- Pre-commit passes against main. `tests/unit/torch/export` and
`tests/unit/torch/quantization` pass (2065) on torch 2.14 and
transformers 5.18; 11 diffusers cases and one diffusers test module fail
the same way on main in that environment.
- Review round 4, 2026-10-29 (`46742ffd24e`, Claude's review), comments
only: the held windows' call site says that no window opens there until
the no-gather export sets `keep_fused_experts`, and the GPU test says
what ends a rank left waiting in a window. Pre-commit passes against
main.

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

- Is this change backward compatible?: ✅ Plain-tensor NVFP4 packing is
unchanged, and the windows apply only on the no-gather path.
- 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 no-gather export's entry lands with #2752.
- Did you get Claude approval on this PR?: ✅ At `ebfb6a7b050`. Its
reviews of `a48ce7aa55a` and `6033bb8e2a8` found issues that review
rounds 3 and 4 address.

### Additional Information

Split out of #2750, part of the expert-parallel PTQ series for Hugging
Face MoE models.


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

## Summary by CodeRabbit

* **Bug Fixes**
* Improved quantized weight export for sharded models across distributed
layouts, including models with fused experts retained.
* Added support for NVFP4 quantization of distributed tensor shards
while preserving their original shape.
  * Corrected NVFP4 scaling for blocks containing only zero values.
* Improved weight handling during export and ensured packed weights and
scales match unsharded results across tested configurations.
<!-- 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 Oct 30, 2026
[3/3] of #2751's split, on [2/3]'s transport (#3101): the reverse
conversion on each rank's whole tensors, with each merge group and its
quantization state kept on one owner (_merge_groups, _revert_whole_sd),
and the shards' writing: even files numbered into one global range,
staged as .tmp files and renamed into place once every rank has written,
the index last (_even_bins, _write_even_shards). Every step a rank can
fail alone runs in the failure-carrying all_reduce.

This collects the branch's history from before the split, when it held
the whole writer; the commits after the split follow on their own.

Signed-off-by: Shengliang Xu <[email protected]>
shengliangxu added a commit that referenced this pull request Oct 30, 2026
…on each rank's own experts (#3122)

> [!NOTE]
> **[1/2] of #3074's split.** A reviewer asked on #3074 for its
expert-parallel correctness fix to land on its own, with a Bug Fixes
changelog entry, apart from #3074's two backward-breaking changes
(calibration on `grouped_mm` by default, and the new `calibrate()`
error). This PR is that fix. #3074, now [2/2], sits on it and keeps the
rest.
>
> **Base:** `main` (`2b900c8fa41`).

### What does this PR do?

Type of change: Bug fix

Under the expert parallelism of transformers 5.16 and later (the
`grouped_gemm` plan style), a fused experts module keeps each expert
weight as a DTensor sharded over the experts (`Shard(0)`) and sets
`num_experts` to the rank's count. Its forward runs on local tensors,
but ModelOpt also reads the expert weights outside the forward, by local
expert index:

- max calibration's weight pass and `fold_weight`, through
`get_expert_weight`;
- the weight-input hooks of local Hessian and imatrix (`on_weight` at
registration, and the eager per-expert capture);
- GPTQ's per-expert helpers;
- the native FP8 wrapper's dequantization, which also indexes
`*_scale_inv`.

An index into the DTensor names a global expert, and each such read
all-gathers every expert. (Before 5.16, transformers kept each rank's
slice as a plain tensor, which these reads indexed correctly.) On two
ranks with a 4-expert Qwen3-MoE experts module under weight-only INT8,
main calibrates rank 1's two weight quantizers on rank 0's experts 0 and
1 instead of its own experts 2 and 3. `fold_weight` folds into the
gathered copies, so no rank's own experts get folded, rank 0's included.

`_QuantFusedExperts._local_experts` hands those readers the rank's own
shard, in quantizer order. A DTensor holding every expert (FSDP2) is
indexed as before. Two layouts are refused instead of read wrong:

- a DTensor whose local shard does not hold the module's experts (one
replicated over the ranks, say), which would otherwise be indexed as
global experts;
- native FP8 expert weights sharded over the experts, in
`unpack_weight`, which would otherwise unpack into a buffer for every
expert from this rank's experts. Both projections are checked before
either is unpacked.

### Usage

No API change.

### Testing

- New tests in
`tests/unit/torch/quantization/plugins/test_fused_experts.py` run on CPU
over two gloo ranks, with experts sharded as transformers shards them.
All six cases fail on main and pass here:
- weight calibration and `fold_weight` use each rank's own experts:
plain, and with the dense part FSDP2-sharded, on named and unnamed
meshes;
- a replicated expert DTensor, and native FP8 experts sharded over the
experts, are refused;
- registering the weight-input hooks hands `on_weight` each rank's first
local expert, and runs no collective;
  - GPTQ builds its expert helpers from each rank's own experts.
- `tests/unit/torch/quantization` on CPU (torch 2.14, transformers
5.18): the six new cases pass, and every other result matches main's.
- pre-commit, mypy included, passes against main.
- Review suggestion (Claude), 2026-10-29: `unpack_weight` checks both
projections before unpacking either, so a refusal leaves the module
unchanged; the refusal test shards `down_proj` alone and checks that
`gate_up_proj` is still FP8, which fails with the per-projection check.
The changelog entry and `_local_experts`' docstring name transformers
5.16, where expert-parallel weights became DTensors. pre-commit passes
against main.
- Rebased on 2026-10-30 onto main `99c3834f62c` (after #3093, #3108,
#3101, #2737, #3099 and #2750 merged), with its own diff unchanged and
no conflicts. pre-commit, now with main's ruff 0.17 and mypy 2.4 hooks,
passes.

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

Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)
and your commits are signed (`git commit -s -S`).

Make sure you read and follow the [Security Best
Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors)
(e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(...,
weights_only=False)`, `pickle`, etc.).

- Is this change backward compatible?: ✅ <!--- A weight layout the
quantizers cannot index now raises instead of calibrating the wrong
experts. -->
- 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)?:
✅ (Bug Fixes)
- Did you get Claude approval on this PR?: ❌ <!--- Requested. The same
code was reviewed and approved as part of #3074. -->

### Additional Information

Split out of #3074 at a reviewer's request. Jira: OMNIML-6073.



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

## Summary by CodeRabbit

* **Bug Fixes**
* Fixed weight calibration, GPTQ quantization, and weight folding for
Hugging Face fused MoE models split across expert-parallel ranks. Each
rank now uses its local experts’ weights.
* Unsupported expert-sharding layouts now return a clear error when
weights cannot be safely indexed or unpacked.
* **Improvements**
* Preserved native scaled FP8 expert weights through quantization and
export, with exported weights checked against reconstructed BF16
references.
<!-- 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 Oct 30, 2026
… each tensor's owner rank (#2751)

> [!NOTE]
> **The expert-parallel PTQ series is now a tree instead of one stack**
(re-cut 2026-10-27, from main 1521053), so PRs that do not depend on
each other can be reviewed and merged in parallel. This PR was [15/21].
Rebased onto main 7c3c868 later the same day, after #2739 merged,
and onto main f03651e that night.
>
> **[3/3] of this PR's split** (2026-10-29), at its review's request:
[1/3] #3100 (the reverse conversion's `unmatched_merges` hook), [2/3]
#3101 (`_materialize_owned`, ownership and transport), and this PR
(reverse conversion and shard writing). Merge in that order. [1/3] #3100
merged on 2026-10-29 (`8ab63386152`) and [2/3] #3101 the same day
(`4bef85279e4`); this PR now targets `main`.
>
> **Base:** `main`, on #3101's squash `4bef85279e4`. The diff below is
this PR's alone.
>
> **Re-cut:** the `gloo_world_of_one` fixture its tests use is in #3101
now, in the same text #3099 adds, so either order merges cleanly. Review
fixes since are listed at the end of Testing.

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

- `main`
  - #2745 fused experts under grouped_mm (merged)
    - #3074 calibration on grouped_mm
      - #3067 Nemotron-H's experts under grouped_mm
  - #2739 meta-DCP checkpoint load (merged)
  - #2736 distribution plan, run group, collectives (merged)
    - #2740 calibration on per-rank data
    - #2750 keep-fused fold
    - #3100 conversion hook, [1/3] (merged)
      - #3101 ownership and transport, [2/3] (merged)
        - **#2751 shard writing, [3/3] (this PR)**
      - #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

Main's FSDP2 export already writes each rank's share, but it first
unshards each FSDP2 unit in turn, an all-gather of that unit to every
rank. It also refuses conversion mappings that merge or split tensors,
since one unit at a time cannot regroup them, and it does not handle
expert-parallel shards. In this writer every tensor moves once, whole,
to one owner rank and is written from there
(`modelopt/torch/export/distributed_writer.py`). After the split this PR
holds the last of its pieces: `_materialize_owned` is in #3101, and the
conversion's `unmatched_merges` hook is in #3100.

- **`_materialize_owned`** (now in #3101) gives each tensor exactly one
owner rank and makes it whole there:
  - replicated and plain values need no transport;
- dim-0 shards travel point-to-point, batched and bucketed per peer (one
bucket per key deadlocked at 16 ranks);
- each group of keys the reverse conversion merges into one tensor
(`_merge_groups`) goes to one owner, with its weights' quantization
state, so the merge, or its refusal of a quantized group, happens there.

Placements it cannot assemble, and shards that do not tile the global
shape, raise rather than risk a silently mis-assembled checkpoint; a
zero-element tensor in such a layout is refused like a non-empty one.
Experts arrive whole and plain, one disjoint set per rank: an expert
that is still a DTensor is refused on every rank before anything moves.
- **`_revert_whole_sd`** runs the reverse weight conversion on those
whole tensors, so they go out under the checkpoint's names.
transformers' conversion ops cannot express a placement. Ownership keeps
each merge group whole on one rank, so no rank sees part of one. The
reverse runs inside the failure-carrying `all_reduce`, so a refusal on
any rank, such as a merge's refusal of a quantized or incomplete group,
makes every rank keep its in-memory names together.
- **`_write_even_shards`**:
- bin-packs each rank's set into evenly sized files numbered into one
global range;
- refuses a name two ranks both hold, on every rank, in its first
collective, before any file is written;
- writes the files with safetensors, both names of a tensor two keys
share included (one is copied, as `ShardedSafetensorsWriter` does),
which `save_file` would otherwise refuse;
  - unions the index;
- never overwrites a checkpoint: a directory already holding
`model.safetensors`, its index, or `model-NNNNN-of-NNNNN.safetensors`
files is refused on every rank in the first collective, before anything
is written. Other files, auxiliary weights such as `mtp.safetensors`
included, are left alone;
- writes every file under a temporary name and renames them into place
only once every rank has written all of its own, the index last, so no
index names a shard that is not in place.
- **Failing together.** The export directory's creation with the file
counts and tensor names, the shard writes and rank 0's index write each
run inside the failure-carrying `all_reduce` (#2736), so one rank's
failure raises on every rank with that rank's error rather than leaving
the others in an unmatched collective.

A tensor over `max_shard_size` gets a file of its own, as in HF, and the
rest still pack.

The entry point that drives them arrives in #2752.

**Why not a DCP writer, or main's streaming writer
(`_StreamingShardWriter`, `name_shards_and_write_index`)?**

- DCP writes its own format, not safetensors shards under the hub's
names with an index. vLLM and TRT-LLM would need a consolidation pass
over it, and that pass is the gather this writer avoids.
- The streaming writer serves main's FSDP2 export, which unshards each
unit, an all-gather of it to every rank, and refuses conversion mappings
that merge or split tensors. This writer moves each tensor once, whole,
to one owner, so a merge can run there; that part has nothing to extend.
- The file writing itself could share code with `_StreamingShardWriter`,
which already stages to temporary files, given three things this writer
needs:
- every step fails on every rank together, by running in the
failure-carrying `all_reduce`, where the streaming path names its shards
on rank 0 after a barrier and a `gather_object`;
  - a name two ranks both hold is refused before anything is written;
  - each rank's owned set is bin-packed into even files.

That sharing is deferred to a follow-up. It would change main's
streaming export, a path this series does not otherwise touch, and no
checkpoint format, so it can land on its own once this writer is in,
without growing a PR already split for size.

The metadata collective carries each sharded tensor's dtype, every dense
tensor's size and the merge units, which owners are assigned from; ranks
that disagree on any of them are refused on every rank. The send buffers
are freed once the transfers finish, before a rank assembles what it
owns (a `P2POp` and its request each keep their tensor, so the transfer
runs in a helper that drops both); on top of its own shards a rank holds
at most about twice its owned set. On two gloo ranks with 128 MiB of
shards each:

| Send buffers | Peak RSS above the shards |
|---|---|
| kept while a rank assembles (previous revision) | 257 MiB |
| freed before it assembles (this revision) | 193 MiB |

### Usage

N/A: internal to the distributed export (#2752).

### Testing

- New `tests/unit/torch/export/test_distributed_writer.py`, on CPU under
gloo, drives each piece directly:
- HF shard-size parsing, a unit in any case read as bytes, as the
streaming export reads it (transformers reads a lowercase `b` as bits);
- binning: balanced, bins added until each fits, an oversized tensor
isolated, no empty bins;
  - DTensor sizes and the shard-0 placement check;
- ownership making every tensor whole and plain, and rejecting
placements it cannot assemble;
- the reverse conversion renaming in place and keeping in-memory names
when it fails;
  - shard files and an index covering every tensor once;
- two ranks where one rank's directory or write fails, or two ranks hold
one name: both raise, and the name collision leaves no shard file. Run
on a 10 s gloo group, these fail in seconds on the code before the fix
rather than waiting out the process group's timeout.
- Mutation-checked: each test fails under at least one deliberate break
of the code.
- Each helper's tests are one table, and checks a remaining test covers
are dropped; the two-rank jobs use the shared `bounded_collectives`.
Each drop is checked by mutation.
- On two ranks, `_materialize_owned` moves an uneven shard, an empty one
and two dtypes to their owners, and a dtype disagreement, or an expert
that only rank 1 still holds as a DTensor, is refused on every rank. An
empty `Shard(1)` tensor is refused, and two names for one CPU tensor are
both written. The expert, collision, empty-tensor and shared-tensor
cases each fail without their fix (mutation-checked).
- On two ranks, what a rank sent is freed before it stores an assembled
tensor, a rank that received nothing included; a dense size that differs
across ranks is refused on every rank; and `_write_even_shards` with
uneven file counts numbers the files across ranks and indexes both
ranks' tensors. Each fails without its fix (mutation-checked).
- 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: each merge group goes to one owner rank, so
the reverse conversion merges it; the shard size is read with the
streaming export's parser; the mesh memo's comment gives its real
reason. 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: the merge groups are sorted before
the units are built, so every rank derives the same owners whatever
order its keys come in; a new case shows a quantized merge group,
refused by the rank holding its scales, falling back on every rank. 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 3: a merged weight's quantization
state stays in its merge group, so the rank that merges a quantized
group refuses it even when the merge pattern does not match the scales;
groups that share a key form one unit whatever their order; the ranks
check in the metadata collective that they formed the same units. 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 refusal of ranks that
group the keys differently lists each rank's first differing merge
units.
- Review fix, 2026-10-27 night: when the shard or index step fails,
every rank removes the files it wrote, a partial one included, so a
retry starts from the directory as it was. The one-rank-failure test
checks the directory is left empty; its shard and index cases fail
without the change.
- Review suggestions, 2026-10-27, last round: a failed write's cleanup
ignores an `unlink` error, so the error naming the failing rank is the
one raised, and a comment says a retry rebuilds the state dict. The new
test fails without the change.
- Review suggestion, 2026-10-27, last round: files a failed write's
cleanup cannot remove are named in one warning, and the write's own
error is still the one raised. The extended test fails without the
change.
- The same `gloo_world_of_one` fix as #2750's, in this PR's copy of the
fixture, so the two stay identical.
- The same `test_meta_dcp_load.py` fixture deletion as #2750's, so the
two stay identical.
- Review suggestion, 2026-10-28, second round: each tensor is dropped
right after its host copy, so a file's tensors are no longer held on the
device while it is written; the new test fails without the change.
- Review fix, 2026-10-28, seventh round: the comment by the drop now
says it frees each tensor once its host copy exists. It does not lower
the device peak, which is the allocation at entry with or without it, so
a peak-memory measurement reads the same either way by construction and
is no evidence against it; the memory still held when each file is
written is what moves. Measured on 4 GPUs, in a distributed HF export of
tiny FP8 and NVFP4 models that runs this writer on CUDA tensors (torch
2.15 pre-release, transformers 5.18; this PR's own writer test runs on
CPU, where device memory does not move). The table gives the device
bytes allocated (`torch.cuda.memory_allocated`) on each rank just before
`save_file`. Each rank wrote one file, so a file was its whole owned
set; a rank writing several files was not measured.

| Model | Tensors per rank | Held before this change | Held with it |
Released before the write |
|---|---|---|---|---|
| FP8, dense, tied embeddings | 5 to 20 | 167,424 to 167,936 | 109,056 |
58,368 to 58,880 (35%) |
| FP8, MoE | 39 to 53 | 526,848 to 528,384 | 275,456 | 251,392 to
252,928 (48%) |
| NVFP4, dense, tied embeddings | 6 to 25 | 131,072 to 131,584 | 97,280
| 33,792 to 34,304 (26%) |
| NVFP4, MoE | 49 to 71 | 371,712 to 376,320 | 220,672 | 151,040 to
155,648 (41%) |
- Rebased on 2026-10-28, late night, onto #2736 at `cf4597dcbeb`, on
main `1ca8bd1fc4d` (after #3088 and #2745 merged), without conflicts;
this PR's own diff is unchanged. Its tests pass (143), and pre-commit
passes against main.
- Rebased on 2026-10-28, late night, onto main `bdc45368d10` after #2736
merged; #2736's squash has the tree of its last head, so this PR's tree
is unchanged.
- Review (meenchen's review bot), 2026-10-29, all items:
- **Split in three:** #3100, #3101 and this PR. This branch merges
#3101, so its own commits stay; source lines are about 40, 347 and 254.
- **Rollback:** a failed export no longer deletes a checkpoint already
in the directory. Every file is written under a temporary name, and the
ranks rename theirs into place only once every rank has written all of
its own, the index last. A failure before then removes only the
temporary files. The one-rank-failure test runs over an existing
checkpoint too and checks it byte for byte; its shard and index cases
fail without the change. A new test re-exports over a checkpoint.
- **Imports:** the writer's, the fixture's and a test's imports moved to
module scope.
- **Docstrings:** the long ones keep their constraints; the narrative
moved here.
- **GPU tests:** `tests/gpu/torch/export/test_distributed_writer_gpu.py`
runs from two GPUs. It moves BF16, FP8 and uint8 shards of uneven and
empty extent over NCCL and writes several files per rank. The GB200 runs
and measurements follow below.
  - **Results:** 148 tests pass, and pre-commit passes against main.
- **Narrative moved from the docstrings:** bucketing the transfers by
peer replaced one operation per (key, peer), which at 235B was about
12.7k operations and 660 s for a few GB of payload.
- GPU runs on GB200 of
`tests/gpu/torch/export/test_distributed_writer_gpu.py` (its two tests),
ran at `f577fc05af0`. The code is unchanged at this head; only [2/3]'s
docstrings and tests changed since.

  | GPUs | Result | Time |
  |---|---|---|
  | 1 | 2 skipped (need two GPUs) | 0.5 s |
  | 2 | 2 passed | 17.6 s |
  | 4 | 2 passed | 23.5 s |

- Measured on GB200 at `f577fc05af0` with a synthetic sharded state
dict: 600 keys of shape (8741, 4096), 360 BF16, 150 FP8 e4m3 and 90
uint8, 32.0 GiB in total. 8741 rows divide by neither 4 nor 8, so the
dim-0 shards are uneven. Timed `_materialize_owned(sd, set(), rank,
world)`, then `_write_even_shards(sd, out_dir, "5GB", rank, world)`.
Rank 0 is shown; all ranks were near-identical.

| GPUs | Input per rank | Owned per rank | Transport | Peak device
memory in the transport, above its input | Write | Files per rank |
Bytes written per rank | Peak host RSS (process lifetime) |
  |---|---|---|---|---|---|---|---|---|
| 4 (one node) | 8.01 GiB | 8.00 GiB | 6.22 s | 12.01 GiB | 4.36 s | 2 |
8.00 GiB | 8.68 GiB |
| 8 (two nodes × 4) | 4.00 GiB | 4.00 GiB | 14.15 s | 7.01 GiB | 2.57 s
| 1 | 4.00 GiB | 8.49 GiB |

- The device peak is `torch.cuda.max_memory_allocated()` after
`reset_peak_memory_stats`, minus the allocation before the transport.
During the transfer a rank holds one send buffer and one receive buffer
per (peer, dtype). The send buffers copy its shards of the tensors other
ranks own, (w-1)/w of its input; the receive buffers hold the other
ranks' shards of the tensors it owns, (w-1)/w of its owned set. Their
sum is the measured peak at both sizes. In this run the state dict held
the only reference to each input shard, so a rank freed its inputs as it
assembled.
- Host RSS is `ru_maxrss`, the maximum over the process's life. It was
2.1 GiB before the write, so the write's own peak is at most the number
shown.
- The 8 GPUs span two nodes, so that transport time includes cross-node
NCCL traffic and does not scale like-for-like against the one-node run.
- Re-measured on GB200 at `239260c7d8d` with the input DTensors kept
alive through the write, as the model keeps its parameters in a real
export. The writer's code is the same as at `f577fc05af0` (docstrings
differ) and is unchanged at `2470bc4a4f7`. Same 32.0 GiB state dict;
rank 0 is shown, and all ranks were near-identical.

| GPUs | Owned per rank | Transport | Peak device memory above the
allocation before the transport (transport and write) | Write | Files
per rank | Peak host RSS during the write |
  |---|---|---|---|---|---|---|
| 4 (one node) | 8.00 GiB | 6.83 s | 14.01 GiB | 4.12 s | 2 | 8.65 GiB |
| 8 (two nodes × 4) | 4.00 GiB | 14.76 s | 7.51 GiB | 2.52 s | 1 | 8.21
GiB |

- With the inputs alive, the peak comes from the assembly: the receive
buffers, (w-1)/w of the owned set, plus the assembled owned tensors.
Their sum is the measured peak at both sizes, within
`_materialize_owned`'s bound of about twice the owned set.
- The write never raised the peak above the transport's: it copies each
tensor to the host and drops it, so it adds time, not device memory.
- Host RSS here is windowed to the write (the high-water mark is reset
just before it); the first table's is the process-lifetime `ru_maxrss`.
- 2026-10-29: merges [2/3]'s review round (`46e42e10a74`, rebased onto
#3100's `b9fbb242300`). That brings [1/3]'s docstring and test, plus
[2/3]'s merge-group and strided-shard tests and trimmed docstrings. No
change of its own. Pre-commit passes against main;
`test_distributed_writer.py`, `test_quant_aware_conversion.py` and
`test_meta_dcp_load.py` pass (149).
- 2026-10-29, later (`2470bc4a4f7`, test only):
`test_the_index_goes_in_place_only_after_every_shard` pins the commit
order. Rank 1 fails to rename its shard into place after every file is
written, and the index must stay as it was: absent in an empty
directory, byte for byte over an existing checkpoint. So an index in the
directory never names missing shards. With the shard and index commits
swapped, both cases fail, and every other writer test stays green. The
writer's code is unchanged since `239260c7d8d`.
`test_distributed_writer.py` passes (44), and pre-commit passes against
main.
- 2026-10-29 (meenchen's review bot): why the writer is neither a DCP
writer nor main's streaming writer, and why sharing its file writing
with the latter is deferred, is now in the description above, moved from
the review reply. Description only.
- Review (meenchen's review bot), 2026-10-29, second round
(`285c30bf08e`): once every rank has committed, rank 0 removes an
earlier checkpoint's `model-NNNNN-of-NNNNN.safetensors` files the new
index does not name, and a `model.safetensors`, which transformers loads
ahead of the index. The replacement test runs over an earlier one-shard,
three-shard and single-file checkpoint, with a `config.json` and an
off-index weight file that must stay; the three-shard and single-file
cases fail without the removal. The failure tests' existing checkpoint
gained a `model.safetensors`, so a removal on a failure path fails them
(checked by running it in the failure handler). The docstring states the
commit's limit: a rename failing partway through the final commit can
leave a checkpoint already there mixed; it is documented rather than
fixed, for the reasons in the review thread.
`test_distributed_writer.py` passes (46), and pre-commit passes against
main. Source lines: 272.
- 2026-10-29, later: merges [2/3]'s second review round (`055b57bd7cf`):
mixed-device shards and whole-tensor disagreements refused on every
rank, each transfer round's buffers freed when it ends. No change of its
own (`1feacd040c9`). The writer, conversion and meta-DCP tests pass
(158), and pre-commit passes against main.
- Review fix, 2026-10-29 (`03ae6f5d5ff`, meenchen's review bot): a
reverse conversion that fails with an exception carrying no message now
counts as a failure. Before, `RuntimeError()` read as success, so rank 0
committed hub names while rank 1 kept in-memory ones (reproduced on two
gloo ranks with tiny Mixtral). The one-rank-failure test gains that
case, which fails without the fix. `test_distributed_writer.py` passes
(52), and pre-commit passes against main.
- GPU run, 2026-10-29, ran at `1feacd040c9` (the same code as the
current head). GB200, torch 2.11.0a0 (NGC 26.02), transformers 5.9.0:

| `tests/gpu/torch/export/test_distributed_writer_gpu.py` (2 tests) | 1
GPU | 2 GPUs | 4 GPUs |
  |---|---|---|---|
  | Result | 2 skipped | 2 passed, 20.3 s | 2 passed, 22.5 s |
- Review (meenchen's review bot), 2026-10-29, third round
(`d9bf5aafbbb`, the user's call): the writer refuses, on every rank and
before writing anything, a directory that already holds a checkpoint
(`model.safetensors`, its index, or `model-NNNNN-of-NNNNN.safetensors`),
so a commit failure can no longer mix one. The refusal is decided in the
first collective, so one rank's view of the directory stops them all.
This replaces the documented commit limit and the stale-file cleanup of
`285c30bf08e`, which is removed with its tests; the staged `.tmp` writes
stay. A two-rank test checks the refusal for a one-shard, three-shard
and single-file earlier checkpoint, each left byte for byte, and fails
without the refusal. Another exports beside a `config.json` and an
auxiliary weights file, and fails if the pattern also matches the
auxiliary file. `test_distributed_writer.py` passes (49), and pre-commit
passes against main. Source lines: 270.
- 2026-10-29, later: merges [2/3] rebased onto main `2b900c8fa41` with
its third review round (`b73c052e45f`): every rank initializes NCCL
before a transfer only some ranks take part in, with a fresh-group GPU
test, and the transport's memory bound names what a rank sends. No
change of its own (`8b6f3a275f7`). The writer and conversion tests pass
(128), and pre-commit passes against main.
- GPU run, 2026-10-29, at `8b6f3a275f7`. GB200, torch 2.11.0a0 (NGC
26.02), CUDA 13.1, NCCL 2.29.2, transformers 5.9.0:

| `tests/gpu/torch/export/test_distributed_writer_gpu.py` | 2 GPUs | 4
GPUs |
  |---|---|---|
| Result | 2 passed, 1 skipped (the fresh-group test needs 3 or more),
20.4 s | 3 passed, 46.1 s |
- 2026-10-29, later: merges [2/3]'s docstring note that owners are
weighed by bytes (`764036cd64e`). No change of its own (`2a65d9fa364`);
pre-commit passes against main.
- Rebased on 2026-10-29 onto #3101's squash `4bef85279e4` after it
merged, with this PR's own diff unchanged. The history is now linear:
one commit for the pieces as they stood when the split was made, then
this PR's four commits since. #3100's and #3101's pre-squash commits are
dropped. Pre-commit passes against main; the writer and conversion tests
pass (128).
- Claude review, 2026-10-29 (approved, two suggestions; `55b62f6fdf4`,
docstring and message only): `_write_even_shards`' docstring says that a
failure during the final renames leaves the shards already renamed,
which a retry is refused over until they are removed, and the refusal's
message names that cause. It also says the caller drops tied weights by
name. Pre-commit passes against main; `test_distributed_writer.py`
passes (49).
- Rebased on 2026-10-30 onto main `99c3834f62c` (after #3099 and #2750
merged, and #2737), own diff unchanged and no conflicts: main's new
commits touch none of this PR's files. Pre-commit passes against main.

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

- Is this change backward compatible?: ✅ Additive; nothing calls these
yet.
- 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 no-gather export's entry lands with #2752.
- Did you get Claude approval on this PR?: ❌ Not yet.

### Additional Information

Part 15 of 21 of expert-parallel PTQ for Hugging Face MoE models; its
[1/3] #3100 and [2/3] #3101 have merged.

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

* **New Features**
* Added distributed checkpoint export in Hugging Face safetensors
format, writing tensors across ranks without gathering the full model on
every rank.
* Exported files are balanced by size, with oversized tensors placed in
their own files and an index generated for the shards.
* Export supports eligible sharded tensors and reverses supported
quantization-related weight conversions.
* **Bug Fixes**
* Exports detect incompatible shards, tensor-name collisions, and write
failures across ranks to help prevent incomplete or inconsistent
checkpoints.
<!-- 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.

4 participants