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
67 changes: 3 additions & 64 deletions deepspeed/checkpoint/affine.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

import torch

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'
Expand Down Expand Up @@ -562,21 +565,6 @@ def _flat_buffer(tensor):
return flat


def _product(shape):
count = 1
for dim in shape:
count *= dim
return count


def _row_major_strides(shape):
"""Element stride per axis for a densely packed tensor of this shape."""
strides = [1] * len(shape)
for axis in range(len(shape) - 2, -1, -1):
strides[axis] = strides[axis + 1] * shape[axis + 1]
return tuple(strides)


def replicated_map(shape, tp_degree, scale=1.0):
"""Every rank holds the whole parameter.

Expand Down Expand Up @@ -932,10 +920,6 @@ def _nest_replicated_block(copies, intervals_by_outer_rank, pieces_by_rank):
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.
Expand All @@ -948,43 +932,6 @@ def _dense_rows(piece):
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
Expand All @@ -998,14 +945,6 @@ def _check_monotone_dest(piece):
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
Expand Down
121 changes: 121 additions & 0 deletions deepspeed/checkpoint/affine_geometry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
"""Index and box arithmetic shared by affine maps, transfer planning and storage maps.

Pure functions on shapes, strides, offsets and axis-aligned boxes. They know nothing about pieces,
ranks or tensors, so one implementation can serve every module that describes or plans shards.
"""

from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple

__all__ = [
'LogicalBox', 'coordinate', 'dot', 'product', 'row_major_range_boxes', 'row_major_strides', 'strided_address'
]


def product(shape: Sequence[int]) -> int:
count = 1
for size in shape:
count *= size
return count


def row_major_strides(shape: Sequence[int]) -> Tuple[int, ...]:
"""Element stride per axis for a densely packed tensor of this shape."""
strides = [1] * len(shape)
for axis in range(len(shape) - 2, -1, -1):
strides[axis] = strides[axis + 1] * shape[axis + 1]
return tuple(strides)


def coordinate(offset: int, strides: Tuple[int, ...], shape: Tuple[int, ...]) -> Optional[Tuple[int, ...]]:
"""The grid coordinate a storage offset names, or None when it names nothing."""
coordinates = []
rest = offset
for stride, size in zip(strides, shape):
position, remainder = divmod(rest, stride)
if position >= size:
return None
coordinates.append(position)
rest = remainder
return tuple(coordinates) if rest == 0 else None


def dot(index, strides):
return sum(position * stride for position, stride in zip(index, strides))


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 row_major_range_boxes(shape, low, high, dense_rows=0) -> List[Tuple[Tuple[int, ...], Tuple[int, ...]]]:
"""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


@dataclass(frozen=True)
class LogicalBox:
"""An axis-aligned block of the logical parameter: its first coordinate and its extents."""
origin: Tuple[int, ...]
extent: Tuple[int, ...]

@property
def volume(self) -> int:
return product(self.extent)

@property
def is_empty(self) -> bool:
return any(size == 0 for size in self.extent)

def upper(self) -> Tuple[int, ...]:
return tuple(low + size for low, size in zip(self.origin, self.extent))

def intersection(self, other: 'LogicalBox') -> 'LogicalBox':
low = tuple(max(a, b) for a, b in zip(self.origin, other.origin))
high = tuple(min(a, b) for a, b in zip(self.upper(), other.upper()))
return LogicalBox(low, tuple(max(0, h - l) for h, l in zip(high, low)))

def contains(self, other: 'LogicalBox') -> bool:
return all(other_low >= low and other_high <= high
for low, high, other_low, other_high in zip(self.origin, self.upper(), other.origin, other.upper()))

def __repr__(self) -> str:
return f'Box({self.origin}+{self.extent})'
59 changes: 2 additions & 57 deletions deepspeed/checkpoint/affine_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
from typing import Callable, Dict, FrozenSet, List, Optional, Sequence, Tuple

