Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 96 additions & 16 deletions deepspeed/checkpoint/affine.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,13 +246,22 @@ def holders(self):

def validate(self):
"""Check shard element counts, and destination bounds and overlap from piece metadata."""
for rank, pieces in self.pieces_by_rank.items():
held = sum(piece.numel for piece in pieces)
expected = _product(self.shard_shapes[rank])
if held != expected:
raise ValueError(f'Rank {rank} holds a shard of {expected} elements but its pieces '
f'account for {held}.')
self._validate_destinations(rank, pieces, self.shard_shapes[rank])
for rank in self.pieces_by_rank:
self._validate_rank(rank)

def _validate_rank(self, rank):
pieces = self.pieces_by_rank[rank]
held = sum(piece.numel for piece in pieces)
expected = _product(self.shard_shapes[rank])
if held != expected:
raise ValueError(f'Rank {rank} holds a shard of {expected} elements but its pieces '
f'account for {held}.')
for piece in pieces:
for side, strides in (('source', piece.source_strides), ('destination', piece.dest_strides)):
if _overlaps_itself(piece.shape, strides):
raise ValueError(f'Rank {rank} piece {piece} reaches one {side} address twice within itself, '
'so one of its elements would silently overwrite another.')
self._validate_destinations(rank, pieces, self.shard_shapes[rank])

def _validate_destinations(self, rank, pieces, shard_shape):
"""Check that dense intervals and strided boxes stay within the shard and do not overlap."""
Expand Down Expand Up @@ -371,26 +380,49 @@ def rebuild(self, shards, scale_power=1):
any_shard = next(iter(shards.values()))
full_param = torch.empty(self.numel, dtype=any_shard.dtype, device=any_shard.device)

written = {}
# validate() reads destinations from metadata and never looks at sources, so a map can
# pass it while two ranks claim one block and nothing holds another. Recording who wrote
# each element, one byte each, catches both for any strides; otherwise the result would
# keep whatever torch.empty left behind.
written = torch.zeros(self.numel, dtype=torch.uint8, device=full_param.device)
for rank, pieces in self.pieces_by_rank.items():
if not pieces:
continue
flat_shard = _flat_buffer(shards[rank])
placed = torch.zeros(flat_shard.numel(), dtype=torch.bool, device=flat_shard.device)
for piece in pieces:
_place(placed, piece, rank)
target = piece.source_view(full_param)
source = piece.dest_view(flat_shard)
if len(piece.locations) > 1 and piece.source_offset in written:
source = _scaled(piece.dest_view(flat_shard), piece.scale, scale_power)
writer = _REPLICA if len(piece.locations) > 1 else _SINGLE_HOLDER
previous = piece.source_view(written)
seen = previous != _UNWRITTEN
if seen.any():
# Only replicas may share an element. Checking the earlier writer as well as this
# piece keeps the answer the same whichever rank is visited first.
if writer != _REPLICA or not (previous[seen] == _REPLICA).all():
raise ValueError(f'Rank {rank} piece {piece} writes part of a block another piece already '
'wrote, and one of the two names a single holder, so one would silently '
'overwrite the other.')
# Every rank holding a replicated piece must agree. Letting the last
# writer win would hide rank drift or a corrupt shard, which the
# category-based converter guards against explicitly.
if not torch.equal(target, _scaled(source, piece.scale, scale_power)):
# category-based converter guards against explicitly. Comparing element by
# element also covers replicas that two ranks cut at different boundaries.
if not torch.equal(target[seen], source[seen]):
raise ValueError(f'Ranks {sorted(piece.locations)} hold different data for the same '
f'block of a replicated parameter, starting at offset '
f'{piece.source_offset}.')
continue
target.copy_(_scaled(source, piece.scale, scale_power))
written[piece.source_offset] = True

if seen.all():
continue
target.copy_(source)
previous.fill_(writer)
_require_placed(placed, rank)

missing = (written == _UNWRITTEN).nonzero()
if missing.numel():
raise ValueError(f'Affine map for a parameter of shape {self.logical_shape} leaves '
f'{missing.numel()} element(s) uncovered, starting at offset {int(missing[0])}, '
'so the parameter cannot be rebuilt from its shards.')
return full_param.view(self.logical_shape)

