Skip to content

AutoEP + AutoTP folding: Universal Checkpointing under ZeRO-3 - #8848

Open
pengdurice wants to merge 7 commits into
deepspeedai:masterfrom
pengdurice:peng-autoep-folding-ucp-v1
Open

pengdurice wants to merge 7 commits into
deepspeedai:masterfrom
pengdurice:peng-autoep-folding-ucp-v1

Conversation

@pengdurice

@pengdurice pengdurice commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

AutoEP + AutoTP folding: Universal Checkpointing under ZeRO-3

Part of: #8672 (Q4 2026 roadmap), "Mixture-of-Expert (MoE) Training Scaling and Kernel Development": "AutoEP Performance Optimization & Parallel Folding (AutoEP + AutoTP)" (PoC @tohtana @pengdurice). Follows #8670.

Problem

#8670 makes ds_to_universal refuse a folded ZeRO-3 checkpoint: "Universal checkpoint conversion of an AutoEP +
AutoTP folded ZeRO-3 checkpoint is not supported yet. Load it with the same topology." So a folded run can only resume
with the same TP size, EP size and number of GPUs.

Four things stood in the way: three in the conversion, one in the load.

  1. File keys. The AutoEP expert step of the ZeRO-3 conversion keyed checkpoint files by the ZeRO data-parallel rank
    alone (_zero3_rank_from_file). ZeRO-3 files are named zero_pp_rank_{dp}_mp_rank_{tp}. Under folding the files of
    different TP ranks share a data-parallel rank, so they collided. That is why AutoEP + AutoTP folding under ZeRO-3 #8670 refused.
  2. Experts in the AutoTP universal info. collect_autotp_universal_checkpoint_info publishes every parameter AutoTP
    left untouched as TP-replicated, with an affine map built from its local shape. Under folding that includes the AutoEP
    expert weights (experts.w1/w2/w3), but the TP peers hold different experts, so this layout is wrong. Any reader
    that plans from the published patterns or affine maps would trust it.
  3. The TP merge's strict check. _merge_tp_slice_files asserts that every pattern in AutoTP's universal info was
    used. The expert patterns of item 2 are never used by the TP merge, because the AutoEP step merges those weights,
    so the assertion fails.
  4. The layout check on load. _load_checkpoint compares the folding layout recorded in the model-states file with
    the runtime's (_validate_autoep_folding_checkpoint_metadata). This rejects any other TP size, EP size or an
    unfolded runtime, although a universal load re-cuts every tensor for the runtime's layout.