from .affine import AffinePiece, ParamAffineMap
from .affine_geometry import (LogicalBox, coordinate as _coordinate, product as _product, row_major_strides as
_row_major_strides)

__all__ = [
'AffineTransferError', 'InvalidMapError', 'InvalidReplicaPolicyError', 'UnsupportedLayoutError', 'PlanBudget',
Expand Down Expand Up @@ -90,36 +92,6 @@ class PlanStatistics:
plan_bytes: int


@dataclass(frozen=True)
class LogicalBox:
"""An axis-aligned block of the logical parameter: its first coordinate and its extents."""
origin: Tuple[int, ...]
extent: Tuple[int, ...]

@property
def volume(self) -> int:
return _product(self.extent)

@property
def is_empty(self) -> bool:
return any(size == 0 for size in self.extent)

def upper(self) -> Tuple[int, ...]:
return tuple(low + size for low, size in zip(self.origin, self.extent))

def intersection(self, other: 'LogicalBox') -> 'LogicalBox':
low = tuple(max(a, b) for a, b in zip(self.origin, other.origin))
high = tuple(min(a, b) for a, b in zip(self.upper(), other.upper()))
return LogicalBox(low, tuple(max(0, h - l) for h, l in zip(high, low)))

def contains(self, other: 'LogicalBox') -> bool:
return all(other_low >= low and other_high <= high
for low, high, other_low, other_high in zip(self.origin, self.upper(), other.origin, other.upper()))

def __repr__(self) -> str:
return f'Box({self.origin}+{self.extent})'


@dataclass(frozen=True)
class _Frame:
"""One piece: where it sits in the logical parameter and where it sits in one rank's shard."""
Expand Down Expand Up @@ -212,33 +184,6 @@ def to_dict(self) -> Dict[str, List[object]]:
}


def _product(shape: Sequence[int]) -> int:
count = 1
for size in shape:
count *= size
return count


def _row_major_strides(shape: Sequence[int]) -> Tuple[int, ...]:
strides = [1] * len(shape)
for axis in range(len(shape) - 2, -1, -1):
strides[axis] = strides[axis + 1] * shape[axis + 1]
return tuple(strides)


def _coordinate(offset: int, strides: Tuple[int, ...], shape: Tuple[int, ...]) -> Optional[Tuple[int, ...]]:
"""The grid coordinate a storage offset names, or None when it names nothing."""
coordinates = []
rest = offset
for stride, size in zip(strides, shape):
coordinate, remainder = divmod(rest, stride)
if coordinate >= size:
return None
coordinates.append(coordinate)
rest = remainder
return tuple(coordinates) if rest == 0 else None


def _frame_of(piece: AffinePiece, rank: int, side: str, logical_shape: Tuple[int, ...],
shard_shape: Tuple[int, ...]) -> Optional[_Frame]:
"""Accept a piece only as an axis-aligned box, and refuse whatever else it might be.
Expand Down
15 changes: 1 addition & 14 deletions deepspeed/checkpoint/autoep_affine.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

from deepspeed.checkpoint.affine import AFFINE_MAP_FORMAT_VERSION, AffinePiece, ParamAffineMap, nest_affine_maps
from deepspeed.checkpoint.affine_geometry import product as _product, row_major_strides as _row_major_strides
from deepspeed.checkpoint.affine_transfer import plan_transfer
from deepspeed.checkpoint.zero_affine import zero_storage_affine_map
from deepspeed.checkpoint.constants import (AFFINE_MAP, AFFINE_MAP_PARAMS, AFFINE_MAP_VERSION, AUTOEP_AFFINE_MAPS,
Expand Down Expand Up @@ -334,17 +335,3 @@ def _positive_int(value, name):
if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
raise ValueError(f'{name} must be a positive integer; got {value!r}.')
return value


def _product(shape):
count = 1
for dim in shape:
count *= dim
return count


def _row_major_strides(shape):
strides = [1] * len(shape)
for axis in range(len(shape) - 2, -1, -1):
strides[axis] = strides[axis + 1] * shape[axis + 1]
return tuple(strides)
Loading