From 18423bfa1f73bfe305507b682399cb83f009a6de Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 22 Oct 2026 08:27:57 +0000 Subject: [PATCH 1/7] Describe AutoEP expert storage by nesting placement and ZeRO maps AutoEPMoELayer.expert_storage_affine_maps() describes, in global ranks, where every element of each packed expert parameter is stored: the packed [local_experts, ...] tensor of every expert-data-parallel replica under ZeRO-0/1/2, or each holder's ds_tensor partition without padding under ZeRO-3. A transfer plan built from it reads straight from training storage, so expert weights no longer need to be normalized to packed EP tensors first. autoep_storage_affine_map nests the placement's layout map with ZeRO's storage map of each packed tensor, so every holder of an element, across EDP replicas and redundant experts, is listed for the planner's replica selection. The maps are in the parameter's own shape. The maps are built locally: groups keeps the ranks of every expert data parallel group, which every rank creates anyway, so a rank can locate other ranks' replicas without a collective. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/affine_ir_spec.md | 2 + deepspeed/checkpoint/autoep_affine.py | 78 ++++++++++- deepspeed/module_inject/auto_ep_layer.py | 75 +++++++++- deepspeed/utils/groups.py | 19 +++ docs/code-docs/source/autoep.rst | 32 ++++- tests/unit/checkpoint/test_autoep_affine.py | 146 +++++++++++++++++++- tests/unit/utils/test_groups.py | 14 ++ tests/unit/v1/moe/test_autoep_checkpoint.py | 80 +++++++++++ 8 files changed, 435 insertions(+), 11 deletions(-) diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index c9108518d107..078bf835bb0a 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -613,6 +613,8 @@ expert parameters, and `AutoEPMoELayer.plan_expert_transfer(target_placement)` c them with a target descriptor through `plan_transfer` into shard-to-shard copies. Plan ranks are EP-local ranks of the respective placements; the plan is not executed, and ZeRO and EDP storage must still be normalized before its offsets apply. +`AutoEPMoELayer.expert_storage_affine_maps()` removes that step by describing the storage +itself (§10). `deepspeed/checkpoint/zero_affine.py` takes the first step for live training storage. It describes, in global ranks, where ZeRO keeps each element of a parameter: the low-precision diff --git a/deepspeed/checkpoint/autoep_affine.py b/deepspeed/checkpoint/autoep_affine.py index 0314aac781e8..e2ee13447041 100644 --- a/deepspeed/checkpoint/autoep_affine.py +++ b/deepspeed/checkpoint/autoep_affine.py @@ -2,13 +2,15 @@ # DeepSpeed Team """AutoEP expert placement descriptors and their affine lowering. -The descriptor records placement in EP-local rank coordinates. ZeRO and EDP -fragments are deliberately outside this map: callers must first normalize -storage to one logical, packed expert tensor per EP rank. +The descriptor records placement in EP-local rank coordinates, and +``autoep_placement_to_affine_map`` describes one logical, packed expert tensor +per EP rank. ``autoep_storage_affine_map`` adds the expert-data-parallel and +ZeRO layer on top: it describes what each global rank actually stores. """ -from deepspeed.checkpoint.affine import AFFINE_MAP_FORMAT_VERSION, AffinePiece, ParamAffineMap +from deepspeed.checkpoint.affine import AFFINE_MAP_FORMAT_VERSION, AffinePiece, ParamAffineMap, nest_affine_maps from deepspeed.checkpoint.affine_transfer import plan_transfer +from deepspeed.checkpoint.zero_affine import zero_storage_affine_map from deepspeed.checkpoint.constants import (AFFINE_MAP, AFFINE_MAP_PARAMS, AFFINE_MAP_VERSION, AUTOEP_AFFINE_MAPS, AUTOEP_EXPERT_PLACEMENT, AUTOEP_PLACEMENT_EP_SIZE, AUTOEP_PLACEMENT_EXPERTS, AUTOEP_PLACEMENT_NUM_EXPERTS, @@ -23,6 +25,7 @@ 'legacy_uniform_autoep_placement_descriptor', 'autoep_placements_equal', 'autoep_placement_to_affine_map', + 'autoep_storage_affine_map', 'autoep_metadata_to_affine_map', 'extract_autoep_rank_tensor', 'plan_autoep_placement_transfer', @@ -169,6 +172,40 @@ def autoep_placement_to_affine_map(descriptor, logical_shape): return affine_map +def autoep_storage_affine_map(descriptor, logical_shape, holders_by_ep_rank, partition_numel_by_ep_rank=None): + """Lower one expert parameter to the storage each global rank actually holds. + + ``holders_by_ep_rank`` maps every rank ID of ``descriptor`` to the global ranks that store that + EP rank's packed ``[local_experts, ...]`` tensor, in expert-data-parallel (EDP) rank order. + + Without ``partition_numel_by_ep_rank``, every holder stores the whole packed tensor, as EDP + replicas do under ZeRO-0/1/2. With it, holder ``d`` of EP rank ``r`` stores elements + ``[d * n, (d + 1) * n)`` of the flattened packed tensor, where ``n`` is + ``partition_numel_by_ep_rank[r]``, as ZeRO-3 does. ZeRO-3's trailing padding holds no + parameter elements and is not part of the shard, so a holder whose partition is all padding, + like every holder of an EP rank without experts, has an empty shard. + + The returned map describes the parameter in its own shape and is keyed by global rank; each + shard is the holder's flat storage. It nests the placement's layout map with ZeRO's + storage map of each packed tensor, so every holder of an element, across EDP replicas and + redundant experts, is listed in the piece's ``locations``; choosing among them is left to the + transfer planner's replica selection. + """ + layout = autoep_placement_to_affine_map(descriptor, logical_shape) + entries_by_rank = {entry[AUTOEP_PLACEMENT_RANK]: entry for entry in descriptor[AUTOEP_PLACEMENT_RANKS]} + holders_by_ep_rank = _validated_storage_holders(holders_by_ep_rank, entries_by_rank) + + storage_by_ep_rank = {} + for ep_rank, global_ranks in holders_by_ep_rank.items(): + packed_numel = _product(layout.shard_shapes[ep_rank]) + partition_numel = None + if partition_numel_by_ep_rank is not None: + partition_numel = _storage_partition_numel(partition_numel_by_ep_rank, ep_rank, len(global_ranks), + packed_numel) + storage_by_ep_rank[ep_rank] = zero_storage_affine_map(packed_numel, global_ranks, partition_numel) + return nest_affine_maps(layout, storage_by_ep_rank) + + def autoep_metadata_to_affine_map(metadata, logical_shape, param_name=None): """Load a persisted AutoEP affine map, falling back to legacy placement lowering.""" serialized_map = metadata.get(AFFINE_MAP) @@ -252,6 +289,39 @@ def _pieces_for_rank(experts, holders, expert_shape, expert_numel, source_stride return pieces +def _validated_storage_holders(holders_by_ep_rank, entries_by_rank): + if not isinstance(holders_by_ep_rank, dict): + raise TypeError('holders_by_ep_rank must map each EP rank ID to its global holder ranks.') + if set(holders_by_ep_rank) != set(entries_by_rank): + raise ValueError(f'holders_by_ep_rank names EP ranks {sorted(holders_by_ep_rank)}; the placement ' + f'descriptor names {sorted(entries_by_rank)}.') + seen = set() + validated = {} + for ep_rank in sorted(holders_by_ep_rank): + global_ranks = list(holders_by_ep_rank[ep_rank]) + if not global_ranks: + raise ValueError(f'EP rank {ep_rank} has no global holder rank.') + for global_rank in global_ranks: + if not isinstance(global_rank, int) or isinstance(global_rank, bool) or global_rank < 0: + raise ValueError(f'Global holder rank {global_rank!r} of EP rank {ep_rank} is not a ' + 'non-negative integer.') + if global_rank in seen: + raise ValueError(f'Global rank {global_rank} holds storage for more than one EP rank entry.') + seen.add(global_rank) + validated[ep_rank] = global_ranks + return validated + + +def _storage_partition_numel(partition_numel_by_ep_rank, ep_rank, num_holders, packed_numel): + partition_numel = partition_numel_by_ep_rank.get(ep_rank) + if not isinstance(partition_numel, int) or isinstance(partition_numel, bool) or partition_numel < 0: + raise ValueError(f'Partition size {partition_numel!r} of EP rank {ep_rank} is not a non-negative integer.') + if partition_numel * num_holders < packed_numel: + raise ValueError(f'EP rank {ep_rank} packs {packed_numel} elements, but its {num_holders} holders of ' + f'{partition_numel} elements each cannot store them.') + return partition_numel + + def _expert_holders(entries_by_rank, num_experts): holders = {expert_id: set() for expert_id in range(num_experts)} for rank, entry in entries_by_rank.items(): diff --git a/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index fbdfab2f5dff..dbf6e48f90a2 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -14,6 +14,7 @@ from __future__ import annotations +import math from functools import lru_cache from typing import Literal, NamedTuple @@ -22,7 +23,8 @@ import deepspeed.comm as dist from deepspeed.accelerator import get_accelerator from deepspeed.checkpoint.autoep_affine import (autoep_experts_for_rank, autoep_placement_to_affine_map, - autoep_placements_equal, legacy_uniform_autoep_placement_descriptor, + autoep_placements_equal, autoep_storage_affine_map, + legacy_uniform_autoep_placement_descriptor, plan_autoep_placement_transfer) from deepspeed.checkpoint.affine import ParamAffineMap from deepspeed.checkpoint.affine_transfer import PlanBudget, TransferPlan @@ -792,11 +794,80 @@ def expert_affine_maps(self) -> dict[str, ParamAffineMap]: """Return the affine map of each live expert parameter (``w1``, ``w2``, ``w3``). Map ranks are EP-local ranks; translate them with ``dist.get_global_rank(self.ep_group, rank)``. - Each rank's shard is the unpartitioned packed ``[local_experts, ...]`` tensor. + Each rank's shard is the unpartitioned packed ``[local_experts, ...]`` tensor; use + :meth:`expert_storage_affine_maps` for the expert-data-parallel and ZeRO-3 storage. """ placement = self._live_expert_placement() return {name: self._live_expert_affine_map(name, placement) for name in ("w1", "w2", "w3")} + def _expert_storage_group(self, params: dict[str, nn.Parameter]): + partitioned = [hasattr(param, "ds_id") for param in params.values()] + if all(partitioned): + storage_groups = {id(param.ds_process_group): param.ds_process_group for param in params.values()} + if len(storage_groups) != 1: + raise ValueError("AutoEP expert parameters are ZeRO-3 partitioned over different process groups.") + return next(iter(storage_groups.values())) + if any(partitioned): + raise ValueError("Only some AutoEP expert parameters are ZeRO-3 partitioned.") + if self.folding_group_handles is not None: + return self.folding_group_handles.edp_group + from deepspeed.utils import groups + return groups._get_expert_data_parallel_group(self.ep_group_name) + + def expert_storage_affine_maps(self) -> dict[str, ParamAffineMap]: + """Return the affine map of the storage each global rank holds for ``w1``, ``w2`` and ``w3``. + + This is computed locally from the expert data parallel group table and the placement, so it + involves no communication and any rank may call it on its own. + + Map ranks are global ranks and the logical shape is the parameter's own shape. Each shard is + a rank's flat storage: the packed ``[local_experts, ...]`` tensor under ZeRO-0/1/2, where all + expert-data-parallel replicas are listed as holders, or the rank's ZeRO-3 partition + ``ds_tensor`` without its trailing padding. Optimizer state is not described. + """ + if self.folding_group_handles is not None and self.folding_group_handles.spec.etp_size > 1: + raise NotImplementedError("Expert storage maps do not describe expert tensor-parallel shards yet.") + placement = self._live_expert_placement() + params = {name: getattr(self.experts, name) for name in ("w1", "w2", "w3")} + for name in params: + self._live_expert_affine_map(name, placement) + storage_group = self._expert_storage_group(params) + partitioned = hasattr(params["w1"], "ds_id") + + # The EDP group of each EP rank's global rank holds that EP rank's packed tensor. Every rank + # built all EDP groups, so the table answers this without assuming a rank layout. + from deepspeed.utils import groups + group_of_rank = {} + for group_ranks in groups._get_expert_data_parallel_group_table(self.ep_group_name): + for global_rank in group_ranks: + group_of_rank[global_rank] = list(group_ranks) + own_storage_ranks = dist.get_all_ranks_from_group(storage_group) + if group_of_rank.get(dist.get_rank()) != own_storage_ranks: + raise RuntimeError(f"Expert storage group ranks {own_storage_ranks} do not match the expert data " + f"parallel group table for {self.ep_group_name}.") + holders_by_ep_rank = {} + for ep_rank, global_rank in enumerate(dist.get_all_ranks_from_group(self.ep_group)): + holders_by_ep_rank[ep_rank] = group_of_rank[global_rank] + + storage_maps = {} + for name, param in params.items(): + logical_shape = self._expert_logical_shape(param) + partition_numel_by_ep_rank = None + if partitioned: + # ZeRO-3 pads each packed tensor to a multiple of the group size and splits it evenly. + expert_numel = math.prod(logical_shape[1:]) + partition_numel_by_ep_rank = {} + for ep_rank, holders in holders_by_ep_rank.items(): + packed_numel = len(autoep_experts_for_rank(placement, ep_rank)) * expert_numel + partition_numel_by_ep_rank[ep_rank] = -(-packed_numel // len(holders)) + expected = partition_numel_by_ep_rank[self.ep_rank] + if param.ds_tensor.ds_numel != expected: + raise RuntimeError(f"Expert parameter {name} has a ZeRO-3 partition of {param.ds_tensor.ds_numel} " + f"elements, but even partitioning gives {expected}.") + storage_maps[name] = autoep_storage_affine_map(placement, logical_shape, holders_by_ep_rank, + partition_numel_by_ep_rank) + return storage_maps + def plan_expert_transfer(self, target_placement: dict, limits: PlanBudget | None = None, diff --git a/deepspeed/utils/groups.py b/deepspeed/utils/groups.py index 777850de5f1c..e5473e42a3cc 100644 --- a/deepspeed/utils/groups.py +++ b/deepspeed/utils/groups.py @@ -42,6 +42,10 @@ _EXPERT_DATA_PARALLEL_GROUP = {} # Mapping of expert data parallel group to ranks _EXPERT_DATA_PARALLEL_GROUP_RANKS = {} +# Mapping of expert data parallel group name to the ranks of every group with that name, not only the +# caller's. Every rank builds all groups anyway, so keeping them lets ranks locate other ranks' replicas +# without a collective. +_EXPERT_DATA_PARALLEL_GROUP_TABLE = {} # dist world group needs to be cloned for some cases _WORLD_GROUP = None # ZeRO parameter partitioning group that the current rank belongs to. @@ -111,6 +115,7 @@ def _release_process_group_references(group=None): _EXPERT_PARALLEL_GROUP_RANKS.clear() _EXPERT_DATA_PARALLEL_GROUP.clear() _EXPERT_DATA_PARALLEL_GROUP_RANKS.clear() + _EXPERT_DATA_PARALLEL_GROUP_TABLE.clear() _ALL_TO_ALL_GROUP.clear() _WORLD_GROUP = None _ZERO_PARAM_INTRA_PARALLEL_GROUP = None @@ -430,6 +435,7 @@ def _create_expert_and_data_parallel(expert_parallel_size_, # Build the expert data parallel groups. # Only create group if it does not already exist if group_name not in _EXPERT_DATA_PARALLEL_GROUP: + edp_table = [] for pp_stage_start in range(0, world_size, pp_stride): for i in range(expert_parallel_size_): if use_data_before_expert_parallel_: @@ -437,12 +443,14 @@ def _create_expert_and_data_parallel(expert_parallel_size_, else: ranks = range(pp_stage_start + i, pp_stage_start + pp_stride, expert_parallel_size_) group = dist.new_group(ranks) + edp_table.append(tuple(ranks)) log_dist( f'Creating expert data parallel process group named {group_name} with ranks: {list(ranks)}', [0]) if rank in ranks: _EXPERT_DATA_PARALLEL_GROUP[group_name] = group _EXPERT_DATA_PARALLEL_GROUP_RANKS[group_name] = ranks + _EXPERT_DATA_PARALLEL_GROUP_TABLE[group_name] = tuple(edp_table) # Build the expert parallel groups. # Only create group if it does not already exist @@ -491,6 +499,7 @@ def _create_expert_and_data_parallel(expert_parallel_size_, from deepspeed.module_inject.auto_ep_folding import expected_folding_group_tables folding_tables = expected_folding_group_tables(folding_spec) + edp_table = [] for pp_stage_start in range(0, world_size, pp_stride): stage_ranks = list(range(pp_stage_start, pp_stage_start + pp_stride)) stage_rank_set = set(stage_ranks) @@ -529,10 +538,12 @@ def _create_expert_and_data_parallel(expert_parallel_size_, for edp_ranks in edp_groups_list: group = dist.new_group(edp_ranks) + edp_table.append(tuple(edp_ranks)) log_dist(f'Creating expert data parallel process group named {group_name} with ranks: {edp_ranks}', [0]) if rank in edp_ranks: _EXPERT_DATA_PARALLEL_GROUP[group_name] = group _EXPERT_DATA_PARALLEL_GROUP_RANKS[group_name] = edp_ranks + _EXPERT_DATA_PARALLEL_GROUP_TABLE[group_name] = tuple(edp_table) def _get_expert_parallel_ranks(world_size, @@ -659,6 +670,7 @@ def _create_expert_data_and_model_parallel(expert_parallel_size_, mpu, use_data_ if rank in list(ranks): _EXPERT_DATA_PARALLEL_GROUP[group_name] = group _EXPERT_DATA_PARALLEL_GROUP_RANKS[group_name] = ranks + _EXPERT_DATA_PARALLEL_GROUP_TABLE[group_name] = tuple(tuple(ranks) for ranks in expert_data_parallel_groups) def _get_max_expert_size(): @@ -715,6 +727,13 @@ def _get_expert_data_parallel_group_ranks(group_name): return _EXPERT_DATA_PARALLEL_GROUP_RANKS[group_name] +def _get_expert_data_parallel_group_table(group_name): + """Get the ranks of every expert data parallel group named ``group_name``, in creation order.""" + assert group_name in _EXPERT_DATA_PARALLEL_GROUP_TABLE, \ + 'expert data parallel group is not initialized' + return _EXPERT_DATA_PARALLEL_GROUP_TABLE[group_name] + + def _get_expert_data_parallel_group_dict(): """Get the expert data parallel group dict.""" return _EXPERT_DATA_PARALLEL_GROUP diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 7d8d0ee4c4e1..75c0bae84eed 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -683,7 +683,8 @@ plan optimizer states, and does not change the placement the layer runs with. order. That tensor is the unpartitioned parameter: under ZeRO-3, gather the parameter (for example with ``deepspeed.zero.GatheredParameters``) before applying the offsets. Ranks are EP-local, so expert-data-parallel replicas - are not candidates here. + are not candidates here; plan from ``expert_storage_affine_maps()`` to read + from them. - When several source ranks hold an element, the plan reads it from the lowest-ranked holder. Pass ``replica_selector``, a callable that receives a ``ReplicaSelectionRequest`` and returns the ``source_rank`` of one of its @@ -694,5 +695,34 @@ plan optimizer states, and does not change the placement the layer runs with. layer's placement descriptor describes anything else, both methods raise ``NotImplementedError``. +``expert_affine_maps()`` describes one packed tensor per EP rank, so ZeRO and +expert-data-parallel (EDP) storage has to be normalized before its offsets apply. +``expert_storage_affine_maps()`` instead describes what every process actually +stores, so a plan built from it reads directly from runtime storage: + +.. code-block:: python + + from deepspeed.checkpoint.affine_transfer import plan_transfer + + # Built locally from the expert data parallel group table; no communication. + storage_maps = layer.expert_storage_affine_maps() # {"w1": ParamAffineMap, ...} + plan = plan_transfer(target_map, storage_maps["w1"]) + +- Map ranks are global ranks. The logical shape is the parameter's own shape, + and each shard is a rank's flat storage, so offsets count elements of + ``param.data.view(-1)`` or, under ZeRO-3, of ``param.ds_tensor``. + ``target_map`` must use the same logical shape; + ``autoep_storage_affine_map`` in ``deepspeed.checkpoint.autoep_affine`` builds + one from a placement descriptor and its holders. +- Under ZeRO-0/1/2, every EDP replica of an EP rank stores the whole packed + tensor and is listed as a holder. The plan reads from the lowest global rank + unless ``replica_selector`` chooses another candidate. +- Under ZeRO-3, each EDP rank stores its partition of the packed tensor. The + trailing padding is not part of a shard, so a rank whose partition is all + padding, or whose EP rank holds no experts, has an empty shard and is never + a source or target of a copy. +- Optimizer states are not described. Expert tensor parallelism + (``expert_tensor_parallel_size > 1``) raises ``NotImplementedError``. + The maps and plans use the affine representation that Universal Checkpoint uses for expert parameters; see ``deepspeed/checkpoint/affine_ir_spec.md``. diff --git a/tests/unit/checkpoint/test_autoep_affine.py b/tests/unit/checkpoint/test_autoep_affine.py index f5cc7622533f..241ba0d4aaa1 100644 --- a/tests/unit/checkpoint/test_autoep_affine.py +++ b/tests/unit/checkpoint/test_autoep_affine.py @@ -7,10 +7,11 @@ import torch from deepspeed.checkpoint.affine import AFFINE_MAP_FORMAT_VERSION, ParamAffineMap +from deepspeed.checkpoint.affine_transfer import plan_transfer from deepspeed.checkpoint.autoep_affine import (AUTOEP_PLACEMENT_VERSION, autoep_experts_for_rank, autoep_metadata_to_affine_map, autoep_placement_to_affine_map, - autoep_placements_equal, extract_autoep_rank_tensor, - legacy_uniform_autoep_placement_descriptor, + autoep_placements_equal, autoep_storage_affine_map, + extract_autoep_rank_tensor, legacy_uniform_autoep_placement_descriptor, make_autoep_placement_descriptor, validate_autoep_placement_descriptor) from deepspeed.checkpoint.constants import (AFFINE_MAP, AFFINE_MAP_PARAMS, AFFINE_MAP_VERSION, AUTOEP_AFFINE_MAPS, AUTOEP_EXPERT_PLACEMENT, AUTOEP_PLACEMENT_RANKS) @@ -239,10 +240,147 @@ def test_extract_target_rank_uses_target_packed_order(): assert torch.equal(actual, expected) -def test_placements_equal_identifies_ranks_by_id(): - descriptor = make_autoep_placement_descriptor(4, [[3, 0], [], [2, 1, 0]]) +def _oracle_storage(full_tensor, experts_by_rank, holders_by_ep_rank, partition_numel_by_ep_rank=None): + """What each global rank stores, built by indexing the full tensor rather than through a map.""" + storage = {} + for ep_rank, packed in _oracle_shards(full_tensor, experts_by_rank).items(): + flat = packed.reshape(-1) + for edp_rank, global_rank in enumerate(holders_by_ep_rank[ep_rank]): + if partition_numel_by_ep_rank is None: + storage[global_rank] = flat.clone() + continue + partition_numel = partition_numel_by_ep_rank[ep_rank] + # ZeRO-3 pads the flattened tensor at its end; the padding holds no parameter elements. + storage[global_rank] = flat[edp_rank * partition_numel:(edp_rank + 1) * partition_numel].clone() + return storage + + +def _execute(plan, source_storage, target_storage): + writes = {rank: torch.zeros_like(storage, dtype=torch.int64) for rank, storage in target_storage.items()} + for segment in plan.segments: + source = torch.as_strided(source_storage[segment.source_rank], segment.shape, segment.source_strides, + segment.source_offset) + torch.as_strided(target_storage[segment.target_rank], segment.shape, segment.target_strides, + segment.target_offset).copy_(source) + torch.as_strided(writes[segment.target_rank], segment.shape, segment.target_strides, + segment.target_offset).add_(1) + return writes + + +# EP=2 x EDP=2 over global ranks 0..3, then EP=3 x EDP=2 with reordered, replicated and empty +# placements on interleaved global ranks. Partition sizes split experts mid-row and leave padding. +_SOURCE = ([[0, 1], [2, 3]], {0: [0, 2], 1: [1, 3]}, {0: 23, 1: 23}) +_TARGET = ([[3, 0], [], [2, 1, 0]], {0: [5, 1], 1: [0, 4], 2: [3, 2]}, {0: 30, 1: 0, 2: 38}) + + +@pytest.mark.parametrize('zero3', [False, True]) +@pytest.mark.parametrize('layout', [_SOURCE, _TARGET], ids=['uniform', 'replicated_and_empty']) +def test_storage_map_describes_what_each_global_rank_stores(layout, zero3): + experts_by_rank, holders, partitions = layout + partitions = partitions if zero3 else None + full_tensor = torch.arange(4 * 3 * 5, dtype=torch.float32).reshape(4, 3, 5) + descriptor = make_autoep_placement_descriptor(4, experts_by_rank) + expected = _oracle_storage(full_tensor, experts_by_rank, holders, partitions) + + affine_map = autoep_storage_affine_map(descriptor, full_tensor.shape, holders, partitions) + + affine_map.validate_coverage() + assert affine_map.shard_shapes == {rank: tuple(storage.shape) for rank, storage in expected.items()} + for rank, storage in expected.items(): + torch.testing.assert_close(affine_map.extract(full_tensor, rank), storage, rtol=0, atol=0) + torch.testing.assert_close(affine_map.rebuild(expected), full_tensor, rtol=0, atol=0) + + +def test_storage_map_offers_every_edp_replica_to_the_planner(): + experts_by_rank, holders, _ = _SOURCE + full_tensor = torch.arange(4 * 6, dtype=torch.float32).reshape(4, 6) + source_map = autoep_storage_affine_map(make_autoep_placement_descriptor(4, experts_by_rank), full_tensor.shape, + holders) + target_experts, target_holders, target_partitions = _TARGET + target_map = autoep_storage_affine_map(make_autoep_placement_descriptor(4, target_experts), full_tensor.shape, + target_holders, target_partitions) + source_storage = _oracle_storage(full_tensor, experts_by_rank, holders) + replica_sets = {frozenset(ranks) for ranks in holders.values()} + offered = [] + + def highest_replica(request): + offered.append(frozenset(candidate.source_rank for candidate in request.candidates)) + return max(candidate.source_rank for candidate in request.candidates) + + for selector, used_ranks in ((None, {0, 1}), (highest_replica, {2, 3})): + plan = plan_transfer(target_map, source_map, replica_selector=selector) + assert {segment.source_rank for segment in plan.segments} == used_ranks + target_storage = {rank: torch.full(shape, float('nan')) for rank, shape in target_map.shard_shapes.items()} + writes = _execute(plan, source_storage, target_storage) + expected = _oracle_storage(full_tensor, target_experts, target_holders, target_partitions) + for rank, storage in expected.items(): + torch.testing.assert_close(target_storage[rank], storage, rtol=0, atol=0) + assert torch.all(writes[rank] == 1) + assert offered and set(offered) <= replica_sets + + +def test_zero3_storage_plans_directly_into_a_new_placement(): + full_tensor = torch.arange(4 * 3 * 5, dtype=torch.float32).reshape(4, 3, 5) + layouts = [] + for experts_by_rank, holders, partitions in (_SOURCE, _TARGET): + descriptor = make_autoep_placement_descriptor(4, experts_by_rank) + layouts.append((autoep_storage_affine_map(descriptor, full_tensor.shape, holders, partitions), + _oracle_storage(full_tensor, experts_by_rank, holders, partitions))) + (source_map, source_storage), (target_map, expected) = layouts + + plan = plan_transfer(target_map, source_map) + + target_storage = {rank: torch.full(shape, float('nan')) for rank, shape in target_map.shard_shapes.items()} + writes = _execute(plan, source_storage, target_storage) + for rank, storage in expected.items(): + torch.testing.assert_close(target_storage[rank], storage, rtol=0, atol=0) + assert torch.all(writes[rank] == 1) + # Global ranks 0 and 4 hold the empty EP rank; rank 1's ZeRO-3 partition is all padding. + assert target_map.shard_shapes[0] == target_map.shard_shapes[4] == target_map.shard_shapes[1] == (0, ) + assert not {0, 4, 1} & {segment.target_rank for segment in plan.segments} + + +def test_storage_map_follows_explicit_rank_ids(): + experts_by_rank, holders, partitions = _TARGET + descriptor = make_autoep_placement_descriptor(4, experts_by_rank) reordered = dict(descriptor) reordered[AUTOEP_PLACEMENT_RANKS] = list(reversed(descriptor[AUTOEP_PLACEMENT_RANKS])) assert autoep_placements_equal(descriptor, reordered) assert not autoep_placements_equal(descriptor, make_autoep_placement_descriptor(4, [[0, 3], [], [2, 1, 0]])) + for zero3_partitions in (None, partitions): + expected = autoep_storage_affine_map(descriptor, (4, 6), holders, zero3_partitions) + actual = autoep_storage_affine_map(reordered, (4, 6), dict(reversed(list(holders.items()))), zero3_partitions) + assert actual.to_dict() == expected.to_dict() + + +@pytest.mark.parametrize('holders, partitions, match', [ + ({ + 0: [0, 2] + }, None, 'names EP ranks'), + ({ + 0: [0, 2], + 1: [1, 2] + }, None, 'more than one EP rank'), + ({ + 0: [0, 2], + 1: [] + }, None, 'no global holder'), + ({ + 0: [0, 2], + 1: [1, 3] + }, { + 0: 23, + 1: 14 + }, 'cannot store'), + ({ + 0: [0, 2], + 1: [1, 3] + }, { + 0: 23 + }, 'Partition size'), +]) +def test_storage_map_rejects_holders_that_do_not_store_the_placement(holders, partitions, match): + descriptor = make_autoep_placement_descriptor(4, [[0, 1], [2, 3]]) + with pytest.raises(ValueError, match=match): + autoep_storage_affine_map(descriptor, (4, 3, 5), holders, partitions) diff --git a/tests/unit/utils/test_groups.py b/tests/unit/utils/test_groups.py index 72a0eb8ef517..fd4050500a4b 100644 --- a/tests/unit/utils/test_groups.py +++ b/tests/unit/utils/test_groups.py @@ -211,3 +211,17 @@ def test_nonmember_destroy_preserves_cached_groups(self): assert value.item() == 1 dist.all_reduce(value) assert value.item() == self.world_size + + def test_subgroup_destroy_keeps_expert_data_parallel_table(self): + groups._create_expert_and_data_parallel(expert_parallel_size_=self.world_size) + (group_name, own_group), = groups._EXPERT_DATA_PARALLEL_GROUP.items() + expected_table = tuple((rank, ) for rank in range(self.world_size)) + assert groups._get_expert_data_parallel_group_table(group_name) == expected_table + + # Only the members of a subgroup release it, so a table describing every subgroup must + # outlive it on those ranks too, or ranks would disagree about the topology. + dist.destroy_process_group(group=own_group) + + assert group_name not in groups._EXPERT_DATA_PARALLEL_GROUP + assert groups._get_expert_data_parallel_group_table(group_name) == expected_table + dist.barrier() diff --git a/tests/unit/v1/moe/test_autoep_checkpoint.py b/tests/unit/v1/moe/test_autoep_checkpoint.py index 90dc56941b49..12db8bf876c5 100644 --- a/tests/unit/v1/moe/test_autoep_checkpoint.py +++ b/tests/unit/v1/moe/test_autoep_checkpoint.py @@ -648,6 +648,86 @@ def test_zero3_universal_weights_only_preserves_fp32_master_weights(self, tmpdir engine.destroy() +class TestAutoEPExpertStorageMaps(DistributedTest): + world_size = 4 + + @pytest.mark.parametrize("zero_stage, autotp_size", [(2, 1), (3, 1), (3, 2)]) + def test_storage_maps_match_runtime_ownership_and_plan_into_a_new_placement(self, zero_stage, autotp_size): + from deepspeed.checkpoint.affine_transfer import plan_transfer + from deepspeed.checkpoint.autoep_affine import autoep_storage_affine_map, make_autoep_placement_descriptor + + seed_everything(8800 + zero_stage) + config = make_autoep_integration_config(zero_stage=zero_stage, ep_size=2) + # The optimizer is irrelevant here; avoid depending on a fused Adam build. + config["optimizer"]["params"]["torch_adam"] = True + if autotp_size > 1: + # Folded AutoTP leaves routed experts whole, so its TP peers are additional EDP holders. + config["tensor_parallel"] = { + "autotp_size": autotp_size, + "partition_config": { + "use_default_specs": False, + "layer_specs": [{ + "patterns": [".*\\.weight$"], + "partition_type": "skip", + }], + }, + } + engine, _, _, _ = deepspeed.initialize(model=MockMoETransformer(), config=config) + rank = dist.get_rank() + # Four experts on four ranks, one each, without EDP replicas or ZeRO partitions. + target_experts = [[3], [0], [2], [1]] + target_placement = make_autoep_placement_descriptor(4, target_experts) + + # Building the maps needs no communication, so one rank can do it while the others wait; + # a collective inside would deadlock here. + solo_maps = None + if rank == 0: + solo_maps = [module.expert_storage_affine_maps() for _, module in _autoep_modules(engine)] + dist.barrier() + + for index, (_, module) in enumerate(_autoep_modules(engine)): + storage_maps = module.expert_storage_affine_maps() + if solo_maps is not None: + for name in EXPERT_WEIGHT_NAMES: + assert storage_maps[name].shard_shapes == solo_maps[index][name].shard_shapes + assert storage_maps[name].pieces_by_rank == solo_maps[index][name].pieces_by_rank + for name in EXPERT_WEIGHT_NAMES: + param = getattr(module.experts, name) + affine_map = storage_maps[name] + stored = (param.ds_tensor if zero_stage == 3 else param.data).detach().reshape(-1) + stored = stored[:affine_map.shard_shapes[rank][0]].float().cpu() + with deepspeed.zero.GatheredParameters([param], enabled=zero_stage == 3): + packed = param.detach().float().cpu() + + records = [None] * dist.get_world_size() + dist.all_gather_object(records, (module.ep_rank, packed, stored)) + # The runtime packs EP rank r's experts as the r-th contiguous block. + packed_by_ep_rank = {ep_rank: packed for ep_rank, packed, _ in records} + full = torch.cat([packed_by_ep_rank[ep_rank] for ep_rank in sorted(packed_by_ep_rank)]) + storage = {global_rank: stored for global_rank, (_, _, stored) in enumerate(records)} + + assert affine_map.logical_shape == tuple(full.shape) + for global_rank, shard in storage.items(): + torch.testing.assert_close(affine_map.extract(full, global_rank), shard, rtol=0, atol=0) + + target_map = autoep_storage_affine_map(target_placement, full.shape, + {ep_rank: [ep_rank] + for ep_rank in range(4)}) + plan = plan_transfer(target_map, affine_map) + targets = { + ep_rank: torch.full(shape, float("nan")) + for ep_rank, shape in target_map.shard_shapes.items() + } + for segment in plan.segments: + torch.as_strided(targets[segment.target_rank], segment.shape, segment.target_strides, + segment.target_offset).copy_( + torch.as_strided(storage[segment.source_rank], segment.shape, + segment.source_strides, segment.source_offset)) + for ep_rank, experts in enumerate(target_experts): + torch.testing.assert_close(targets[ep_rank], full[experts].reshape(-1), rtol=0, atol=0) + engine.destroy() + + class TestAutoEPZero3UniversalCheckpoint4GPU(DistributedTest): world_size = 4 From b7a95bce3e6061e5cc44ac3a9ece0ab874ba2ded Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 29 Oct 2026 08:11:16 +0000 Subject: [PATCH 2/7] Refuse quantized and NVMe-offloaded ZeRO-3 expert storage maps A quantized ZeRO-3 partition is encoded with a separate scale, and an NVMe-offloaded partition is only a placeholder in memory, so element offsets into either do not address the weights. Apply the same check zero_param_storage_affine_map already applies. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi --- deepspeed/module_inject/auto_ep_layer.py | 7 ++++++- tests/unit/v1/moe/test_autoep_checkpoint.py | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index dbf6e48f90a2..baacf451ebf7 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -823,7 +823,8 @@ def expert_storage_affine_maps(self) -> dict[str, ParamAffineMap]: Map ranks are global ranks and the logical shape is the parameter's own shape. Each shard is a rank's flat storage: the packed ``[local_experts, ...]`` tensor under ZeRO-0/1/2, where all expert-data-parallel replicas are listed as holders, or the rank's ZeRO-3 partition - ``ds_tensor`` without its trailing padding. Optimizer state is not described. + ``ds_tensor`` without its trailing padding. Optimizer state is not described. Quantized and + NVMe-offloaded ZeRO-3 storage is not supported. """ if self.folding_group_handles is not None and self.folding_group_handles.spec.etp_size > 1: raise NotImplementedError("Expert storage maps do not describe expert tensor-parallel shards yet.") @@ -833,6 +834,10 @@ def expert_storage_affine_maps(self) -> dict[str, ParamAffineMap]: self._live_expert_affine_map(name, placement) storage_group = self._expert_storage_group(params) partitioned = hasattr(params["w1"], "ds_id") + if partitioned: + from deepspeed.checkpoint.zero_affine import _check_zero3_param_storage + for param in params.values(): + _check_zero3_param_storage(param) # The EDP group of each EP rank's global rank holds that EP rank's packed tensor. Every rank # built all EDP groups, so the table answers this without assuming a rank layout. diff --git a/tests/unit/v1/moe/test_autoep_checkpoint.py b/tests/unit/v1/moe/test_autoep_checkpoint.py index 12db8bf876c5..b7694bb2cf5d 100644 --- a/tests/unit/v1/moe/test_autoep_checkpoint.py +++ b/tests/unit/v1/moe/test_autoep_checkpoint.py @@ -727,6 +727,25 @@ def test_storage_maps_match_runtime_ownership_and_plan_into_a_new_placement(self torch.testing.assert_close(targets[ep_rank], full[experts].reshape(-1), rtol=0, atol=0) engine.destroy() + @pytest.mark.parametrize("encoding", ["quantized", "nvme"]) + def test_zero3_storage_maps_refuse_storage_without_plain_elements(self, encoding): + from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum + + config = make_autoep_integration_config(zero_stage=3, ep_size=2) + config["optimizer"]["params"]["torch_adam"] = True + engine, _, _, _ = deepspeed.initialize(model=MockMoETransformer(), config=config) + _, module = next(iter(_autoep_modules(engine))) + # Stand in for the runtime markers: an encoded partition carries a scale, and a partition + # swapped out to NVMe is only a placeholder, so element offsets into either are meaningless. + storage = module.experts.w2.ds_tensor + if encoding == "quantized": + storage.ds_quant_scale = torch.ones(1) + else: + storage.final_location = OffloadDeviceEnum.nvme + with pytest.raises(NotImplementedError, match="ZeRO-3 parameter storage has no affine storage map"): + module.expert_storage_affine_maps() + engine.destroy() + class TestAutoEPZero3UniversalCheckpoint4GPU(DistributedTest): world_size = 4 From ca18d3a56ef2d6f25c06680bd4b246fb3187381f Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 29 Oct 2026 10:53:46 +0000 Subject: [PATCH 3/7] Describe AutoEP experts in AutoTP storage maps; document authoritative copies autotp_storage_affine_maps treated AutoEP experts, which AutoTP leaves whole on every TP rank, as replicated over TP, describing one EP rank's packed tensor as the whole parameter. Take their maps from the AutoEP layer, and refuse expert optimizer states before any collective. Document that storage maps list only authoritative copies (those the optimizer step updates and the forward reads), that derived copies such as gathered ZeRO-3 parameters are left out, and that maps must be rebuilt after every rank switches to a new expert placement. The storage-map test reads shards through zero_param_storage_shard and covers ZeRO-2 with AutoTP. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/affine_ir_spec.md | 30 +++++++++++++++++---- deepspeed/checkpoint/zero_affine.py | 29 +++++++++++++++++--- docs/code-docs/source/autoep.rst | 27 ++++++++++++++++--- tests/unit/v1/moe/test_autoep_checkpoint.py | 21 ++++++++++++--- 4 files changed, 92 insertions(+), 15 deletions(-) diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index 078bf835bb0a..1964637293b9 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -691,8 +691,12 @@ cannot be merged across those rows and keeps one piece per row. Callers: - `autotp_storage_affine_maps(model)` nests each parameter's published AutoTP layout map with the storage of every TP shard. A parameter AutoTP leaves whole in a model built under `zero.Init` stays partitioned over the whole world, so every TP rank reports the storage of - one shared copy; that storage describes the parameter on its own, without nesting. + one shared copy; that storage describes the parameter on its own, without nesting. The + experts of an AutoEP layer are left whole on every TP rank but differ by EP rank, so this + takes their maps from the AutoEP layer instead of the TP layout. - AutoEP expert storage nests the placement's layout map with each EP rank's EDP storage. + It needs no communication: the placement, the EDP group table and the ZeRO-3 even split + are known to every rank. **10.4 Replica choice** stays with the planner (§2.4): every holder appears in `locations`, and the planner's default or a `replica_selector` picks one. @@ -700,7 +704,23 @@ and the planner's default or a `replica_selector` picks one. **10.5 Plan lifetime.** Maps and plans depend only on layout and partitioning, not on values. A caller builds them once and executes the plan for every sync, until either side's placement, parallel sizes or ZeRO partitioning changes. A parameter whose buffer is -reallocated keeps its plan; only the shard views must be fetched again. - -**10.6 Not described.** Offload tiers, MiCS / hpZ, expert tensor parallelism, quantized -ZeRO-3 storage, non-elementwise transforms. +reallocated keeps its plan; only the shard views must be fetched again. A map computed +locally from a placement is only consistent if every rank uses the same placement, so a +runtime that changes placement, such as expert load balancing, must rebuild maps and plans +after every rank has switched. + +**10.6 Authoritative and derived copies.** A storage map lists only *authoritative* copies: +storage that the optimizer step updates and the next forward reads, such as `param.data` or +a ZeRO-3 `ds_tensor`. A write through the map therefore lasts. The runtime also keeps +*derived* copies that it regenerates from authoritative ones: the gathered copy of a +persistent ZeRO-3 parameter, ZeRO++ hpZ secondary partitions, fused inference weights. +A fresh derived copy holds the same values and could serve as a source, but writing it +alone is lost or leaves the authoritative copy stale, so maps leave it out and shard +accessors refuse it (`zero_param_storage_shard` on a gathered parameter). Whether a copy is +authoritative depends on the side: the low-precision parameters are authoritative for a +rollout engine, but on a training engine they are derived from the fp32 master weights, +which the next step casts back over them. + +**10.7 Not described.** Offload tiers, MiCS / hpZ, expert tensor parallelism, quantized +ZeRO-3 storage, non-elementwise transforms, derived copies as sources, and AutoEP expert +optimizer states. diff --git a/deepspeed/checkpoint/zero_affine.py b/deepspeed/checkpoint/zero_affine.py index 866a31f0bd85..66f7a5c165b5 100644 --- a/deepspeed/checkpoint/zero_affine.py +++ b/deepspeed/checkpoint/zero_affine.py @@ -268,7 +268,8 @@ def autotp_storage_affine_maps(model, optimizer_states=False, tp_group=None): master copy and optimizer states instead, matching ``zero_optimizer_storage_shard``, and a parameter without them maps to ``None``. A parameter AutoTP did not partition is replicated over the tensor-parallel group, unless it kept the partition over the whole world that - ``zero.Init`` gave it, which describes it on its own. + ``zero.Init`` gave it, which describes it on its own. The experts of an AutoEP layer are + described by its ``expert_storage_affine_maps``; their optimizer states are not supported. Collective: the tensor-parallel ranks exchange their shards' storage maps in one all-gather over ``tp_group`` (the AutoTP group by default), and every rank must call this with the same @@ -286,7 +287,23 @@ def autotp_storage_affine_maps(model, optimizer_states=False, tp_group=None): if marker is not None: marker() - named_params = list(model.named_parameters()) + # AutoTP leaves AutoEP experts whole on every tensor-parallel rank, but each EP rank holds + # different experts, so a replicated layout would describe one EP rank's packed tensor as the + # whole parameter. The AutoEP layer knows its placement and describes their storage instead. + from deepspeed.module_inject.auto_ep_layer import AutoEPMoELayer + expert_maps = {} + for module in model.modules(): + if not isinstance(module, AutoEPMoELayer): + continue + if optimizer_states: + raise NotImplementedError('AutoEP expert optimizer states have no affine storage map.') + for weight_name, storage_map in module.expert_storage_affine_maps().items(): + expert_maps[id(getattr(module.experts, weight_name))] = storage_map + + named_params = [] + for name, param in model.named_parameters(): + if id(param) not in expert_maps: + named_params.append((name, param)) params = [param for _, param in named_params] if optimizer_states: storage_maps = zero_optimizer_storage_affine_maps(params) @@ -314,4 +331,10 @@ def autotp_storage_affine_maps(model, optimizer_states=False, tp_group=None): layout = replicated_map(layout.logical_shape, 1) inner = {0: inner[0]} maps[name] = nest_affine_maps(layout, inner) - return maps + ordered = {} + for name, param in model.named_parameters(): + if id(param) in expert_maps: + ordered[name] = expert_maps[id(param)] + else: + ordered[name] = maps[name] + return ordered diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 75c0bae84eed..0210a7336fbd 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -709,8 +709,10 @@ stores, so a plan built from it reads directly from runtime storage: plan = plan_transfer(target_map, storage_maps["w1"]) - Map ranks are global ranks. The logical shape is the parameter's own shape, - and each shard is a rank's flat storage, so offsets count elements of - ``param.data.view(-1)`` or, under ZeRO-3, of ``param.ds_tensor``. + and each shard is a rank's flat storage, which + ``zero_param_storage_shard(param)`` in ``deepspeed.checkpoint.zero_affine`` + returns: ``param.data.view(-1)``, or under ZeRO-3 the partition + ``param.ds_tensor`` without its padding. ``target_map`` must use the same logical shape; ``autoep_storage_affine_map`` in ``deepspeed.checkpoint.autoep_affine`` builds one from a placement descriptor and its holders. @@ -721,8 +723,27 @@ stores, so a plan built from it reads directly from runtime storage: trailing padding is not part of a shard, so a rank whose partition is all padding, or whose EP rank holds no experts, has an empty shard and is never a source or target of a copy. -- Optimizer states are not described. Expert tensor parallelism +- The maps list only authoritative copies: the storage the optimizer step + updates and the next forward reads, so a write through the maps lasts. + Copies the runtime derives from them are not listed. One is the gathered + copy ZeRO-3 keeps of a persistent parameter between forwards: it holds the + same values after a step, but a write to it is lost once it is released, and + a write to the shard alone is not seen while it serves the forward. For this + reason ``zero_param_storage_shard`` refuses a gathered parameter; call + ``engine.empty_partition_cache()`` before writing. +- The maps describe the low-precision parameters the forward reads, which is + what a rollout engine consumes. When a training engine is the target, these + parameters are themselves derived from its fp32 master weights, and its next + optimizer step overwrites them. The fp32 master weights and optimizer states + are not described yet. Expert tensor parallelism (``expert_tensor_parallel_size > 1``) raises ``NotImplementedError``. +- Every rank computes the maps from the layer's placement descriptor. Build + them, and any plan from them, again whenever the placement changes, for + example after expert load balancing moves experts, and only once every rank + has switched to the new placement. +- ``autotp_storage_affine_maps(model)`` in ``deepspeed.checkpoint.zero_affine`` + describes the experts of an AutoEP layer with this method, so a model-wide + description under AutoTP and AutoEP is consistent. The maps and plans use the affine representation that Universal Checkpoint uses for expert parameters; see ``deepspeed/checkpoint/affine_ir_spec.md``. diff --git a/tests/unit/v1/moe/test_autoep_checkpoint.py b/tests/unit/v1/moe/test_autoep_checkpoint.py index b7694bb2cf5d..95cfba341b72 100644 --- a/tests/unit/v1/moe/test_autoep_checkpoint.py +++ b/tests/unit/v1/moe/test_autoep_checkpoint.py @@ -651,10 +651,11 @@ def test_zero3_universal_weights_only_preserves_fp32_master_weights(self, tmpdir class TestAutoEPExpertStorageMaps(DistributedTest): world_size = 4 - @pytest.mark.parametrize("zero_stage, autotp_size", [(2, 1), (3, 1), (3, 2)]) + @pytest.mark.parametrize("zero_stage, autotp_size", [(2, 1), (3, 1), (2, 2), (3, 2)]) def test_storage_maps_match_runtime_ownership_and_plan_into_a_new_placement(self, zero_stage, autotp_size): from deepspeed.checkpoint.affine_transfer import plan_transfer from deepspeed.checkpoint.autoep_affine import autoep_storage_affine_map, make_autoep_placement_descriptor + from deepspeed.checkpoint.zero_affine import autotp_storage_affine_maps, zero_param_storage_shard seed_everything(8800 + zero_stage) config = make_autoep_integration_config(zero_stage=zero_stage, ep_size=2) @@ -685,7 +686,14 @@ def test_storage_maps_match_runtime_ownership_and_plan_into_a_new_placement(self solo_maps = [module.expert_storage_affine_maps() for _, module in _autoep_modules(engine)] dist.barrier() - for index, (_, module) in enumerate(_autoep_modules(engine)): + autotp_maps = None + if autotp_size > 1: + # A model-wide AutoTP description must describe the experts as their AutoEP layer does. + autotp_maps = autotp_storage_affine_maps(engine.module) + with pytest.raises(NotImplementedError, match="AutoEP expert optimizer states"): + autotp_storage_affine_maps(engine.module, optimizer_states=True) + + for index, (module_name, module) in enumerate(_autoep_modules(engine)): storage_maps = module.expert_storage_affine_maps() if solo_maps is not None: for name in EXPERT_WEIGHT_NAMES: @@ -694,8 +702,13 @@ def test_storage_maps_match_runtime_ownership_and_plan_into_a_new_placement(self for name in EXPERT_WEIGHT_NAMES: param = getattr(module.experts, name) affine_map = storage_maps[name] - stored = (param.ds_tensor if zero_stage == 3 else param.data).detach().reshape(-1) - stored = stored[:affine_map.shard_shapes[rank][0]].float().cpu() + if autotp_maps is not None: + autotp_map = autotp_maps[f"{module_name}.experts.{name}"] + assert autotp_map.logical_shape == affine_map.logical_shape + assert autotp_map.shard_shapes == affine_map.shard_shapes + assert autotp_map.pieces_by_rank == affine_map.pieces_by_rank + stored = zero_param_storage_shard(param).detach().float().cpu() + assert stored.numel() == affine_map.shard_shapes[rank][0] with deepspeed.zero.GatheredParameters([param], enabled=zero_stage == 3): packed = param.detach().float().cpu() From 8c5766e99443ee3d2f60f3d512226ac2fc68154a Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 29 Oct 2026 10:56:09 +0000 Subject: [PATCH 4/7] Drop placement-change guidance until the runtime changes placement Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/affine_ir_spec.md | 5 +---- docs/code-docs/source/autoep.rst | 4 ---- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index 1964637293b9..70951095ddf4 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -704,10 +704,7 @@ and the planner's default or a `replica_selector` picks one. **10.5 Plan lifetime.** Maps and plans depend only on layout and partitioning, not on values. A caller builds them once and executes the plan for every sync, until either side's placement, parallel sizes or ZeRO partitioning changes. A parameter whose buffer is -reallocated keeps its plan; only the shard views must be fetched again. A map computed -locally from a placement is only consistent if every rank uses the same placement, so a -runtime that changes placement, such as expert load balancing, must rebuild maps and plans -after every rank has switched. +reallocated keeps its plan; only the shard views must be fetched again. **10.6 Authoritative and derived copies.** A storage map lists only *authoritative* copies: storage that the optimizer step updates and the next forward reads, such as `param.data` or diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 0210a7336fbd..9a30fdd1fc88 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -737,10 +737,6 @@ stores, so a plan built from it reads directly from runtime storage: optimizer step overwrites them. The fp32 master weights and optimizer states are not described yet. Expert tensor parallelism (``expert_tensor_parallel_size > 1``) raises ``NotImplementedError``. -- Every rank computes the maps from the layer's placement descriptor. Build - them, and any plan from them, again whenever the placement changes, for - example after expert load balancing moves experts, and only once every rank - has switched to the new placement. - ``autotp_storage_affine_maps(model)`` in ``deepspeed.checkpoint.zero_affine`` describes the experts of an AutoEP layer with this method, so a model-wide description under AutoTP and AutoEP is consistent. From 7d142be9e041d6b865b407e0794ff6460846ce22 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 29 Oct 2026 10:56:37 +0000 Subject: [PATCH 5/7] Describe only implemented behavior in storage-map docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/affine_ir_spec.md | 10 +++++----- docs/code-docs/source/autoep.rst | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index 70951095ddf4..247f6aac4cc7 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -711,13 +711,13 @@ storage that the optimizer step updates and the next forward reads, such as `par a ZeRO-3 `ds_tensor`. A write through the map therefore lasts. The runtime also keeps *derived* copies that it regenerates from authoritative ones: the gathered copy of a persistent ZeRO-3 parameter, ZeRO++ hpZ secondary partitions, fused inference weights. -A fresh derived copy holds the same values and could serve as a source, but writing it -alone is lost or leaves the authoritative copy stale, so maps leave it out and shard -accessors refuse it (`zero_param_storage_shard` on a gathered parameter). Whether a copy is +Writing a derived copy alone is lost or leaves the authoritative copy stale, so maps leave +it out and shard accessors refuse it (`zero_param_storage_shard` on a gathered parameter). +Whether a copy is authoritative depends on the side: the low-precision parameters are authoritative for a rollout engine, but on a training engine they are derived from the fp32 master weights, which the next step casts back over them. **10.7 Not described.** Offload tiers, MiCS / hpZ, expert tensor parallelism, quantized -ZeRO-3 storage, non-elementwise transforms, derived copies as sources, and AutoEP expert -optimizer states. +ZeRO-3 storage, non-elementwise transforms, derived copies, and AutoEP expert optimizer +states. diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 9a30fdd1fc88..9447f0ced860 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -735,7 +735,7 @@ stores, so a plan built from it reads directly from runtime storage: what a rollout engine consumes. When a training engine is the target, these parameters are themselves derived from its fp32 master weights, and its next optimizer step overwrites them. The fp32 master weights and optimizer states - are not described yet. Expert tensor parallelism + are not described. Expert tensor parallelism (``expert_tensor_parallel_size > 1``) raises ``NotImplementedError``. - ``autotp_storage_affine_maps(model)`` in ``deepspeed.checkpoint.zero_affine`` describes the experts of an AutoEP layer with this method, so a model-wide From 845cd6eb5a298e3d6007429f5fc4487ecb7434de Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 29 Oct 2026 11:33:59 +0000 Subject: [PATCH 6/7] Raise on every TP peer when one rank refuses its expert storage Each EP rank holds different experts, so one rank can refuse its expert storage (e.g. a quantized partition) while its tensor-parallel peers accept theirs, leaving them waiting in the all-gather. Send the refusal through the same all-gather so every peer raises. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/zero_affine.py | 38 +++++++++++++++------ tests/unit/v1/moe/test_autoep_checkpoint.py | 14 ++++++++ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/deepspeed/checkpoint/zero_affine.py b/deepspeed/checkpoint/zero_affine.py index 66f7a5c165b5..333e3429e65f 100644 --- a/deepspeed/checkpoint/zero_affine.py +++ b/deepspeed/checkpoint/zero_affine.py @@ -291,27 +291,43 @@ def autotp_storage_affine_maps(model, optimizer_states=False, tp_group=None): # different experts, so a replicated layout would describe one EP rank's packed tensor as the # whole parameter. The AutoEP layer knows its placement and describes their storage instead. from deepspeed.module_inject.auto_ep_layer import AutoEPMoELayer + autoep_layers = [module for module in model.modules() if isinstance(module, AutoEPMoELayer)] + if optimizer_states and autoep_layers: + raise NotImplementedError('AutoEP expert optimizer states have no affine storage map.') + + # Each EP rank holds different experts, so one rank may refuse its expert storage (for example + # a quantized partition) while its tensor-parallel peers accept theirs. The refusal travels with + # the all-gather so that every peer raises instead of waiting in it. + local_error = None expert_maps = {} - for module in model.modules(): - if not isinstance(module, AutoEPMoELayer): - continue - if optimizer_states: - raise NotImplementedError('AutoEP expert optimizer states have no affine storage map.') - for weight_name, storage_map in module.expert_storage_affine_maps().items(): - expert_maps[id(getattr(module.experts, weight_name))] = storage_map + try: + for module in autoep_layers: + for weight_name, storage_map in module.expert_storage_affine_maps().items(): + expert_maps[id(getattr(module.experts, weight_name))] = storage_map + except (NotImplementedError, ValueError, RuntimeError) as error: + local_error = error named_params = [] for name, param in model.named_parameters(): if id(param) not in expert_maps: named_params.append((name, param)) params = [param for _, param in named_params] - if optimizer_states: - storage_maps = zero_optimizer_storage_affine_maps(params) + if local_error is not None: + local = {'error': f'{type(local_error).__name__}: {local_error}'} else: - storage_maps = [zero_param_storage_affine_map(param) for param in params] - local = [None if storage_map is None else storage_map.to_dict() for storage_map in storage_maps] + if optimizer_states: + storage_maps = zero_optimizer_storage_affine_maps(params) + else: + storage_maps = [zero_param_storage_affine_map(param) for param in params] + local = [None if storage_map is None else storage_map.to_dict() for storage_map in storage_maps] gathered = [None] * tp_world_size dist.all_gather_object(gathered, local, group=tp_group) + if local_error is not None: + raise local_error + for tp_rank, rank_maps in enumerate(gathered): + if isinstance(rank_maps, dict): + raise RuntimeError(f"Tensor-parallel rank {tp_rank} cannot describe its AutoEP expert storage: " + f"{rank_maps['error']}") maps = {} for position, (name, param) in enumerate(named_params): diff --git a/tests/unit/v1/moe/test_autoep_checkpoint.py b/tests/unit/v1/moe/test_autoep_checkpoint.py index 95cfba341b72..4c89f690a677 100644 --- a/tests/unit/v1/moe/test_autoep_checkpoint.py +++ b/tests/unit/v1/moe/test_autoep_checkpoint.py @@ -692,6 +692,20 @@ def test_storage_maps_match_runtime_ownership_and_plan_into_a_new_placement(self autotp_maps = autotp_storage_affine_maps(engine.module) with pytest.raises(NotImplementedError, match="AutoEP expert optimizer states"): autotp_storage_affine_maps(engine.module, optimizer_states=True) + if zero_stage == 3: + # Only rank 0 refuses its expert storage; its tensor-parallel peers must raise too + # instead of waiting for it in the collective, and other groups are unaffected. + from deepspeed.utils import groups + storage = _autoep_modules(engine)[0][1].experts.w2.ds_tensor + if rank == 0: + storage.ds_quant_scale = torch.ones(1) + if 0 in dist.get_all_ranks_from_group(groups.get_tensor_model_parallel_group()): + with pytest.raises((NotImplementedError, RuntimeError), match="storage"): + autotp_storage_affine_maps(engine.module) + else: + autotp_storage_affine_maps(engine.module) + if rank == 0: + del storage.ds_quant_scale for index, (module_name, module) in enumerate(_autoep_modules(engine)): storage_maps = module.expert_storage_affine_maps() From 0e9fd35c9d6eaa58387254a701b992e2dabcdc11 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 29 Oct 2026 13:29:45 +0000 Subject: [PATCH 7/7] Describe expert storage maps as current behavior in the spec Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/affine_ir_spec.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index 247f6aac4cc7..6c91ca46fa7d 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -613,8 +613,8 @@ expert parameters, and `AutoEPMoELayer.plan_expert_transfer(target_placement)` c them with a target descriptor through `plan_transfer` into shard-to-shard copies. Plan ranks are EP-local ranks of the respective placements; the plan is not executed, and ZeRO and EDP storage must still be normalized before its offsets apply. -`AutoEPMoELayer.expert_storage_affine_maps()` removes that step by describing the storage -itself (§10). +`AutoEPMoELayer.expert_storage_affine_maps()` describes that storage in global ranks +(§10). `deepspeed/checkpoint/zero_affine.py` takes the first step for live training storage. It describes, in global ranks, where ZeRO keeps each element of a parameter: the low-precision @@ -692,8 +692,8 @@ cannot be merged across those rows and keeps one piece per row. Callers: with the storage of every TP shard. A parameter AutoTP leaves whole in a model built under `zero.Init` stays partitioned over the whole world, so every TP rank reports the storage of one shared copy; that storage describes the parameter on its own, without nesting. The - experts of an AutoEP layer are left whole on every TP rank but differ by EP rank, so this - takes their maps from the AutoEP layer instead of the TP layout. + experts of an AutoEP layer are whole on every TP rank and differ by EP rank; their maps + are the layer's `expert_storage_affine_maps()`. - AutoEP expert storage nests the placement's layout map with each EP rank's EDP storage. It needs no communication: the placement, the EDP group table and the ZeRO-3 even split are known to every rank. @@ -713,10 +713,9 @@ a ZeRO-3 `ds_tensor`. A write through the map therefore lasts. The runtime also persistent ZeRO-3 parameter, ZeRO++ hpZ secondary partitions, fused inference weights. Writing a derived copy alone is lost or leaves the authoritative copy stale, so maps leave it out and shard accessors refuse it (`zero_param_storage_shard` on a gathered parameter). -Whether a copy is -authoritative depends on the side: the low-precision parameters are authoritative for a -rollout engine, but on a training engine they are derived from the fp32 master weights, -which the next step casts back over them. +Whether a copy is authoritative depends on the side: the low-precision parameters are +authoritative for a rollout engine, but on a training engine they are derived from the fp32 +master weights, which the next step casts back over them. **10.7 Not described.** Offload tiers, MiCS / hpZ, expert tensor parallelism, quantized ZeRO-3 storage, non-elementwise transforms, derived copies, and AutoEP expert optimizer