def _reject_scaled_optimizer_state(self, scale_power):
Expand All @@ -415,17 +447,21 @@ def _reject_scaled_optimizer_state(self, scale_power):

def extract(self, full_param, rank, scale_power=1):
"""Produce one rank's shard from the full parameter. The inverse of ``rebuild``."""
self._validate_rank(rank)
self._reject_scaled_optimizer_state(scale_power)
flat_param = _flat_buffer(full_param)
shard_shape = self.shard_shapes[rank]
shard = torch.empty(_product(shard_shape), dtype=full_param.dtype, device=full_param.device)

placed = torch.zeros(shard.numel(), dtype=torch.bool, device=shard.device)
for piece in self.pieces_by_rank[rank]:
_place(placed, piece, rank)
target = piece.dest_view(shard)
target.copy_(piece.source_view(flat_param))
factor = piece.scale**scale_power
if factor != 1.0:
target.mul_(factor)
_require_placed(placed, rank)

return shard.view(shard_shape)

Expand Down Expand Up @@ -468,6 +504,50 @@ def _scaled(tensor, scale, scale_power):
return tensor / factor


# What rebuild records for each element of the full tensor: nobody has written it yet, a piece
# naming a single holder did, or a replica did.
_UNWRITTEN, _SINGLE_HOLDER, _REPLICA = 0, 1, 2


def _overlaps_itself(shape, strides):
"""Whether two positions of a view with this shape and these strides share an address.

Taking the axes that move in order of stride, the view is free of overlap when each stride
clears every address the axes before it reach. That holds for every layout the builders here
produce. A view that interleaves its axes some other way is refused even where it would not
collide, which keeps this to a few comparisons per piece instead of a walk over its elements.
"""
reach = 0
for stride, size in sorted((stride, size) for size, stride in zip(shape, strides) if size > 1):
if stride <= reach:
return True
reach += stride * (size - 1)
return False


def _place(placed, piece, rank):
"""Mark the shard addresses ``piece`` occupies in ``placed``, refusing one already taken.

``validate()`` checks destinations from metadata, which cannot place a view that wraps past
the end of a shard row. A mask of the shard places every stride exactly.
"""
view = piece.dest_view(placed)
if view.any():
index = view.nonzero()[0].tolist()
address = piece.dest_offset + sum(position * stride for position, stride in zip(index, piece.dest_strides))
raise ValueError(f'Rank {rank} writes shard address {address} twice, so one piece would '
'silently overwrite another.')
view.fill_(True)


def _require_placed(placed, rank):
"""Refuse a shard that its pieces leave partly unplaced, which a self-overlapping piece can do."""
if not placed.all():
missing = (~placed).nonzero()
raise ValueError(f'Rank {rank} pieces leave {missing.numel()} of its {placed.numel()} shard addresses '
f'unwritten, starting at {int(missing[0])}.')


def _flat_buffer(tensor):
"""Flatten ``tensor`` into a buffer whose storage starts at its first element.

Expand Down
175 changes: 172 additions & 3 deletions tests/unit/checkpoint/test_affine_shard_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,14 +553,28 @@ def test_strided_destination_that_wraps_a_shard_row_round_trips():
torch.testing.assert_close(affine_map.rebuild({0: affine_map.extract(full, 0)}), full)


def test_full_check_refuses_a_destination_collision_of_any_stride():
def _colliding_strided_map():
# The first piece writes shard addresses 0 and 2, the second writes 1 and 2, and address 3
# is never written. Neither piece is a box of the shard's grid, so only walking the
# addresses can see it.
pieces = [AffinePiece((2, ), 0, (1, ), 0, (2, ), [0]), AffinePiece((2, ), 2, (1, ), 1, (1, ), [0])]
affine_map = ParamAffineMap((4, ), {0: (4, )}, {0: pieces})
return ParamAffineMap((4, ), {0: (4, )}, {0: pieces})


def test_full_check_refuses_a_destination_collision_of_any_stride():
with pytest.raises(ValueError, match='twice'):
affine_map.validate_coverage()
_colliding_strided_map().validate_coverage()


def test_conversion_refuses_a_destination_collision_of_any_stride():
# validate() accepts this map, so converting through it would read shard address 2 for two
# elements and never read address 3, and restoring would leave address 3 uninitialised.
affine_map = _colliding_strided_map()
affine_map.validate()
with pytest.raises(ValueError, match='twice'):
affine_map.extract(torch.arange(4.), 0)
with pytest.raises(ValueError, match='twice'):
affine_map.rebuild({0: torch.arange(4.)})


def test_strided_destination_validation_does_not_enumerate_elements(monkeypatch):
Expand Down Expand Up @@ -599,6 +613,161 @@ def test_disagreeing_replicas_are_refused():
affine_map.rebuild(shards)


def test_replicas_cut_at_different_boundaries_are_compared_in_full():
# Rank 0 holds the replicated block as one piece and rank 1 as two halves. Comparing only a
# piece that starts where an earlier one did would check rank 1's first half and let its
# second half overwrite rank 0's unchecked.
pieces_by_rank = {
0: [AffinePiece((8, ), 0, (1, ), 0, (1, ), [0, 1])],
1: [AffinePiece((4, ), 0, (1, ), 0, (1, ), [0, 1]),
AffinePiece((4, ), 4, (1, ), 4, (1, ), [0, 1])],
}
affine_map = ParamAffineMap((8, ), {0: (8, ), 1: (8, )}, pieces_by_rank)
affine_map.validate_coverage()
full = torch.arange(8.)
torch.testing.assert_close(affine_map.rebuild({0: full, 1: full.clone()}), full)
drifted = full.clone()
drifted[6] += 1
with pytest.raises(ValueError, match='different data'):
affine_map.rebuild({0: full, 1: drifted})


@pytest.mark.parametrize('logical_shape, source_offsets, match', [((9, ), (0, 4), 'uncovered'),
((8, ), (0, 0), 'single holder')],
ids=['nothing-holds-the-last-element', 'two-ranks-own-one-block'])
def test_conversion_refuses_a_map_that_does_not_cover_the_parameter(logical_shape, source_offsets, match):
# Each rank fully writes its shard of four, so validate() accepts both maps. Without a check
# on the source side, rebuild would keep whatever torch.empty left where no rank writes.
pieces_by_rank = {
rank: [AffinePiece((4, ), offset, (1, ), 0, (1, ), [rank])]
for rank, offset in enumerate(source_offsets)
}
affine_map = ParamAffineMap(logical_shape, {0: (4, ), 1: (4, )}, pieces_by_rank)
affine_map.validate()
with pytest.raises(ValueError, match=match):
affine_map.rebuild({rank: torch.full((4, ), float(rank + 1)) for rank in (0, 1)})


@pytest.mark.parametrize('first', [0, 1])
def test_a_replica_overlapping_a_single_holder_is_refused_in_either_order(first):
# Rank 0 declares the block a replica held by ranks 0 and 1, while rank 1 declares itself its
# only holder. Which rank rebuild visits first must not decide whether that is caught.
pieces = {
0: [AffinePiece((4, ), 0, (1, ), 0, (1, ), [0, 1])],
1: [AffinePiece((4, ), 0, (1, ), 0, (1, ), [1])],
}
affine_map = ParamAffineMap((4, ), {0: (4, ), 1: (4, )}, {rank: pieces[rank] for rank in (first, 1 - first)})
with pytest.raises(ValueError, match='single holder'):
affine_map.rebuild({0: torch.arange(4.), 1: torch.arange(4.)})


_SELF_OVERLAPPING_VIEWS = {
# Rank 0's source view reads addresses 0, 1, 1 and 2, so one shard value is lost, and which one
# survives depends on the device.
'source': ((6, ), {
0: (4, ),
1: (3, )
}, {
0: [AffinePiece((2, 2), 0, (1, 1), 0, (2, 1), [0])],
1: [AffinePiece((3, ), 3, (1, ), 0, (1, ), [1])]
}),
# A zero stride repeats one element. extract would copy it twice without complaint.
'zero-stride': ((4, ), {
0: (2, ),
1: (2, )
}, {
0: [AffinePiece((2, ), 0, (0, ), 0, (1, ), [0])],
1: [AffinePiece((2, ), 2, (1, ), 0, (1, ), [1])]
}),
# The destination view writes shard addresses 0, 1, 1 and 2, and never 3.
'destination': ((4, ), {
0: (4, )
}, {
0: [AffinePiece((2, 2), 0, (2, 1), 0, (1, 1), [0])]
}),
}


@pytest.mark.parametrize('case', sorted(_SELF_OVERLAPPING_VIEWS))
def test_a_view_that_overlaps_itself_is_refused(case):
logical_shape, shard_shapes, pieces_by_rank = _SELF_OVERLAPPING_VIEWS[case]
affine_map = ParamAffineMap(logical_shape, shard_shapes, pieces_by_rank)
with pytest.raises(ValueError, match='itself'):
affine_map.extract(torch.arange(float(affine_map.numel)), 0)
with pytest.raises(ValueError, match='itself'):
affine_map.rebuild({rank: torch.zeros(shape) for rank, shape in shard_shapes.items()})


def _random_widths(rng, total, tp_degree):
cuts = sorted(rng.sample(range(1, total), tp_degree - 1))
return [stop - start for start, stop in zip([0] + cuts, cuts + [total])]


def _random_layout(rng):
from deepspeed.checkpoint.affine import block_gather_map, segmented_map
tp_degree = rng.choice([2, 3, 4])
shape = (rng.randint(5, 12), rng.randint(5, 12))
axis = rng.choice([0, 1])
total = shape[axis]
kind = rng.choice(['split', 'replicated', 'segmented', 'blocks'])
if kind == 'split':
return contiguous_split_map(shape, _random_widths(rng, total, tp_degree), axis)
if kind == 'replicated':
return replicated_map(shape, tp_degree)
if kind == 'segmented':
replicated_rows = rng.randint(1, total - tp_degree)
split = total - replicated_rows
return segmented_map(shape, [(split, False), (replicated_rows, True)], axis, tp_degree,
[_random_widths(rng, split, tp_degree)])
blocks = list(range(total))
rng.shuffle(blocks)
block_ids_by_rank, start = {}, 0
for rank, width in enumerate(_random_widths(rng, total, tp_degree)):
block_ids_by_rank[rank] = sorted(blocks[start:start + width])
start += width
return block_gather_map(shape, block_ids_by_rank, 1, axis)


def _corrupt_one_piece(affine_map, rng):
rank = rng.choice(sorted(affine_map.pieces_by_rank))
pieces = affine_map.pieces_by_rank[rank]
index = rng.randrange(len(pieces))
piece = pieces[index]
fields = [piece.source_offset, list(piece.source_strides), piece.dest_offset, list(piece.dest_strides)]
which = rng.randrange(4)
if which in (0, 2):
fields[which] = max(0, fields[which] + rng.choice([-2, -1, 1, 2]))
else:
axis = rng.randrange(len(piece.shape))
fields[which][axis] = max(1, fields[which][axis] + rng.choice([-1, 1]))
pieces[index] = AffinePiece(piece.shape, fields[0], fields[1], fields[2], fields[3], piece.locations)


def test_a_corrupted_map_is_refused_or_still_exact():
"""Fixed seed: converting through a map with one corrupted offset or stride fails or is exact.

The shards come from the map before it is corrupted, as a checkpoint's shards were written by
the real layout. Extracting and rebuilding through the same wrong map could let an error cancel.
"""
import random
rng = random.Random(20261031)
refused = 0
for _ in range(300):
affine_map = _random_layout(rng)
full = torch.arange(1, affine_map.numel + 1, dtype=torch.float32).view(affine_map.logical_shape)
shards = {rank: affine_map.extract(full, rank) for rank in affine_map.pieces_by_rank}
_corrupt_one_piece(affine_map, rng)
try:
rebuilt = affine_map.rebuild(shards)
except (ValueError, RuntimeError):
refused += 1
continue
assert torch.equal(rebuilt, full), affine_map.to_dict()
# Most corruptions break the map; the rest still describe a valid layout. Either way the run
# must have exercised refusals, or it shows nothing.
assert refused > 100


def test_shard_that_disagrees_with_the_map_is_refused():
"""A shard longer than the map describes would be silently truncated to its prefix."""
affine_map = contiguous_split_map((10, 8), [3, 3, 2, 2], 0)
Expand Down
Loading