Change

  • deepspeed/checkpoint/ds_to_universal.py:
    • The AutoEP ZeRO-3 files are keyed by (TP rank, DP rank), with _zero3_tp_dp_ranks_from_file, which the dense
      merge already uses. _zero3_rank_from_file is no longer used and is removed, along with the folding refusal. The
      docstring of _autoep_expert_param_names_by_rank states the key.
    • _merge_tp_slice_files no longer counts a pattern as unused when it only matches parameters excluded from this
      merge. The ZeRO-3 path now passes the AutoEP expert names as excluded; the ZeRO-1/2 path already did. With the
      change to layers.py below, new checkpoints no longer publish these patterns; this keeps checkpoints saved before
      it convertible.
    • When an optimizer file has no ds_zero_partition_groups entry for an expert sub-group, the converter raises
      instead of falling back to the dense data-parallel size and rank. Expert sub-groups are partitioned over the
      expert-data-parallel group, so that fallback would be wrong. Every partition-native AutoEP ZeRO-3 checkpoint
      records the entry.
    • The expert reassembly itself is unchanged. It already uses each file's EP rank and ZeRO partition rank. Under
      folding each expert slice exists on exactly one rank, and the existing duplicate and completeness checks still
      apply.
  • deepspeed/module_inject/layers.py collect_autotp_universal_checkpoint_info: skip the expert parameters of AutoEP
    layers (the parameters with allreduce=False in a module marked _is_autoep_layer). AutoEP records their placement
    in its own checkpoint metadata. The router and the shared expert are still published as TP-replicated: they are the
    same on every TP peer. Experts of the legacy deepspeed.moe layer are not affected.
  • deepspeed/runtime/engine.py _load_checkpoint: skip the folding-layout check when checkpoint.load_universal is
    set. Rigid loads keep it. The other folding-metadata checks are on the ZeRO-1/2 per-expert files and the per-rank
    ZeRO files, which a universal load does not read.
  • Loading tensors needs no change. For each parameter, load_hp_checkpoint_state in stage3.py cuts the EP slice,
    then the TP shard, then the ZeRO partition in the parameter's own group (dense data-parallel or expert
    data-parallel). That is what folding needs. A module-only load (load_module_only=True) goes through
    load_module_checkpoint_state_from_checkpoint_dir_stage3, which uses the same function.
  • Docs: docs/code-docs/source/autoep.rst (universal loads, including module-only loads, can change
    tensor_parallel.autotp_size; regular loads need the same autoep_size and autotp_size) and
    docs/_pages/config-json.md.
  • Tests, in tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py:
    • TestZero3FoldedCheckpoint no longer expects the conversion to be refused.

    • New TestZero3FoldedUniversalCheckpoint. A distributed fixture trains a folded TP 2 x EP 2 run on 4 ranks for one
      AdamW step, saves, converts, and records every parameter and both Adam states at full size, then the losses and
      parameters of the next step. Each target layout loads the universal checkpoint and must restore every recorded
      tensor exactly. Targets with the source's 2 data-parallel groups read the same batches, so they must also repeat
      the next step. Targets, each in fp32 and bf16:

      Target (ranks, TP, EP) What changes from the source (4 ranks, TP 2, EP 2)
      4, 2, 2 nothing
      4, 2, 4 EP 4: each EP group spans both TP groups
      4, 2, 4, CPU optimizer offload (AutoEP + AutoTP folding: allow CPU optimizer offload under ZeRO-3 #8829) the same, with the optimizer on the CPU
      4, 4, 2 TP 4: one dense data-parallel group
      8, 4, 2 more ranks, the same 2 dense data-parallel groups
      2, 1, 2 AutoEP without AutoTP
      4, 1, 4 AutoEP without AutoTP: dense data parallel 2 → 4, expert data parallel 2 → 1, TP 2 → 1
    • The next-step comparison leaves out only the pass-through half of each attention key head of k_proj.bias
      ([..., 8:] with head_dim=16, partial_rotary_factor=0.5). Those entries add the same amount to every score of
      a query, which the softmax cancels, so their true gradient is zero; their computed gradient is rounding noise that
      another layout adds up in another order, and AdamW turns that noise into steps of about lr. RoPE rotates the other
      half by position, so it has a real gradient and is compared.

    • New TestZero3FoldedUniversalModuleOnlyLoad: the same converted checkpoint loaded with load_module_only=True
      into (4, 2, 4) and (4, 1, 4), in fp32 and bf16. Every fp32 weight must equal the recorded state. In fp32, (4, 2, 4)
      must also give the source's next losses, which checks the weights the model computes with.

    • New TestFoldedUniversalSchemaLeavesOutExperts: a folded TP 2 x EP 2 run saves a checkpoint; in every model-state
      file, no expert weight matches a tp_replicated_parameter_patterns entry or has an affine map.

    • test_autoep_unit.py: the converter's AutoEP detection test reads the metadata under the new
      (TP rank, DP rank) key.

Not covered:

  • ZeRO-1/2 conversion of folded checkpoints. It stores experts in per-expert files, one per TP rank, and is still
    refused in autoep_universal.py (resolve_expert_ckpt_path).
  • Folded layouts with AutoTP's default specifications (MLP column and row, row-parallel bias, vocabulary-parallel
    embedding and head). The test shards only the attention projections. The routed experts are the only part folding
    adds to the converter; the dense AutoTP categories go through the same ZeRO-3 TP merge as an unfolded AutoTP run.

Tests

On master 4a9efc1 with this change, 1 node of 8 NVIDIA H200 (driver 595.112.07), torch 2.8.0+cu126, pytest 8.3.5:

