diff --git a/deepspeed/checkpoint/affine.py b/deepspeed/checkpoint/affine.py index 312076fb8e93..6d886dca7b3e 100644 --- a/deepspeed/checkpoint/affine.py +++ b/deepspeed/checkpoint/affine.py @@ -22,7 +22,7 @@ __all__ = [ 'AffinePiece', 'ParamAffineMap', 'AFFINE_MAP_FORMAT_VERSION', 'SCALE_POWER_BY_STATE', 'replicated_map', - 'contiguous_split_map', 'sub_param_map', 'segmented_map', 'block_gather_map' + 'contiguous_split_map', 'sub_param_map', 'segmented_map', 'block_gather_map', 'nest_affine_maps' ] # Encoding version of the stored map, independent of the universal checkpoint version so @@ -634,3 +634,222 @@ def block_gather_map(shape, block_ids_by_rank, block_size, partition_dim): pieces_by_rank[rank] = pieces return ParamAffineMap(logical_shape=shape, shard_shapes=shard_shapes, pieces_by_rank=pieces_by_rank) + + +def nest_affine_maps(outer, inner_by_outer_rank): + """Compose a layout map with a description of how each of its shards is stored. + + ``outer`` describes the parameter's layout: the shard each layout rank (a tensor- or + expert-parallel rank) holds. ``inner_by_outer_rank[r]`` describes how layout shard ``r``, + flattened to ``(numel,)``, is spread over the processes that store it, as + ``deepspeed.checkpoint.zero_affine.zero_storage_affine_map`` does for ZeRO replicas and + partitions. Its pieces must be contiguous intervals. + + The result describes the parameter in its own shape, keyed by the inner ranks, and each shard is + what a process stores: a flat run of its layout shard. A stored run is generally not a box of the + parameter, since a ZeRO partition may begin or end inside a row, so it is described by a few + boxes, each contiguous in storage: a partial row at either end and the whole rows between. A + block that is not contiguous in its layout shard, such as one split along a trailing axis inside + the shard, is cut further until each box is. An element listed on several layout ranks is held by + the union of their holders, so pieces are cut wherever any of those holders' storage begins or + ends. + """ + if set(inner_by_outer_rank) != set(outer.shard_shapes): + raise ValueError(f'Storage is described for layout ranks {sorted(inner_by_outer_rank)}, but the layout has ' + f'ranks {sorted(outer.shard_shapes)}.') + storage_shapes = {} + for outer_rank, inner in inner_by_outer_rank.items(): + shard_numel = _product(outer.shard_shapes[outer_rank]) + if inner.logical_shape != (shard_numel, ): + raise ValueError(f'Layout rank {outer_rank} holds {shard_numel} elements, but its storage map describes ' + f'shape {inner.logical_shape}.') + for storage_rank, shape in inner.shard_shapes.items(): + if storage_rank in storage_shapes: + # One shard per process: a process storing two layout shards would need two buffers. + raise ValueError(f'Rank {storage_rank} stores more than one layout shard.') + storage_shapes[storage_rank] = shape + intervals_by_outer_rank = {rank: _storage_intervals(inner) for rank, inner in inner_by_outer_rank.items()} + + # Replicated layout pieces describe the same block on each of their holders. + replicas = {} + for outer_rank, pieces in outer.pieces_by_rank.items(): + for piece in pieces: + if piece.numel == 0: + continue + key = (piece.shape, piece.source_offset, piece.source_strides) + replicas.setdefault(key, []).append((outer_rank, piece)) + + pieces_by_rank = {rank: [] for rank in storage_shapes} + for copies in replicas.values(): + listed = {outer_rank for outer_rank, _ in copies} + for _, piece in copies: + if piece.locations != listed: + raise ValueError(f'Layout piece {piece} lists holders {sorted(piece.locations)}, but layout ranks ' + f'{sorted(listed)} hold it.') + _nest_replicated_block(copies, intervals_by_outer_rank, pieces_by_rank) + + affine_map = ParamAffineMap(logical_shape=outer.logical_shape, + shard_shapes=storage_shapes, + pieces_by_rank=pieces_by_rank) + affine_map.validate() + return affine_map + + +def _storage_intervals(inner): + # (start, stop, storage rank, offset in that rank's shard, scale) for every stored interval. + intervals = [] + for storage_rank, pieces in inner.pieces_by_rank.items(): + for piece in pieces: + if piece.numel == 0: + continue + if piece.source_strides != (1, ) or piece.dest_strides != (1, ): + raise ValueError(f'Storage piece {piece} of rank {storage_rank} is not a contiguous interval.') + intervals.append( + (piece.source_offset, piece.source_offset + piece.numel, storage_rank, piece.dest_offset, piece.scale)) + return sorted(intervals) + + +def _nest_replicated_block(copies, intervals_by_outer_rank, pieces_by_rank): + # Cuts are row-major element indices of the block. Between two cuts, every copy lies inside one + # stored interval of every holder; each range between cuts is then split into boxes that are + # contiguous in every copy's shard. + block = copies[0][1] + cuts = {0, block.numel} + for outer_rank, piece in copies: + _check_monotone_dest(piece) + for start, stop, _, _, _ in intervals_by_outer_rank[outer_rank]: + for boundary in (start, stop): + cuts.add(_first_index_at_or_after(piece, boundary)) + cuts = sorted(cuts) + + for low, high in zip(cuts, cuts[1:]): + if low == high: + continue + stored = [] + for outer_rank, piece in copies: + address = _strided_address(piece.shape, piece.dest_offset, piece.dest_strides, low) + covering = [ + interval for interval in intervals_by_outer_rank[outer_rank] if interval[0] <= address < interval[1] + ] + if not covering: + raise ValueError(f'Layout rank {outer_rank} holds shard element {address}, but its storage map ' + 'stores it on no rank.') + stored.extend((piece, address, interval) for interval in covering) + locations = {interval[2] for _, _, interval in stored} + # A box must be one run of addresses in every copy, so the most fragmented copy decides. + dense_rows = max(_dense_rows(piece) for piece, _, _ in stored) + for origin, extent in _row_major_range_boxes(block.shape, low, high, dense_rows): + source_offset = block.source_offset + _dot(origin, block.source_strides) + for piece, _, (start, _, storage_rank, storage_offset, storage_scale) in stored: + address = piece.dest_offset + _dot(origin, piece.dest_strides) + pieces_by_rank[storage_rank].append( + AffinePiece(shape=extent, + source_offset=source_offset, + source_strides=block.source_strides, + dest_offset=storage_offset + address - start, + dest_strides=_row_major_strides(extent), + locations=locations, + scale=piece.scale * storage_scale)) + + +def _dot(index, strides): + return sum(position * stride for position, stride in zip(index, strides)) + + +def _dense_rows(piece): + # The number of leading axes after which the piece is contiguous in its shard: a box of the piece + # that spans every later axis in full, and only those, is one run of shard addresses. + run = 1 + for axis in range(len(piece.shape) - 1, -1, -1): + size, stride = piece.shape[axis], piece.dest_strides[axis] + if size > 1 and stride != run: + return axis + 1 + run *= size + return 0 + + +def _row_major_range_boxes(shape, low, high, dense_rows=0): + """Split the row-major index range ``[low, high)`` of ``shape`` into ``(origin, extent)`` boxes. + + At most two boxes per axis: a partial run at either end and whole runs between. The first + ``dense_rows`` axes are never merged, so a box spans more than one position of such an axis only + where the storage is contiguous across it. + """ + if low >= high: + return [] + if not shape: + return [((), ())] + if len(shape) == 1: + return [((low, ), (high - low, ))] + inner = _product(shape[1:]) + first, low_rest = divmod(low, inner) + last, high_rest = divmod(high, inner) + + def within(row, start, stop): + return [((row, ) + origin, (1, ) + extent) + for origin, extent in _row_major_range_boxes(shape[1:], start, stop, dense_rows - 1)] + + if first == last: + return within(first, low_rest, high_rest) + boxes = [] + if low_rest: + boxes.extend(within(first, low_rest, inner)) + first += 1 + if dense_rows > 0: + for row in range(first, last): + boxes.extend(within(row, 0, inner)) + elif last > first: + boxes.append(((first, ) + (0, ) * (len(shape) - 1), (last - first, ) + tuple(shape[1:]))) + if high_rest: + boxes.extend(within(last, 0, high_rest)) + return boxes + + +def _check_monotone_dest(piece): + # Storage intervals are ranges of shard addresses. A piece whose addresses grow with its + # row-major element index meets such a range in one run of indices; any other piece could + # interleave with it. + later_span = 0 + for size, stride in reversed(list(zip(piece.shape, piece.dest_strides))): + if size > 1: + if stride <= later_span: + raise NotImplementedError(f'Layout piece {piece} does not store its elements in row-major order, so ' + 'its storage cannot be described.') + later_span += stride * (size - 1) + + +def _strided_address(shape, offset, strides, index): + address = offset + for size, stride in reversed(list(zip(shape, strides))): + index, position = divmod(index, size) + address += position * stride + return address + + +def _first_index_at_or_after(piece, address): + # The smallest row-major index whose shard address is at least ``address``; ``numel`` if none. + remaining = address - piece.dest_offset + if remaining <= 0: + return 0 + spans = [] + later_span = 0 + for size, stride in reversed(list(zip(piece.shape, piece.dest_strides))): + spans.append(later_span) + later_span += stride * (size - 1) + spans.reverse() + if remaining > later_span: + return piece.numel + + index = 0 + for axis, (size, stride) in enumerate(zip(piece.shape, piece.dest_strides)): + position = 0 + if size > 1: + # The first position from which the later axes can still reach ``remaining``. + position = max(0, -(-(remaining - spans[axis]) // stride)) + index = index * size + position + remaining -= position * stride + if remaining <= 0: + for later_size in piece.shape[axis + 1:]: + index *= later_size + return index + return index diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index f31771d773d2..c9108518d107 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -614,6 +614,22 @@ them with a target descriptor through `plan_transfer` into shard-to-shard copies 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. +`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 +copy (`zero_param_storage_affine_map`: replicas under ZeRO-0/1/2, `ds_tensor` partitions +under ZeRO-3, padding excluded), and the fp32 master copy with its optimizer states +(`zero_optimizer_storage_affine_maps`: ZeRO-1/2 fragments gathered from each rank's +`_hp_mapping`, which may cut a parameter mid-row, and the ZeRO-3 fp32 partition). The +matching `*_storage_shard` accessors return the flat views of ZeRO's own buffers, so a +plan's writes land in the optimizer. Offloaded states, MiCS and hpZ have no map yet. +Both parameter storage accessors reject quantized ZeRO-3 storage (`ds_quant_scale`): +its encoded values and separate quantization scales cannot be treated as ordinary +parameter elements. They reject NVMe-offloaded ZeRO-3 storage too, whose partition is a +placeholder while swapped out. `zero_param_storage_shard` also rejects a gathered ZeRO-3 +parameter: the forward reads the gathered copy, which persistent parameters keep between +steps, so a write to the partition alone would be lost. `engine.empty_partition_cache()` +releases every gathered copy first. + --- ## 9. Staging @@ -629,3 +645,60 @@ and EDP storage must still be normalized before its offsets apply. Steps 1–3 change no behaviour: they add a representation and prove it agrees with the current one. Only step 4 changes what a checkpoint contains, and only by adding a key. + +--- + +## 10. Phase 2 — live storage maps + +Phase 2 plans `M_t ∘ M_s⁻¹` between two live topologies. A live topology is what each process +actually holds, so its map must describe storage, not only the parallel layout. + +**10.1 Two kinds of map.** +- *Layout map*: the parameter's N-D logical shape, keyed by ranks of the parallel group that + defines the layout (TP, EP). The layer builds it from its own semantics, checkpoints persist + it, and it remains the only geometry contract. +- *Storage map*: keyed by global rank; each shard is a process's flat buffer (`param.data`, + ZeRO-3 `ds_tensor`, an fp32 or optimizer-state fragment). It exists at runtime only and is + never persisted. Built from a layout map (10.3), it keeps the layout's N-D logical shape; + without a layout it describes the flattened parameter `(numel,)`. + +Both satisfy P1–P5. A plan's endpoints must be the same kind and the same logical shape; +`plan_transfer` rejects different logical shapes, so a flat storage map cannot be planned +against an N-D one of the same parameter. Matching rank namespaces is the caller's job. + +**10.2 N-D boxes in flat storage.** A ZeRO partition of an N-D layout shard is a contiguous +interval of its flattened buffer, which is generally not one box of the N-D parameter: it is +a partial row, then whole rows, then a partial row, recursively over the axes, so at most +`2 * ndim - 1` boxes. Each box is dense in the buffer (its storage strides are its own +row-major strides). `plan_transfer` accepts such a piece in a 1-D shard and treats its +storage as the interval `[dest_offset, dest_offset + numel)`; any other shard must have the +logical parameter's rank. Describing the flattened parameter instead would cut a column of a +row-major weight, such as a row-parallel shard, into one piece per row. + +**10.3 Derivation.** A storage map is derived, never hand-built: +`storage = nest_affine_maps(layout, {layout rank: inner})`, where `inner` describes how one +flattened layout shard is stored over its data-parallel group (`zero_storage_affine_map`: +replicas, or ZeRO-3 partitions `[d*n, (d+1)*n)` without padding). Nesting keeps P5: layout +pieces that describe the same block on several layout ranks are one block whose holders are +the union of every rank's holders, and the block is cut wherever any of those holders' +storage begins or ends; each resulting interval becomes the boxes of 10.2. A layout piece +that is not dense within its layout shard, such as a block narrower than the shard's rows, +cannot be merged across those rows and keeps one piece per row. Callers: +- `zero_param_storage_affine_map` and `zero_optimizer_storage_affine_maps` describe a dense + parameter (no layout, so they are already the storage map). +- `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. +- AutoEP expert storage nests the placement's layout map with each EP rank's EDP storage. + +**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. + +**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. diff --git a/deepspeed/checkpoint/affine_transfer.py b/deepspeed/checkpoint/affine_transfer.py index 87452bd6ec20..e38ecb819542 100644 --- a/deepspeed/checkpoint/affine_transfer.py +++ b/deepspeed/checkpoint/affine_transfer.py @@ -246,7 +246,8 @@ def _frame_of(piece: AffinePiece, rank: int, side: str, logical_shape: Tuple[int Both stride vectors must be the row-major strides of the tensor they address, which is what makes the box arithmetic below valid and what every builder in ``affine.py`` already emits. An axis the piece does not span is absent from storage, so its stride is not compared -- that is also where a - permutation would hide, and a permutation is not one box. + permutation would hide, and a permutation is not one box. A flat shard is the one exception: it may + hold a multi-axis box as a dense run, which is how ZeRO stores a tensor-parallel shard. """ where = f'{side} rank {rank} piece {piece!r}' if len(piece.shape) != len(logical_shape): @@ -271,6 +272,11 @@ def _frame_of(piece: AffinePiece, rank: int, side: str, logical_shape: Tuple[int for axis, (got, want, size) in enumerate(zip(piece.source_strides, logical_strides, piece.shape)): if size > 1 and got != want: raise UnsupportedLayoutError(f'{where}: source axis {axis} strides {got}, expected {want}') + flat_storage = len(shard_shape) == 1 and len(piece.shape) != 1 + if flat_storage: + # A flat shard, as ZeRO stores one, holds a box of a multi-axis parameter as one run of + # addresses: the box's own row-major strides. Its place in the shard is that run. + shard_strides = _row_major_strides(tuple(piece.shape)) for axis, (got, want, size) in enumerate(zip(piece.dest_strides, shard_strides, piece.shape)): if size > 1 and got != want: raise UnsupportedLayoutError(f'{where}: dest axis {axis} strides {got}, expected {want}') @@ -279,7 +285,10 @@ def _frame_of(piece: AffinePiece, rank: int, side: str, logical_shape: Tuple[int box = LogicalBox(origin, tuple(piece.shape)) if not LogicalBox(tuple([0] * len(logical_shape)), logical_shape).contains(box): raise InvalidMapError(f'{where}: covers {box!r}, outside the logical parameter of {logical_shape}') - local = LogicalBox(_origin(piece.dest_offset, shard_strides, shard_shape, where, 'dest'), tuple(piece.shape)) + if flat_storage: + local = LogicalBox((piece.dest_offset, ), (piece.numel, )) + else: + local = LogicalBox(_origin(piece.dest_offset, shard_strides, shard_shape, where, 'dest'), tuple(piece.shape)) if not LogicalBox(tuple([0] * len(shard_shape)), shard_shape).contains(local): raise InvalidMapError(f'{where}: writes {local!r}, outside the {shard_shape} shard') return _Frame(rank=rank, @@ -302,7 +311,8 @@ def _normalized(map_: ParamAffineMap, side: str, limits: PlanBudget) -> List[_Fr logical_shape = tuple(map_.logical_shape) if len(logical_shape) > limits.max_ndim: raise UnsupportedLayoutError(f'{side}: {len(logical_shape)} axes exceeds max_ndim {limits.max_ndim}') - if any(len(tuple(shape)) != len(logical_shape) for shape in map_.shard_shapes.values()): + # A flat shard is flat storage, such as ZeRO's; its pieces carry the axis correspondence. + if any(len(tuple(shape)) not in (1, len(logical_shape)) for shape in map_.shard_shapes.values()): raise UnsupportedLayoutError( f'{side}: a shard is described with a different number of axes than the logical parameter, so ' 'no axis correspondence exists to plan against') diff --git a/deepspeed/checkpoint/zero_affine.py b/deepspeed/checkpoint/zero_affine.py new file mode 100644 index 000000000000..866a31f0bd85 --- /dev/null +++ b/deepspeed/checkpoint/zero_affine.py @@ -0,0 +1,317 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +"""Affine maps of the storage ZeRO keeps for a model parameter. + +A transfer planner needs every legal holder of every element. These maps describe a flattened +parameter keyed by global rank, both for the low-precision parameter the model computes with and +for the fp32 master copy and optimizer states that ZeRO partitions across the data-parallel group. +Each map comes with an accessor for the matching local shard, which is a view of ZeRO's storage, +so it can be read as a transfer source or written as a transfer target. + +Under AutoTP these maps describe one tensor-parallel shard; ``autotp_storage_affine_maps`` nests +them in each parameter's AutoTP layout to describe the whole parameter in its own shape. +""" + +import torch + +import deepspeed.comm as dist +from deepspeed.accelerator import get_accelerator +from deepspeed.checkpoint.affine import AffinePiece, ParamAffineMap, nest_affine_maps, replicated_map + +__all__ = [ + 'zero_storage_affine_map', 'zero_param_storage_affine_map', 'zero_param_storage_shard', + 'zero_optimizer_storage_affine_maps', 'zero_optimizer_storage_shard', 'autotp_storage_affine_maps' +] + + +def _flat_piece(numel, start, rank): + return AffinePiece(shape=(numel, ), + source_offset=start, + source_strides=(1, ), + dest_offset=0, + dest_strides=(1, ), + locations=[rank]) + + +def _fragment_affine_map(numel, fragments): + # ``fragments`` lists (rank, start, length): each rank holds one contiguous range, possibly empty. + shard_shapes = {} + pieces_by_rank = {} + for rank, start, length in fragments: + shard_shapes[rank] = (length, ) + pieces_by_rank[rank] = [_flat_piece(length, start, rank)] if length > 0 else [] + affine_map = ParamAffineMap(logical_shape=(numel, ), shard_shapes=shard_shapes, pieces_by_rank=pieces_by_rank) + affine_map.validate() + return affine_map + + +def _zero3_bounds(numel, partition_numel, index): + # The trailing padding of the last partitions holds no parameter elements, so it is not part of the shard. + start = min(index * partition_numel, numel) + stop = min(start + partition_numel, numel) + return start, stop - start + + +def zero_storage_affine_map(numel, holder_ranks, partition_numel=None): + """Describe a flattened parameter of ``numel`` elements stored by ``holder_ranks``. + + Without ``partition_numel`` every holder stores the whole parameter, as data-parallel + replicas do under ZeRO-0/1/2, so the one piece lists every holder. With it, holder ``i`` + stores elements ``[i * n, (i + 1) * n)`` as ZeRO-3 does; the trailing padding holds no + parameter elements and is not part of the shard, so a holder past the end has an empty shard. + """ + numel = int(numel) + holder_ranks = [int(rank) for rank in holder_ranks] + if numel < 0: + raise ValueError(f'Parameter numel cannot be negative: {numel}.') + if not holder_ranks or len(set(holder_ranks)) != len(holder_ranks): + raise ValueError(f'Holder ranks must be a non-empty list of distinct ranks: {holder_ranks}.') + + if partition_numel is None: + piece = AffinePiece(shape=(numel, ), + source_offset=0, + source_strides=(1, ), + dest_offset=0, + dest_strides=(1, ), + locations=holder_ranks) + affine_map = ParamAffineMap(logical_shape=(numel, ), + shard_shapes={rank: (numel, ) + for rank in holder_ranks}, + pieces_by_rank={rank: [piece] + for rank in holder_ranks}) + affine_map.validate() + return affine_map + + partition_numel = int(partition_numel) + if partition_numel < 0 or partition_numel * len(holder_ranks) < numel: + raise ValueError(f'{len(holder_ranks)} partitions of {partition_numel} elements cannot hold {numel} elements.') + fragments = [] + for index, rank in enumerate(holder_ranks): + start, length = _zero3_bounds(numel, partition_numel, index) + fragments.append((rank, start, length)) + return _fragment_affine_map(numel, fragments) + + +def _zero3_local_numel(param): + index = dist.get_rank(group=param.ds_process_group) + _, length = _zero3_bounds(param.ds_numel, param.ds_tensor.ds_numel, index) + return length + + +def _global_ranks(group): + # dist.get_all_ranks_from_group never ends on the world group: torch maps any rank of the + # world group to itself instead of raising past the end. + return [dist.get_global_rank(group, rank) for rank in range(dist.get_world_size(group))] + + +def _check_zero3_param_storage(param): + from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum + + if hasattr(param.ds_tensor, 'ds_quant_scale'): + raise NotImplementedError('Quantized ZeRO-3 parameter storage has no affine storage map.') + # NVMe offload swaps a partition out of memory and leaves a placeholder in its place. + if getattr(param.ds_tensor, 'final_location', None) == OffloadDeviceEnum.nvme: + raise NotImplementedError('NVMe-offloaded ZeRO-3 parameter storage has no affine storage map.') + + +def zero_param_storage_affine_map(param, replica_group=None): + """Describe the storage of a live low-precision ``param`` across global ranks. + + A ZeRO-3 parameter is described by its own partition group and ``ds_tensor`` size. + Otherwise every rank of ``replica_group`` holds a whole copy. It defaults to the group ZeRO + partitions the parameter's optimizer state over, which is the expert data-parallel group for + MoE experts, and to the data-parallel group for a parameter outside a ZeRO optimizer. Under + tensor parallelism the map describes this rank's tensor-parallel shard, which its + data-parallel peers hold too. + + Quantized and NVMe-offloaded ZeRO-3 parameter storage is not supported. + """ + if hasattr(param, 'ds_id'): + _check_zero3_param_storage(param) + holders = _global_ranks(param.ds_process_group) + return zero_storage_affine_map(param.ds_numel, holders, param.ds_tensor.ds_numel) + if replica_group is None: + replica_group = getattr(param, '_dp_group', None) + if replica_group is None: + from deepspeed.utils import groups + replica_group = groups._get_data_parallel_group() + return zero_storage_affine_map(param.numel(), _global_ranks(replica_group)) + + +def zero_param_storage_shard(param): + """This rank's shard of ``param`` as laid out by ``zero_param_storage_affine_map``: a flat view. + + A ZeRO-3 parameter must be partitioned. A gathered copy, which ZeRO-3 keeps for persistent + parameters between forwards, would go on serving the forward after the shard is written, so + release gathered copies with ``engine.empty_partition_cache()`` first. + """ + if hasattr(param, 'ds_id'): + from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus + + _check_zero3_param_storage(param) + if param.ds_status != ZeroParamStatus.NOT_AVAILABLE: + raise RuntimeError(f'ZeRO-3 parameter {param.ds_id} is gathered, so its shard is not its only copy; ' + 'call engine.empty_partition_cache() first.') + return param.ds_tensor.data.view(-1).narrow(0, 0, _zero3_local_numel(param)) + return param.data.view(-1) + + +def _zero3_optimizer_offloaded(param): + return param._z3_optimizer.offload_optimizer + + +def zero_optimizer_storage_affine_maps(params): + """Describe where ZeRO keeps the fp32 master copy and optimizer states of each of ``params``. + + Returns one map per parameter, in order, or ``None`` for a parameter without an fp32 copy, + such as a frozen one. The master copy and every optimizer state of a parameter share its map. + Under ZeRO-1/2 (and the bf16 optimizer) each rank of the parameter's data-parallel group holds + one contiguous range of it, possibly empty, so the ranks exchange their ranges in one all-gather + per group: every rank must pass the same parameters in the same order. Under ZeRO-3 the + partitions follow the parameter's own, and no communication is needed. + + Offloaded optimizer states are not supported, since their shards would not be device tensors. + """ + params = list(params) + maps = [None] * len(params) + # ZeRO-1/2 parameters grouped by the group their ranges are exchanged over, in first-seen order + # so that every rank issues the all-gathers in the same order. + by_group = {} + for position, param in enumerate(params): + if hasattr(param, 'ds_id'): + # ZeRO-3 keeps no fp32 copy of a frozen parameter. + if not hasattr(param, '_z3_optimizer') or not param.requires_grad: + continue + if _zero3_optimizer_offloaded(param): + raise NotImplementedError('Offloaded ZeRO-3 optimizer states have no affine storage map.') + maps[position] = zero_param_storage_affine_map(param) + elif getattr(param, '_dp_group', None) is not None: + by_group.setdefault(param._dp_group, []).append(position) + + device = torch.device(get_accelerator().current_device_name()) + for group, positions in by_group.items(): + # Each rank reports (start, length, offloaded) for every parameter; a rank without a range of a + # parameter reports an empty one. Offload is reported rather than checked locally so that every + # rank raises together instead of leaving its peers in the all-gather. + local = torch.zeros(len(positions), 3, dtype=torch.int64, device=device) + for row, position in enumerate(positions): + mapping = params[position]._hp_mapping + if mapping is not None: + address = mapping.lp_fragment_address + local[row] = torch.tensor([address.start, address.numel, int(mapping.use_offload)]) + world_size = dist.get_world_size(group=group) + # Gloo wants the output stacked along the input's first axis, not along a new one. + gathered = torch.empty(world_size * len(positions), 3, dtype=torch.int64, device=device) + dist.all_gather_into_tensor(gathered, local, group=group) + gathered = gathered.view(world_size, len(positions), 3).cpu() + if bool(gathered[:, :, 2].any()): + raise NotImplementedError('Offloaded ZeRO optimizer states have no affine storage map.') + ranks = _global_ranks(group) + for row, position in enumerate(positions): + fragments = [(rank, int(gathered[index, row, 0]), int(gathered[index, row, 1])) + for index, rank in enumerate(ranks)] + maps[position] = _fragment_affine_map(params[position].numel(), fragments) + return maps + + +def zero_optimizer_storage_shard(param, optim_state_key=None): + """This rank's shard of the fp32 master copy of ``param``, or of its ``optim_state_key`` state. + + The shard is a flat view of ZeRO's storage, laid out as ``zero_optimizer_storage_affine_maps`` + describes it, so writing it updates the optimizer. Returns ``None`` where that has no map. + """ + if hasattr(param, 'ds_id'): + if not hasattr(param, '_z3_optimizer') or not param.requires_grad: + return None + if _zero3_optimizer_offloaded(param): + raise NotImplementedError('Offloaded ZeRO-3 optimizer states have no affine storage map.') + shard = param._z3_optimizer.get_local_fp32_param(param, optim_state_key) + return shard.view(-1).narrow(0, 0, _zero3_local_numel(param)) + + if getattr(param, '_dp_group', None) is None: + return None + mapping = param._hp_mapping + if mapping is None: + # The rank holds no range of this parameter. + return torch.empty(0, dtype=torch.float32, device=get_accelerator().current_device_name()) + if mapping.use_offload: + raise NotImplementedError('Offloaded ZeRO optimizer states have no affine storage map.') + if optim_state_key is not None and mapping.optim_fragment is None: + raise RuntimeError('ZeRO links optimizer states to parameters at the first optimizer step; ' + f'call this after it to read {optim_state_key!r}.') + return mapping.get_hp_fragment(optim_state_key) + + +def _autotp_layout_map(name, param, tp_world_size): + from deepspeed.module_inject.layers import _get_param_uc_conversion_meta + + meta = _get_param_uc_conversion_meta(param) + if not meta: + # AutoTP leaves such a parameter whole on every tensor-parallel rank. + return replicated_map(tuple(getattr(param, 'ds_shape', param.shape)), tp_world_size) + if meta.get('unsupported_reason'): + raise NotImplementedError(f"AutoTP parameter '{name}' has no affine layout: {meta['unsupported_reason']}") + if meta.get('affine_map') is None: + raise NotImplementedError(f"AutoTP parameter '{name}' publishes no affine layout map.") + return ParamAffineMap.from_dict(meta['affine_map']) + + +def autotp_storage_affine_maps(model, optimizer_states=False, tp_group=None): + """Describe what every process stores of each parameter of an AutoTP ``model`` under ZeRO. + + Returns ``{name: map}`` over ``model.named_parameters()``. Each map nests the parameter's + AutoTP layout map with the ZeRO storage of every tensor-parallel shard, so it describes the + parameter in its own shape keyed by global rank, and each rank's shard is the one + ``zero_param_storage_shard`` returns. With ``optimizer_states`` the maps describe the fp32 + 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. + + 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 + model. A rank's storage of a layout piece that is dense in its shard is at most + ``2 * ndim - 1`` boxes; any other layout piece keeps one piece per row. + """ + if tp_group is None: + from deepspeed.utils import groups + tp_group = groups.get_tensor_model_parallel_group() + tp_world_size = dist.get_world_size(group=tp_group) + + # Some AutoTP layers publish their metadata only when asked. + for module in model.modules(): + marker = getattr(module, '_mark_uc_metadata', None) + if marker is not None: + marker() + + named_params = list(model.named_parameters()) + params = [param for _, param in named_params] + 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) + + maps = {} + for position, (name, param) in enumerate(named_params): + storage_by_tp_rank = [rank_maps[position] for rank_maps in gathered] + if all(storage is None for storage in storage_by_tp_rank): + maps[name] = None + continue + if any(storage is None for storage in storage_by_tp_rank): + raise ValueError(f"Parameter '{name}' has storage on some tensor-parallel ranks but not on others.") + layout = _autotp_layout_map(name, param, tp_world_size) + inner = {tp_rank: ParamAffineMap.from_dict(storage) for tp_rank, storage in enumerate(storage_by_tp_rank)} + replicated = layout.to_dict() == replicated_map(layout.logical_shape, tp_world_size).to_dict() + shared = all(storage == storage_by_tp_rank[0] for storage in storage_by_tp_rank) + if tp_world_size > 1 and replicated and shared: + # A parameter AutoTP leaves whole in a model built under zero.Init keeps its partition over + # the whole world, so every tensor-parallel rank reports the storage of the same one copy. + layout = replicated_map(layout.logical_shape, 1) + inner = {0: inner[0]} + maps[name] = nest_affine_maps(layout, inner) + return maps diff --git a/tests/unit/checkpoint/test_affine_transfer_plan.py b/tests/unit/checkpoint/test_affine_transfer_plan.py index caff1cc8c8a1..b00fe855f1b4 100644 --- a/tests/unit/checkpoint/test_affine_transfer_plan.py +++ b/tests/unit/checkpoint/test_affine_transfer_plan.py @@ -397,13 +397,98 @@ def test_two_pieces_claiming_one_shard_range_are_refused(): plan_transfer(replicated_map((4, 4), 1), source) -def test_a_shard_described_with_the_wrong_rank_is_refused(): - """A flat shard against a matrix parameter has no axis correspondence to plan along.""" +def test_a_flat_shard_holds_a_dense_box_of_a_matrix(): + """Flat storage, as ZeRO keeps it, may hold boxes of a matrix as dense runs of addresses.""" + full = torch.arange(32.).reshape(4, 8) + # Columns [0, 3) then columns [3, 8), each stored densely one after the other. + source = ParamAffineMap(logical_shape=(4, 8), + shard_shapes={0: (32, )}, + pieces_by_rank={ + 0: [ + AffinePiece((4, 3), 0, (8, 1), 0, (3, 1), [0]), + AffinePiece((4, 5), 3, (8, 1), 12, (5, 1), [0]), + ] + }) + storage = torch.cat([full[:, :3].reshape(-1), full[:, 3:].reshape(-1)]) + target = contiguous_split_map((4, 8), [2, 3, 3], 1) + + plan = plan_transfer(target, source) + + written = {rank: torch.full(shape, float('nan')) for rank, shape in target.shard_shapes.items()} + for segment in plan.segments: + torch.as_strided(written[segment.target_rank], segment.shape, segment.target_strides, + segment.target_offset).copy_( + torch.as_strided(storage, segment.shape, segment.source_strides, segment.source_offset)) + for rank, shard in written.items(): + assert torch.equal(shard, target.extract(full, rank)) + + +def _zero_cut_mid_row(): + # ZeRO cuts the flattened (4, 8) parameter at element 13, inside row 1. + return ParamAffineMap(logical_shape=(4, 8), + shard_shapes={ + 0: (13, ), + 1: (19, ) + }, + pieces_by_rank={ + 0: [ + AffinePiece((1, 8), 0, (8, 1), 0, (8, 1), [0]), + AffinePiece((1, 5), 8, (8, 1), 8, (5, 1), [0]), + ], + 1: [ + AffinePiece((1, 3), 13, (8, 1), 0, (3, 1), [1]), + AffinePiece((2, 8), 16, (8, 1), 3, (8, 1), [1]), + ], + }), { + 0: lambda full: full.reshape(-1)[:13], + 1: lambda full: full.reshape(-1)[13:] + } + + +def _flat_and_matrix_shards(): + # One rank keeps rows [0, 2) flat while the other keeps rows [2, 4) as a matrix. + return ParamAffineMap(logical_shape=(4, 8), + shard_shapes={ + 0: (16, ), + 1: (2, 8) + }, + pieces_by_rank={ + 0: [AffinePiece((2, 8), 0, (8, 1), 0, (8, 1), [0])], + 1: [AffinePiece((2, 8), 16, (8, 1), 0, (8, 1), [1])], + }), { + 0: lambda full: full[:2].reshape(-1), + 1: lambda full: full[2:] + } + + +@pytest.mark.parametrize('make_target', [_zero_cut_mid_row, _flat_and_matrix_shards], + ids=['flat_target_cut_mid_row', 'flat_and_matrix_shards']) +def test_flat_storage_is_written_as_well_as_read(make_target): + """Restoring into ZeRO storage writes flat shards; one map may also mix flat and matrix shards.""" + full = torch.arange(32.).reshape(4, 8) + source = contiguous_split_map((4, 8), [3, 5], 1) + target, expected = make_target() + + plan = plan_transfer(target, source) + + written = {rank: torch.full(shape, float('nan')) for rank, shape in target.shard_shapes.items()} + for segment in plan.segments: + read = torch.as_strided(source.extract(full, segment.source_rank), segment.shape, segment.source_strides, + segment.source_offset) + torch.as_strided(written[segment.target_rank], segment.shape, segment.target_strides, + segment.target_offset).copy_(read) + for rank, shard in written.items(): + assert torch.equal(shard, expected[rank](full)) + + +@pytest.mark.parametrize('shard_shape, dest_strides', [((32, ), (8, 1)), ((2, 2, 4), (4, 1))], + ids=['flat_but_not_dense', 'other_rank']) +def test_a_shard_without_axis_correspondence_is_refused(shard_shape, dest_strides): source = ParamAffineMap(logical_shape=(4, 4), - shard_shapes={0: (16, )}, - pieces_by_rank={0: [AffinePiece((4, 4), 0, (4, 1), 0, (4, 1), [0])]}) + shard_shapes={0: shard_shape}, + pieces_by_rank={0: [AffinePiece((4, 4), 0, (4, 1), 0, dest_strides, [0])]}) - with pytest.raises(UnsupportedLayoutError, match='number of axes'): + with pytest.raises(UnsupportedLayoutError): plan_transfer(replicated_map((4, 4), 1), source) diff --git a/tests/unit/checkpoint/test_convert_checkpoint.py b/tests/unit/checkpoint/test_convert_checkpoint.py index 3b59234832b8..a6592139c729 100644 --- a/tests/unit/checkpoint/test_convert_checkpoint.py +++ b/tests/unit/checkpoint/test_convert_checkpoint.py @@ -188,8 +188,8 @@ def test_convert_zero_checkpoint_to_fp32_state_dict(self, tmp_path): assert tensor.dtype == torch.bfloat16 torch.testing.assert_close(tensor.float(), state_dict[name], rtol=5e-3, atol=5e-3) - fp32_size = (fp32_save_dir / 'pytorch_model.bin').stat().size - bf16_size = (bf16_save_dir / 'pytorch_model.bin').stat().size + fp32_size = (fp32_save_dir / 'pytorch_model.bin').stat().st_size + bf16_size = (bf16_save_dir / 'pytorch_model.bin').stat().st_size assert bf16_size < fp32_size * 0.6 diff --git a/tests/unit/checkpoint/test_zero_affine.py b/tests/unit/checkpoint/test_zero_affine.py new file mode 100644 index 000000000000..e1be668225e2 --- /dev/null +++ b/tests/unit/checkpoint/test_zero_affine.py @@ -0,0 +1,480 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team + +import pytest +import torch + +import deepspeed +import deepspeed.comm as dist +from deepspeed.accelerator import get_accelerator +from deepspeed.checkpoint.affine import (contiguous_split_map, nest_affine_maps, replicated_map, segmented_map, + sub_param_map) +from deepspeed.checkpoint.affine_transfer import PlanBudget, plan_transfer +from deepspeed.checkpoint.zero_affine import (autotp_storage_affine_maps, zero_optimizer_storage_affine_maps, + zero_optimizer_storage_shard, zero_param_storage_affine_map, + zero_param_storage_shard, zero_storage_affine_map) +from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum +from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_optimizer_state +from unit.common import DistributedTest +from unit.simple_model import random_dataloader + + +def test_replicas_list_every_holder(): + full = torch.arange(6.) + affine_map = zero_storage_affine_map(6, [4, 1, 6]) + + assert set(affine_map.shard_shapes) == {1, 4, 6} + for rank in (1, 4, 6): + assert torch.equal(affine_map.extract(full, rank), full) + + asked = [] + + def selector(request): + asked.append(sorted(candidate.source_rank for candidate in request.candidates)) + return request.candidates[-1].source_rank + + plan_transfer(contiguous_split_map((6, ), [3, 3], 0), affine_map, PlanBudget(), replica_selector=selector) + # Each target block may be read from any of the three replicas. + assert asked == [[1, 4, 6], [1, 4, 6]] + + +def test_zero3_partitions_drop_padding(): + # 10 elements in partitions of 4: holders keep 4, 4 and 2 elements; the fourth is all padding. + full = torch.arange(10.) + affine_map = zero_storage_affine_map(10, [2, 0, 3, 1], partition_numel=4) + + assert affine_map.shard_shapes == {2: (4, ), 0: (4, ), 3: (2, ), 1: (0, )} + assert torch.equal(affine_map.extract(full, 2), full[0:4]) + assert torch.equal(affine_map.extract(full, 0), full[4:8]) + assert torch.equal(affine_map.extract(full, 3), full[8:10]) + assert affine_map.extract(full, 1).numel() == 0 + + +@pytest.mark.parametrize('numel, holders, partition', [(9, [0, 1], 4), (4, [0, 0], None), (4, [], None)]) +def test_rejects_storage_that_cannot_hold_the_parameter(numel, holders, partition): + with pytest.raises(ValueError): + zero_storage_affine_map(numel, holders, partition) + + +@pytest.mark.parametrize('accessor', [zero_param_storage_affine_map, zero_param_storage_shard]) +def test_rejects_quantized_zero3_parameter_storage(accessor): + param = torch.nn.Parameter(torch.zeros(8), requires_grad=False) + param.ds_id = 0 + param.ds_numel = 8 + param.ds_tensor = torch.zeros(4, dtype=torch.int8) + param.ds_tensor.ds_numel = 4 + param.ds_tensor.ds_quant_scale = torch.ones(1) + + with pytest.raises(NotImplementedError, match='Quantized ZeRO-3 parameter storage'): + accessor(param) + + +@pytest.mark.parametrize('accessor', [zero_param_storage_affine_map, zero_param_storage_shard]) +def test_rejects_nvme_offloaded_zero3_parameter_storage(accessor): + # A partition swapped out to NVMe leaves a one-element placeholder in memory. + param = torch.nn.Parameter(torch.zeros(8), requires_grad=False) + param.ds_id = 0 + param.ds_numel = 8 + param.ds_tensor = torch.zeros(1) + param.ds_tensor.ds_numel = 4 + param.ds_tensor.final_location = OffloadDeviceEnum.nvme + + with pytest.raises(NotImplementedError, match='NVMe-offloaded ZeRO-3 parameter storage'): + accessor(param) + + +def _stored_by_rank(layout_shards, holders_by_layout_rank, partition_by_layout_rank=None): + """What each process stores, by slicing each flattened layout shard with ZeRO's rule.""" + stored = {} + for layout_rank, shard in layout_shards.items(): + flat = shard.reshape(-1) + for index, rank in enumerate(holders_by_layout_rank[layout_rank]): + if partition_by_layout_rank is None: + stored[rank] = flat.clone() + continue + partition = partition_by_layout_rank[layout_rank] + stored[rank] = flat[index * partition:(index + 1) * partition].clone() + return stored + + +def _nested(layout, holders_by_layout_rank, partition_by_layout_rank=None): + inner = {} + for layout_rank, holders in holders_by_layout_rank.items(): + numel = torch.Size(layout.shard_shapes[layout_rank]).numel() + partition = None if partition_by_layout_rank is None else partition_by_layout_rank[layout_rank] + inner[layout_rank] = zero_storage_affine_map(numel, holders, partition) + return nest_affine_maps(layout, inner) + + +def _check_storage(affine_map, full, stored): + # validate_coverage also proves every piece names exactly the processes that store its elements. + affine_map.validate_coverage() + assert affine_map.logical_shape == tuple(full.shape) + assert affine_map.shard_shapes == {rank: tuple(shard.shape) for rank, shard in stored.items()} + for rank, shard in stored.items(): + torch.testing.assert_close(affine_map.extract(full, rank), shard, rtol=0, atol=0) + torch.testing.assert_close(affine_map.rebuild(stored), full, rtol=0, atol=0) + + +# Uneven column split of a 4 x 8 weight over two tensor-parallel ranks, the layout of a row-parallel +# linear layer. Its pieces are strided in the flattened weight. +_FULL = torch.arange(32, dtype=torch.float32).reshape(4, 8) +_COLUMNS = {0: _FULL[:, :3], 1: _FULL[:, 3:]} +_HOLDERS = {0: [0, 2], 1: [1, 3]} + + +@pytest.mark.parametrize('partition', [None, {0: 6, 1: 10}, {0: 7, 1: 11}], ids=['replicas', 'even', 'mid_row']) +def test_nest_describes_zero_storage_of_a_column_split(partition): + layout = contiguous_split_map(_FULL.shape, [3, 5], partition_dim=1) + + affine_map = _nested(layout, _HOLDERS, partition) + + _check_storage(affine_map, _FULL, _stored_by_rank(_COLUMNS, _HOLDERS, partition)) + + +def test_nest_describes_a_contiguous_storage_run_as_a_few_boxes(): + # A process stores one contiguous run of its layout shard: whole rows between two partial rows. + # One piece per row would make planning a large row-parallel weight slow, so the run must stay + # at most three boxes however many rows it spans. + full = torch.arange(64 * 48, dtype=torch.float32).reshape(64, 48) + layout = contiguous_split_map(full.shape, [20, 28], partition_dim=1) + holders = {0: [0, 1, 2], 1: [3, 4]} + partition = {0: 450, 1: 900} + + affine_map = _nested(layout, holders, partition) + + _check_storage(affine_map, full, _stored_by_rank({0: full[:, :20], 1: full[:, 20:]}, holders, partition)) + for rank in range(5): + assert len(affine_map.pieces_by_rank[rank]) <= 3 + + +def test_nest_merges_holders_of_replicated_layout_shards_split_at_different_places(): + # Two layout ranks hold the whole tensor but partition it over groups of different sizes, so an + # element's holders are the union of one process from each group, cut at both groups' boundaries. + layout = replicated_map(_FULL.shape, 2) + holders = {0: [0, 1], 1: [2, 3, 4]} + partition = {0: 16, 1: 11} + + affine_map = _nested(layout, holders, partition) + + _check_storage(affine_map, _FULL, _stored_by_rank({0: _FULL, 1: _FULL}, holders, partition)) + for offset, ranks in affine_map.holders().items(): + assert ranks == {offset // 16, 2 + offset // 11} + + +def test_nest_keeps_fused_sub_parameters_apart(): + full = torch.arange(6 * 4, dtype=torch.float32).reshape(6, 4) + # Fused QKV: rows [0, 2), [2, 4) and [4, 6) are each split between two ranks. + layout = sub_param_map(full.shape, [2, 2, 2], [[1, 1], [1, 1], [1, 1]], partition_dim=0) + shards = {rank: full[[rank, 2 + rank, 4 + rank]] for rank in range(2)} + holders = {0: [0, 1], 1: [2, 3]} + partition = {0: 7, 1: 6} + + _check_storage(_nested(layout, holders, partition), full, _stored_by_rank(shards, holders, partition)) + + +def test_nest_keeps_boxes_dense_in_every_replica(): + # The last column is a strided column of rank 0's whole-weight shard but all of rank 1's shard, + # so a box spanning both rows would be one run of addresses on rank 1 only. + full = torch.arange(6, dtype=torch.float32).reshape(2, 3) + layout = segmented_map(full.shape, [(2, False), (1, True)], 1, 2, [[2, 0]]) + holders = {0: [0], 1: [1]} + + _check_storage(_nested(layout, holders), full, _stored_by_rank({0: full, 1: full[:, 2:]}, holders)) + + +def test_nest_and_plan_a_scalar_parameter(): + full = torch.tensor(5.0) + holders = {0: [0, 1], 1: [2]} + source = _nested(replicated_map((), 2), holders) + stored = _stored_by_rank({0: full, 1: full}, holders) + _check_storage(source, full, stored) + + plan = plan_transfer(replicated_map((), 1), source) + + target = torch.full((), float('nan')) + for segment in plan.segments: + source_view = torch.as_strided(stored[segment.source_rank], segment.shape, segment.source_strides, + segment.source_offset) + torch.as_strided(target, segment.shape, segment.target_strides, segment.target_offset).copy_(source_view) + assert target.item() == 5.0 + + +def test_nested_storage_plans_into_another_layout(): + source = _nested(contiguous_split_map(_FULL.shape, [3, 5], partition_dim=1), _HOLDERS, {0: 7, 1: 11}) + target_holders = {0: [4], 1: [5, 6], 2: [7]} + target = _nested(contiguous_split_map(_FULL.shape, [1, 2, 1], partition_dim=0), target_holders, {0: 8, 1: 9, 2: 8}) + source_storage = _stored_by_rank(_COLUMNS, _HOLDERS, {0: 7, 1: 11}) + expected = _stored_by_rank({0: _FULL[:1], 1: _FULL[1:3], 2: _FULL[3:]}, target_holders, {0: 8, 1: 9, 2: 8}) + + plan = plan_transfer(target, source) + + target_storage = {rank: torch.full(shape, float('nan')) for rank, shape in target.shard_shapes.items()} + writes = {rank: torch.zeros(shape, dtype=torch.int64) for rank, shape in target.shard_shapes.items()} + for segment in plan.segments: + source_view = 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_view) + torch.as_strided(writes[segment.target_rank], segment.shape, segment.target_strides, + segment.target_offset).add_(1) + for rank, shard in expected.items(): + torch.testing.assert_close(target_storage[rank], shard, rtol=0, atol=0) + assert torch.all(writes[rank] == 1) + + +def test_nest_rejects_storage_that_does_not_match_the_layout(): + layout = contiguous_split_map(_FULL.shape, [3, 5], partition_dim=1) + with pytest.raises(ValueError, match='layout ranks'): + nest_affine_maps(layout, {0: zero_storage_affine_map(12, [0])}) + with pytest.raises(ValueError, match='holds 12 elements'): + nest_affine_maps(layout, {0: zero_storage_affine_map(32, [0]), 1: zero_storage_affine_map(20, [1])}) + with pytest.raises(ValueError, match='more than one layout shard'): + nest_affine_maps(layout, {0: zero_storage_affine_map(12, [0]), 1: zero_storage_affine_map(20, [0])}) + + +class StraddlingModel(torch.nn.Module): + # 351 trainable elements split over two ranks put the boundary inside ``first.bias``, so one + # parameter is held in part by each rank. ``frozen`` has no optimizer state. + def __init__(self, hidden_dim): + super().__init__() + self.frozen = torch.nn.Linear(hidden_dim, hidden_dim) + self.frozen.requires_grad_(False) + self.first = torch.nn.Linear(hidden_dim, hidden_dim) + self.second = torch.nn.Linear(hidden_dim, hidden_dim, bias=False) + + def forward(self, x, y): + return torch.nn.functional.cross_entropy(self.second(self.first(self.frozen(x))), y) + + +def _full_param(param): + if hasattr(param, 'ds_id'): + with deepspeed.zero.GatheredParameters([param]): + return param.data.detach().clone().view(-1) + return param.data.detach().clone().view(-1) + + +def _full_optimizer_value(param, key): + if key is None: + return safe_get_full_fp32_param(param).view(-1) + return safe_get_full_optimizer_state(param, key).view(-1) + + +class TestZeroOptimizerStorageMaps(DistributedTest): + world_size = 2 + + @pytest.mark.parametrize('zero_stage, bf16_optimizer', [(1, False), (2, False), (3, False), (1, True)]) + def test_maps_describe_live_storage(self, zero_stage, bf16_optimizer): + if not get_accelerator().is_bf16_supported(): + pytest.skip('requires bf16') + hidden_dim = 13 + config = { + 'train_micro_batch_size_per_gpu': 1, + 'optimizer': { + 'type': 'Adam', + 'params': { + 'lr': 1e-2, + 'torch_adam': True + } + }, + 'bf16': { + 'enabled': True + }, + 'zero_optimization': { + 'stage': zero_stage + }, + } + if bf16_optimizer: + # fp32 gradient accumulation under ZeRO-1 selects the bf16 optimizer. + config['data_types'] = {'grad_accum_dtype': 'fp32'} + if zero_stage == 3: + with deepspeed.zero.Init(config_dict_or_path=config): + model = StraddlingModel(hidden_dim) + else: + model = StraddlingModel(hidden_dim) + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + params = list(engine.module.parameters()) + rank = dist.get_rank() + + if zero_stage != 3: + # first.bias straddles the partition boundary, so every rank holds part of it. + with pytest.raises(RuntimeError, match='first optimizer step'): + zero_optimizer_storage_shard(engine.module.first.bias, 'exp_avg') + + for x, y in random_dataloader(engine, 3, hidden_dim, engine.device, torch.bfloat16): + engine.backward(engine(x, y)) + engine.step() + + if zero_stage == 3: + # ZeRO-3 keeps small parameters gathered between steps; a write to the shard alone would be lost. + with pytest.raises(RuntimeError, match='empty_partition_cache'): + zero_param_storage_shard(engine.module.second.weight) + engine.empty_partition_cache() + + maps = zero_optimizer_storage_affine_maps(params) + assert maps[0] is None and maps[1] is None + assert zero_optimizer_storage_shard(engine.module.frozen.weight) is None + for param, affine_map in zip(params[2:], maps[2:]): + affine_map.validate_coverage() + + # The low-precision parameter is the fp32 master copy rounded, which checks the master + # copy's map against storage that does not come from the optimizer. + full_param = _full_param(param) + assert torch.equal(_full_optimizer_value(param, None).to(full_param.dtype), full_param) + param_map = zero_param_storage_affine_map(param) + assert torch.equal(zero_param_storage_shard(param), param_map.extract(full_param, rank)) + + for key in (None, 'exp_avg', 'exp_avg_sq'): + full = _full_optimizer_value(param, key) + assert torch.equal(zero_optimizer_storage_shard(param, key), affine_map.extract(full, rank)) + + # The shard is ZeRO's storage: writing each rank's id into it must show up in the gathered + # state exactly where the map places that rank's range. + zero_optimizer_storage_shard(param, 'exp_avg').fill_(rank + 1) + written = _full_optimizer_value(param, 'exp_avg') + expected = torch.zeros_like(written) + for holder, pieces in affine_map.pieces_by_rank.items(): + for piece in pieces: + expected[piece.source_offset:piece.source_offset + piece.shape[0]] = holder + 1 + assert torch.equal(written, expected) + + # A write to the parameter's shard must reach the next forward. + zero_param_storage_shard(engine.module.second.weight).zero_() + outputs = [] + hook = engine.module.second.register_forward_hook(lambda module, args, output: outputs.append(output)) + for x, y in random_dataloader(engine, 1, hidden_dim, engine.device, torch.bfloat16): + engine(x, y) + hook.remove() + assert torch.all(outputs[0] == 0) + + engine.destroy() + + +class ThreeLinears(torch.nn.Module): + + def __init__(self, hidden_dim): + super().__init__() + self.linears = torch.nn.ModuleList([torch.nn.Linear(hidden_dim, hidden_dim) for _ in range(3)]) + + def forward(self, x, y): + for linear in self.linears: + x = linear(x) + return torch.nn.functional.cross_entropy(x, y) + + +def _all_shards(shard): + gathered = [None] * dist.get_world_size() + # .clone() drops the view's offset into the flat buffer; on CPU .cpu() alone would pickle it. + dist.all_gather_object(gathered, shard.detach().cpu().clone()) + return dict(enumerate(gathered)) + + +def _one_holder_each(layout): + # Every layout rank is a process of its own, as a rollout engine without ZeRO would be. + inner = { + rank: zero_storage_affine_map(torch.Size(shape).numel(), [rank]) + for rank, shape in layout.shard_shapes.items() + } + return nest_affine_maps(layout, inner) + + +class TestAutoTPStorageMaps(DistributedTest): + world_size = 4 + reuse_dist_env = False + + @pytest.mark.parametrize('zero_stage, zero_init', [(1, False), (2, False), (3, False), (3, True)]) + def test_maps_describe_live_storage_of_tp2_dp2(self, zero_stage, zero_init): + if not get_accelerator().is_bf16_supported(): + pytest.skip('requires bf16') + hidden_dim = 12 + config = { + 'train_micro_batch_size_per_gpu': 1, + 'optimizer': { + 'type': 'Adam', + 'params': { + 'lr': 1e-2, + 'torch_adam': True + } + }, + 'bf16': { + 'enabled': True + }, + 'zero_optimization': { + 'stage': zero_stage + }, + 'tensor_parallel': { + 'autotp_size': 2, + 'partition_config': { + 'use_default_specs': + False, + 'layer_specs': [ + { + 'patterns': [r'.*linears\.0\.weight$'], + 'partition_type': 'column' + }, + { + 'patterns': [r'.*linears\.1\.weight$'], + 'partition_type': 'row' + }, + { + 'patterns': [r'.*linears\.2\.weight$'], + 'partition_type': 'skip' + }, + ], + }, + }, + } + torch.manual_seed(0) + if zero_init: + # zero.Init partitions every parameter over the whole world before AutoTP sees the model. + with deepspeed.zero.Init(config_dict_or_path=config): + model = ThreeLinears(hidden_dim) + # The weights before AutoTP and ZeRO touch them: the oracle for what each process stores. + reference = { + name: _full_param(param).cpu().view(param.ds_shape) + for name, param in model.named_parameters() + } + else: + model = ThreeLinears(hidden_dim) + reference = {name: param.detach().to(torch.bfloat16) for name, param in model.named_parameters()} + shapes = {name: tuple(full.shape) for name, full in reference.items()} + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + params = dict(engine.module.named_parameters()) + rank = dist.get_rank() + + maps = autotp_storage_affine_maps(engine.module) + + assert set(maps) == set(reference) + for name, affine_map in maps.items(): + affine_map.validate_coverage() + assert torch.equal(zero_param_storage_shard(params[name]).cpu(), affine_map.extract(reference[name], rank)) + + # Plan from the live storage into four tensor-parallel ranks split along dim 0. + target = _one_holder_each(contiguous_split_map(shapes[name], [hidden_dim // 4] * 4, 0)) + plan = plan_transfer(target, affine_map) + source_storage = _all_shards(zero_param_storage_shard(params[name])) + written = {r: torch.full(s, float('nan'), dtype=torch.bfloat16) for r, s in target.shard_shapes.items()} + for segment in plan.segments: + torch.as_strided(written[segment.target_rank], segment.shape, segment.target_strides, + segment.target_offset).copy_( + torch.as_strided(source_storage[segment.source_rank], segment.shape, + segment.source_strides, segment.source_offset)) + for target_rank, shard in written.items(): + assert torch.equal(shard, target.extract(reference[name], target_rank)) + + for x, y in random_dataloader(engine, 2, hidden_dim, engine.device, torch.bfloat16): + engine.backward(engine(x, y)) + engine.step() + engine.empty_partition_cache() + + optimizer_maps = autotp_storage_affine_maps(engine.module, optimizer_states=True) + for name, affine_map in optimizer_maps.items(): + affine_map.validate_coverage() + # The trained low-precision parameter, rebuilt through its map, is the fp32 master copy rounded. + full_param = maps[name].rebuild(_all_shards(zero_param_storage_shard(params[name]))) + master = zero_optimizer_storage_shard(params[name]).to(torch.bfloat16).cpu() + assert torch.equal(master, affine_map.extract(full_param, rank)) + + engine.destroy()