diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index c9108518d107..6c91ca46fa7d 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()` 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 @@ -689,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 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. **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,5 +706,17 @@ A caller builds them once and executes the plan for every sync, until either sid 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. +**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. +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, and AutoEP expert optimizer +states. 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/checkpoint/zero_affine.py b/deepspeed/checkpoint/zero_affine.py index 866a31f0bd85..333e3429e65f 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,15 +287,47 @@ 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 + 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 = {} + 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): @@ -314,4 +347,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/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index fbdfab2f5dff..baacf451ebf7 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,85 @@ 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. 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.") + 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") + 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. + 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..9447f0ced860 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,51 @@ 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, 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. +- 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. +- 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. 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 + 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/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..4c89f690a677 100644 --- a/tests/unit/v1/moe/test_autoep_checkpoint.py +++ b/tests/unit/v1/moe/test_autoep_checkpoint.py @@ -648,6 +648,132 @@ 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), (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) + # 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() + + 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) + 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() + 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] + 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() + + 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() + + @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