File Result
tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py (includes the 14 universal-checkpoint, 4 module-only and 1 schema cases) 88 passed
the same file, -m sequential 2 passed
tests/unit/v1/moe/test_autoep_checkpoint.py 47 passed, 2 skipped (ZeRO-1/2 universal-checkpoint cases that run only with DEEPSPEED_RUN_H100_TESTS=1)
tests/unit/v1/moe/test_autoep_autotp_checkpoint.py 6 passed, 2 skipped (resume cases that run only with DEEPSPEED_RUN_H100_TESTS=1)
tests/unit/v1/moe/test_autoep_unit.py (includes the converter's AutoEP detection test, updated for the (TP rank, DP rank) keys) 214 passed
tests/unit/checkpoint/test_autoep_affine_universal.py 21 passed
tests/unit/runtime/tensor_parallel/test_autotp_universal_checkpoint.py 33 passed
tests/unit/checkpoint/test_autotp_uc_checkpoint.py 47 passed
tests/unit/checkpoint/test_affine_shard_map.py 286 passed
tests/unit/checkpoint/test_fp32_master_only.py 8 passed
tests/unit/checkpoint/test_reshape_checkpoint.py 8 passed
tests/unit/v1/zero/test_zero2_gradient_safety.py 58 passed
tests/unit/v1/autotp/test_autotp_custom_patterns.py 28 passed
tests/unit/v1/autotp/test_tp_plan_e2e.py 10 passed
tests/unit/checkpoint/test_universal_checkpoint.py 150 passed
tests/unit/v1/autotp/test_autotp_training.py 44 passed, 2 skipped (the existing BF16-optimizer overflow skips); -m sequential: 66 passed

These are the test files that use a function this PR changes (ds_to_universal, collect_autotp_universal_checkpoint_info,
the universal-load branch of the AutoEP folding check). No test failed.

The new schema test fails, as it should, when deepspeed/module_inject/layers.py is taken from master 4a9efc1 and
everything else is kept: model.layers.1.mlp.experts.w1 is TP-replicated in .../zero_pp_rank_0_mp_rank_00_model_states.pt.

On CPU (DS_ACCELERATOR=cpu, torch 2.8.0): test_autoep_unit.py, test_autoep_affine_universal.py,
test_autoep_affine.py, tests/unit/runtime/tensor_parallel/test_autotp_universal_checkpoint.py,
test_autotp_uc_checkpoint.py, test_affine_shard_map.py: 614 passed, 19 skipped (cases that need an accelerator).

pre-commit run --files passes on the changed files.

Further checks (not part of the PR's tests)

Earlier, on master 5f266e2 with the folding optimizer-offload change (#8829, merged since) applied: a wider version
of the universal test with 7 target layouts. Besides the same layout, EP 4, TP 4, 8 ranks with TP 4 and AutoEP without
AutoTP: 8 ranks with TP 2 x EP 4, and AutoEP EP 4 without AutoTP. Run in fp32 and bf16, and in 3 offload combinations:
saved and loaded without offload, saved and loaded with offload, saved without and loaded with offload. All 42 loads
restore every parameter and both Adam states exactly. Every target with the source's 2 data-parallel groups repeats
the next step: losses equal, and parameters within 1e-4 relative, leaving out the whole attention key bias (that run
predates the narrower exclusion). In bf16 only the same layout repeats it.

Duplicate check

Searched open pull requests on 2026-11-18 ("ds_to_universal", "universal checkpoint AutoEP", "folding universal",
"AutoEP AutoTP folding"): none converts folded ZeRO-3 checkpoints. #9080 (universal loads across ZeRO stages) edits
ds_to_universal.py and engine.py in other functions (_save_optimizer_state_stage3, checkpoint file names).
#8844 (mine, merged) also edited _consolidate_zero3_autoep_expert_states; this branch merges it.

AI assistance

This change, its tests and this description were prepared with AI assistance (Claude).

Signed-off-by: pengdurice <pengduhit@gmail.com>

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

Thanks for picking this up, it fills an important gap for the folding work. I went through the converter path for folded ZeRO-3: routed experts aren't TP-sliced under folding (expert TP = 1), fragments don't collide since each global rank has a unique (ep_rank, edp_rank), ZeRO padding is stripped via ds_zero_partition_groups, and TP-replicated params go through replicated_map.rebuild. A synthetic folded grid over 7 layouts with odd sizes (so EDP padding occurs) reassembles fp32 / exp_avg / exp_avg_sq bitwise for me. The engine change is a no-op for non-folded runs, and comparing against the source engine's live state in the GPU test is the right reference.

1. [blocking] Existing unit test now fails with KeyError: 0 — ds_to_universal.py:709, test_autoep_unit.py:941

_autoep_expert_param_names_by_rank now keys metadata_by_rank by (tp_rank, dp_rank), but test_universal_converter_detects_zero3_partitioned_autoep_model_state still indexes metadata_by_rank[0]. It fails on CPU (DS_ACCELERATOR=cpu), and it's the one failure in the cpu-torch-latest check on 9362efc. Could you update it to metadata_by_rank[(0, 0)] and note the key shape in the helper's docstring, since other tests import it?

2. [should-fix] Docs promise module-only loads that aren't tested — config-json.md:1147

The new text promises weights-only / module-only universal loads at a different autotp_size, but TestZero3FoldedUniversalCheckpoint only exercises the default load_checkpoint. Module-only goes through load_module_checkpoint_state_from_checkpoint_dir_stage3, which never sees a folded source here. Could you add one load_module_only=True target that compares fp32 against the recorded state, or narrow the docs? Also, autoep.rst around L597 still says only autoep_size / DP size can change via universal checkpointing; worth mentioning autotp_size for folded runs.

3. [should-fix] CI covers a narrow set of layout changes — test_autoep_autotp_sharded_attention.py:529-535

On the 4-GPU runners (8, 4, 2) skips, so no CI-run target grows the dense DP degree; only (4, 4, 2) changes it, down to 1. A 4-rank (4, 1, 4) target would move dense DP 2→4, EDP 2→1 and TP 2→1 in one case. Also, with ATTENTION_ONLY_TP_SPECS only q/k/v (+bias) and o_proj are TP-sliced; the default-spec layouts (MLP gate/up column, down row, row-parallel bias, vocab-parallel embedding/head) never reach this converter path. One use_default_specs target, or a note in the description that they're out of scope?

4. [question] Experts are published as TP-replicated in the AutoTP UC metadata — ds_to_universal.py:608-611

Under folding, collect_autotp_universal_checkpoint_info publishes ...experts.w[123] as TP-replicated with a replicated_map over the EP-local shape, but TP peers hold different experts (with TP=EP=2 the groups coincide). Filtering those patterns out of the strict check works for this converter, but the metadata itself stays wrong. Would it be cleaner to skip AutoEP expert params when collecting AutoTP UC info? Anything that later plans from AFFINE_MAP in UC info (e.g. the shard-to-shard planner / executor) would otherwise trust a wrong map.

5. [nit] k_proj.bias exclusion — test_autoep_autotp_sharded_attention.py:577

The key bias only has a zero true gradient on its non-rotary half. With partial_rotary_factor=0.5 the rotary half is rotated by position-dependent RoPE; in fp64 on this tiny GLM-4-MoE I get max |grad| ≈ 1e-4 on the rotary dims (same order as q_proj.bias) vs ≈ 4e-11 on the pass-through dims. Could you exclude only [..., int(head_dim * partial_rotary_factor):] of each head instead of dropping the whole tensor?

6. [nit] Fallback partition values — ds_to_universal.py:870-871

If ds_zero_partition_groups were missing, this falls back to the dense DP size / rank, which is wrong for expert sub-groups (partitioned over EDP). Every partition-native AutoEP ZeRO-3 checkpoint writes it, so raising here seems safer than guessing.

banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Oct 21, 2026
deepspeedai#8855)

## Summary

Fixes a stale test expectation.
`TestTiedOutputHead::test_row_parallel_tied_head_is_refused[False/True]`
in `tests/unit/v1/moe/test_autoep_autotp_sharded_attention.py` fails on
master:

```
AssertionError: AutoTP sharded an output head whose weight is tied to the input embedding
```

The test (added in deepspeedai#8670) expects AutoTP to refuse a row-parallel output
head whose weight is tied to the input embedding. Since 3c6a5ca
("[AutoTP] Support tied embeddings for row-parallel…"), AutoTP supports
this case: it replaces the embedding with a `HiddenParallelEmbedding`
that shares the head's sharded weight. The two changes landed a day
apart, so the expectation was already stale when deepspeedai#8670 merged.

Change (test only, no runtime code modified):
- Rename the test to `test_row_parallel_tied_head_keeps_the_tie`.
- With and without `zero.Init`, check after `deepspeed.initialize` that
the embedding is a `HiddenParallelEmbedding` and `lm_head.weight is
embed_tokens.weight`.
- Run it in the CPU multi-rank nightly (`cpu-torch-multi-latest`).
Before, it skipped on CPU and needed 4 GPUs, so no nightly ran it: the
GPU nightly (`ci/torch_latest.py`) has exactly 2 GPUs. The check only
builds the engine, so it needs no accelerator: drop the CPU skip and
mark it `sequential`, because that nightly selects tests under `unit/v1`
only through its sequential phase. It keeps 4 ranks, which that nightly
admits (`LOCAL_SIZE=4`).

The original concern of the test still holds: under `zero.Init` AutoTP
gathers the partitioned head weight into a new parameter, and if the
embedding kept the old one the two would train as separate copies. The
identity check catches that. Numerical training parity of a tied
row-parallel head is already covered by
`TestTiedRowParallelOutputHeadTraining` in
`tests/unit/v1/autotp/test_autotp_training.py`.

## Related work

No open PR fixes this test. deepspeedai#8829 and deepspeedai#8848 both list these two failures
as pre-existing and leave them unchanged. I searched open PRs touching
`TestTiedOutputHead` and tied/vocab-parallel output heads.

## Tests

```
cd tests
# CPU, as in cpu-torch-multi-latest
DS_ACCELERATOR=cpu LOCAL_SIZE=4 DS_DISABLE_REUSE_DIST_ENV=1 pytest -p no:randomly --forked -m sequential "unit/v1/moe/test_autoep_autotp_sharded_attention.py::TestTiedOutputHead"
# XPU
CUDA_VISIBLE_DEVICES=4,5,6,7 pytest -p no:randomly -m sequential "unit/v1/moe/test_autoep_autotp_sharded_attention.py::TestTiedOutputHead"
```

| Test | master `cc7b5125d` | This PR |
|---|---|---|
| `TestTiedOutputHead[zero_init=False]` | failed on XPU
(`AssertionError` above) | passed on CPU (4 gloo ranks) and XPU (4
ranks) |
| `TestTiedOutputHead[zero_init=True]` | failed on XPU (`AssertionError`
above) | passed on CPU (4 gloo ranks) and XPU (4 ranks) |

`pre-commit run --files` on the changed file passes.

Hardware and software:
- CPU: Intel Xeon Platinum 8457C, 4 ranks over gloo
- XPU: 4× Intel Arc Pro B70
- Level Zero driver 1.15.39122 (compute runtime 26.27.39122.11)
- torch 2.14.0.dev20260804+xpu, transformers 5.17.0

## Compatibility matrix

Test-only change; no numerics, performance or memory impact.

| | Validated | Not validated |
|---|---|---|
| ZeRO | Stage 3, with and without `zero.Init` (as in the test) | Other
stages (not exercised by this test) |
| Precision | fp32 | |
| Offload | | Not exercised |
| Parallelism | AutoTP 2 × AutoEP 2 folding, world size 4 | |
| Accelerator | CPU, XPU | CUDA (not run locally; the GPU nightly does
not select `sequential` tests) |

## AI assistance

This PR was developed with AI assistance (GitHub Copilot CLI). I
reviewed every changed line and ran the tests above.

cc @pengdurice @0z5a @delock

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Oct 26, 2026
…pspeedai#8800)

## Summary

deepspeedai#8623 plans shard-to-shard copies between two `ParamAffineMap`s. Today,
though, the only AutoEP maps come from checkpoint metadata, so nothing
at runtime can feed the planner. This PR closes that gap: it builds the
source map from the placement the live `AutoEPMoELayer` actually holds,
and builds the target map from a target placement descriptor. Both maps
then go straight to `plan_transfer`.

```
AutoEP runtime placement -> source / target ParamAffineMap -> plan_transfer (deepspeedai#8623) -> copy descriptors
```

Maps of what each process actually stores under expert data parallelism
(EDP) and ZeRO are left to a follow-up, which builds them by nesting
these layout maps with ZeRO's storage maps.

Related: deepspeedai#8252 (§8.4 AutoEP expert placement), deepspeedai#8230, deepspeedai#8544.

## Changes

- `AutoEPMoELayer.expert_affine_maps()` returns the affine maps of the
live `w1`/`w2`/`w3`.
- Map ranks are EP-local ranks. The docstring explains how to translate
them with `dist.get_global_rank(self.ep_group, rank)`.
- Each shard is the unpartitioned packed `[local_experts, ...]` tensor.
ZeRO-3/EDP fragments stay outside the map, and the shape comes from
`ds_shape`.
  - No collectives.
- `AutoEPMoELayer.plan_expert_transfer(target_placement, limits=None, *,
replica_selector=None)` returns one `TransferPlan` per expert parameter.
- It only plans: it moves no data, swaps no parameters and migrates no
optimizer state.
- `autoep_affine.plan_autoep_placement_transfer(source_placement,
target_placement, logical_shape, ...)` is the layer-independent form.
Both placements go through the existing
`autoep_placement_to_affine_map`, so no second placement→map conversion
is introduced.
- Placements are compared by explicit rank IDs rather than list order
(`autoep_placements_equal`), and each parameter's published
`DS_AUTOEP_UC_META` placement and affine map must equal the live
lowering.
- The live placement must match how `repack_expert_weights` actually
packed the weights; today that is contiguous and uniform. A descriptor
that disagrees raises `NotImplementedError`, rather than producing a map
that addresses shards the weights do not have.
- A placement the descriptor can express is not necessarily one the
runtime can execute. The target placement is only used for planning.

## Not in scope

- Executing plans or transporting data (deepspeedai#8809), parameter swap,
optimizer-state migration.
- Storage maps of EDP replicas and ZeRO-3 fragments (follow-up PR), and
replica selection policy (deepspeedai#8252).
- Placement generation/versioning: the runtime does not change placement
after construction yet.
- Runtime support for non-uniform placements.

## Tests

`tests/unit/v1/moe/test_autoep_unit.py`:
- `test_live_expert_maps_address_the_packed_runtime_weights`: for each
rank, the map's shard shape and contents match the real packed
`w1/w2/w3`. The reference is the full tensor from
`repack_expert_weights(ep_size=1)`, which does not depend on any affine
map.
-
`test_plan_expert_transfer_moves_live_shards_into_target_packed_order`:
from EP=2 into 3 ranks with reordered, uneven, empty and replicated
placements; executing the plan reproduces the target shards, every
element is written once, and planning never calls `rebuild`/`extract`.
- `test_live_expert_maps_reject_a_placement_the_weights_do_not_have`,
`test_live_expert_maps_identify_placement_ranks_by_id`,
`test_live_expert_maps_reject_a_published_map_the_placement_does_not_produce`.

`tests/unit/checkpoint/test_autoep_affine.py`:
`test_placements_equal_identifies_ranks_by_id`.

Results (Intel Arc Pro B70):
- `test_autoep_unit.py`, `test_autoep_affine.py`,
`test_autoep_affine_universal.py`, `test_affine_transfer_plan.py`,
`test_affine_shard_map.py`, `test_autoep_zero3_metadata.py`: 432 passed,
6 skipped.
- `test_autoep_checkpoint.py` (8× B70): 32 passed, 2 skipped.


## Contribution checklist

**Related work.**
- This PR builds on deepspeedai#8623 (`plan_transfer`).
- Plan execution is deepspeedai#8809; replica policy is deepspeedai#8252.
- deepspeedai#8844 and deepspeedai#8848 change Universal Checkpointing for AutoEP. They do not
produce runtime maps.

A search for AutoEP placement and transfer and for affine maps found no
overlapping PR.

**Commands and results.** Hardware and software: Intel Arc Pro B70 (XPU,
XCCL), Level Zero driver 1.15.39122 (compute runtime 26.27.39122.11),
torch 2.14.0.dev20260804+xpu.
```
pytest -p no:randomly tests/unit/v1/moe/test_autoep_unit.py tests/unit/checkpoint/test_autoep_affine.py \
  tests/unit/checkpoint/test_autoep_affine_universal.py tests/unit/checkpoint/test_affine_transfer_plan.py \
  tests/unit/checkpoint/test_affine_shard_map.py tests/unit/checkpoint/test_autoep_zero3_metadata.py
pytest -p no:randomly tests/unit/v1/moe/test_autoep_checkpoint.py
```
Results are listed under Tests above.

**Numerics, performance, memory.** Training is not affected. The new
methods only run when called and use no collectives.

**Compatibility matrix.**

| | Validated | Not validated |
|---|---|---|
| ZeRO | Independent: maps describe the unpartitioned packed tensors |
Storage under EDP/ZeRO (follow-up) |
| Parallelism | EP=2; target placements on 3 ranks | |
| Precision | Dtype-independent: maps describe shapes and offsets | |
| Accelerator | XPU | CUDA, HPU |

**AI assistance.** This PR was developed with AI assistance (GitHub
Copilot CLI). I reviewed every changed line and ran the tests above.

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
pengdurice and others added 2 commits November 13, 2026 19:09
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
…zer offload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 17, 2026
…time (deepspeedai#8844)

# Universal Checkpointing: read AutoEP ZeRO-3 optimizer files one at a
time

## Problem

`ds_to_universal` converts a ZeRO-3 AutoEP checkpoint in two parts. The
dense parameters go through the usual
extract-and-merge path, which reads one optimizer file per worker and
writes fragments to `tmp/`. The routed experts
go through `_consolidate_zero3_autoep_expert_states`, which first loads
**every** rank's optimizer file into one dict
(`optim_states_by_rank`) and then keeps a copy of every expert fragment
in memory until all of them are merged.

Together those files hold every optimizer state of the model: fp32 (or
bf16) master weights plus both Adam moments.
For a large MoE model that is more than one host has:

| Model | Parameters | Optimizer state, fp32 master + fp32 Adam (12
B/param) | bf16 master + bf16 Adam (6 B/param) |
|---|---|---|---|
| MiniMax-M3 | 426.2B | 4.65 TiB | 2.33 TiB |
| GLM-5.2 | 743.4B | 8.11 TiB | 4.06 TiB |

The H200 nodes this was found on have 2 TiB of host memory, so the
conversion cannot finish for either model.

## Change

`_consolidate_zero3_autoep_expert_states` reads one rank's optimizer
file at a time:

- Each expert fragment it finds is written to
`<output>/tmp/autoep_expert_fragments/` (one file per parameter,
  optimizer state, EP rank and partition rank).
- Every reference into the rank's optimizer state, including the loop
variables, is dropped before the next file is
  read.
- The merge then loads, for one parameter and one state at a time, only
that parameter's fragments, and deletes each
fragment file once it is read, so the disk does not hold every fragment
and every universal file at the same time.

Peak host memory becomes one optimizer file plus one full expert tensor,
instead of all optimizer files.

The checks are unchanged: missing ranks, duplicate or missing
expert-data-parallel partitions, shape mismatches and
placement disagreements raise the same errors. The temporary fragments
live under `<output>/tmp`, which the converter
already uses for the dense fragments and removes at the end.

## Peak host memory

Measured with a probe on one checkpoint: a 4-layer mock MoE model (64
experts, hidden 1024, expert intermediate
4096: 3.22B expert parameters) trained one step and saved with ZeRO-3
and AutoEP EP 4 on 8 GPUs (bf16, Adam), giving
8 optimizer files of 36.19 GiB in total. Each version ran only
`_consolidate_zero3_autoep_expert_states`, in its own
process; peak resident memory is `ru_maxrss` (0.4 GiB of it is the
imports).

| | Peak host memory | Time | Output |
|---|---|---|---|
| master 3fe2d95 | 109.20 GiB | 93.6 s | |
| this change | 13.13 GiB | 203.6 s | all 36 universal files (fp32,
exp_avg, exp_avg_sq of each expert weight) bitwise equal to master's |

Master holds about 3 times the optimizer files at once; with this change
the peak is about one optimizer file plus one
parameter's tensors, and it does not grow with the number of ranks. The
cost is time: the fragments are written to
and read back from `<output>/tmp`, 2.2x slower here on a shared Lustre
file system. For MiniMax-M3 and GLM-5.2 the
old path cannot finish at all on a 2 TiB host.

Hardware: 1 node of 8 NVIDIA H100 80GB (driver 595.112.07), torch
2.8.0+cu126. Probe script:
`ucp_expert_memory_probe.py` (modes `save`, `convert`, `compare`).

## Tests

On master 3fe2d95 with this change, 1 node of 8 NVIDIA H100 80GB
(driver 595.112.07), torch 2.8.0+cu126, pytest 8.3.5:

| Test | Result |
|---|---|
| `tests/unit/checkpoint/test_autoep_affine_universal.py` (calls the
function directly) and `tests/unit/v1/moe/test_autoep_checkpoint.py`
(AutoEP ZeRO-3 save, convert, load at other layouts) | 69 cases: 67
passed, 2 skipped (ZeRO-1/2 universal-checkpoint cases that run only
with `DEEPSPEED_RUN_H100_TESTS=1`; this change is on the ZeRO-3 path) |

`pre-commit run --files` passes on the changed file.

## Duplicate check

Searched open pull requests on 2026-11-13 ("ds_to_universal", "universal
checkpoint AutoEP"). deepspeedai#9069 and deepspeedai#8973 change
how ZeRO-3 loads universal checkpoints and partial-offload checkpoints,
not `ds_to_universal.py`. deepspeedai#8848 (mine) also
edits `_consolidate_zero3_autoep_expert_states` (keys by tensor-parallel
and data-parallel rank); whichever of the two
merges second needs a small rebase.

## Compatibility

| Cell | Validated |
|---|---|
| ZeRO-3 + AutoEP checkpoint conversion, save / convert / load at other
layouts | yes (tests) |
| Dense (non-AutoEP) ZeRO-3 conversion | path unchanged |
| ZeRO-1 / ZeRO-2 conversion | path unchanged |

## AI assistance

This change, its tests and this description were prepared with AI
assistance (Claude).

---------

Signed-off-by: pengdurice <pengduhit@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
VitorEAFeliciano pushed a commit to Navegos/DeepSpeed that referenced this pull request Nov 17, 2026
…thout TP (deepspeedai#9069)

A ZeRO-3 checkpoint saved without TP can't be resumed in an AutoTP +
ZeRO-3 run through the universal checkpoint.

### Why

`ds_to_universal` writes each state of a ZeRO-3 checkpoint saved without
TP as a bare tensor (`merge_zero3_slices`); every other path writes a
dict with the tensor under `param`.
`DeepSpeedZeroOptimizer_Stage3.load_hp_checkpoint_state` takes the
AutoTP shard only when the file holds a dict. With a bare tensor it
partitions the whole weight as if it were this rank's TP shard, and the
copy into the flat buffer fails:

```
RuntimeError: start (272) + length (256) exceeds dimension size (280).
```

`_resolve_autotp_partition` cuts the shard using the target parameter's
AutoTP metadata and the loaded tensor, and never reads the dict, so the
check isn't needed.

### What

The target parameter alone decides whether to slice (`if param is not
None:`). Checkpoints converted before this keep loading, since the
loader accepts both formats as before.

Whether every conversion path should write the same format is left for
later, as discussed with @delock: the loader would still have to accept
bare tensors from checkpoints that were already converted.

No open PR touches this check (searched for `load_hp_checkpoint_state`
and ZeRO-3 universal AutoTP; deepspeedai#8848 changes the converter, not
`stage3.py`).

### Test

`TestZero3UniversalCheckpointWithoutTp` in
`test_autotp_uc_checkpoint.py` trains 4 steps under ZeRO-3 without TP,
converts, and loads into ZeRO-3 at TP1 and at AutoTP TP2. It compares
the fp32 weights, both Adam moments and the step counts with the saved
state bit for bit, since conversion and restore only copy. On master the
TP2 case fails with the error above; the TP1 case passes before and
after. `_affine_resume_engine` gains a `zero_stage` argument (default 1)
so the test reuses the existing resume model and helpers.

### Validation

- GPU, 4× A100-SXM4-40GB, driver 595.71.05, torch 2.12.1+cu130, NCCL
2.29.7, Python 3.12.11, `pytest --forked
tests/unit/checkpoint/test_autotp_uc_checkpoint.py
tests/unit/checkpoint/test_universal_checkpoint.py
tests/unit/checkpoint/test_autoep_affine_universal.py`: 217 passed with
the fix. With only the `stage3.py` change reverted, the new TP2 case
fails with the error above and the TP1 case passes.
- CPU, macOS arm64, Python 3.9.6, torch 2.8.0, gloo (`DS_ACCELERATOR=cpu
LOCAL_SIZE=4`): the same result for the new test, before and after. The
FusedAdam tests in these files can't build the op on macOS, so they ran
on GPU only.
- Qwen3-0.6B, bf16, the same 4× A100 node type and software, DP4 →
TP2×DP2 → DP4 under ZeRO-3, 20 steps per layout. Each change saves, runs
`ds_to_universal` and loads in the new layout, then compares every fp32
weight and both Adam moments with the saved state bit for bit. On master
the TP2×DP2 load fails with `start (187907840) + length (1048576)
exceeds dimension size (187924480)`; with the fix both changes restore
all 930 tensors bit for bit.
- pre-commit passes on the changed files.

### Checked and not changed

- ZeRO-1/2 (`universal_checkpoint.load_hp_checkpoint_state`) reads
`ckpt_dict[PARAM]` unconditionally, but stage 1/2 conversion always
writes the dict, and a ZeRO-3 universal checkpoint doesn't reach that
loader today: a ZeRO-1 engine looks for `mp_rank_00_model_states.pt`,
while the converted ZeRO-3 folder has
`zero_pp_rank_0_mp_rank_00_model_states.pt`, so the load stops in
`state_dict_factory.check_ckpt_list`.
- The AutoEP branch above this check is unchanged.

Validated: ZeRO-3 without offload; fp32 (the unit test) and bf16
(Qwen3-0.6B); TP1 → TP1, TP1 → TP2, and DP4 → TP2×DP2 → DP4. Not
validated: CPU or NVMe offload, fp16, pipeline parallelism.

Signed-off-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
pengdurice and others added 2 commits November 18, 2026 16:29
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
- Leave AutoEP expert weights out of the AutoTP universal-checkpoint info; under folding the TP peers hold different experts.
- Raise when an expert sub-group has no ds_zero_partition_groups entry instead of using the dense DP size and rank.
- Tests: module-only load, a (4, 1, 4) target, the saved schema, the key bias compared on its rotary half, and the
  (TP rank, DP rank) key in the AutoEP detection test.
- Docs: universal and module-only loads can change tensor_parallel.autotp_size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot removed the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 18, 2026
@pengdurice
pengdurice marked this pull request as ready for review November 18, 2026 16:53
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T17:02:47.674119Z 07fdd4d Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 07fdd4df2f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread docs/code-docs/source/autoep.rst Outdated
Comment on lines +70 to +71
a different ``tensor_parallel.autotp_size`` (folded or not), or any
combination, when the target ``autoep_size`` divides the model's expert count.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Qualify the promised topology combinations

When a target keeps tensor_parallel.autotp_size > 1 but changes autoep_size to 1, the stated divisor condition is satisfied, yet validate_folding_global rejects that engine in deepspeed/module_inject/auto_ep_folding.py:244-246 before the universal checkpoint can load. The new “or any combination” claim therefore advertises an unsupported topology; either support this target or state that autoep_size must remain greater than 1 whenever AutoTP is enabled.

Useful? React with 👍 / 👎.

With tensor_parallel.autotp_size > 1, folding rejects autoep_size 1 at deepspeed.initialize, so that target cannot
load a universal checkpoint. Say so where the docs list the supported layout changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants