diff --git a/deepspeed/checkpoint/affine_transfer_cost.py b/deepspeed/checkpoint/affine_transfer_cost.py new file mode 100644 index 000000000000..aed54dd6704c --- /dev/null +++ b/deepspeed/checkpoint/affine_transfer_cost.py @@ -0,0 +1,186 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +"""Estimate how long a set of affine transfers takes, and keep the cheapest way to run it. + +Plans that move the same data can differ in time by more than 5x: which holder each target reads, +whether a node's copy crosses the network once and then spreads inside the node, how many rounds +the staging budget cuts each message into. A plan says what moves, and by the planner's guarantee +it is exact whichever holder it reads (``affine_transfer``). This module only prices plans, so +choosing between them never changes what arrives. + +The model is the one of RFC #9026. ``execute_transfers`` runs a batch as rounds: in round ``k``, +each process posts its ``k``-th message to or from every peer in one ``batch_isend_irecv``, which +``schedule_transfers`` lists without running anything. Every byte of a message occupies resources +on its way, such as the sender's network send, the receiver's network receive, or the link between +two GPUs of a node. Each resource binds on its own, so a round takes its most loaded resource's +bytes over that resource's capacity, plus a fixed cost per round:: + + rounds = sum over rounds k of (seconds_per_round + max over resources r of B[r, k] / C[r]) + +The host also launches one copy per staged or local region. Those launches overlap the bytes +rather than adding to them, so a call takes ``seconds_per_call + max(rounds, launches)``, where +``launches`` is the region count of the process with the most regions times ``seconds_per_region``. + +The capacities and costs depend on the machine, the transport configuration and the executor, so +they are calibrated for each. Every rank must reach the same choice, because each rank runs its own +half of the chosen plan, so the model must be built from data every rank shares, never from a +rank-local measurement. A plan's one-time preparation is not priced here. +""" + +import math +from dataclasses import dataclass +from typing import Callable, Dict, Hashable, Mapping, Sequence, Tuple + +from .affine_transfer import AffineTransferError, TransferPlan +from .affine_transfer_executor import StagingBudget, TransferEndpoints, schedule_transfers + +__all__ = ['TransferCostModel', 'TransferStage', 'PlanChoice', 'node_route', 'estimate_seconds', 'cheapest'] + +# A resource is a tuple whose first entry names its kind, such as ('network_send', 3). +Resource = Tuple[Hashable, ...] +Route = Callable[[int, int], Sequence[Resource]] + +_INTRA_NODE_KINDS = ('device_send', 'device_receive', 'device_pair') + + +@dataclass(frozen=True) +class TransferCostModel: + """The calibrated costs of one machine, transport configuration and executor. + + ``route(sender, receiver)`` names the resources that a message between two processes occupies. + ``capacity`` gives bytes per second for every kind of resource a route names; a resource that no + route names does not limit anything. The other fields are in seconds. + """ + route: Route + capacity: Mapping[Hashable, float] + seconds_per_call: float = 0.0 + seconds_per_round: float = 0.0 + seconds_per_region: float = 0.0 + + def __post_init__(self): + for kind, value in self.capacity.items(): + if not _is_number(value) or not value > 0 or math.isinf(value): + raise AffineTransferError(f'capacity of {kind!r} is {value!r}, not a positive finite number') + for name in ('seconds_per_call', 'seconds_per_round', 'seconds_per_region'): + value = getattr(self, name) + if not _is_number(value) or not value >= 0 or math.isinf(value): + raise AffineTransferError(f'{name} is {value!r}, not a non-negative finite number') + + +@dataclass(frozen=True) +class TransferStage: + """What one ``execute_transfers`` call is given, apart from the buffers. + + ``plans`` are in request order, since that order fixes how chunks are packed into rounds. + """ + plans: Sequence[TransferPlan] + endpoints: TransferEndpoints + element_size: int + budget: StagingBudget = StagingBudget() + + +@dataclass(frozen=True) +class PlanChoice: + """The name of the cheapest candidate, and the estimate in seconds of every candidate.""" + name: str + seconds: Mapping[str, float] + + +def node_route(nodes: Mapping[int, int], intra_node: Sequence[str] = ('device_send', 'device_receive')) -> Route: + """Route each message by the nodes of its two processes. + + Across nodes, a message occupies the sender's ``network_send`` and the receiver's + ``network_receive``. Within a node, it occupies the kinds named in ``intra_node``: + ``device_send`` and ``device_receive`` are each process's own link, as on NVSwitch, and + ``device_pair`` is the link from the sender to the receiver, as with NVLink between two GPUs. + """ + nodes = dict(nodes) + intra_node = tuple(intra_node) + for kind in intra_node: + if kind not in _INTRA_NODE_KINDS: + raise AffineTransferError(f'unknown intra-node resource {kind!r}; expected one of {_INTRA_NODE_KINDS}') + + def route(sender: int, receiver: int) -> Tuple[Resource, ...]: + for process in (sender, receiver): + if process not in nodes: + raise AffineTransferError(f'process {process} has no node') + if nodes[sender] != nodes[receiver]: + return (('network_send', sender), ('network_receive', receiver)) + resources = [] + for kind in intra_node: + if kind == 'device_send': + resources.append((kind, sender)) + elif kind == 'device_receive': + resources.append((kind, receiver)) + else: + resources.append((kind, sender, receiver)) + return tuple(resources) + + return route + + +def estimate_seconds(stages: Sequence[TransferStage], model: TransferCostModel) -> float: + """The model's time for running ``stages`` one after another, each as one ``execute_transfers`` call. + + A two-stage relay is two stages. The executor does not overlap them, so neither does the estimate. + """ + return sum(_call_seconds(stage, model) for stage in stages) + + +def cheapest(candidates: Mapping[str, Sequence[TransferStage]], model: TransferCostModel) -> PlanChoice: + """Estimate every candidate and keep the cheapest. + + Each candidate is a way to run the same move, as the stages ``estimate_seconds`` takes. A tie goes + to the name that sorts first, so every rank that is given the same candidates chooses the same one. + """ + if not candidates: + raise AffineTransferError('there is no candidate to choose from') + for name in candidates: + if not isinstance(name, str): + raise AffineTransferError(f'candidate names must be strings, got {name!r}') + seconds = {name: estimate_seconds(candidates[name], model) for name in sorted(candidates)} + name = min(seconds, key=lambda name: (seconds[name], name)) + return PlanChoice(name=name, seconds=seconds) + + +def _call_seconds(stage: TransferStage, model: TransferCostModel) -> float: + schedules = schedule_transfers(stage.plans, stage.endpoints, stage.budget, stage.element_size) + + # Bytes through each resource in each round. Every message is listed once by its sender and once + # by its receiver, with the same rounds, so counting the senders' side counts each byte once. + loads: Dict[int, Dict[Resource, int]] = {} + most_regions = 0 + for process, schedule in schedules.items(): + for peer, rounds in schedule.sends.items(): + resources = model.route(process, peer) + for index, scheduled in enumerate(rounds): + load = loads.setdefault(index, {}) + for resource in resources: + load[resource] = load.get(resource, 0) + scheduled.elements * stage.element_size + # A round sent or received in place needs no copy; a staged one packs or unpacks each chunk. + staged = [ + scheduled for rounds in list(schedule.sends.values()) + list(schedule.receives.values()) + for scheduled in rounds if not scheduled.direct + ] + regions = sum(scheduled.chunks for scheduled in staged) + schedule.local_copy_chunks + most_regions = max(most_regions, regions) + + round_seconds = 0.0 + for index in sorted(loads): + busiest = max((load / _capacity(model, resource) for resource, load in loads[index].items()), default=0.0) + round_seconds += model.seconds_per_round + busiest + launch_seconds = most_regions * model.seconds_per_region + return model.seconds_per_call + max(round_seconds, launch_seconds) + + +def _capacity(model: TransferCostModel, resource: Resource) -> float: + kind = resource[0] + if kind not in model.capacity: + raise AffineTransferError(f'resource {resource!r} is routed, but the model has no capacity for {kind!r}') + return model.capacity[kind] + + +def _is_number(value: object) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 41901705fec1..abf0c6a41afe 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -259,3 +259,40 @@ process holds up to ``(2 + max(widths)) * max(sizes)`` bytes, 2.25 GiB with the default width at 8 processes per node and 256 MiB, so pass shorter ``sizes`` or smaller fan widths on large jobs. The numbers describe the transport used for the measurement (torch point-to-point) on that topology. + +Choosing between plans +---------------------- + +Plans that move the same data can differ in time by more than 5x, for example +when a node's copy crosses the network once and is then exchanged over NVLink +instead of being sent to every rank. ``affine_transfer_cost`` prices each way +of running a move from its schedule and keeps the cheapest:: + + from deepspeed.checkpoint.affine_transfer_cost import (TransferCostModel, TransferStage, + cheapest, node_route) + + model = TransferCostModel(node_route(node_of_process, intra_node=('device_pair', )), + {'network_send': 68.4e9, 'network_receive': 23.4e9, + 'device_pair': 52.1e9}) + choice = cheapest({'direct': [TransferStage(plans, endpoints, element_size)], + 'relay': [TransferStage(fetch_plans, fetch_endpoints, element_size), + TransferStage(spread_plans, node_endpoints, element_size)]}, + model) + +Each candidate is a list of stages, one ``execute_transfers`` call each, run one +after another. Within a call, each round costs its most loaded resource's bytes +over that resource's capacity, plus ``seconds_per_round``. The host's copy +launches, ``seconds_per_region`` for each staged or local region, overlap the +bytes rather than adding to them, so the larger of the two counts, and each call +adds ``seconds_per_call``. ``node_route`` sends a message between nodes through +the sender's ``network_send`` and the receiver's ``network_receive``, and within +a node through ``device_send`` and ``device_receive`` (each GPU's own link, as on +NVSwitch) or ``device_pair`` (NVLink between two GPUs); any callable that names +a message's resources can replace it. ``choice.name`` is the cheapest candidate +and ``choice.seconds`` holds every estimate. A tie goes to the name that sorts +first. + +The capacities and costs are calibrated for each machine, transport +configuration and executor. Every rank must build the same model and the same +candidates, so that every rank chooses the same plan. A plan's one-time +preparation, and overlap between two stages, are not priced yet. diff --git a/tests/unit/checkpoint/test_affine_transfer_cost.py b/tests/unit/checkpoint/test_affine_transfer_cost.py new file mode 100644 index 000000000000..d4ffd4644177 --- /dev/null +++ b/tests/unit/checkpoint/test_affine_transfer_cost.py @@ -0,0 +1,136 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +"""Check ``affine_transfer_cost`` against bytes over capacity worked out by hand. + +Each expected time below is computed in the test from the bytes a schedule moves and the capacities +the model is given, not by calling the code under test. The GH200 case uses the capacities of RFC +#9026, so its direct and sharded estimates are the RFC's own model rows (502 and 367 ms). +""" + +import pytest + +from deepspeed.checkpoint.affine import contiguous_split_map, replicated_map +from deepspeed.checkpoint.affine_replica_policy import local_first_least_loaded +from deepspeed.checkpoint.affine_transfer import AffineTransferError, plan_transfer, plan_transfers +from deepspeed.checkpoint.affine_transfer_cost import (TransferCostModel, TransferStage, cheapest, estimate_seconds, + node_route) +from deepspeed.checkpoint.affine_transfer_executor import StagingBudget, TransferEndpoints + +GiB = 1 << 30 + + +def _one_sender_two_receivers(): + # 16 float32 elements to each of two receivers on another node, 8 elements per message: two rounds. + plan = plan_transfer(replicated_map((4, 4), 2), replicated_map((4, 4), 1)) + return TransferStage([plan], TransferEndpoints({0: 0}, {0: 1, 1: 2}), 4, StagingBudget(32)) + + +def test_a_round_takes_its_busiest_resource(): + stage = _one_sender_two_receivers() + route = node_route({0: 0, 1: 1, 2: 1}) + # Each round, the sender sends 2 x 32 bytes and each receiver receives 32 bytes. + receive_bound = {'network_send': 100.0, 'network_receive': 40.0} + model = TransferCostModel(route, receive_bound, seconds_per_call=2.0, seconds_per_round=0.5) + assert estimate_seconds([stage], model) == pytest.approx(2.0 + 2 * (0.5 + 32 / 40)) + send_bound = {'network_send': 50.0, 'network_receive': 1000.0} + model = TransferCostModel(route, send_bound, seconds_per_call=2.0, seconds_per_round=0.5) + assert estimate_seconds([stage], model) == pytest.approx(2.0 + 2 * (0.5 + 64 / 50)) + + +def test_resources_bind_on_their_own(): + # Process 2 receives one row from process 0 on the other node and one from process 3 on its own, + # in the same round. The two arrive over different resources, so the round takes the slower one, + # not the sum: the mixed incast of RFC #9026 (45.8 ms predicted, 46.0 ms measured on GH200). + plan = plan_transfer(replicated_map((2, 8), 1), contiguous_split_map((2, 8), [1, 1], 0)) + stage = TransferStage([plan], TransferEndpoints({0: 0, 1: 3}, {0: 2}), 4) + route = node_route({0: 0, 2: 1, 3: 1}, intra_node=('device_pair', )) + capacity = {'network_send': 1e9, 'network_receive': 16.0, 'device_pair': 32.0} + assert estimate_seconds([stage], TransferCostModel(route, capacity)) == pytest.approx(max(32 / 16, 32 / 32)) + + +def test_host_launches_overlap_the_bytes(): + # Process 0 sends each of two strided column blocks to its own receiver, packing each into its + # arena: two regions. The receivers take theirs in place, so they launch no copy. + plan = plan_transfer(contiguous_split_map((2, 4), [2, 2], 1), replicated_map((2, 4), 1)) + stage = TransferStage([plan], TransferEndpoints({0: 0}, {0: 1, 1: 2}), 4) + route = node_route({0: 0, 1: 1, 2: 1}) + capacity = {'network_send': 32.0, 'network_receive': 1e9} # the sender's 32 bytes take 1 s + for seconds_per_region in (0.1, 2.0): + model = TransferCostModel(route, capacity, seconds_per_call=0.5, seconds_per_region=seconds_per_region) + assert estimate_seconds([stage], model) == pytest.approx(0.5 + max(1.0, 2 * seconds_per_region)) + + # With both target locations on process 0, the two blocks are local copies: two regions, no message. + local = TransferStage([plan], TransferEndpoints({0: 0}, {0: 0, 1: 0}), 4) + model = TransferCostModel(route, capacity, seconds_per_call=0.5, seconds_per_region=0.25) + assert estimate_seconds([local], model) == pytest.approx(0.5 + 2 * 0.25) + + # Every round of this batch is one contiguous region on both sides, sent and received in place. + in_place = _one_sender_two_receivers() + model = TransferCostModel(route, {'network_send': 64.0, 'network_receive': 1e9}, seconds_per_region=10.0) + assert estimate_seconds([in_place], model) == pytest.approx(2 * 64 / 64) + + +def test_gh200_relay_beats_direct_and_sharded(): + # 8 GiB of bf16 from trainers on node 0 into four engines on node 1, with the GH200 capacities of + # RFC #9026: 68.4 GB/s network send and 23.4 GB/s network receive per GPU, 52.1 GB/s per NVLink pair. + shape, element_size, budget = (4, GiB), 2, StagingBudget(64 << 20) + trainers = {i: i for i in range(4)} + engines = {i: 4 + i for i in range(4)} + nodes = {process: process // 4 for process in range(8)} + capacity = {'network_send': 68.4e9, 'network_receive': 23.4e9, 'device_pair': 52.1e9} + model = TransferCostModel(node_route(nodes, intra_node=('device_pair', )), capacity) + every_engine = replicated_map(shape, 4) + rows = contiguous_split_map(shape, [1] * 4, 0) + + # Direct: every engine reads the whole weight from trainer 0, whose network send carries it four times. + direct_plan = plan_transfer(every_engine, replicated_map(shape, 1)) + direct = [TransferStage([direct_plan], TransferEndpoints({0: 0}, engines), element_size, budget)] + + # Sharded: each trainer holds one row, so every engine receives the whole weight from four senders. + sharded_plan = plan_transfer(every_engine, rows) + sharded = [TransferStage([sharded_plan], TransferEndpoints(trainers, engines), element_size, budget)] + + # Relay: each engine fetches one row from its own trainer replica, then the engines exchange the + # rows inside node 1. An engine's own row stays on its GPU in stage two, so it moves no bytes. + fetch_plan = plan_transfers({'w': (rows, replicated_map(shape, 4))}, + source_processes=trainers, + target_processes=engines, + element_size={'w': element_size}, + replica_policy=local_first_least_loaded)['w'] + spread_plan = plan_transfer(every_engine, rows) + relay = [ + TransferStage([fetch_plan], TransferEndpoints(trainers, engines), element_size, budget), + TransferStage([spread_plan], TransferEndpoints(engines, engines), element_size, budget), + ] + + choice = cheapest({'direct': direct, 'sharded': sharded, 'relay': relay}, model) + weight = 8 * GiB + assert choice.seconds['direct'] == pytest.approx(4 * weight / 68.4e9) + assert choice.seconds['sharded'] == pytest.approx(weight / 23.4e9) + assert choice.seconds['relay'] == pytest.approx(weight / 4 / 23.4e9 + weight / 4 / 52.1e9) + assert choice.name == 'relay' + + +def test_a_tie_goes_to_the_first_name(): + stage = _one_sender_two_receivers() + capacity = {'network_send': 1.0, 'network_receive': 1.0} + choice = cheapest({'b': [stage], 'a': [stage]}, TransferCostModel(node_route({0: 0, 1: 1, 2: 1}), capacity)) + assert choice.name == 'a' + assert choice.seconds['a'] == choice.seconds['b'] + + +def test_inputs_it_cannot_price_are_refused(): + stage = _one_sender_two_receivers() + both = {'network_send': 1.0, 'network_receive': 1.0} + with pytest.raises(AffineTransferError, match='no capacity for'): + estimate_seconds([stage], TransferCostModel(node_route({0: 0, 1: 1, 2: 1}), {'network_send': 1.0})) + with pytest.raises(AffineTransferError, match='has no node'): + estimate_seconds([stage], TransferCostModel(node_route({0: 0, 1: 1}), both)) + with pytest.raises(AffineTransferError, match='positive finite'): + TransferCostModel(node_route({}), {'network_send': 0.0}) + with pytest.raises(AffineTransferError, match='unknown intra-node resource'): + node_route({}, intra_node=('nvlink', )) + with pytest.raises(AffineTransferError, match='no candidate'): + cheapest({}, TransferCostModel(node_route({}), {}))