From 02e7e174d0b89641c825bff5245083c1121c6df0 Mon Sep 17 00:00:00 2001 From: Achyuthan Sivasankar Date: Tue, 10 Nov 2026 21:31:22 -0500 Subject: [PATCH 1/5] Describe a parameter held in several layouts as one affine map A rollout replica can keep a tensor-parallel shard that is still current while the trainer's ZeRO-3 partitions hold the whole parameter. union_affine_maps cuts each layout's pieces at the edges of the blocks the other layouts hold and lists every holder, so plan_transfer can read either copy. Move the planner's box subtraction into affine_geometry so both use one copy. Signed-off-by: Achyuthan Sivasankar --- deepspeed/checkpoint/affine.py | 100 ++++++++++++++- deepspeed/checkpoint/affine_geometry.py | 28 ++++- deepspeed/checkpoint/affine_ir_spec.md | 10 ++ deepspeed/checkpoint/affine_transfer.py | 28 +---- docs/code-docs/source/affine-transfer.rst | 20 +++ .../test_affine_transfer_executor.py | 36 +++++- .../checkpoint/test_affine_transfer_plan.py | 118 +++++++++++++++++- 7 files changed, 308 insertions(+), 32 deletions(-) diff --git a/deepspeed/checkpoint/affine.py b/deepspeed/checkpoint/affine.py index 0d424de577c1..1ead8bf1f6a5 100644 --- a/deepspeed/checkpoint/affine.py +++ b/deepspeed/checkpoint/affine.py @@ -20,13 +20,14 @@ import torch -from .affine_geometry import LogicalBox, address_range, boxes_disjoint, coordinate, overlaps_itself +from .affine_geometry import LogicalBox, address_range, boxes_disjoint, coordinate, overlaps_itself, subtract from .affine_geometry import (dot as _dot, product as _product, row_major_range_boxes as _row_major_range_boxes, row_major_strides as _row_major_strides, strided_address as _strided_address) __all__ = [ 'AffinePiece', 'ParamAffineMap', 'AFFINE_MAP_FORMAT_VERSION', 'SCALE_POWER_BY_STATE', 'replicated_map', - 'contiguous_split_map', 'sub_param_map', 'segmented_map', 'block_gather_map', 'nest_affine_maps' + 'contiguous_split_map', 'sub_param_map', 'segmented_map', 'block_gather_map', 'nest_affine_maps', + 'union_affine_maps' ] # Encoding version of the stored map, independent of the universal checkpoint version so @@ -932,3 +933,98 @@ def _first_index_at_or_after(piece, address): index *= later_size return index return index + + +def union_affine_maps(maps): + """One map of a parameter that several layouts hold at the same time. + + Each map describes the same parameter in its own layout, held by its own locations: for example a + trainer's ZeRO-3 partitions and a surviving tensor-parallel shard of an inference copy. A location is + one buffer, so a process that holds the parameter in two layouts appears under two locations, and + the transfer's endpoints bind both of them to that process. + + A planner may read a block from any of its holders, so it needs any two blocks to be equal or + disjoint, and each block to list every location that holds it. Each piece is therefore cut at the + edges of the blocks the other layouts hold over it, and each cut piece lists the holders from every + layout. A cut keeps the piece's strides and moves its offsets, so every location still stores + exactly what it did. Pieces must be axis-aligned blocks of the parameter. + """ + if not maps: + raise ValueError('A union needs at least one map.') + union = maps[0] + for other in maps[1:]: + union = _union_of_two(union, other) + return union + + +def _union_of_two(first, second): + if first.logical_shape != second.logical_shape: + raise ValueError(f'The layouts describe parameters of shape {first.logical_shape} and ' + f'{second.logical_shape}, so they cannot describe the same parameter.') + shared = sorted(set(first.shard_shapes) & set(second.shard_shapes)) + if shared: + raise ValueError(f'Locations {shared} appear in both layouts; give each layout its own locations, one ' + 'per buffer.') + pieces_by_rank = {} + for this, other in ((first, second), (second, first)): + blocks = _blocks_held(other) + for rank, pieces in this.pieces_by_rank.items(): + pieces_by_rank[rank] = [part for piece in pieces for part in _cut(piece, this.logical_shape, blocks)] + affine_map = ParamAffineMap(logical_shape=first.logical_shape, + shard_shapes={ + **first.shard_shapes, + **second.shard_shapes + }, + pieces_by_rank=pieces_by_rank) + affine_map.validate() + return affine_map + + +def _blocks_held(affine_map): + # Each block the map holds, once, with the locations its pieces list. Sorted, so a cut does not depend + # on the order in which the map lists its pieces. + holders = {} + for pieces in affine_map.pieces_by_rank.values(): + for piece in pieces: + if piece.numel: + block = _block_of(piece, affine_map.logical_shape) + holders[block] = holders.get(block, frozenset()) | piece.locations + return sorted(holders.items(), key=lambda item: (item[0].origin, item[0].extent)) + + +def _block_of(piece, logical_shape): + # Only an axis-aligned block of the parameter can be cut at another block's edges by coordinates. + strides = _row_major_strides(logical_shape) + origin = None + if len(piece.shape) == len(logical_shape) and all( + size <= 1 or stride == expected + for size, stride, expected in zip(piece.shape, piece.source_strides, strides)): + origin = coordinate(piece.source_offset, strides, logical_shape) + if origin is None: + raise NotImplementedError(f'Piece {piece} is not an axis-aligned block of a parameter of shape ' + f'{logical_shape}, so it cannot be cut at another layout\'s block edges.') + return LogicalBox(origin, piece.shape) + + +def _cut(piece, logical_shape, blocks): + # ``piece`` cut at the edges of ``blocks``: each part another layout also holds lists those holders + # too, and the parts no other layout holds keep the piece's own. + if not piece.numel: + return [piece] + block = _block_of(piece, logical_shape) + parts = [] + rest = [block] + for other, holders in blocks: + overlap = block.intersection(other) + if not overlap.is_empty: + parts.append((overlap, piece.locations | holders)) + rest = [part for box in rest for part in subtract(box, other)] + parts.extend((box, piece.locations) for box in rest) + return [_part_of(piece, block.origin, box, locations) for box, locations in parts] + + +def _part_of(piece, origin, box, locations): + # The part of ``piece`` over ``box``: the same strides, with both offsets moved to the box's corner. + shift = tuple(low - start for low, start in zip(box.origin, origin)) + return AffinePiece(box.extent, piece.source_offset + _dot(shift, piece.source_strides), piece.source_strides, + piece.dest_offset + _dot(shift, piece.dest_strides), piece.dest_strides, locations, piece.scale) diff --git a/deepspeed/checkpoint/affine_geometry.py b/deepspeed/checkpoint/affine_geometry.py index d02562ab1bd7..b1d5e8205db7 100644 --- a/deepspeed/checkpoint/affine_geometry.py +++ b/deepspeed/checkpoint/affine_geometry.py @@ -11,7 +11,7 @@ __all__ = [ 'LogicalBox', 'address_range', 'coordinate', 'dot', 'overlaps_itself', 'product', 'row_major_range_boxes', - 'row_major_strides', 'strided_address' + 'row_major_strides', 'strided_address', 'subtract' ] @@ -181,3 +181,29 @@ def boxes_disjoint(boxes: Sequence[LogicalBox], max_checks: Optional[int] = None return False open_boxes.append(box) return True + + +def subtract(region: LogicalBox, cut: LogicalBox) -> List[LogicalBox]: + """Return the disjoint parts of a box outside another box.""" + overlap = region.intersection(cut) + if overlap.is_empty: + return [region] + origin = list(region.origin) + extent = list(region.extent) + pieces = [] + for axis, (low, high) in enumerate(zip(overlap.origin, overlap.upper())): + if origin[axis] < low: + shape = extent.copy() + shape[axis] = low - origin[axis] + pieces.append(LogicalBox(tuple(origin), tuple(shape))) + extent[axis] -= shape[axis] + origin[axis] = low + end = origin[axis] + extent[axis] + if high < end: + start = origin.copy() + shape = extent.copy() + start[axis] = high + shape[axis] = end - high + pieces.append(LogicalBox(tuple(start), tuple(shape))) + extent[axis] = high - origin[axis] + return pieces diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index adf13ed6d7b0..48202ce7a1d4 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -740,3 +740,13 @@ 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. + +**10.8 One parameter in several layouts.** A parameter can be held in two layouts at once, such +as a trainer's ZeRO-3 partitions and a rollout replica's tensor-parallel shard that is still +current. `union_affine_maps([storage, shard])` describes both as one source. The layouts use +disjoint locations, one per buffer; the transfer's endpoints may bind several locations to one +process. Every piece is cut at the edges of the blocks the other layouts hold over it, and each +cut piece lists the holders from every layout, so P5 holds and the planner may read either copy. +A cut keeps a piece's strides and moves its offsets, so every location keeps its storage. A +ZeRO-3 block of several rows cut at a column edge keeps its row-major strides and its partition's +offset, so it is not dense in its 1-D shard (10.2): it is described, but not yet planned. diff --git a/deepspeed/checkpoint/affine_transfer.py b/deepspeed/checkpoint/affine_transfer.py index 7e917794dd45..40eb4bff3abc 100644 --- a/deepspeed/checkpoint/affine_transfer.py +++ b/deepspeed/checkpoint/affine_transfer.py @@ -32,7 +32,7 @@ from .affine import AffinePiece, ParamAffineMap from .affine_geometry import (LogicalBox, boxes_disjoint, coordinate as _coordinate, product as _product, - row_major_strides as _row_major_strides) + row_major_strides as _row_major_strides, subtract as _subtract) __all__ = [ 'AffineTransferError', 'InvalidMapError', 'InvalidReplicaPolicyError', 'UnsupportedLayoutError', 'PlanBudget', @@ -508,32 +508,6 @@ def _covers_exactly(region: LogicalBox, parts: Sequence[LogicalBox]) -> bool: return sum(part.volume for part in parts) == region.volume -def _subtract(region: LogicalBox, cut: LogicalBox) -> List[LogicalBox]: - """Return the disjoint parts of a box outside another box.""" - overlap = region.intersection(cut) - if overlap.is_empty: - return [region] - origin = list(region.origin) - extent = list(region.extent) - pieces = [] - for axis, (low, high) in enumerate(zip(overlap.origin, overlap.upper())): - if origin[axis] < low: - shape = extent.copy() - shape[axis] = low - origin[axis] - pieces.append(LogicalBox(tuple(origin), tuple(shape))) - extent[axis] -= shape[axis] - origin[axis] = low - end = origin[axis] + extent[axis] - if high < end: - start = origin.copy() - shape = extent.copy() - start[axis] = high - shape[axis] = end - high - pieces.append(LogicalBox(tuple(start), tuple(shape))) - extent[axis] = high - origin[axis] - return pieces - - def _covers_union(region: LogicalBox, boxes: Sequence[LogicalBox], limits: PlanBudget) -> bool: """Check a union without enumerating parameter elements or counting replica overlap twice.""" uncovered = [] if region.is_empty else [region] diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index ab6a89354660..d3668b38d462 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -75,6 +75,26 @@ per-request ``replica_selector`` as a batch policy. Every rank must return the s cost inputs must come from data every rank shares, such as a link calibration gathered across ranks, never from a rank-local measurement. +Several layouts as one source +----------------------------- + +A parameter can be held in two layouts at once, such as a trainer's ZeRO-3 +partitions and an inference shard that is still current. +``union_affine_maps`` from ``deepspeed.checkpoint.affine`` merges their maps into +one source map, so the planner can read each block from any layout that holds +it. Each layout uses its own locations, one per buffer, and +``TransferEndpoints`` may bind several locations to one process:: + + from deepspeed.checkpoint.affine import union_affine_maps + + source_map = union_affine_maps([zero3_storage_map, surviving_shard_map]) + plan = plan_transfer(target_map, source_map) + +Pieces are cut where the layouts' blocks meet and keep their strides, so each +buffer is read as it is stored. The planner does not yet accept a ZeRO-3 block +that a column edge cuts across several rows. Maintenance contact: +``@Achyuthan-S``. + Transport and staging --------------------- diff --git a/tests/unit/checkpoint/test_affine_transfer_executor.py b/tests/unit/checkpoint/test_affine_transfer_executor.py index 8603e019804d..a7a2fd325cdf 100644 --- a/tests/unit/checkpoint/test_affine_transfer_executor.py +++ b/tests/unit/checkpoint/test_affine_transfer_executor.py @@ -12,11 +12,13 @@ import torch import deepspeed.comm as dist from deepspeed.accelerator import get_accelerator -from deepspeed.checkpoint.affine import contiguous_split_map, replicated_map +from deepspeed.checkpoint.affine import (ParamAffineMap, contiguous_split_map, nest_affine_maps, replicated_map, + union_affine_maps) from deepspeed.checkpoint.affine_transfer import PlanBudget, plan_transfer from deepspeed.checkpoint.affine_transfer_executor import (AffineTransferExecutionError, StagingBudget, TransferEndpoints, TransferRequest, _is_packed, execute_transfer, execute_transfers, schedule_transfers) +from deepspeed.checkpoint.zero_affine import zero_storage_affine_map from unit.common import DistributedTest UNWRITTEN = float('nan') @@ -401,6 +403,38 @@ def test_a_lazy_view_crossing_processes_is_refused_on_both(self, kind, side): assert not store.any() +class TestB2TwoLayoutsOnOneProcess(DistributedTest): + """A process that holds a parameter in two layouts serves each of its buffers under its own location.""" + world_size = 2 + + def test_a_union_source_reads_both_buffers_of_one_process(self): + _join_transfer_group() + rows, cols = 8, 6 + numel = rows * cols + zero = nest_affine_maps(replicated_map((rows, cols), 1), + {0: zero_storage_affine_map(numel, [100, 101], numel // 2)}) + # Process 0 also keeps row shard 0 of a tensor-parallel copy that is still current. + layout = contiguous_split_map((rows, cols), [4, 4], 0) + shard = ParamAffineMap((rows, cols), {0: layout.shard_shapes[0]}, {0: layout.pieces_by_rank[0]}) + source = union_affine_maps([zero, shard]) + target = contiguous_split_map((rows, cols), [3, 3], 1) + endpoints = TransferEndpoints(source={0: 0, 100: 0, 101: 1}, target={0: 1, 1: 0}) + dtype = torch.float32 + full = _full(rows, cols, dtype) + source_buffers = { + location: source.extract(full, location).contiguous() + for location, process in endpoints.source.items() if process == dist.get_rank() + } + target_buffers = _targets(target, endpoints, dtype) + + plan = plan_transfer(target, source, PlanBudget()) + # The lowest holder is read by default, so the row shard serves the rows it holds. + assert 0 in {segment.source_rank for segment in plan.segments} + execute_transfer(plan, source_buffers, target_buffers, endpoints, dtype) + + _assert_matches(target_buffers, target, full) + + class TestB2TransferCPU: def test_packed_regions_are_exactly_the_contiguous_views(self): diff --git a/tests/unit/checkpoint/test_affine_transfer_plan.py b/tests/unit/checkpoint/test_affine_transfer_plan.py index 48641a18637e..53851f41149a 100644 --- a/tests/unit/checkpoint/test_affine_transfer_plan.py +++ b/tests/unit/checkpoint/test_affine_transfer_plan.py @@ -30,10 +30,12 @@ import torch from deepspeed.checkpoint.affine import (AffinePiece, ParamAffineMap, block_gather_map, contiguous_split_map, - replicated_map, segmented_map, sub_param_map) + nest_affine_maps, replicated_map, segmented_map, sub_param_map, + union_affine_maps) from deepspeed.checkpoint.affine_geometry import LogicalBox, boxes_disjoint from deepspeed.checkpoint.affine_transfer import (AffineTransferError, InvalidMapError, PlanBudget, TransferSegment, UnsupportedLayoutError, plan_transfer) +from deepspeed.checkpoint.zero_affine import zero_storage_affine_map SENTINEL = -12345.0 @@ -1037,3 +1039,117 @@ def test_a_single_corrupt_piece_is_reported_rather_than_planned_around(): ) with pytest.raises(AffineTransferError): plan_transfer(contiguous_split_map((16, 8), [4, 4, 4, 4], 0), broken) + + +# ---------------------------------------------------------------- one parameter in several layouts + + +def _zero3_storage(shape, partitions, first_location): + """ZeRO-3 partitions of the flattened parameter, described in the parameter's own shape.""" + numel = _product(shape) + locations = list(range(first_location, first_location + partitions)) + return nest_affine_maps(replicated_map(shape, 1), + {0: zero_storage_affine_map(numel, locations, -(-numel // partitions))}) + + +def _surviving(layout, ranks, first_location): + """The shards that ``ranks`` hold in ``layout``, at locations counted from ``first_location``.""" + moved = {rank: first_location + rank for rank in ranks} + + def move(piece): + holders = {moved[holder] for holder in piece.locations} + return AffinePiece(piece.shape, piece.source_offset, piece.source_strides, piece.dest_offset, + piece.dest_strides, holders) + + shard_shapes = {moved[rank]: layout.shard_shapes[rank] for rank in ranks} + pieces = {moved[rank]: [move(piece) for piece in layout.pieces_by_rank[rank]] for rank in ranks} + return ParamAffineMap(layout.logical_shape, shard_shapes, pieces) + + +def _assert_union_holds_what_each_layout_holds(union, layouts, full): + """Each element lists every location of every layout that holds it, and each location keeps its shard.""" + holders = [layout.holders() for layout in layouts] + merged = union.holders() + for offset in range(full.numel()): + assert merged[offset] == set().union(*(by_layout.get(offset, set()) for by_layout in holders)), offset + for layout in layouts: + for location in layout.shard_shapes: + assert torch.equal(union.extract(full, location), layout.extract(full, location)), location + + +@pytest.mark.parametrize('rows,cols,sizes,survivors,partitions', [ + (6, 5, [3, 3], [0], 4), + (7, 4, [3, 2, 2], [0, 2], 3), + (5, 6, [2, 3], [1], 1), + (6, 5, [3, 3], [0, 1], 5), +]) +def test_a_surviving_row_shard_and_zero3_partitions_plan_as_one_source(rows, cols, sizes, survivors, partitions): + """A tensor-parallel row shard that is still current, and the trainer's ZeRO-3 partitions, as one source. + + A partition may start or end inside a row, so its blocks overlap the shard's without being equal + until both are cut. + """ + zero = _zero3_storage((rows, cols), partitions, first_location=100) + shard = _surviving(contiguous_split_map((rows, cols), sizes, 0), survivors, first_location=0) + source = union_affine_maps([zero, shard]) + full = _full(rows, cols, seed=rows * cols) + _assert_union_holds_what_each_layout_holds(source, [zero, shard], full) + + shards = _shards(source, lambda map_, rank: map_.extract(full, rank)) + for target in (contiguous_split_map((rows, cols), _split(rows, 2), + 0), contiguous_split_map((rows, cols), _split(cols, 3), 1)): + plan = plan_transfer(target, source) + produced = _apply_plan(plan, target, shards) + for rank in target.shard_shapes: + assert torch.equal(produced[rank], target.extract(full, rank)), rank + # The lowest holder is read by default, so the surviving shard serves every block it holds. + assert {segment.source_rank for segment in plan.segments} & set(survivors) + + +def test_a_union_of_three_layouts_does_not_depend_on_their_order(): + """Merging folds pairwise, so every order must give the same holders and an exact plan.""" + rows, cols = 12, 5 + layouts = [ + _zero3_storage((rows, cols), 5, first_location=100), + _surviving(contiguous_split_map((rows, cols), [6, 6], 0), [1], first_location=0), + _surviving(contiguous_split_map((rows, cols), [4, 4, 4], 0), [0, 2], first_location=10), + ] + full = _full(rows, cols, seed=7) + target = contiguous_split_map((rows, cols), _split(cols, 2), 1) + for order in itertools.permutations(layouts): + source = union_affine_maps(list(order)) + _assert_union_holds_what_each_layout_holds(source, layouts, full) + produced = _apply_plan(plan_transfer(target, source), target, + _shards(source, lambda map_, rank: map_.extract(full, rank))) + for rank in target.shard_shapes: + assert torch.equal(produced[rank], target.extract(full, rank)), rank + + +def test_a_column_cut_keeps_every_zero3_element_where_it_is(): + """Cut at a column edge, a ZeRO-3 block of several rows keeps its strides and its partition's offset. + + The union stays exact either way; whether a plan may read such a block is the planner's question. + """ + rows, cols = 6, 5 + zero = _zero3_storage((rows, cols), 2, first_location=100) + shard = _surviving(contiguous_split_map((rows, cols), [3, 2], 1), [0], first_location=0) + source = union_affine_maps([zero, shard]) + full = _full(rows, cols, seed=11) + _assert_union_holds_what_each_layout_holds(source, [zero, shard], full) + shards = {location: source.extract(full, location) for location in source.shard_shapes} + assert torch.equal(source.rebuild(shards).view(rows, cols), full) + + +def test_a_union_refuses_layouts_it_cannot_merge(): + shard = contiguous_split_map((4, 6), [2, 2], 0) + with pytest.raises(ValueError, match='at least one map'): + union_affine_maps([]) + # Both layouts name locations 0 and 1, so one location would stand for two buffers. + with pytest.raises(ValueError, match='appear in both layouts'): + union_affine_maps([shard, contiguous_split_map((4, 6), [3, 3], 1)]) + with pytest.raises(ValueError, match='shape'): + union_affine_maps([shard, _surviving(contiguous_split_map((6, 4), [3, 3], 0), [0], first_location=10)]) + # A transposed block has no corner and extent in the parameter's coordinates to cut at. + transposed = ParamAffineMap((4, 6), {20: (6, 4)}, {20: [AffinePiece((6, 4), 0, (1, 6), 0, (4, 1), {20})]}) + with pytest.raises(NotImplementedError, match='axis-aligned block'): + union_affine_maps([shard, transposed]) From 6f80096f76f586c1f24f63808e5b078995d9f4cc Mon Sep 17 00:00:00 2001 From: Achyuthan Sivasankar Date: Fri, 13 Nov 2026 09:05:47 -0500 Subject: [PATCH 2/5] Cut a union at every block's edges, and refuse runs that wrap a row Replicas within one layout may store a region whole or in parts, so cutting a piece only at the other layout's blocks could place the same elements twice in one shard. Cut every piece into the disjoint refinement of all the blocks both layouts hold, each part listing every holder. A row-major run longer than what is left of its row is not a block, so refuse it instead of cutting it as one. Signed-off-by: Achyuthan Sivasankar --- deepspeed/checkpoint/affine.py | 54 ++++++++++++------- deepspeed/checkpoint/affine_ir_spec.md | 5 +- .../checkpoint/test_affine_transfer_plan.py | 35 ++++++++++++ 3 files changed, 72 insertions(+), 22 deletions(-) diff --git a/deepspeed/checkpoint/affine.py b/deepspeed/checkpoint/affine.py index 1ead8bf1f6a5..c05d1408a9d2 100644 --- a/deepspeed/checkpoint/affine.py +++ b/deepspeed/checkpoint/affine.py @@ -945,7 +945,7 @@ def union_affine_maps(maps): A planner may read a block from any of its holders, so it needs any two blocks to be equal or disjoint, and each block to list every location that holds it. Each piece is therefore cut at the - edges of the blocks the other layouts hold over it, and each cut piece lists the holders from every + edges of every block held over it, in any layout, and each cut piece lists the holders from every layout. A cut keeps the piece's strides and moves its offsets, so every location still stores exactly what it did. Pieces must be axis-aligned blocks of the parameter. """ @@ -965,11 +965,11 @@ def _union_of_two(first, second): if shared: raise ValueError(f'Locations {shared} appear in both layouts; give each layout its own locations, one ' 'per buffer.') + blocks = _disjoint_blocks(first, second) pieces_by_rank = {} - for this, other in ((first, second), (second, first)): - blocks = _blocks_held(other) - for rank, pieces in this.pieces_by_rank.items(): - pieces_by_rank[rank] = [part for piece in pieces for part in _cut(piece, this.logical_shape, blocks)] + for affine_map in (first, second): + for rank, pieces in affine_map.pieces_by_rank.items(): + pieces_by_rank[rank] = [part for piece in pieces for part in _cut(piece, first.logical_shape, blocks)] affine_map = ParamAffineMap(logical_shape=first.logical_shape, shard_shapes={ **first.shard_shapes, @@ -980,16 +980,31 @@ def _union_of_two(first, second): return affine_map -def _blocks_held(affine_map): - # Each block the map holds, once, with the locations its pieces list. Sorted, so a cut does not depend - # on the order in which the map lists its pieces. +def _disjoint_blocks(*maps): + # Every block the maps hold, cut wherever two of them meet, so the parts are disjoint and each lists every + # location that holds it. Replicas within one map may cut the same region at different edges, so its own + # blocks are cut against each other too. Sorted, so the parts do not depend on the order the maps list them. holders = {} - for pieces in affine_map.pieces_by_rank.values(): - for piece in pieces: - if piece.numel: - block = _block_of(piece, affine_map.logical_shape) - holders[block] = holders.get(block, frozenset()) | piece.locations - return sorted(holders.items(), key=lambda item: (item[0].origin, item[0].extent)) + for affine_map in maps: + for pieces in affine_map.pieces_by_rank.values(): + for piece in pieces: + if piece.numel: + block = _block_of(piece, affine_map.logical_shape) + holders[block] = holders.get(block, frozenset()) | piece.locations + parts = [] + for block, block_holders in sorted(holders.items(), key=lambda item: (item[0].origin, item[0].extent)): + refined = [] + rest = [block] + for part, part_holders in parts: + overlap = part.intersection(block) + if overlap.is_empty: + refined.append((part, part_holders)) + continue + refined.append((overlap, part_holders | block_holders)) + refined.extend((box, part_holders) for box in subtract(part, block)) + rest = [box for remaining in rest for box in subtract(remaining, part)] + parts = refined + [(box, block_holders) for box in rest] + return parts def _block_of(piece, logical_shape): @@ -1000,6 +1015,9 @@ def _block_of(piece, logical_shape): size <= 1 or stride == expected for size, stride, expected in zip(piece.shape, piece.source_strides, strides)): origin = coordinate(piece.source_offset, strides, logical_shape) + # A row-major run longer than what is left of its row wraps into the next row, so it is not a block. + if origin is not None and any(low + size > bound for low, size, bound in zip(origin, piece.shape, logical_shape)): + origin = None if origin is None: raise NotImplementedError(f'Piece {piece} is not an axis-aligned block of a parameter of shape ' f'{logical_shape}, so it cannot be cut at another layout\'s block edges.') @@ -1007,19 +1025,15 @@ def _block_of(piece, logical_shape): def _cut(piece, logical_shape, blocks): - # ``piece`` cut at the edges of ``blocks``: each part another layout also holds lists those holders - # too, and the parts no other layout holds keep the piece's own. + # ``piece`` cut into the disjoint ``blocks`` that cover it, each part with that block's holders. if not piece.numel: return [piece] block = _block_of(piece, logical_shape) parts = [] - rest = [block] for other, holders in blocks: overlap = block.intersection(other) if not overlap.is_empty: - parts.append((overlap, piece.locations | holders)) - rest = [part for box in rest for part in subtract(box, other)] - parts.extend((box, piece.locations) for box in rest) + parts.append((overlap, holders)) return [_part_of(piece, block.origin, box, locations) for box, locations in parts] diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index 48202ce7a1d4..c043e9deffb1 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -745,8 +745,9 @@ states. as a trainer's ZeRO-3 partitions and a rollout replica's tensor-parallel shard that is still current. `union_affine_maps([storage, shard])` describes both as one source. The layouts use disjoint locations, one per buffer; the transfer's endpoints may bind several locations to one -process. Every piece is cut at the edges of the blocks the other layouts hold over it, and each -cut piece lists the holders from every layout, so P5 holds and the planner may read either copy. +process. Every piece is cut at the edges of every block held over it, in any layout (replicas +within one layout may cut a region at different edges), and each cut piece lists the holders from +every layout, so P5 holds and the planner may read either copy. A cut keeps a piece's strides and moves its offsets, so every location keeps its storage. A ZeRO-3 block of several rows cut at a column edge keeps its row-major strides and its partition's offset, so it is not dense in its 1-D shard (10.2): it is described, but not yet planned. diff --git a/tests/unit/checkpoint/test_affine_transfer_plan.py b/tests/unit/checkpoint/test_affine_transfer_plan.py index 53851f41149a..1a8e3ae5bd3f 100644 --- a/tests/unit/checkpoint/test_affine_transfer_plan.py +++ b/tests/unit/checkpoint/test_affine_transfer_plan.py @@ -1153,3 +1153,38 @@ def test_a_union_refuses_layouts_it_cannot_merge(): transposed = ParamAffineMap((4, 6), {20: (6, 4)}, {20: [AffinePiece((6, 4), 0, (1, 6), 0, (4, 1), {20})]}) with pytest.raises(NotImplementedError, match='axis-aligned block'): union_affine_maps([shard, transposed]) + # Row-major strides, but eight elements from the start of a six-wide row run into the next row. + wrapping = ParamAffineMap( + (4, 6), {30: (24, )}, + {30: [AffinePiece((1, 8), 0, (6, 1), 0, (8, 1), {30}), + AffinePiece((1, 16), 8, (6, 1), 8, (16, 1), {30})]}) + with pytest.raises(NotImplementedError, match='axis-aligned block'): + union_affine_maps([shard, wrapping]) + + +def test_a_union_cuts_replicas_that_split_a_block_differently(): + """Replicas within one layout may store a block whole or in parts, so its own edges are cut at too.""" + rows, cols = 6, 5 + whole_and_halves = ParamAffineMap( + (rows, cols), + { + 0: (rows, cols), + 1: (rows, cols) + }, + { + 0: [AffinePiece((rows, cols), 0, (cols, 1), 0, (cols, 1), {0, 1})], + # The same block in two halves, stored in the other order. + 1: [ + AffinePiece((3, cols), 0, (cols, 1), 3 * cols, (cols, 1), {0, 1}), + AffinePiece((3, cols), 3 * cols, (cols, 1), 0, (cols, 1), {0, 1}) + ], + }) + zero = _zero3_storage((rows, cols), 4, first_location=100) + source = union_affine_maps([whole_and_halves, zero]) + full = _full(rows, cols, seed=13) + _assert_union_holds_what_each_layout_holds(source, [whole_and_halves, zero], full) + target = contiguous_split_map((rows, cols), _split(cols, 2), 1) + produced = _apply_plan(plan_transfer(target, source), target, + _shards(source, lambda map_, rank: map_.extract(full, rank))) + for rank in target.shard_shapes: + assert torch.equal(produced[rank], target.extract(full, rank)), rank From e30068d097c61f03a42013ab0b035538937e44fe Mon Sep 17 00:00:00 2001 From: Achyuthan Sivasankar Date: Wed, 18 Nov 2026 23:34:54 -0500 Subject: [PATCH 3/5] Keep a union close to linear in its partitions, and raise the planner's errors A union compared every block with every part found so far, and cut every piece against every part, so its time grew with the square of the number of ZeRO-3 partitions: about 48 s at 1000 partitions of a 4096 x 4096 parameter. The blocks come in order of their first row, so a part that ends above a block is final, and each block now meets only the parts that reach into its rows. The parts refine every block, so a piece is cut against only the parts that start in its rows. The pieces are the same. Layouts that contradict each other now raise InvalidMapError, and a piece that is not a block UnsupportedLayoutError, so a caller that falls back on AffineTransferError also catches a union that cannot be formed. Signed-off-by: Achyuthan Sivasankar --- deepspeed/checkpoint/affine.py | 69 ++++++++++++++----- .../checkpoint/test_affine_transfer_plan.py | 9 +-- 2 files changed, 55 insertions(+), 23 deletions(-) diff --git a/deepspeed/checkpoint/affine.py b/deepspeed/checkpoint/affine.py index c05d1408a9d2..8da499e60017 100644 --- a/deepspeed/checkpoint/affine.py +++ b/deepspeed/checkpoint/affine.py @@ -18,6 +18,8 @@ See ``deepspeed/checkpoint/affine_ir_spec.md`` for the full specification. """ +from bisect import bisect_left + import torch from .affine_geometry import LogicalBox, address_range, boxes_disjoint, coordinate, overlaps_itself, subtract @@ -948,6 +950,9 @@ def union_affine_maps(maps): edges of every block held over it, in any layout, and each cut piece lists the holders from every layout. A cut keeps the piece's strides and moves its offsets, so every location still stores exactly what it did. Pieces must be axis-aligned blocks of the parameter. + + Layouts that contradict each other raise ``InvalidMapError``, and a piece that is not an axis-aligned + block raises ``UnsupportedLayoutError``, as the planner reports the same problems. """ if not maps: raise ValueError('A union needs at least one map.') @@ -958,25 +963,33 @@ def union_affine_maps(maps): def _union_of_two(first, second): + # affine_transfer imports this module, so its error types are imported where they are raised. + from .affine_transfer import InvalidMapError if first.logical_shape != second.logical_shape: - raise ValueError(f'The layouts describe parameters of shape {first.logical_shape} and ' - f'{second.logical_shape}, so they cannot describe the same parameter.') + raise InvalidMapError(f'The layouts describe parameters of shape {first.logical_shape} and ' + f'{second.logical_shape}, so they cannot describe the same parameter.') shared = sorted(set(first.shard_shapes) & set(second.shard_shapes)) if shared: - raise ValueError(f'Locations {shared} appear in both layouts; give each layout its own locations, one ' - 'per buffer.') + raise InvalidMapError(f'Locations {shared} appear in both layouts; give each layout its own locations, ' + 'one per buffer.') blocks = _disjoint_blocks(first, second) + first_rows = [_rows(box)[0] for box, _ in blocks] pieces_by_rank = {} for affine_map in (first, second): for rank, pieces in affine_map.pieces_by_rank.items(): - pieces_by_rank[rank] = [part for piece in pieces for part in _cut(piece, first.logical_shape, blocks)] + pieces_by_rank[rank] = [ + part for piece in pieces for part in _cut(piece, first.logical_shape, blocks, first_rows) + ] affine_map = ParamAffineMap(logical_shape=first.logical_shape, shard_shapes={ **first.shard_shapes, **second.shard_shapes }, pieces_by_rank=pieces_by_rank) - affine_map.validate() + try: + affine_map.validate() + except ValueError as error: + raise InvalidMapError(f'The layouts do not form one map: {error}') from error return affine_map @@ -991,20 +1004,34 @@ def _disjoint_blocks(*maps): if piece.numel: block = _block_of(piece, affine_map.logical_shape) holders[block] = holders.get(block, frozenset()) | piece.locations - parts = [] + # The blocks come in order of their first row, so a part that ends at or above a block's first row meets + # neither that block nor any later one, and is final. Comparing each block only with the parts still open, + # those reaching into its rows, keeps the work close to linear in the number of partitions. + final, open_parts = [], [] for block, block_holders in sorted(holders.items(), key=lambda item: (item[0].origin, item[0].extent)): - refined = [] + first_row = _rows(block)[0] + reached = [] + for part, part_holders in open_parts: + (final if _rows(part)[1] <= first_row else reached).append((part, part_holders)) + open_parts = [] rest = [block] - for part, part_holders in parts: + for part, part_holders in reached: overlap = part.intersection(block) if overlap.is_empty: - refined.append((part, part_holders)) + open_parts.append((part, part_holders)) continue - refined.append((overlap, part_holders | block_holders)) - refined.extend((box, part_holders) for box in subtract(part, block)) + open_parts.append((overlap, part_holders | block_holders)) + open_parts.extend((box, part_holders) for box in subtract(part, block)) rest = [box for remaining in rest for box in subtract(remaining, part)] - parts = refined + [(box, block_holders) for box in rest] - return parts + open_parts.extend((box, block_holders) for box in rest) + return sorted(final + open_parts, key=lambda item: (item[0].origin, item[0].extent)) + + +def _rows(box): + # The rows a block spans on the parameter's first axis; a scalar has one. + if not box.origin: + return 0, 1 + return box.origin[0], box.origin[0] + box.extent[0] def _block_of(piece, logical_shape): @@ -1019,18 +1046,22 @@ def _block_of(piece, logical_shape): if origin is not None and any(low + size > bound for low, size, bound in zip(origin, piece.shape, logical_shape)): origin = None if origin is None: - raise NotImplementedError(f'Piece {piece} is not an axis-aligned block of a parameter of shape ' - f'{logical_shape}, so it cannot be cut at another layout\'s block edges.') + from .affine_transfer import UnsupportedLayoutError # imported here, as in _union_of_two + raise UnsupportedLayoutError(f'Piece {piece} is not an axis-aligned block of a parameter of shape ' + f'{logical_shape}, so it cannot be cut at another layout\'s block edges.') return LogicalBox(origin, piece.shape) -def _cut(piece, logical_shape, blocks): - # ``piece`` cut into the disjoint ``blocks`` that cover it, each part with that block's holders. +def _cut(piece, logical_shape, blocks, first_rows): + # ``piece`` cut into the disjoint ``blocks`` that cover it, each part with that block's holders. The blocks + # refine every block a layout holds, so one that meets this piece lies inside it and starts in its rows: + # ``first_rows`` (the blocks' first rows, in their sorted order) finds those without comparing the rest. if not piece.numel: return [piece] block = _block_of(piece, logical_shape) + low, high = _rows(block) parts = [] - for other, holders in blocks: + for other, holders in blocks[bisect_left(first_rows, low):bisect_left(first_rows, high)]: overlap = block.intersection(other) if not overlap.is_empty: parts.append((overlap, holders)) diff --git a/tests/unit/checkpoint/test_affine_transfer_plan.py b/tests/unit/checkpoint/test_affine_transfer_plan.py index 1a8e3ae5bd3f..e7058cce9f89 100644 --- a/tests/unit/checkpoint/test_affine_transfer_plan.py +++ b/tests/unit/checkpoint/test_affine_transfer_plan.py @@ -1141,24 +1141,25 @@ def test_a_column_cut_keeps_every_zero3_element_where_it_is(): def test_a_union_refuses_layouts_it_cannot_merge(): + # The planner's error types, so a caller that falls back on an AffineTransferError catches these too. shard = contiguous_split_map((4, 6), [2, 2], 0) with pytest.raises(ValueError, match='at least one map'): union_affine_maps([]) # Both layouts name locations 0 and 1, so one location would stand for two buffers. - with pytest.raises(ValueError, match='appear in both layouts'): + with pytest.raises(InvalidMapError, match='appear in both layouts'): union_affine_maps([shard, contiguous_split_map((4, 6), [3, 3], 1)]) - with pytest.raises(ValueError, match='shape'): + with pytest.raises(InvalidMapError, match='shape'): union_affine_maps([shard, _surviving(contiguous_split_map((6, 4), [3, 3], 0), [0], first_location=10)]) # A transposed block has no corner and extent in the parameter's coordinates to cut at. transposed = ParamAffineMap((4, 6), {20: (6, 4)}, {20: [AffinePiece((6, 4), 0, (1, 6), 0, (4, 1), {20})]}) - with pytest.raises(NotImplementedError, match='axis-aligned block'): + with pytest.raises(UnsupportedLayoutError, match='axis-aligned block'): union_affine_maps([shard, transposed]) # Row-major strides, but eight elements from the start of a six-wide row run into the next row. wrapping = ParamAffineMap( (4, 6), {30: (24, )}, {30: [AffinePiece((1, 8), 0, (6, 1), 0, (8, 1), {30}), AffinePiece((1, 16), 8, (6, 1), 8, (16, 1), {30})]}) - with pytest.raises(NotImplementedError, match='axis-aligned block'): + with pytest.raises(UnsupportedLayoutError, match='axis-aligned block'): union_affine_maps([shard, wrapping]) From 57ff761e8e3973f5642e5fb46c0977dff2346d9e Mon Sep 17 00:00:00 2001 From: Achyuthan Sivasankar Date: Sun, 22 Nov 2026 00:52:01 -0500 Subject: [PATCH 4/5] Plan a column cut from the surviving column shard Now that the planner reads flat shards at the parameter's own strides (#9070), a union of ZeRO-3 partitions and a surviving column shard plans exactly. Check the plan, not only the map. Signed-off-by: Achyuthan Sivasankar --- .../checkpoint/test_affine_transfer_plan.py | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/tests/unit/checkpoint/test_affine_transfer_plan.py b/tests/unit/checkpoint/test_affine_transfer_plan.py index e7058cce9f89..ee98fdd6b913 100644 --- a/tests/unit/checkpoint/test_affine_transfer_plan.py +++ b/tests/unit/checkpoint/test_affine_transfer_plan.py @@ -1125,20 +1125,32 @@ def test_a_union_of_three_layouts_does_not_depend_on_their_order(): assert torch.equal(produced[rank], target.extract(full, rank)), rank -def test_a_column_cut_keeps_every_zero3_element_where_it_is(): +@pytest.mark.parametrize('rows,cols,sizes,survivors,partitions', [ + (6, 5, [3, 2], [0], 2), + (7, 4, [2, 1, 1], [0, 2], 3), + (9, 4, [2, 2], [1], 7), +]) +def test_a_column_cut_plans_from_the_surviving_column_shard(rows, cols, sizes, survivors, partitions): """Cut at a column edge, a ZeRO-3 block of several rows keeps its strides and its partition's offset. - The union stays exact either way; whether a plan may read such a block is the planner's question. + Such a block is not dense in its flat shard, so this also needs the planner to read strided flat shards. """ - rows, cols = 6, 5 - zero = _zero3_storage((rows, cols), 2, first_location=100) - shard = _surviving(contiguous_split_map((rows, cols), [3, 2], 1), [0], first_location=0) + zero = _zero3_storage((rows, cols), partitions, first_location=100) + shard = _surviving(contiguous_split_map((rows, cols), sizes, 1), survivors, first_location=0) source = union_affine_maps([zero, shard]) - full = _full(rows, cols, seed=11) + full = _full(rows, cols, seed=rows * cols) _assert_union_holds_what_each_layout_holds(source, [zero, shard], full) - shards = {location: source.extract(full, location) for location in source.shard_shapes} + shards = _shards(source, lambda map_, rank: map_.extract(full, rank)) assert torch.equal(source.rebuild(shards).view(rows, cols), full) + for target in (contiguous_split_map((rows, cols), _split(rows, 2), + 0), contiguous_split_map((rows, cols), _split(cols, 3), 1)): + plan = plan_transfer(target, source) + produced = _apply_plan(plan, target, shards) + for rank in target.shard_shapes: + assert torch.equal(produced[rank], target.extract(full, rank)), rank + assert {segment.source_rank for segment in plan.segments} & set(survivors) + def test_a_union_refuses_layouts_it_cannot_merge(): # The planner's error types, so a caller that falls back on an AffineTransferError catches these too. From a9e3a45ce7f75d4f7d961819f855356e6a2f4e28 Mon Sep 17 00:00:00 2001 From: Achyuthan Sivasankar Date: Sun, 22 Nov 2026 11:53:36 -0500 Subject: [PATCH 5/5] Say that a column cut is planned, and size the budget for a union The spec and affine-transfer.rst still said the planner refuses a ZeRO-3 block that a column edge cuts across rows, which #9070 changed. The rst example also called plan_transfer with the default PlanBudget, which refuses most unions at the sizes the PR measures; it now passes a larger max_pieces_per_map and gives the piece counts. Signed-off-by: Achyuthan Sivasankar --- deepspeed/checkpoint/affine_ir_spec.md | 3 ++- docs/code-docs/source/affine-transfer.rst | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/deepspeed/checkpoint/affine_ir_spec.md b/deepspeed/checkpoint/affine_ir_spec.md index c043e9deffb1..27656f007eb4 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -750,4 +750,5 @@ within one layout may cut a region at different edges), and each cut piece lists every layout, so P5 holds and the planner may read either copy. A cut keeps a piece's strides and moves its offsets, so every location keeps its storage. A ZeRO-3 block of several rows cut at a column edge keeps its row-major strides and its partition's -offset, so it is not dense in its 1-D shard (10.2): it is described, but not yet planned. +offset, so it is not dense in its 1-D shard: it is stored in parameter order (10.2), which the +planner reads, so a column cut is planned as well as described. diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index d3668b38d462..7138bb6bc993 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -86,14 +86,23 @@ it. Each layout uses its own locations, one per buffer, and ``TransferEndpoints`` may bind several locations to one process:: from deepspeed.checkpoint.affine import union_affine_maps + from deepspeed.checkpoint.affine_transfer import PlanBudget, plan_transfer source_map = union_affine_maps([zero3_storage_map, surviving_shard_map]) - plan = plan_transfer(target_map, source_map) + # A union is cut at every layout's edges, so it has more pieces than either layout. + plan = plan_transfer(target_map, source_map, PlanBudget(max_pieces_per_map=1 << 16)) Pieces are cut where the layouts' blocks meet and keep their strides, so each -buffer is read as it is stored. The planner does not yet accept a ZeRO-3 block -that a column edge cuts across several rows. Maintenance contact: -``@Achyuthan-S``. +buffer is read as it is stored. A ZeRO-3 block that a column edge cuts across +several rows keeps its row-major strides and is read as a strided flat shard. + +The union's piece count grows with the number of partitions times the edges +each one crosses, so it can exceed the default ``PlanBudget``, which allows +4,096 pieces per map. For a (4096, 4096) parameter, ZeRO-3 partitions plus an +8-way row split give 1,196 pieces at 200 partitions and 5,996 at 1,000; with +an 8-way column split, 6,782 and 33,976. Raise ``max_pieces_per_map`` to fit. +At 1,000 partitions with a column split, a plan into a column-split target also +needs a larger ``max_merge_checks``. Maintenance contact: ``@Achyuthan-S``. Transport and staging ---------------------