diff --git a/deepspeed/checkpoint/affine.py b/deepspeed/checkpoint/affine.py index 0d424de577c1..8da499e60017 100644 --- a/deepspeed/checkpoint/affine.py +++ b/deepspeed/checkpoint/affine.py @@ -18,15 +18,18 @@ 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 +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 +935,141 @@ 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 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.') + union = maps[0] + for other in maps[1:]: + union = _union_of_two(union, other) + return union + + +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 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 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, first_rows) + ] + affine_map = ParamAffineMap(logical_shape=first.logical_shape, + shard_shapes={ + **first.shard_shapes, + **second.shard_shapes + }, + pieces_by_rank=pieces_by_rank) + try: + affine_map.validate() + except ValueError as error: + raise InvalidMapError(f'The layouts do not form one map: {error}') from error + return affine_map + + +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 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 + # 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)): + 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 reached: + overlap = part.intersection(block) + if overlap.is_empty: + open_parts.append((part, part_holders)) + continue + 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)] + 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): + # 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) + # 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: + 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, 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[bisect_left(first_rows, low):bisect_left(first_rows, high)]: + overlap = block.intersection(other) + if not overlap.is_empty: + parts.append((overlap, holders)) + 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..27656f007eb4 100644 --- a/deepspeed/checkpoint/affine_ir_spec.md +++ b/deepspeed/checkpoint/affine_ir_spec.md @@ -740,3 +740,15 @@ 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 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: 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/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..7138bb6bc993 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -75,6 +75,35 @@ 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 + from deepspeed.checkpoint.affine_transfer import PlanBudget, plan_transfer + + source_map = union_affine_maps([zero3_storage_map, surviving_shard_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. 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 --------------------- 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..ee98fdd6b913 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,165 @@ 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 + + +@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. + + Such a block is not dense in its flat shard, so this also needs the planner to read strided flat shards. + """ + 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=rows * cols) + _assert_union_holds_what_each_layout_holds(source, [zero, shard], full) + 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. + 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(InvalidMapError, match='appear in both layouts'): + union_affine_maps([shard, contiguous_split_map((4, 6), [3, 3], 1)]) + 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(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(UnsupportedLayoutError, 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