From 3ba2b6c48bbe1c043d122e45ab9392ec7b3e48bb Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Sat, 31 Oct 2026 13:05:42 +0000 Subject: [PATCH 01/16] Calibrate affine transfer links per path, including fan-out and fan-in Add calibrate_links/fit_links: raw local, pairwise, concurrent, 1-to-N and N-to-1 timings labelled by a path_of(from, to) hook, with a per-path alpha + bytes/bandwidth summary, as measured inputs for transfer cost models. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi (cherry picked from commit 3cfa4153ce3372068031c232205c7cb0bbac2748) --- .../checkpoint/affine_transfer_calibration.py | 313 ++++++++++++++++++ docs/code-docs/source/affine-transfer.rst | 40 +++ .../test_affine_transfer_calibration.py | 179 ++++++++++ 3 files changed, 532 insertions(+) create mode 100644 deepspeed/checkpoint/affine_transfer_calibration.py create mode 100644 tests/unit/checkpoint/test_affine_transfer_calibration.py diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py new file mode 100644 index 000000000000..0383cef9252a --- /dev/null +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -0,0 +1,313 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""Measure the links an affine transfer uses, as raw times by message size. + +A transfer plan says how many bytes go between which processes; this module measures how long +that takes on the machine at hand. Spec-sheet bandwidth is not a usable substitute: what a +transfer sees depends on the communication library, on how many links share a switch, root port +or receiver, and on fixed per-message costs, none of which a datasheet states. + +``calibrate_links`` records raw samples, each labeled with a path class by ``path_of``; +``fit_links`` summarizes them per path as a fixed cost plus a bandwidth, with the fit error +alongside so a consumer can see where that form does not hold. Modeling contention beyond the +measured patterns, and choosing plans, belong to the replica policy above the planner. + +Processes are ranks of the default process group. Plan locations are not processes; when the +transfer group is the default group, ``TransferEndpoints`` maps locations to these ranks. +""" + +import statistics +import time +from typing import Callable, Dict, List, Optional, Sequence, Tuple + +import torch + +import deepspeed.comm as dist +from deepspeed.accelerator import get_accelerator + +__all__ = [ + 'CALIBRATION_SCHEMA', 'DEFAULT_SIZES', 'LOCAL', 'PEER', 'INTRA_NODE', 'INTER_NODE', 'default_path_of', + 'node_path_of', 'calibrate_links', 'fit_links' +] + +CALIBRATION_SCHEMA = 1 + +# 4 KiB to 256 MiB: small messages fix the per-message cost, and fast links reach line rate only +# from about 64 MiB up. +DEFAULT_SIZES = tuple(1 << shift for shift in range(12, 29, 2)) + +LOCAL = 'local' +PEER = 'peer' +INTRA_NODE = 'intra_node' +INTER_NODE = 'inter_node' + + +def default_path_of(from_process: int, to_process: int) -> str: + """Tell a copy within one process from a transfer between two.""" + return LOCAL if from_process == to_process else PEER + + +def node_path_of(processes_per_node: int) -> Callable[[int, int], str]: + """Classify by node, for processes numbered node by node.""" + if processes_per_node <= 0: + raise ValueError('processes_per_node must be positive') + + def path_of(from_process: int, to_process: int) -> str: + if from_process == to_process: + return LOCAL + if from_process // processes_per_node == to_process // processes_per_node: + return INTRA_NODE + return INTER_NODE + + return path_of + + +def _synchronize() -> None: + get_accelerator().synchronize() + + +def _exchange(send: torch.Tensor, to_processes: Sequence[int], receives: Sequence[Tuple[torch.Tensor, int]]) -> None: + # oneCCL hangs on a group call that starts with a receive, so sends always go first. + ops = [dist.P2POp(dist.isend, send, process) for process in to_processes] + ops += [dist.P2POp(dist.irecv, buffer, process) for buffer, process in receives] + if ops: + for handle in dist.batch_isend_irecv(ops): + handle.wait() + + +def _timed_exchange(send, to_processes, receives) -> float: + dist.barrier() + _synchronize() + started = time.perf_counter() + _exchange(send, to_processes, receives) + _synchronize() + return time.perf_counter() - started + + +def _timed_copy(send: torch.Tensor, recv: torch.Tensor) -> float: + _synchronize() + started = time.perf_counter() + recv.copy_(send) + _synchronize() + return time.perf_counter() - started + + +def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, + repeats: int = 10, + warmup: int = 2, + path_of: Callable[[int, int], str] = default_path_of, + fan_width: Optional[int] = None) -> Dict: + """Time local copies, every ordered process pair alone, all processes at once, and fans. + + Every process of the default group must call this. It returns the same dictionary on every + process, with ``repeats`` samples per entry and no aggregation: + + - ``local``: a device-local copy on each process. + - ``peer``: each ordered pair with every other process idle, so that links through different + switches and sockets are each sampled. A sample is the slower of its two endpoints. + - ``concurrent``: every process sends to ``process + shift`` and receives from + ``process - shift`` at the same time, for every shift, so links are sampled while sharing. + - ``fan_out``: for every root, the root sends one message to each of its ``fan_width`` peers, + ``root + 1`` onwards, at once (1 to N), while every other process is idle. + - ``fan_in``: for every root, each of its peers sends one message to the root at once (N to 1), + so the root's receive side is shared. + + ``bytes`` is the size of one message. ``path`` on each sample is + ``path_of(from_process, to_process)``, so measured times can be joined to a plan's messages by + the same classification. Fan entries keep the root's time apart from its peers' times, and + label each peer with the path of its own message. + + ``fan_width`` defaults to every other process; 0 skips the fans. The pair sweep makes + ``world_size * (world_size - 1) * len(sizes) * (warmup + repeats)`` barriers, so keep ``sizes`` + short on large jobs. Each process allocates ``(2 + fan_width) * max(sizes)`` bytes of device + memory at most. + """ + if repeats <= 0 or warmup < 0: + raise ValueError('repeats must be positive and warmup non-negative') + if any(size <= 0 for size in sizes): + raise ValueError('sizes must be positive byte counts') + + rank = dist.get_rank() + world = dist.get_world_size() + if fan_width is None: + fan_width = world - 1 + if not 0 <= fan_width < world: + raise ValueError(f'fan_width must be between 0 and {world - 1}, got {fan_width}') + fan_peers = {root: [(root + step) % world for step in range(1, fan_width + 1)] for root in range(world)} + device = torch.device(get_accelerator().current_device_name()) + local_times: Dict[int, List[float]] = {} + peer_times: Dict[tuple, List[float]] = {} + concurrent_times: Dict[tuple, List[float]] = {} + fan_times: Dict[tuple, List[float]] = {} + for size in sizes: + send = torch.ones(size, dtype=torch.uint8, device=device) + recv = torch.empty(size, dtype=torch.uint8, device=device) + + times = [_timed_copy(send, recv) for _ in range(warmup + repeats)] + local_times[size] = times[warmup:] + + for source in range(world): + for target in range(world): + if source == target: + continue + to_processes = [target] if rank == source else [] + receives = [(recv, source)] if rank == target else [] + times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + if rank in (source, target): + peer_times[(size, source, target)] = times[warmup:] + + for shift in range(1, world): + to_processes = [(rank + shift) % world] + receives = [(recv, (rank - shift) % world)] + times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + concurrent_times[(size, shift)] = times[warmup:] + + for root in range(world if fan_width else 0): + peers = fan_peers[root] + if rank == root: + to_processes, receives = peers, [] + else: + to_processes, receives = [], ([(recv, root)] if rank in peers else []) + times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + fan_times[('fan_out', size, root)] = times[warmup:] + + if rank == root: + receives = [(torch.empty(size, dtype=torch.uint8, device=device), peer) for peer in peers] + to_processes = [] + else: + receives, to_processes = [], ([root] if rank in peers else []) + times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + fan_times[('fan_in', size, root)] = times[warmup:] + + # Samples stay on their own process until every timing is done, so no collective runs inside a timed region. + gathered = [None] * world + dist.all_gather_object(gathered, (local_times, peer_times, concurrent_times, fan_times)) + + local, peer, concurrent = [], [], [] + fans = {'fan_out': [], 'fan_in': []} + for size in sizes: + for process in range(world): + local.append({'bytes': size, 'process': process, 'path': LOCAL, 'seconds': gathered[process][0][size]}) + for source in range(world): + for target in range(world): + if source == target: + continue + key = (size, source, target) + seconds = [max(pair) for pair in zip(gathered[source][1][key], gathered[target][1][key])] + peer.append({ + 'bytes': size, + 'from_process': source, + 'to_process': target, + 'path': path_of(source, target), + 'seconds': seconds + }) + for shift in range(1, world): + concurrent.append({ + 'bytes': size, + 'shift': shift, + 'paths': [path_of(process, (process + shift) % world) for process in range(world)], + 'seconds_by_process': [gathered[process][2][(size, shift)] for process in range(world)], + }) + for root in range(world if fan_width else 0): + peers = fan_peers[root] + for kind, fans_of_kind in fans.items(): + key = (kind, size, root) + paths = [path_of(root, peer) if kind == 'fan_out' else path_of(peer, root) for peer in peers] + fans_of_kind.append({ + 'bytes': size, + 'root': root, + 'peers': peers, + 'paths': paths, + 'root_seconds': gathered[root][3][key], + 'seconds_by_peer': [gathered[peer][3][key] for peer in peers], + }) + return { + 'schema': CALIBRATION_SCHEMA, + 'world_size': world, + 'communication_backend': get_accelerator().communication_backend_name(), + 'repeats': repeats, + 'warmup': warmup, + 'local': local, + 'peer': peer, + 'concurrent': concurrent, + 'fan_width': fan_width, + 'fan_out': fans['fan_out'], + 'fan_in': fans['fan_in'], + } + + +def _fit(points: List[tuple]) -> Dict: + """Fit ``seconds = alpha + bytes / bandwidth`` to (bytes, seconds) points. + + Residuals are weighted by 1/seconds, so the fit minimizes relative error. Unweighted least + squares would let the largest messages decide everything and leave alpha meaningless. + """ + weights = [1.0 / (seconds * seconds) for _, seconds in points] + total = sum(weights) + mean_x = sum(w * x for w, (x, _) in zip(weights, points)) / total + mean_y = sum(w * y for w, (_, y) in zip(weights, points)) / total + spread = sum(w * (x - mean_x)**2 for w, (x, _) in zip(weights, points)) + if spread == 0: + raise ValueError('a fit needs at least two distinct message sizes') + slope = sum(w * (x - mean_x) * (y - mean_y) for w, (x, y) in zip(weights, points)) / spread + alpha = mean_y - slope * mean_x + predicted = [alpha + slope * x for x, _ in points] + return { + 'alpha_seconds': alpha, + # A non-positive slope means time did not grow with size, so no bandwidth is implied. + 'bytes_per_second': 1.0 / slope if slope > 0 else None, + 'max_relative_error': max(abs(p - y) / y for p, (_, y) in zip(predicted, points)), + 'sizes': sorted({x + for x, _ in points}), + } + + +def _fit_groups(groups: Dict[str, Dict[int, List[float]]]) -> Dict[str, Dict]: + fits = {} + for path, seconds_by_size in groups.items(): + points = [(size, statistics.median(seconds)) for size, seconds in sorted(seconds_by_size.items())] + fits[path] = _fit(points) + return fits + + +def fit_links(calibration: Dict) -> Dict: + """Summarize a ``calibrate_links`` result as ``alpha + bytes / bandwidth`` per path. + + Samples are pooled by path label and by size, and the median at each size is fitted, so a + single slow repeat does not move the line. Returns ``{'schema', 'local', 'peer', + 'concurrent', 'fan_out', 'fan_in'}``; each but the first maps a path label to + ``alpha_seconds``, ``bytes_per_second``, ``max_relative_error`` and the ``sizes`` fitted. + ``concurrent`` is fitted from what each process saw while every process was sending, i.e. + per-link cost under the shift sharing pattern, not in isolation. ``fan_out`` and ``fan_in`` + are fitted from the peers' times, each under its own message's path, so they give per-link + cost while one sender or one receiver is shared; the root's times stay in the raw result. + """ + if calibration.get('schema') != CALIBRATION_SCHEMA: + raise ValueError(f'unsupported calibration schema {calibration.get("schema")!r}') + + local: Dict[str, Dict[int, List[float]]] = {} + for sample in calibration['local']: + local.setdefault(sample['path'], {}).setdefault(sample['bytes'], []).extend(sample['seconds']) + + peer: Dict[str, Dict[int, List[float]]] = {} + for sample in calibration['peer']: + peer.setdefault(sample['path'], {}).setdefault(sample['bytes'], []).extend(sample['seconds']) + + concurrent: Dict[str, Dict[int, List[float]]] = {} + for sample in calibration['concurrent']: + for path, seconds in zip(sample['paths'], sample['seconds_by_process']): + concurrent.setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) + + fits = { + 'schema': CALIBRATION_SCHEMA, + 'local': _fit_groups(local), + 'peer': _fit_groups(peer), + 'concurrent': _fit_groups(concurrent), + } + for kind in ('fan_out', 'fan_in'): + fanned: Dict[str, Dict[int, List[float]]] = {} + for sample in calibration[kind]: + for path, seconds in zip(sample['paths'], sample['seconds_by_peer']): + fanned.setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) + fits[kind] = _fit_groups(fanned) + return fits diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 6f27352ae90a..6a2ded10f099 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -46,3 +46,43 @@ zero-copy transport such as GPUDirect RDMA would instead take each round's removes the arena copy but needs a registration lifetime this API has no place for, so the wire contract (one packed message per peer per round) is expected to change when such a path lands. + +Calibrating links +----------------- + +``calibrate_links`` measures what moving bytes costs between the processes of +the default group, so that a cost model or replica policy can price a plan's +messages with numbers from the machine it runs on. It only measures; it does not +plan, choose replicas, or fit anything by itself. Every process calls it and +receives the same raw samples:: + + from deepspeed.checkpoint.affine_transfer_calibration import (calibrate_links, fit_links, + node_path_of) + + calibration = calibrate_links(path_of=node_path_of(processes_per_node=8)) + fits = fit_links(calibration) + fits['fan_in']['inter_node'] # {'alpha_seconds', 'bytes_per_second', ...} + +Five patterns are sampled at every size, 4 KiB to 256 MiB by default: + +- ``local``: a device-local copy on each process. +- ``peer``: each ordered process pair alone (1 to 1). +- ``concurrent``: every process sends to ``process + shift`` at once, so links + are measured while shared. +- ``fan_out``: one root sends to ``fan_width`` peers at once (1 to N). +- ``fan_in``: ``fan_width`` peers send to one root at once (N to 1), measuring + receiver contention. + +Each message is labelled with ``path_of(from_process, to_process)``. The default +labels only ``local`` and ``peer``; ``node_path_of`` splits ``peer`` into +``intra_node`` and ``inter_node``, and any callable can be used, for example one +that tells NVLink from PCIe pairs. ``fit_links`` pools the samples per label and +fits ``alpha + bytes / bandwidth`` to the median at each size. + +Processes here are default-group ranks. A plan's source and target locations are +mapped to processes by ``TransferEndpoints``, so translate through it before +joining a plan's messages with these labels. The pair sweep makes +``world_size * (world_size - 1)`` barriered samples per size and repeat, and each +process holds up to ``(2 + fan_width) * max(sizes)`` bytes, so pass shorter +``sizes`` or a smaller ``fan_width`` on large jobs. The numbers describe the +transport used for the measurement (torch point-to-point) on that topology. diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py new file mode 100644 index 000000000000..d319117c7bf3 --- /dev/null +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -0,0 +1,179 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +import json +import os + +import pytest + +import deepspeed.comm as dist +from deepspeed.accelerator import get_accelerator +from deepspeed.checkpoint.affine_transfer_calibration import (CALIBRATION_SCHEMA, INTER_NODE, INTRA_NODE, LOCAL, + calibrate_links, fit_links, node_path_of) +from unit.common import DistributedTest + + +def test_rejects_empty_samples(): + with pytest.raises(ValueError): + calibrate_links(repeats=0) + with pytest.raises(ValueError): + calibrate_links(sizes=[0]) + + +def _synthetic_calibration(costs, sizes, world=2): + """A calibration result whose times follow known alpha and bandwidth per path exactly.""" + + def seconds(path, size, slowdown=1.0): + alpha, bandwidth = costs[path] + exact = alpha + size / bandwidth + # One outlier per entry; the median-based fit must ignore it. + return [exact, exact, exact * slowdown * 10] + + path_of = node_path_of(1) + return { + 'schema': + CALIBRATION_SCHEMA, + 'local': [{ + 'bytes': size, + 'process': p, + 'path': LOCAL, + 'seconds': seconds(LOCAL, size) + } for size in sizes for p in range(world)], + 'peer': [{ + 'bytes': size, + 'from_process': s, + 'to_process': t, + 'path': path_of(s, t), + 'seconds': seconds(path_of(s, t), size) + } for size in sizes for s in range(world) for t in range(world) if s != t], + 'concurrent': [{ + 'bytes': size, + 'shift': 1, + 'paths': [path_of(p, (p + 1) % world) for p in range(world)], + 'seconds_by_process': [seconds(INTER_NODE, size) for _ in range(world)], + } for size in sizes], + **{ + kind: [{ + 'bytes': size, + 'root': 0, + 'peers': list(range(1, world)), + 'paths': [INTER_NODE] * (world - 1), + 'root_seconds': seconds(INTER_NODE, size), + 'seconds_by_peer': [seconds(INTER_NODE, size) for _ in range(1, world)], + } for size in sizes] + for kind in ('fan_out', 'fan_in') + }, + } + + +def test_fit_recovers_known_link_costs(): + costs = {LOCAL: (2e-6, 400e9), INTER_NODE: (30e-6, 20e9)} + sizes = [4096, 1 << 16, 1 << 20, 1 << 24] + fits = fit_links(_synthetic_calibration(costs, sizes)) + + for group, path in (('local', LOCAL), ('peer', INTER_NODE), ('concurrent', INTER_NODE), ('fan_out', INTER_NODE), + ('fan_in', INTER_NODE)): + fit = fits[group][path] + alpha, bandwidth = costs[path] + assert fit['alpha_seconds'] == pytest.approx(alpha, rel=1e-6) + assert fit['bytes_per_second'] == pytest.approx(bandwidth, rel=1e-6) + assert fit['max_relative_error'] == pytest.approx(0, abs=1e-6) + assert fit['sizes'] == sizes + assert set(fits['peer']) == {INTER_NODE} + + +def test_fit_reports_error_where_the_line_does_not_hold(): + calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), INTER_NODE: (1e-5, 10e9)}, [4096, 1 << 20, 1 << 24]) + # A protocol switch at the largest size halves bandwidth there. + for sample in calibration['peer']: + if sample['bytes'] == 1 << 24: + sample['seconds'] = [value * 2 for value in sample['seconds']] + assert fit_links(calibration)['peer'][INTER_NODE]['max_relative_error'] > 0.1 + + +def test_fit_rejects_unknown_schema_and_single_size(): + with pytest.raises(ValueError): + fit_links({'schema': CALIBRATION_SCHEMA + 1}) + with pytest.raises(ValueError): + fit_links(_synthetic_calibration({LOCAL: (1e-6, 1e9), INTER_NODE: (1e-6, 1e9)}, [4096])) + + +@pytest.mark.skipif(get_accelerator().device_count() < 4, reason='requires four visible accelerator devices') +class TestCalibrateLinks(DistributedTest): + world_size = 4 + + def test_every_path_is_sampled_and_labeled(self): + get_accelerator().set_device(int(os.environ.get('LOCAL_RANK', dist.get_rank()))) + sizes = [4096, 1 << 20] + # Pretend two processes per node so both peer path classes occur on one machine. + result = calibrate_links(sizes=sizes, repeats=3, warmup=1, path_of=node_path_of(2)) + + gathered = [None] * dist.get_world_size() + dist.all_gather_object(gathered, json.dumps(result, sort_keys=True)) + assert len(set(gathered)) == 1, 'every process must return the same result' + + world = 4 + assert result['schema'] == CALIBRATION_SCHEMA + assert result['world_size'] == world + assert sorted((s['bytes'], s['process']) for s in result['local']) == sorted( + (size, process) for size in sizes for process in range(world)) + assert sorted((s['bytes'], s['from_process'], s['to_process']) for s in result['peer']) == sorted( + (size, source, target) for size in sizes for source in range(world) for target in range(world) + if source != target) + assert sorted((s['bytes'], s['shift']) for s in result['concurrent']) == sorted( + (size, shift) for size in sizes for shift in range(1, world)) + + for sample in result['local']: + assert sample['path'] == LOCAL + for sample in result['peer']: + expected = INTRA_NODE if sample['from_process'] // 2 == sample['to_process'] // 2 else INTER_NODE + assert sample['path'] == expected + for sample in result['concurrent']: + assert sample['paths'] == [node_path_of(2)(p, (p + sample['shift']) % world) for p in range(world)] + assert len(sample['seconds_by_process']) == world + + samples = [s['seconds'] for s in result['local'] + result['peer']] + samples += [seconds for s in result['concurrent'] for seconds in s['seconds_by_process']] + for seconds in samples: + assert len(seconds) == 3 + assert all(value > 0 for value in seconds) + + assert result['fan_width'] == world - 1 + for kind in ('fan_out', 'fan_in'): + assert sorted((s['bytes'], s['root']) for s in result[kind]) == sorted( + (size, root) for size in sizes for root in range(world)) + for sample in result[kind]: + assert sorted(sample['peers'] + [sample['root']]) == list(range(world)) + for seconds in [sample['root_seconds']] + sample['seconds_by_peer']: + assert len(seconds) == 3 + assert all(value > 0 for value in seconds) + + fits = fit_links(result) + assert set(fits['local']) == {LOCAL} + assert set(fits['peer']) == {INTRA_NODE, INTER_NODE} + assert set(fits['concurrent']) <= {INTRA_NODE, INTER_NODE} + assert set(fits['fan_out']) == set(fits['fan_in']) == {INTRA_NODE, INTER_NODE} + + def test_fans_label_each_message_by_its_direction(self): + get_accelerator().set_device(int(os.environ.get('LOCAL_RANK', dist.get_rank()))) + world = 4 + with pytest.raises(ValueError): + calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=world) + + # A direction-sensitive label, so a fan-in message labeled as root -> peer is caught. + result = calibrate_links(sizes=[4096], + repeats=1, + warmup=0, + path_of=lambda source, target: f'{source}->{target}', + fan_width=2) + assert result['fan_width'] == 2 + for sample in result['fan_out']: + root = sample['root'] + assert sample['peers'] == [(root + 1) % world, (root + 2) % world] + assert sample['paths'] == [f'{root}->{peer}' for peer in sample['peers']] + for sample in result['fan_in']: + root = sample['root'] + assert sample['paths'] == [f'{peer}->{root}' for peer in sample['peers']] + + skipped = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=0) + assert skipped['fan_out'] == skipped['fan_in'] == [] From 3f16eff48adbb2b4e8ad741359a9640db3e14a06 Mon Sep 17 00:00:00 2001 From: Achyuthan Sivasankar Date: Mon, 2 Nov 2026 11:21:19 -0500 Subject: [PATCH 02/16] Calibrate fans at several widths and fit each process's send and receive capacity Signed-off-by: Achyuthan Sivasankar (cherry picked from commit dc1722e6fb52f92f484c01455289b117d0fa9c9d) --- .../checkpoint/affine_transfer_calibration.py | 137 +++++++++++------- docs/code-docs/source/affine-transfer.rst | 22 ++- .../test_affine_transfer_calibration.py | 64 ++++++-- 3 files changed, 150 insertions(+), 73 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index 0383cef9252a..9835e690ac74 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -18,7 +18,7 @@ import statistics import time -from typing import Callable, Dict, List, Optional, Sequence, Tuple +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import torch @@ -96,7 +96,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, repeats: int = 10, warmup: int = 2, path_of: Callable[[int, int], str] = default_path_of, - fan_width: Optional[int] = None) -> Dict: + fan_width: Optional[Union[int, Sequence[int]]] = None) -> Dict: """Time local copies, every ordered process pair alone, all processes at once, and fans. Every process of the default group must call this. It returns the same dictionary on every @@ -107,20 +107,22 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, switches and sockets are each sampled. A sample is the slower of its two endpoints. - ``concurrent``: every process sends to ``process + shift`` and receives from ``process - shift`` at the same time, for every shift, so links are sampled while sharing. - - ``fan_out``: for every root, the root sends one message to each of its ``fan_width`` peers, - ``root + 1`` onwards, at once (1 to N), while every other process is idle. - - ``fan_in``: for every root, each of its peers sends one message to the root at once (N to 1), - so the root's receive side is shared. + - ``fan_out``: for every root and fan width, the root sends one message to each of its + ``width`` peers, ``root + 1`` onwards, at once (1 to N), while every other process is idle. + - ``fan_in``: for every root and fan width, each of its peers sends one message to the root + at once (N to 1), so the root's receive side is shared. ``bytes`` is the size of one message. ``path`` on each sample is ``path_of(from_process, to_process)``, so measured times can be joined to a plan's messages by the same classification. Fan entries keep the root's time apart from its peers' times, and label each peer with the path of its own message. - ``fan_width`` defaults to every other process; 0 skips the fans. The pair sweep makes - ``world_size * (world_size - 1) * len(sizes) * (warmup + repeats)`` barriers, so keep ``sizes`` - short on large jobs. Each process allocates ``(2 + fan_width) * max(sizes)`` bytes of device - memory at most. + ``fan_width`` is one width or several, and defaults to every other process; 0 skips the + fans. Measuring more than one width shows how a process's send or receive capacity changes + with the number of peers sharing it, which a single width cannot. Each fan sample records its + ``width``. The pair sweep makes ``world_size * (world_size - 1) * len(sizes) * (warmup + + repeats)`` barriers, so keep ``sizes`` short on large jobs. Each process allocates + ``(2 + max(widths)) * max(sizes)`` bytes of device memory at most. """ if repeats <= 0 or warmup < 0: raise ValueError('repeats must be positive and warmup non-negative') @@ -131,9 +133,16 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, world = dist.get_world_size() if fan_width is None: fan_width = world - 1 - if not 0 <= fan_width < world: - raise ValueError(f'fan_width must be between 0 and {world - 1}, got {fan_width}') - fan_peers = {root: [(root + step) % world for step in range(1, fan_width + 1)] for root in range(world)} + requested = [fan_width] if isinstance(fan_width, int) else list(fan_width) + for width in requested: + if not isinstance(width, int) or not 0 <= width < world: + raise ValueError(f'fan widths must be integers between 0 and {world - 1}, got {width!r}') + widths = sorted(set(requested) - {0}) + fan_peers = { + (root, width): [(root + step) % world for step in range(1, width + 1)] + for root in range(world) + for width in widths + } device = torch.device(get_accelerator().current_device_name()) local_times: Dict[int, List[float]] = {} peer_times: Dict[tuple, List[float]] = {} @@ -162,22 +171,23 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] concurrent_times[(size, shift)] = times[warmup:] - for root in range(world if fan_width else 0): - peers = fan_peers[root] - if rank == root: - to_processes, receives = peers, [] - else: - to_processes, receives = [], ([(recv, root)] if rank in peers else []) - times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] - fan_times[('fan_out', size, root)] = times[warmup:] + for width in widths: + for root in range(world): + peers = fan_peers[(root, width)] + if rank == root: + to_processes, receives = peers, [] + else: + to_processes, receives = [], ([(recv, root)] if rank in peers else []) + times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + fan_times[('fan_out', size, width, root)] = times[warmup:] - if rank == root: - receives = [(torch.empty(size, dtype=torch.uint8, device=device), peer) for peer in peers] - to_processes = [] - else: - receives, to_processes = [], ([root] if rank in peers else []) - times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] - fan_times[('fan_in', size, root)] = times[warmup:] + if rank == root: + receives = [(torch.empty(size, dtype=torch.uint8, device=device), peer) for peer in peers] + to_processes = [] + else: + receives, to_processes = [], ([root] if rank in peers else []) + times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + fan_times[('fan_in', size, width, root)] = times[warmup:] # Samples stay on their own process until every timing is done, so no collective runs inside a timed region. gathered = [None] * world @@ -208,19 +218,21 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'paths': [path_of(process, (process + shift) % world) for process in range(world)], 'seconds_by_process': [gathered[process][2][(size, shift)] for process in range(world)], }) - for root in range(world if fan_width else 0): - peers = fan_peers[root] - for kind, fans_of_kind in fans.items(): - key = (kind, size, root) - paths = [path_of(root, peer) if kind == 'fan_out' else path_of(peer, root) for peer in peers] - fans_of_kind.append({ - 'bytes': size, - 'root': root, - 'peers': peers, - 'paths': paths, - 'root_seconds': gathered[root][3][key], - 'seconds_by_peer': [gathered[peer][3][key] for peer in peers], - }) + for width in widths: + for root in range(world): + peers = fan_peers[(root, width)] + for kind, fans_of_kind in fans.items(): + key = (kind, size, width, root) + paths = [path_of(root, peer) if kind == 'fan_out' else path_of(peer, root) for peer in peers] + fans_of_kind.append({ + 'bytes': size, + 'width': width, + 'root': root, + 'peers': peers, + 'paths': paths, + 'root_seconds': gathered[root][3][key], + 'seconds_by_peer': [gathered[peer][3][key] for peer in peers], + }) return { 'schema': CALIBRATION_SCHEMA, 'world_size': world, @@ -230,7 +242,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'local': local, 'peer': peer, 'concurrent': concurrent, - 'fan_width': fan_width, + 'fan_widths': widths, 'fan_out': fans['fan_out'], 'fan_in': fans['fan_in'], } @@ -262,11 +274,11 @@ def _fit(points: List[tuple]) -> Dict: } -def _fit_groups(groups: Dict[str, Dict[int, List[float]]]) -> Dict[str, Dict]: +def _fit_groups(groups: Dict[object, Dict[int, List[float]]]) -> Dict[object, Dict]: fits = {} - for path, seconds_by_size in groups.items(): + for key, seconds_by_size in groups.items(): points = [(size, statistics.median(seconds)) for size, seconds in sorted(seconds_by_size.items())] - fits[path] = _fit(points) + fits[key] = _fit(points) return fits @@ -274,13 +286,20 @@ def fit_links(calibration: Dict) -> Dict: """Summarize a ``calibrate_links`` result as ``alpha + bytes / bandwidth`` per path. Samples are pooled by path label and by size, and the median at each size is fitted, so a - single slow repeat does not move the line. Returns ``{'schema', 'local', 'peer', - 'concurrent', 'fan_out', 'fan_in'}``; each but the first maps a path label to - ``alpha_seconds``, ``bytes_per_second``, ``max_relative_error`` and the ``sizes`` fitted. - ``concurrent`` is fitted from what each process saw while every process was sending, i.e. - per-link cost under the shift sharing pattern, not in isolation. ``fan_out`` and ``fan_in`` - are fitted from the peers' times, each under its own message's path, so they give per-link - cost while one sender or one receiver is shared; the root's times stay in the raw result. + single slow repeat does not move the line. Every fit holds ``alpha_seconds``, + ``bytes_per_second``, ``max_relative_error`` and the ``sizes`` fitted. Returns: + + - ``local``, ``peer`` and ``concurrent``: a fit per path label. ``concurrent`` is fitted from + what each process saw while every process was sending, i.e. per-link cost under the shift + sharing pattern, not in isolation. + - ``fan_out`` and ``fan_in``: per fan width, a fit per path label, from the peers' times, each + under its own message's path. They give per-link cost while one sender or one receiver is + shared by that many peers. + - ``send`` and ``receive``: per fan width, a fit per process, from the root's time against all + the bytes it sent (fan-out) or received (fan-in). That is the process's aggregate capacity + while that many peers share it, which is what pricing a plan's per-process sent and received + bytes needs. The width is the only condition recorded: on a fabric where *which* peers share + a process matters, as behind PCIe switches, these fits average over the peer sets measured. """ if calibration.get('schema') != CALIBRATION_SCHEMA: raise ValueError(f'unsupported calibration schema {calibration.get("schema")!r}') @@ -304,10 +323,16 @@ def fit_links(calibration: Dict) -> Dict: 'peer': _fit_groups(peer), 'concurrent': _fit_groups(concurrent), } - for kind in ('fan_out', 'fan_in'): - fanned: Dict[str, Dict[int, List[float]]] = {} + for kind, direction in (('fan_out', 'send'), ('fan_in', 'receive')): + fanned: Dict[int, Dict[str, Dict[int, List[float]]]] = {} + rooted: Dict[int, Dict[int, Dict[int, List[float]]]] = {} for sample in calibration[kind]: + width = sample['width'] for path, seconds in zip(sample['paths'], sample['seconds_by_peer']): - fanned.setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) - fits[kind] = _fit_groups(fanned) + fanned.setdefault(width, {}).setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) + # The root moves one message per peer, so its time covers width times the message size. + rooted.setdefault(width, {}).setdefault(sample['root'], {}).setdefault(sample['bytes'] * width, + []).extend(sample['root_seconds']) + fits[kind] = {width: _fit_groups(groups) for width, groups in fanned.items()} + fits[direction] = {width: _fit_groups(groups) for width, groups in rooted.items()} return fits diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 6a2ded10f099..6a052cca46ae 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -59,9 +59,10 @@ receives the same raw samples:: from deepspeed.checkpoint.affine_transfer_calibration import (calibrate_links, fit_links, node_path_of) - calibration = calibrate_links(path_of=node_path_of(processes_per_node=8)) + calibration = calibrate_links(path_of=node_path_of(processes_per_node=8), fan_width=[1, 2, 4, 7]) fits = fit_links(calibration) - fits['fan_in']['inter_node'] # {'alpha_seconds', 'bytes_per_second', ...} + fits['fan_in'][4]['inter_node'] # per-link cost while 4 senders share a receiver + fits['receive'][4][0] # process 0's aggregate receive capacity with 4 senders Five patterns are sampled at every size, 4 KiB to 256 MiB by default: @@ -69,20 +70,27 @@ Five patterns are sampled at every size, 4 KiB to 256 MiB by default: - ``peer``: each ordered process pair alone (1 to 1). - ``concurrent``: every process sends to ``process + shift`` at once, so links are measured while shared. -- ``fan_out``: one root sends to ``fan_width`` peers at once (1 to N). -- ``fan_in``: ``fan_width`` peers send to one root at once (N to 1), measuring +- ``fan_out``: one root sends to ``width`` peers at once (1 to N). +- ``fan_in``: ``width`` peers send to one root at once (N to 1), measuring receiver contention. +``fan_width`` takes one width or a list of them; each fan sample records its +``width``. + Each message is labelled with ``path_of(from_process, to_process)``. The default labels only ``local`` and ``peer``; ``node_path_of`` splits ``peer`` into ``intra_node`` and ``inter_node``, and any callable can be used, for example one that tells NVLink from PCIe pairs. ``fit_links`` pools the samples per label and -fits ``alpha + bytes / bandwidth`` to the median at each size. +fits ``alpha + bytes / bandwidth`` to the median at each size. Fan fits are kept +per width. ``send`` and ``receive`` fit each root's own time against all the +bytes it moved, giving each process's aggregate capacity while that many peers +share it, which is what a plan's per-process sent and received bytes are priced +against. Processes here are default-group ranks. A plan's source and target locations are mapped to processes by ``TransferEndpoints``, so translate through it before joining a plan's messages with these labels. The pair sweep makes ``world_size * (world_size - 1)`` barriered samples per size and repeat, and each -process holds up to ``(2 + fan_width) * max(sizes)`` bytes, so pass shorter -``sizes`` or a smaller ``fan_width`` on large jobs. The numbers describe the +process holds up to ``(2 + max(widths)) * max(sizes)`` bytes, 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. diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py index d319117c7bf3..07ba3c99f5e6 100644 --- a/tests/unit/checkpoint/test_affine_transfer_calibration.py +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -55,6 +55,7 @@ def seconds(path, size, slowdown=1.0): **{ kind: [{ 'bytes': size, + 'width': world - 1, 'root': 0, 'peers': list(range(1, world)), 'paths': [INTER_NODE] * (world - 1), @@ -71,9 +72,11 @@ def test_fit_recovers_known_link_costs(): sizes = [4096, 1 << 16, 1 << 20, 1 << 24] fits = fit_links(_synthetic_calibration(costs, sizes)) - for group, path in (('local', LOCAL), ('peer', INTER_NODE), ('concurrent', INTER_NODE), ('fan_out', INTER_NODE), - ('fan_in', INTER_NODE)): - fit = fits[group][path] + width = 1 # the synthetic fans have one peer, so a root moves one message per fan + for fit, path in ((fits['local'][LOCAL], LOCAL), (fits['peer'][INTER_NODE], INTER_NODE), + (fits['concurrent'][INTER_NODE], INTER_NODE), (fits['fan_out'][width][INTER_NODE], INTER_NODE), + (fits['fan_in'][width][INTER_NODE], + INTER_NODE), (fits['send'][width][0], INTER_NODE), (fits['receive'][width][0], INTER_NODE)): alpha, bandwidth = costs[path] assert fit['alpha_seconds'] == pytest.approx(alpha, rel=1e-6) assert fit['bytes_per_second'] == pytest.approx(bandwidth, rel=1e-6) @@ -82,6 +85,35 @@ def test_fit_recovers_known_link_costs(): assert set(fits['peer']) == {INTER_NODE} +def test_root_fits_give_each_process_its_capacity_at_each_width(): + """A root's time covers every message of its fan, so its capacity is fitted against all of them. + + Fitting the root's time against one message's bytes would understate the capacity by the + width, and pooling widths would blur the capacity's dependence on how many peers share it. + """ + sizes = [4096, 1 << 20, 1 << 24] + alpha = 40e-6 + receive_capacity = {(1, 0): 30e9, (1, 1): 12e9, (3, 0): 20e9, (3, 1): 9e9} + calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), INTER_NODE: (1e-5, 10e9)}, sizes, world=4) + calibration['fan_in'] = [{ + 'bytes': size, + 'width': width, + 'root': root, + 'peers': [(root + step) % 4 for step in range(1, width + 1)], + 'paths': [INTER_NODE] * width, + 'root_seconds': [alpha + width * size / receive_capacity[(width, root)]] * 3, + 'seconds_by_peer': [[alpha + size / 10e9] * 3] * width, + } for size in sizes for width in (1, 3) for root in (0, 1)] + + fits = fit_links(calibration) + assert set(fits['receive']) == set(fits['fan_in']) == {1, 3} + for (width, root), capacity in receive_capacity.items(): + fit = fits['receive'][width][root] + assert fit['bytes_per_second'] == pytest.approx(capacity, rel=1e-6) + assert fit['alpha_seconds'] == pytest.approx(alpha, rel=1e-6) + assert fit['sizes'] == [width * size for size in sizes] + + def test_fit_reports_error_where_the_line_does_not_hold(): calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), INTER_NODE: (1e-5, 10e9)}, [4096, 1 << 20, 1 << 24]) # A protocol switch at the largest size halves bandwidth there. @@ -138,11 +170,12 @@ def test_every_path_is_sampled_and_labeled(self): assert len(seconds) == 3 assert all(value > 0 for value in seconds) - assert result['fan_width'] == world - 1 + assert result['fan_widths'] == [world - 1] for kind in ('fan_out', 'fan_in'): assert sorted((s['bytes'], s['root']) for s in result[kind]) == sorted( (size, root) for size in sizes for root in range(world)) for sample in result[kind]: + assert sample['width'] == world - 1 assert sorted(sample['peers'] + [sample['root']]) == list(range(world)) for seconds in [sample['root_seconds']] + sample['seconds_by_peer']: assert len(seconds) == 3 @@ -152,13 +185,15 @@ def test_every_path_is_sampled_and_labeled(self): assert set(fits['local']) == {LOCAL} assert set(fits['peer']) == {INTRA_NODE, INTER_NODE} assert set(fits['concurrent']) <= {INTRA_NODE, INTER_NODE} - assert set(fits['fan_out']) == set(fits['fan_in']) == {INTRA_NODE, INTER_NODE} + assert set(fits['fan_out'][world - 1]) == set(fits['fan_in'][world - 1]) == {INTRA_NODE, INTER_NODE} + assert set(fits['send'][world - 1]) == set(fits['receive'][world - 1]) == set(range(world)) def test_fans_label_each_message_by_its_direction(self): get_accelerator().set_device(int(os.environ.get('LOCAL_RANK', dist.get_rank()))) world = 4 - with pytest.raises(ValueError): - calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=world) + for invalid in (world, [1, world], [-1]): + with pytest.raises(ValueError): + calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=invalid) # A direction-sensitive label, so a fan-in message labeled as root -> peer is caught. result = calibrate_links(sizes=[4096], @@ -166,7 +201,7 @@ def test_fans_label_each_message_by_its_direction(self): warmup=0, path_of=lambda source, target: f'{source}->{target}', fan_width=2) - assert result['fan_width'] == 2 + assert result['fan_widths'] == [2] for sample in result['fan_out']: root = sample['root'] assert sample['peers'] == [(root + 1) % world, (root + 2) % world] @@ -175,5 +210,14 @@ def test_fans_label_each_message_by_its_direction(self): root = sample['root'] assert sample['paths'] == [f'{peer}->{root}' for peer in sample['peers']] - skipped = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=0) - assert skipped['fan_out'] == skipped['fan_in'] == [] + widths = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=[2, 1, 2]) + assert widths['fan_widths'] == [1, 2] + for kind in ('fan_out', 'fan_in'): + assert sorted((s['width'], s['root']) for s in widths[kind]) == sorted( + (width, root) for width in (1, 2) for root in range(world)) + for sample in widths[kind]: + assert sample['peers'] == [(sample['root'] + step) % world for step in range(1, sample['width'] + 1)] + + for skip in (0, []): + skipped = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=skip) + assert skipped['fan_out'] == skipped['fan_in'] == [] From fc62c0b32caf094fd5e0662b36d7f1ffdf59a476 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Tue, 3 Nov 2026 14:06:31 +0000 Subject: [PATCH 03/16] Key fan fits by peer set; add per-pair fits, fan_peers, group and a node-capped default - fit_links keys fan_out, fan_in, send and receive by (root, sorted peers), so fans of one width with different senders stay apart; the width is len(peers). Adds peer_pairs, a fit per ordered (from, to) pair. - calibrate_links takes fan_peers(root, width) to choose the peers, and an optional group whose ranks number the processes. - The default fan width is one less than the fewest processes on any node, and default peers are on the root's node first. - Docs state that width-keyed fits assume a uniform fabric, with B70 data. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi (cherry picked from commit ba8b39fe334a4f03bb4497bbde2b634770774748) --- .../checkpoint/affine_transfer_calibration.py | 136 +++++++++++------- docs/code-docs/source/affine-transfer.rst | 53 +++++-- .../test_affine_transfer_calibration.py | 90 +++++++++--- ...affine_transfer_executor_external_group.py | 4 + 4 files changed, 200 insertions(+), 83 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index 9835e690ac74..c25006f99c4e 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -12,10 +12,12 @@ alongside so a consumer can see where that form does not hold. Modeling contention beyond the measured patterns, and choosing plans, belong to the replica policy above the planner. -Processes are ranks of the default process group. Plan locations are not processes; when the -transfer group is the default group, ``TransferEndpoints`` maps locations to these ranks. +Processes are ranks of the measured process group, the default group unless ``group`` is given. +Plan locations are not processes; when the transfer runs on the measured group, +``TransferEndpoints`` maps locations to these ranks. """ +import socket import statistics import time from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union @@ -66,20 +68,27 @@ def _synchronize() -> None: get_accelerator().synchronize() -def _exchange(send: torch.Tensor, to_processes: Sequence[int], receives: Sequence[Tuple[torch.Tensor, int]]) -> None: +def _global_rank(group: Optional[object], process: int) -> int: + return dist.get_global_rank(group, process) if group is not None else process + + +def _exchange(send: torch.Tensor, + to_processes: Sequence[int], + receives: Sequence[Tuple[torch.Tensor, int]], + group: Optional[object] = None) -> None: # oneCCL hangs on a group call that starts with a receive, so sends always go first. - ops = [dist.P2POp(dist.isend, send, process) for process in to_processes] - ops += [dist.P2POp(dist.irecv, buffer, process) for buffer, process in receives] + ops = [dist.P2POp(dist.isend, send, _global_rank(group, process), group=group) for process in to_processes] + ops += [dist.P2POp(dist.irecv, buffer, _global_rank(group, process), group=group) for buffer, process in receives] if ops: for handle in dist.batch_isend_irecv(ops): handle.wait() -def _timed_exchange(send, to_processes, receives) -> float: - dist.barrier() +def _timed_exchange(send, to_processes, receives, group: Optional[object] = None) -> float: + dist.barrier(group=group) _synchronize() started = time.perf_counter() - _exchange(send, to_processes, receives) + _exchange(send, to_processes, receives, group) _synchronize() return time.perf_counter() - started @@ -96,11 +105,13 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, repeats: int = 10, warmup: int = 2, path_of: Callable[[int, int], str] = default_path_of, - fan_width: Optional[Union[int, Sequence[int]]] = None) -> Dict: + fan_width: Optional[Union[int, Sequence[int]]] = None, + fan_peers: Optional[Callable[[int, int], Sequence[int]]] = None, + group: Optional[object] = None) -> Dict: """Time local copies, every ordered process pair alone, all processes at once, and fans. - Every process of the default group must call this. It returns the same dictionary on every - process, with ``repeats`` samples per entry and no aggregation: + Every process of ``group`` (the default group unless given) must call this. It returns the + same dictionary on every process, with ``repeats`` samples per entry and no aggregation: - ``local``: a device-local copy on each process. - ``peer``: each ordered pair with every other process idle, so that links through different @@ -108,7 +119,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, - ``concurrent``: every process sends to ``process + shift`` and receives from ``process - shift`` at the same time, for every shift, so links are sampled while sharing. - ``fan_out``: for every root and fan width, the root sends one message to each of its - ``width`` peers, ``root + 1`` onwards, at once (1 to N), while every other process is idle. + ``width`` peers at once (1 to N), while every other process is idle. - ``fan_in``: for every root and fan width, each of its peers sends one message to the root at once (N to 1), so the root's receive side is shared. @@ -117,32 +128,53 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, the same classification. Fan entries keep the root's time apart from its peers' times, and label each peer with the path of its own message. - ``fan_width`` is one width or several, and defaults to every other process; 0 skips the - fans. Measuring more than one width shows how a process's send or receive capacity changes + ``fan_width`` is one width or several; 0 skips the fans. It defaults to one less than the + fewest processes on any node, and at least 1, so default fans fit in a node as jobs grow. + Measuring more than one width shows how a process's send or receive capacity changes with the number of peers sharing it, which a single width cannot. Each fan sample records its - ``width``. The pair sweep makes ``world_size * (world_size - 1) * len(sizes) * (warmup + - repeats)`` barriers, so keep ``sizes`` short on large jobs. Each process allocates - ``(2 + max(widths)) * max(sizes)`` bytes of device memory at most. + ``width``. By default a root's peers are taken from ``root + 1`` onwards, those on its node + first, unless ``fan_peers(root, width)`` returns ``width`` other processes, e.g. the senders + behind one PCIe switch or across a socket; it must return the same peers on every process. + Nodes are told apart by host name. + + The pair sweep makes ``world_size * (world_size - 1) * len(sizes) * (warmup + repeats)`` + barriers, so keep ``sizes`` short on large jobs. Each process allocates + ``(2 + max(widths)) * max(sizes)`` bytes of device memory at most, 2.25 GiB with the default + width at 8 processes per node and 256 MiB messages. """ if repeats <= 0 or warmup < 0: raise ValueError('repeats must be positive and warmup non-negative') if any(size <= 0 for size in sizes): raise ValueError('sizes must be positive byte counts') - rank = dist.get_rank() - world = dist.get_world_size() + if group is not None and callable(getattr(group, 'rank', None)): + # Ask the group itself, as the executor does: torch misnumbers groups built outside the default world. + rank, world = group.rank(), group.size() + else: + rank = dist.get_rank(group=group) + world = dist.get_world_size(group=group) + hostnames = [None] * world + dist.all_gather_object(hostnames, socket.gethostname(), group=group) if fan_width is None: - fan_width = world - 1 + fewest_per_node = min(hostnames.count(host) for host in set(hostnames)) + fan_width = min(world - 1, max(1, fewest_per_node - 1)) requested = [fan_width] if isinstance(fan_width, int) else list(fan_width) for width in requested: if not isinstance(width, int) or not 0 <= width < world: raise ValueError(f'fan widths must be integers between 0 and {world - 1}, got {width!r}') widths = sorted(set(requested) - {0}) - fan_peers = { - (root, width): [(root + step) % world for step in range(1, width + 1)] - for root in range(world) - for width in widths - } + peer_sets = {} + for root in range(world): + ring = [(root + step) % world for step in range(1, world)] + # Peers on the root's node come first so default fans stay in it; the sort is stable, so ring order holds. + nearest = sorted(ring, key=lambda process: hostnames[process] != hostnames[root]) + for width in widths: + peers = list(fan_peers(root, width)) if fan_peers is not None else nearest[:width] + distinct = len(set(peers)) == len(peers) == width + in_range = all(0 <= peer < world and peer != root for peer in peers) + if not (distinct and in_range): + raise ValueError(f'fan_peers({root}, {width}) must return {width} distinct processes other than root') + peer_sets[(root, width)] = peers device = torch.device(get_accelerator().current_device_name()) local_times: Dict[int, List[float]] = {} peer_times: Dict[tuple, List[float]] = {} @@ -161,24 +193,24 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, continue to_processes = [target] if rank == source else [] receives = [(recv, source)] if rank == target else [] - times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + times = [_timed_exchange(send, to_processes, receives, group) for _ in range(warmup + repeats)] if rank in (source, target): peer_times[(size, source, target)] = times[warmup:] for shift in range(1, world): to_processes = [(rank + shift) % world] receives = [(recv, (rank - shift) % world)] - times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + times = [_timed_exchange(send, to_processes, receives, group) for _ in range(warmup + repeats)] concurrent_times[(size, shift)] = times[warmup:] for width in widths: for root in range(world): - peers = fan_peers[(root, width)] + peers = peer_sets[(root, width)] if rank == root: to_processes, receives = peers, [] else: to_processes, receives = [], ([(recv, root)] if rank in peers else []) - times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + times = [_timed_exchange(send, to_processes, receives, group) for _ in range(warmup + repeats)] fan_times[('fan_out', size, width, root)] = times[warmup:] if rank == root: @@ -186,12 +218,12 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, to_processes = [] else: receives, to_processes = [], ([root] if rank in peers else []) - times = [_timed_exchange(send, to_processes, receives) for _ in range(warmup + repeats)] + times = [_timed_exchange(send, to_processes, receives, group) for _ in range(warmup + repeats)] fan_times[('fan_in', size, width, root)] = times[warmup:] # Samples stay on their own process until every timing is done, so no collective runs inside a timed region. gathered = [None] * world - dist.all_gather_object(gathered, (local_times, peer_times, concurrent_times, fan_times)) + dist.all_gather_object(gathered, (local_times, peer_times, concurrent_times, fan_times), group=group) local, peer, concurrent = [], [], [] fans = {'fan_out': [], 'fan_in': []} @@ -220,7 +252,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, }) for width in widths: for root in range(world): - peers = fan_peers[(root, width)] + peers = peer_sets[(root, width)] for kind, fans_of_kind in fans.items(): key = (kind, size, width, root) paths = [path_of(root, peer) if kind == 'fan_out' else path_of(peer, root) for peer in peers] @@ -292,14 +324,18 @@ def fit_links(calibration: Dict) -> Dict: - ``local``, ``peer`` and ``concurrent``: a fit per path label. ``concurrent`` is fitted from what each process saw while every process was sending, i.e. per-link cost under the shift sharing pattern, not in isolation. - - ``fan_out`` and ``fan_in``: per fan width, a fit per path label, from the peers' times, each - under its own message's path. They give per-link cost while one sender or one receiver is - shared by that many peers. - - ``send`` and ``receive``: per fan width, a fit per process, from the root's time against all - the bytes it sent (fan-out) or received (fan-in). That is the process's aggregate capacity - while that many peers share it, which is what pricing a plan's per-process sent and received - bytes needs. The width is the only condition recorded: on a fabric where *which* peers share - a process matters, as behind PCIe switches, these fits average over the peer sets measured. + - ``peer_pairs``: a fit per ordered ``(from_process, to_process)`` pair, from the ``peer`` + samples. It keeps the sender and direction asymmetry that pooling by path label averages + away, as between cards behind PCIe switches. + - ``fan_out`` and ``fan_in``: per fan, keyed by ``(root, peers)`` with the peers sorted, a fit + per path label, from the peers' times, each under its own message's path. They give + per-link cost while those peers share one sender or one receiver. + - ``send`` and ``receive``: per fan, keyed the same way, a fit from the root's time against all + the bytes it sent (fan-out) or received (fan-in). That is the root's aggregate rate with + those peers, which is what pricing a plan's per-process sent and received bytes needs. A + fan finishes when the busiest resource it crosses does: a peer's link, the root, or a link + the peers share. Behind PCIe switches that depends on *which* peers share the root, not only + on how many, so fans are keyed by their peers; the width is ``len(peers)``. """ if calibration.get('schema') != CALIBRATION_SCHEMA: raise ValueError(f'unsupported calibration schema {calibration.get("schema")!r}') @@ -309,8 +345,11 @@ def fit_links(calibration: Dict) -> Dict: local.setdefault(sample['path'], {}).setdefault(sample['bytes'], []).extend(sample['seconds']) peer: Dict[str, Dict[int, List[float]]] = {} + peer_pairs: Dict[Tuple[int, int], Dict[int, List[float]]] = {} for sample in calibration['peer']: peer.setdefault(sample['path'], {}).setdefault(sample['bytes'], []).extend(sample['seconds']) + pair = (sample['from_process'], sample['to_process']) + peer_pairs.setdefault(pair, {}).setdefault(sample['bytes'], []).extend(sample['seconds']) concurrent: Dict[str, Dict[int, List[float]]] = {} for sample in calibration['concurrent']: @@ -321,18 +360,19 @@ def fit_links(calibration: Dict) -> Dict: 'schema': CALIBRATION_SCHEMA, 'local': _fit_groups(local), 'peer': _fit_groups(peer), + 'peer_pairs': _fit_groups(peer_pairs), 'concurrent': _fit_groups(concurrent), } for kind, direction in (('fan_out', 'send'), ('fan_in', 'receive')): - fanned: Dict[int, Dict[str, Dict[int, List[float]]]] = {} - rooted: Dict[int, Dict[int, Dict[int, List[float]]]] = {} + fanned: Dict[tuple, Dict[str, Dict[int, List[float]]]] = {} + rooted: Dict[tuple, Dict[int, List[float]]] = {} for sample in calibration[kind]: - width = sample['width'] + width = len(sample['peers']) + fan = (sample['root'], tuple(sorted(sample['peers']))) for path, seconds in zip(sample['paths'], sample['seconds_by_peer']): - fanned.setdefault(width, {}).setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) + fanned.setdefault(fan, {}).setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) # The root moves one message per peer, so its time covers width times the message size. - rooted.setdefault(width, {}).setdefault(sample['root'], {}).setdefault(sample['bytes'] * width, - []).extend(sample['root_seconds']) - fits[kind] = {width: _fit_groups(groups) for width, groups in fanned.items()} - fits[direction] = {width: _fit_groups(groups) for width, groups in rooted.items()} + rooted.setdefault(fan, {}).setdefault(sample['bytes'] * width, []).extend(sample['root_seconds']) + fits[kind] = {fan: _fit_groups(groups) for fan, groups in fanned.items()} + fits[direction] = _fit_groups(rooted) return fits diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 6a052cca46ae..6d04c542c072 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -51,7 +51,8 @@ Calibrating links ----------------- ``calibrate_links`` measures what moving bytes costs between the processes of -the default group, so that a cost model or replica policy can price a plan's +a process group, the default group unless ``group`` is given, so that a cost +model or replica policy can price a plan's messages with numbers from the machine it runs on. It only measures; it does not plan, choose replicas, or fit anything by itself. Every process calls it and receives the same raw samples:: @@ -61,8 +62,9 @@ receives the same raw samples:: calibration = calibrate_links(path_of=node_path_of(processes_per_node=8), fan_width=[1, 2, 4, 7]) fits = fit_links(calibration) - fits['fan_in'][4]['inter_node'] # per-link cost while 4 senders share a receiver - fits['receive'][4][0] # process 0's aggregate receive capacity with 4 senders + fits['peer_pairs'][(0, 1)] # the link from process 0 to process 1 alone + fits['fan_in'][(0, (1, 2, 3, 4))]['inter_node'] # per-link cost while 1-4 send to 0 at once + fits['receive'][(0, (1, 2, 3, 4))] # process 0's aggregate rate receiving from 1-4 Five patterns are sampled at every size, 4 KiB to 256 MiB by default: @@ -75,22 +77,49 @@ Five patterns are sampled at every size, 4 KiB to 256 MiB by default: receiver contention. ``fan_width`` takes one width or a list of them; each fan sample records its -``width``. +``width``. It defaults to one less than the fewest processes on any node, and at +least 1, so the default fans fit in a node however large the job is. A root's +default peers are taken from ``root + 1`` onwards, those on its node (by host +name) first. ``fan_peers(root, width)`` picks other peers, for example the +senders behind one PCIe switch or across a socket, and must return the same +peers on every process. Each message is labelled with ``path_of(from_process, to_process)``. The default labels only ``local`` and ``peer``; ``node_path_of`` splits ``peer`` into ``intra_node`` and ``inter_node``, and any callable can be used, for example one that tells NVLink from PCIe pairs. ``fit_links`` pools the samples per label and -fits ``alpha + bytes / bandwidth`` to the median at each size. Fan fits are kept -per width. ``send`` and ``receive`` fit each root's own time against all the -bytes it moved, giving each process's aggregate capacity while that many peers -share it, which is what a plan's per-process sent and received bytes are priced -against. - -Processes here are default-group ranks. A plan's source and target locations are +fits ``alpha + bytes / bandwidth`` to the median at each size, and +``peer_pairs`` fits each ordered pair alone. Fan fits are keyed by +``(root, peers)``, with the peers sorted; the width is ``len(peers)``. ``send`` +and ``receive`` fit each root's own time against all the bytes it moved, giving +the root's aggregate rate with those peers, which is what a plan's per-process +sent and received bytes are priced against. + +A fan finishes when the busiest resource it crosses does: a peer's link, the +root, or a link the peers share. Behind PCIe switches that depends on *which* +peers share a process more than on how many, which is why fans are not keyed by +width alone. On 8 B70 cards (xccl, 256 MiB messages) the pairs ranged from 3.6 +to 54 GB/s, depending on the sender and direction, and a root's fan-in +bandwidth at one width varied with its senders:: + + width min ~ max over roots (GB/s) spread + 1 7.0 ~ 53.9 7.7x + 2 12.6 ~ 55.2 4.4x + 4 18.7 ~ 37.3 2.0x + 7 16.4 ~ 23.6 1.4x + +There, use ``peer_pairs``, label paths by topology, and choose the sender sets +to measure with ``fan_peers``; to compare several sets of one width, calibrate +once per set and concatenate the ``fan_out`` and ``fan_in`` samples before +fitting. On a uniform fabric, fits of one width can be pooled by +``len(peers)``. + +Processes here are ranks of ``group``; pass the group the transfer runs on. A +plan's source and target locations are mapped to processes by ``TransferEndpoints``, so translate through it before joining a plan's messages with these labels. The pair sweep makes ``world_size * (world_size - 1)`` barriered samples per size and repeat, and each -process holds up to ``(2 + max(widths)) * max(sizes)`` bytes, so pass shorter +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. diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py index 07ba3c99f5e6..7e2283eade48 100644 --- a/tests/unit/checkpoint/test_affine_transfer_calibration.py +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -3,6 +3,7 @@ import json import os +from unittest.mock import patch import pytest @@ -72,11 +73,12 @@ def test_fit_recovers_known_link_costs(): sizes = [4096, 1 << 16, 1 << 20, 1 << 24] fits = fit_links(_synthetic_calibration(costs, sizes)) - width = 1 # the synthetic fans have one peer, so a root moves one message per fan - for fit, path in ((fits['local'][LOCAL], LOCAL), (fits['peer'][INTER_NODE], INTER_NODE), - (fits['concurrent'][INTER_NODE], INTER_NODE), (fits['fan_out'][width][INTER_NODE], INTER_NODE), - (fits['fan_in'][width][INTER_NODE], - INTER_NODE), (fits['send'][width][0], INTER_NODE), (fits['receive'][width][0], INTER_NODE)): + fan = (0, (1, )) # the synthetic fans have one peer, so a root moves one message per fan + checks = [(fits['local'][LOCAL], LOCAL), (fits['peer'][INTER_NODE], INTER_NODE), + (fits['concurrent'][INTER_NODE], INTER_NODE)] + checks += [(fits[kind][fan][INTER_NODE], INTER_NODE) for kind in ('fan_out', 'fan_in')] + checks += [(fits[direction][fan], INTER_NODE) for direction in ('send', 'receive')] + for fit, path in checks: alpha, bandwidth = costs[path] assert fit['alpha_seconds'] == pytest.approx(alpha, rel=1e-6) assert fit['bytes_per_second'] == pytest.approx(bandwidth, rel=1e-6) @@ -85,33 +87,35 @@ def test_fit_recovers_known_link_costs(): assert set(fits['peer']) == {INTER_NODE} -def test_root_fits_give_each_process_its_capacity_at_each_width(): - """A root's time covers every message of its fan, so its capacity is fitted against all of them. +def test_root_fits_give_each_sender_set_its_rate(): + """A root's time covers every message of its fan, so its rate is fitted against all of them. - Fitting the root's time against one message's bytes would understate the capacity by the - width, and pooling widths would blur the capacity's dependence on how many peers share it. + Fitting the root's time against one message's bytes would understate the rate by the width. + Pooling fans of one width would average sender sets that a PCIe tree tells apart, such as + root 0 receiving from (1, 2) or from (2, 3) below. """ sizes = [4096, 1 << 20, 1 << 24] alpha = 40e-6 - receive_capacity = {(1, 0): 30e9, (1, 1): 12e9, (3, 0): 20e9, (3, 1): 9e9} + receive_rate = {(0, (1, )): 30e9, (1, (2, )): 12e9, (0, (1, 2)): 12e9, (0, (2, 3)): 54e9, (1, (0, 2, 3)): 9e9} calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), INTER_NODE: (1e-5, 10e9)}, sizes, world=4) + # Peers are listed in reverse, as the key must not depend on the order they are listed in. calibration['fan_in'] = [{ 'bytes': size, - 'width': width, + 'width': len(peers), 'root': root, - 'peers': [(root + step) % 4 for step in range(1, width + 1)], - 'paths': [INTER_NODE] * width, - 'root_seconds': [alpha + width * size / receive_capacity[(width, root)]] * 3, - 'seconds_by_peer': [[alpha + size / 10e9] * 3] * width, - } for size in sizes for width in (1, 3) for root in (0, 1)] + 'peers': list(reversed(peers)), + 'paths': [INTER_NODE] * len(peers), + 'root_seconds': [alpha + len(peers) * size / rate] * 3, + 'seconds_by_peer': [[alpha + size / 10e9] * 3] * len(peers), + } for size in sizes for (root, peers), rate in receive_rate.items()] fits = fit_links(calibration) - assert set(fits['receive']) == set(fits['fan_in']) == {1, 3} - for (width, root), capacity in receive_capacity.items(): - fit = fits['receive'][width][root] - assert fit['bytes_per_second'] == pytest.approx(capacity, rel=1e-6) + assert set(fits['receive']) == set(fits['fan_in']) == set(receive_rate) + for (root, peers), rate in receive_rate.items(): + fit = fits['receive'][(root, peers)] + assert fit['bytes_per_second'] == pytest.approx(rate, rel=1e-6) assert fit['alpha_seconds'] == pytest.approx(alpha, rel=1e-6) - assert fit['sizes'] == [width * size for size in sizes] + assert fit['sizes'] == [len(peers) * size for size in sizes] def test_fit_reports_error_where_the_line_does_not_hold(): @@ -123,6 +127,21 @@ def test_fit_reports_error_where_the_line_does_not_hold(): assert fit_links(calibration)['peer'][INTER_NODE]['max_relative_error'] > 0.1 +def test_peer_pair_fits_keep_each_direction(): + """Pooling by path would average the fast and the slow direction of one link.""" + sizes = [4096, 1 << 20, 1 << 24] + alpha = 1e-5 + bandwidth = {(0, 1): 20e9, (1, 0): 5e9} + calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), INTER_NODE: (alpha, 10e9)}, sizes) + for sample in calibration['peer']: + pair = (sample['from_process'], sample['to_process']) + sample['seconds'] = [alpha + sample['bytes'] / bandwidth[pair]] * 3 + + fits = fit_links(calibration) + for pair, expected in bandwidth.items(): + assert fits['peer_pairs'][pair]['bytes_per_second'] == pytest.approx(expected, rel=1e-6) + + def test_fit_rejects_unknown_schema_and_single_size(): with pytest.raises(ValueError): fit_links({'schema': CALIBRATION_SCHEMA + 1}) @@ -185,8 +204,23 @@ def test_every_path_is_sampled_and_labeled(self): assert set(fits['local']) == {LOCAL} assert set(fits['peer']) == {INTRA_NODE, INTER_NODE} assert set(fits['concurrent']) <= {INTRA_NODE, INTER_NODE} - assert set(fits['fan_out'][world - 1]) == set(fits['fan_in'][world - 1]) == {INTRA_NODE, INTER_NODE} - assert set(fits['send'][world - 1]) == set(fits['receive'][world - 1]) == set(range(world)) + every_fan = {(root, tuple(sorted(set(range(world)) - {root}))) for root in range(world)} + assert set(fits['fan_out']) == set(fits['fan_in']) == set(fits['send']) == set(fits['receive']) == every_fan + for kind in ('fan_out', 'fan_in'): + assert all(set(by_path) == {INTRA_NODE, INTER_NODE} for by_path in fits[kind].values()) + + @pytest.mark.parametrize('processes_per_node', [1, 2]) + def test_default_fans_stay_within_a_node(self, processes_per_node): + get_accelerator().set_device(int(os.environ.get('LOCAL_RANK', dist.get_rank()))) + node = dist.get_rank() // processes_per_node + with patch('socket.gethostname', return_value=f'node-{node}'): + result = calibrate_links(sizes=[4096], repeats=1, warmup=0) + + # With one process per node, fans still run, across nodes. + assert result['fan_widths'] == [1] + for sample in result['fan_out'] + result['fan_in']: + same_node = sample['peers'][0] // processes_per_node == sample['root'] // processes_per_node + assert same_node or processes_per_node == 1 def test_fans_label_each_message_by_its_direction(self): get_accelerator().set_device(int(os.environ.get('LOCAL_RANK', dist.get_rank()))) @@ -218,6 +252,16 @@ def test_fans_label_each_message_by_its_direction(self): for sample in widths[kind]: assert sample['peers'] == [(sample['root'] + step) % world for step in range(1, sample['width'] + 1)] + chosen = calibrate_links(sizes=[4096], + repeats=1, + warmup=0, + fan_width=1, + fan_peers=lambda root, width: [(root + 2) % world]) + for sample in chosen['fan_out'] + chosen['fan_in']: + assert sample['peers'] == [(sample['root'] + 2) % world] + with pytest.raises(ValueError): + calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=1, fan_peers=lambda root, width: [root]) + for skip in (0, []): skipped = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=skip) assert skipped['fan_out'] == skipped['fan_in'] == [] diff --git a/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py b/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py index 67e53227b283..8f7bf4a845ad 100644 --- a/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py +++ b/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py @@ -40,6 +40,7 @@ def _worker(rank, port, tmp): from deepspeed.checkpoint.affine import contiguous_split_map from deepspeed.checkpoint.affine_transfer import plan_transfer + from deepspeed.checkpoint.affine_transfer_calibration import calibrate_links from deepspeed.checkpoint.affine_transfer_executor import TransferEndpoints, execute_transfer full = torch.arange(96, dtype=torch.float32).reshape(8, 12) @@ -55,6 +56,7 @@ def _worker(rank, port, tmp): targets = {loc: torch.full(shape, -1.0) for loc, shape in target.shard_shapes.items()} if rank == 1 else {} execute_transfer(plan, sources, targets, endpoints, torch.float32, group=group) mismatched = [loc for loc, shard in targets.items() if not torch.equal(shard, target.extract(full, loc))] + calibration = calibrate_links(sizes=[4096], repeats=1, warmup=0, group=group) # Leave together and tear down before exit. Rank 0 only sends and hosts the store, so without this it can exit # while rank 1 is still on the group, and gloo's threads abort at interpreter exit ("terminate called without # an active exception", SIGABRT in the merge queue). @@ -63,6 +65,8 @@ def _worker(rank, port, tmp): tdist.destroy_process_group() del store assert not mismatched, mismatched + assert calibration['world_size'] == 2 + assert sorted((sample['from_process'], sample['to_process']) for sample in calibration['peer']) == [(0, 1), (1, 0)] @pytest.mark.skipif(get_accelerator().device_name() != 'cpu', From 83284abdae36143db45c25c2f0488f885a74a5df Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Tue, 3 Nov 2026 14:29:19 +0000 Subject: [PATCH 04/16] Drop the card model from the calibration docs example Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi (cherry picked from commit f00ce1749eca6e3da7f4ca11aad6380f55253527) --- docs/code-docs/source/affine-transfer.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 6d04c542c072..a34c690bf42b 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -98,8 +98,8 @@ sent and received bytes are priced against. A fan finishes when the busiest resource it crosses does: a peer's link, the root, or a link the peers share. Behind PCIe switches that depends on *which* peers share a process more than on how many, which is why fans are not keyed by -width alone. On 8 B70 cards (xccl, 256 MiB messages) the pairs ranged from 3.6 -to 54 GB/s, depending on the sender and direction, and a root's fan-in +width alone. On one such 8-GPU node (256 MiB messages) the pairs ranged from +3.6 to 54 GB/s, depending on the sender and direction, and a root's fan-in bandwidth at one width varied with its senders:: width min ~ max over roots (GB/s) spread From 11e311eca6673634b9399d6f1abf0ee4210ec7e3 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Wed, 4 Nov 2026 23:53:24 +0000 Subject: [PATCH 05/16] add docsing for fit_links return Signed-off-by: Jin, Youzhi (cherry picked from commit 2c438245f6dc8d6b5d3ac889b252c4bba748007b) --- deepspeed/checkpoint/affine_transfer_calibration.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index c25006f99c4e..009f72186bd7 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -336,6 +336,9 @@ def fit_links(calibration: Dict) -> Dict: fan finishes when the busiest resource it crosses does: a peer's link, the root, or a link the peers share. Behind PCIe switches that depends on *which* peers share the root, not only on how many, so fans are keyed by their peers; the width is ``len(peers)``. + + The returned fits use tuple keys and are not directly JSON-serializable. Persist the raw + ``calibrate_links`` result instead, then call ``fit_links`` again after loading it. """ if calibration.get('schema') != CALIBRATION_SCHEMA: raise ValueError(f'unsupported calibration schema {calibration.get("schema")!r}') From d7e183820b81cc32e106929a8dd6f537efb5688c Mon Sep 17 00:00:00 2001 From: iLeGend <824040212@qq.com> Date: Thu, 5 Nov 2026 12:32:29 +0800 Subject: [PATCH 06/16] Fit concurrent links only from processes whose send and receive share a path A concurrent sample times a process's send to process + shift and its receive from process - shift together, but was labelled by the send path alone. Across nodes, an intra-node send paired with an inter-node receive takes the inter-node time, so the intra_node concurrent fit came out at 7.5 GB/s over TCP against 65 GB/s for clean intra-node processes on 2x8 H20. Record receive_paths and fit each path only from processes whose send and receive both took it. Document calibrating on the group and settings the transfer uses. Signed-off-by: iLeGend <824040212@qq.com> (cherry picked from commit 575bef3cbba24ebf64a87986b082c403a223a6a7) --- .../checkpoint/affine_transfer_calibration.py | 13 ++++++-- docs/code-docs/source/affine-transfer.rst | 12 +++++-- .../test_affine_transfer_calibration.py | 33 +++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index 009f72186bd7..7f5116c8e1b9 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -118,6 +118,8 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, switches and sockets are each sampled. A sample is the slower of its two endpoints. - ``concurrent``: every process sends to ``process + shift`` and receives from ``process - shift`` at the same time, for every shift, so links are sampled while sharing. + A process's time covers both its send and its receive, so each sample records ``paths`` + for the sends and ``receive_paths`` for the receives. - ``fan_out``: for every root and fan width, the root sends one message to each of its ``width`` peers at once (1 to N), while every other process is idle. - ``fan_in``: for every root and fan width, each of its peers sends one message to the root @@ -244,10 +246,12 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'seconds': seconds }) for shift in range(1, world): + senders = [(process - shift) % world for process in range(world)] concurrent.append({ 'bytes': size, 'shift': shift, 'paths': [path_of(process, (process + shift) % world) for process in range(world)], + 'receive_paths': [path_of(sender, process) for process, sender in enumerate(senders)], 'seconds_by_process': [gathered[process][2][(size, shift)] for process in range(world)], }) for width in widths: @@ -323,7 +327,8 @@ def fit_links(calibration: Dict) -> Dict: - ``local``, ``peer`` and ``concurrent``: a fit per path label. ``concurrent`` is fitted from what each process saw while every process was sending, i.e. per-link cost under the shift - sharing pattern, not in isolation. + sharing pattern, not in isolation. It uses only processes whose send and receive took the + same path, since a process's time covers both; a path no such process saw has no fit. - ``peer_pairs``: a fit per ordered ``(from_process, to_process)`` pair, from the ``peer`` samples. It keeps the sender and direction asymmetry that pooling by path label averages away, as between cards behind PCIe switches. @@ -356,8 +361,10 @@ def fit_links(calibration: Dict) -> Dict: concurrent: Dict[str, Dict[int, List[float]]] = {} for sample in calibration['concurrent']: - for path, seconds in zip(sample['paths'], sample['seconds_by_process']): - concurrent.setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) + for path, receive_path, seconds in zip(sample['paths'], sample['receive_paths'], sample['seconds_by_process']): + # Across nodes, an intra-node send paired with an inter-node receive takes the inter-node time. + if path == receive_path: + concurrent.setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) fits = { 'schema': CALIBRATION_SCHEMA, diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index a34c690bf42b..944af86d87e9 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -70,8 +70,11 @@ Five patterns are sampled at every size, 4 KiB to 256 MiB by default: - ``local``: a device-local copy on each process. - ``peer``: each ordered process pair alone (1 to 1). -- ``concurrent``: every process sends to ``process + shift`` at once, so links - are measured while shared. +- ``concurrent``: every process sends to ``process + shift`` and receives from + ``process - shift`` at once, so links are measured while shared. A process's + time covers both, so ``fit_links`` fits a path only from processes whose send + and receive both took it; with few processes per node, ``intra_node`` may have + no such process and no ``concurrent`` fit. - ``fan_out``: one root sends to ``width`` peers at once (1 to N). - ``fan_in``: ``width`` peers send to one root at once (N to 1), measuring receiver contention. @@ -123,3 +126,8 @@ 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. + +Calibrate on the group and communication settings the transfer will use: the +same links can measure very differently in another group. On two 8-GPU H20 +nodes, one NVLink pair moved 275 GB/s in an 8-process group but 54 GB/s in the +16-process group over RoCE. diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py index 7e2283eade48..7a49cfa11e27 100644 --- a/tests/unit/checkpoint/test_affine_transfer_calibration.py +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -51,6 +51,7 @@ def seconds(path, size, slowdown=1.0): 'bytes': size, 'shift': 1, 'paths': [path_of(p, (p + 1) % world) for p in range(world)], + 'receive_paths': [path_of((p - 1) % world, p) for p in range(world)], 'seconds_by_process': [seconds(INTER_NODE, size) for _ in range(world)], } for size in sizes], **{ @@ -142,6 +143,34 @@ def test_peer_pair_fits_keep_each_direction(): assert fits['peer_pairs'][pair]['bytes_per_second'] == pytest.approx(expected, rel=1e-6) +def test_concurrent_fits_ignore_processes_with_a_mixed_send_and_receive(): + """A process sending within its node while receiving across nodes waits on the slower link. + + Pooling that process's time under its send path would charge the inter-node cost to + ``intra_node``, as on two 8-GPU nodes over TCP (7.5 GB/s fitted vs 65 GB/s clean). + """ + sizes = [4096, 1 << 20, 1 << 24] + costs = {INTRA_NODE: (5e-5, 60e9), INTER_NODE: (1e-4, 5e9)} + calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), **costs}, sizes, world=4) + + def exact(path, size): + alpha, bandwidth = costs[path] + return [alpha + size / bandwidth] * 3 + + calibration['concurrent'] = [{ + 'bytes': size, + 'shift': 1, + 'paths': [INTRA_NODE, INTRA_NODE, INTER_NODE, INTER_NODE], + 'receive_paths': [INTRA_NODE, INTER_NODE, INTRA_NODE, INTER_NODE], + 'seconds_by_process': [exact(INTRA_NODE, size)] + [exact(INTER_NODE, size)] * 3, + } for size in sizes] + + fits = fit_links(calibration)['concurrent'] + for path, (alpha, bandwidth) in costs.items(): + assert fits[path]['alpha_seconds'] == pytest.approx(alpha, rel=1e-6) + assert fits[path]['bytes_per_second'] == pytest.approx(bandwidth, rel=1e-6) + + def test_fit_rejects_unknown_schema_and_single_size(): with pytest.raises(ValueError): fit_links({'schema': CALIBRATION_SCHEMA + 1}) @@ -243,6 +272,10 @@ def test_fans_label_each_message_by_its_direction(self): for sample in result['fan_in']: root = sample['root'] assert sample['paths'] == [f'{peer}->{root}' for peer in sample['peers']] + for sample in result['concurrent']: + shift = sample['shift'] + assert sample['paths'] == [f'{p}->{(p + shift) % world}' for p in range(world)] + assert sample['receive_paths'] == [f'{(p - shift) % world}->{p}' for p in range(world)] widths = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=[2, 1, 2]) assert widths['fan_widths'] == [1, 2] From f3102ed1bd6ca5577fbc31ef7d21f4048cd56208 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 5 Nov 2026 18:23:48 +0000 Subject: [PATCH 07/16] Drop the concurrent calibration pattern Weight transfers are one-way: a training process sends and a rollout process receives, so no process sends and receives at once. The concurrent shift pattern timed every process doing both, which matches no transfer, and needed per-direction path filtering to fit at all. Remove it with its fit, docs and tests, and drop the hardware-specific measurements from the docs. Signed-off-by: Jin, Youzhi (cherry picked from commit 17aa897e6265d6da8cabd03d90488ced48f2afa0) --- .../checkpoint/affine_transfer_calibration.py | 44 +++-------------- docs/code-docs/source/affine-transfer.rst | 22 +-------- .../test_affine_transfer_calibration.py | 49 +------------------ 3 files changed, 9 insertions(+), 106 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index 7f5116c8e1b9..fc9a3a6664df 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -108,7 +108,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, fan_width: Optional[Union[int, Sequence[int]]] = None, fan_peers: Optional[Callable[[int, int], Sequence[int]]] = None, group: Optional[object] = None) -> Dict: - """Time local copies, every ordered process pair alone, all processes at once, and fans. + """Time local copies, every ordered process pair alone, and fans. Every process of ``group`` (the default group unless given) must call this. It returns the same dictionary on every process, with ``repeats`` samples per entry and no aggregation: @@ -116,10 +116,6 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, - ``local``: a device-local copy on each process. - ``peer``: each ordered pair with every other process idle, so that links through different switches and sockets are each sampled. A sample is the slower of its two endpoints. - - ``concurrent``: every process sends to ``process + shift`` and receives from - ``process - shift`` at the same time, for every shift, so links are sampled while sharing. - A process's time covers both its send and its receive, so each sample records ``paths`` - for the sends and ``receive_paths`` for the receives. - ``fan_out``: for every root and fan width, the root sends one message to each of its ``width`` peers at once (1 to N), while every other process is idle. - ``fan_in``: for every root and fan width, each of its peers sends one message to the root @@ -180,7 +176,6 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, device = torch.device(get_accelerator().current_device_name()) local_times: Dict[int, List[float]] = {} peer_times: Dict[tuple, List[float]] = {} - concurrent_times: Dict[tuple, List[float]] = {} fan_times: Dict[tuple, List[float]] = {} for size in sizes: send = torch.ones(size, dtype=torch.uint8, device=device) @@ -199,12 +194,6 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, if rank in (source, target): peer_times[(size, source, target)] = times[warmup:] - for shift in range(1, world): - to_processes = [(rank + shift) % world] - receives = [(recv, (rank - shift) % world)] - times = [_timed_exchange(send, to_processes, receives, group) for _ in range(warmup + repeats)] - concurrent_times[(size, shift)] = times[warmup:] - for width in widths: for root in range(world): peers = peer_sets[(root, width)] @@ -225,9 +214,9 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, # Samples stay on their own process until every timing is done, so no collective runs inside a timed region. gathered = [None] * world - dist.all_gather_object(gathered, (local_times, peer_times, concurrent_times, fan_times), group=group) + dist.all_gather_object(gathered, (local_times, peer_times, fan_times), group=group) - local, peer, concurrent = [], [], [] + local, peer = [], [] fans = {'fan_out': [], 'fan_in': []} for size in sizes: for process in range(world): @@ -245,15 +234,6 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'path': path_of(source, target), 'seconds': seconds }) - for shift in range(1, world): - senders = [(process - shift) % world for process in range(world)] - concurrent.append({ - 'bytes': size, - 'shift': shift, - 'paths': [path_of(process, (process + shift) % world) for process in range(world)], - 'receive_paths': [path_of(sender, process) for process, sender in enumerate(senders)], - 'seconds_by_process': [gathered[process][2][(size, shift)] for process in range(world)], - }) for width in widths: for root in range(world): peers = peer_sets[(root, width)] @@ -266,8 +246,8 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'root': root, 'peers': peers, 'paths': paths, - 'root_seconds': gathered[root][3][key], - 'seconds_by_peer': [gathered[peer][3][key] for peer in peers], + 'root_seconds': gathered[root][2][key], + 'seconds_by_peer': [gathered[peer][2][key] for peer in peers], }) return { 'schema': CALIBRATION_SCHEMA, @@ -277,7 +257,6 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'warmup': warmup, 'local': local, 'peer': peer, - 'concurrent': concurrent, 'fan_widths': widths, 'fan_out': fans['fan_out'], 'fan_in': fans['fan_in'], @@ -325,10 +304,7 @@ def fit_links(calibration: Dict) -> Dict: single slow repeat does not move the line. Every fit holds ``alpha_seconds``, ``bytes_per_second``, ``max_relative_error`` and the ``sizes`` fitted. Returns: - - ``local``, ``peer`` and ``concurrent``: a fit per path label. ``concurrent`` is fitted from - what each process saw while every process was sending, i.e. per-link cost under the shift - sharing pattern, not in isolation. It uses only processes whose send and receive took the - same path, since a process's time covers both; a path no such process saw has no fit. + - ``local`` and ``peer``: a fit per path label. - ``peer_pairs``: a fit per ordered ``(from_process, to_process)`` pair, from the ``peer`` samples. It keeps the sender and direction asymmetry that pooling by path label averages away, as between cards behind PCIe switches. @@ -359,19 +335,11 @@ def fit_links(calibration: Dict) -> Dict: pair = (sample['from_process'], sample['to_process']) peer_pairs.setdefault(pair, {}).setdefault(sample['bytes'], []).extend(sample['seconds']) - concurrent: Dict[str, Dict[int, List[float]]] = {} - for sample in calibration['concurrent']: - for path, receive_path, seconds in zip(sample['paths'], sample['receive_paths'], sample['seconds_by_process']): - # Across nodes, an intra-node send paired with an inter-node receive takes the inter-node time. - if path == receive_path: - concurrent.setdefault(path, {}).setdefault(sample['bytes'], []).extend(seconds) - fits = { 'schema': CALIBRATION_SCHEMA, 'local': _fit_groups(local), 'peer': _fit_groups(peer), 'peer_pairs': _fit_groups(peer_pairs), - 'concurrent': _fit_groups(concurrent), } for kind, direction in (('fan_out', 'send'), ('fan_in', 'receive')): fanned: Dict[tuple, Dict[str, Dict[int, List[float]]]] = {} diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 944af86d87e9..ba1f57e05aae 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -66,15 +66,10 @@ receives the same raw samples:: fits['fan_in'][(0, (1, 2, 3, 4))]['inter_node'] # per-link cost while 1-4 send to 0 at once fits['receive'][(0, (1, 2, 3, 4))] # process 0's aggregate rate receiving from 1-4 -Five patterns are sampled at every size, 4 KiB to 256 MiB by default: +Four patterns are sampled at every size, 4 KiB to 256 MiB by default: - ``local``: a device-local copy on each process. - ``peer``: each ordered process pair alone (1 to 1). -- ``concurrent``: every process sends to ``process + shift`` and receives from - ``process - shift`` at once, so links are measured while shared. A process's - time covers both, so ``fit_links`` fits a path only from processes whose send - and receive both took it; with few processes per node, ``intra_node`` may have - no such process and no ``concurrent`` fit. - ``fan_out``: one root sends to ``width`` peers at once (1 to N). - ``fan_in``: ``width`` peers send to one root at once (N to 1), measuring receiver contention. @@ -101,15 +96,7 @@ sent and received bytes are priced against. A fan finishes when the busiest resource it crosses does: a peer's link, the root, or a link the peers share. Behind PCIe switches that depends on *which* peers share a process more than on how many, which is why fans are not keyed by -width alone. On one such 8-GPU node (256 MiB messages) the pairs ranged from -3.6 to 54 GB/s, depending on the sender and direction, and a root's fan-in -bandwidth at one width varied with its senders:: - - width min ~ max over roots (GB/s) spread - 1 7.0 ~ 53.9 7.7x - 2 12.6 ~ 55.2 4.4x - 4 18.7 ~ 37.3 2.0x - 7 16.4 ~ 23.6 1.4x +width alone. There, use ``peer_pairs``, label paths by topology, and choose the sender sets to measure with ``fan_peers``; to compare several sets of one width, calibrate @@ -126,8 +113,3 @@ 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. - -Calibrate on the group and communication settings the transfer will use: the -same links can measure very differently in another group. On two 8-GPU H20 -nodes, one NVLink pair moved 275 GB/s in an 8-process group but 54 GB/s in the -16-process group over RoCE. diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py index 7a49cfa11e27..494effe465ee 100644 --- a/tests/unit/checkpoint/test_affine_transfer_calibration.py +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -47,13 +47,6 @@ def seconds(path, size, slowdown=1.0): 'path': path_of(s, t), 'seconds': seconds(path_of(s, t), size) } for size in sizes for s in range(world) for t in range(world) if s != t], - 'concurrent': [{ - 'bytes': size, - 'shift': 1, - 'paths': [path_of(p, (p + 1) % world) for p in range(world)], - 'receive_paths': [path_of((p - 1) % world, p) for p in range(world)], - 'seconds_by_process': [seconds(INTER_NODE, size) for _ in range(world)], - } for size in sizes], **{ kind: [{ 'bytes': size, @@ -75,8 +68,7 @@ def test_fit_recovers_known_link_costs(): fits = fit_links(_synthetic_calibration(costs, sizes)) fan = (0, (1, )) # the synthetic fans have one peer, so a root moves one message per fan - checks = [(fits['local'][LOCAL], LOCAL), (fits['peer'][INTER_NODE], INTER_NODE), - (fits['concurrent'][INTER_NODE], INTER_NODE)] + checks = [(fits['local'][LOCAL], LOCAL), (fits['peer'][INTER_NODE], INTER_NODE)] checks += [(fits[kind][fan][INTER_NODE], INTER_NODE) for kind in ('fan_out', 'fan_in')] checks += [(fits[direction][fan], INTER_NODE) for direction in ('send', 'receive')] for fit, path in checks: @@ -143,34 +135,6 @@ def test_peer_pair_fits_keep_each_direction(): assert fits['peer_pairs'][pair]['bytes_per_second'] == pytest.approx(expected, rel=1e-6) -def test_concurrent_fits_ignore_processes_with_a_mixed_send_and_receive(): - """A process sending within its node while receiving across nodes waits on the slower link. - - Pooling that process's time under its send path would charge the inter-node cost to - ``intra_node``, as on two 8-GPU nodes over TCP (7.5 GB/s fitted vs 65 GB/s clean). - """ - sizes = [4096, 1 << 20, 1 << 24] - costs = {INTRA_NODE: (5e-5, 60e9), INTER_NODE: (1e-4, 5e9)} - calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), **costs}, sizes, world=4) - - def exact(path, size): - alpha, bandwidth = costs[path] - return [alpha + size / bandwidth] * 3 - - calibration['concurrent'] = [{ - 'bytes': size, - 'shift': 1, - 'paths': [INTRA_NODE, INTRA_NODE, INTER_NODE, INTER_NODE], - 'receive_paths': [INTRA_NODE, INTER_NODE, INTRA_NODE, INTER_NODE], - 'seconds_by_process': [exact(INTRA_NODE, size)] + [exact(INTER_NODE, size)] * 3, - } for size in sizes] - - fits = fit_links(calibration)['concurrent'] - for path, (alpha, bandwidth) in costs.items(): - assert fits[path]['alpha_seconds'] == pytest.approx(alpha, rel=1e-6) - assert fits[path]['bytes_per_second'] == pytest.approx(bandwidth, rel=1e-6) - - def test_fit_rejects_unknown_schema_and_single_size(): with pytest.raises(ValueError): fit_links({'schema': CALIBRATION_SCHEMA + 1}) @@ -200,20 +164,14 @@ def test_every_path_is_sampled_and_labeled(self): assert sorted((s['bytes'], s['from_process'], s['to_process']) for s in result['peer']) == sorted( (size, source, target) for size in sizes for source in range(world) for target in range(world) if source != target) - assert sorted((s['bytes'], s['shift']) for s in result['concurrent']) == sorted( - (size, shift) for size in sizes for shift in range(1, world)) for sample in result['local']: assert sample['path'] == LOCAL for sample in result['peer']: expected = INTRA_NODE if sample['from_process'] // 2 == sample['to_process'] // 2 else INTER_NODE assert sample['path'] == expected - for sample in result['concurrent']: - assert sample['paths'] == [node_path_of(2)(p, (p + sample['shift']) % world) for p in range(world)] - assert len(sample['seconds_by_process']) == world samples = [s['seconds'] for s in result['local'] + result['peer']] - samples += [seconds for s in result['concurrent'] for seconds in s['seconds_by_process']] for seconds in samples: assert len(seconds) == 3 assert all(value > 0 for value in seconds) @@ -232,7 +190,6 @@ def test_every_path_is_sampled_and_labeled(self): fits = fit_links(result) assert set(fits['local']) == {LOCAL} assert set(fits['peer']) == {INTRA_NODE, INTER_NODE} - assert set(fits['concurrent']) <= {INTRA_NODE, INTER_NODE} every_fan = {(root, tuple(sorted(set(range(world)) - {root}))) for root in range(world)} assert set(fits['fan_out']) == set(fits['fan_in']) == set(fits['send']) == set(fits['receive']) == every_fan for kind in ('fan_out', 'fan_in'): @@ -272,10 +229,6 @@ def test_fans_label_each_message_by_its_direction(self): for sample in result['fan_in']: root = sample['root'] assert sample['paths'] == [f'{peer}->{root}' for peer in sample['peers']] - for sample in result['concurrent']: - shift = sample['shift'] - assert sample['paths'] == [f'{p}->{(p + shift) % world}' for p in range(world)] - assert sample['receive_paths'] == [f'{(p - shift) % world}->{p}' for p in range(world)] widths = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=[2, 1, 2]) assert widths['fan_widths'] == [1, 2] From f27d566228932ffe92f809d2fa98cc91f3177637 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Fri, 6 Nov 2026 18:03:47 +0800 Subject: [PATCH 08/16] Measure pairs both ways and relays Some transfers have a process send and receive at the same time: colocated resharding, the all-gather stage of a relay, a pipelined relay, and moves between trainers of different DP sizes. peer samples gain both_ways. A two-way sample has a pair send to each other at once, with every other process idle, and gives one sample per direction labeled with that direction's path. fit_links keeps peer and peer_pairs one-way and adds peer_both_ways and peer_both_ways_pairs, so a policy can see what a link loses per direction when both directions are busy. The shift pattern returns as relay: every process receives from process - shift while sending to process + shift. Each sample is one process's own time, labeled with who it received from and sent to and with both the receive_path and the send_path, since that time covers both. fit_links fits relay per (receive_path, send_path), so no sample is filed under a path it only half used. Signed-off-by: Jin, Youzhi (cherry picked from commit d00ba3039a5bd0a2cd230d585e517ee5060f5e0d) --- .../checkpoint/affine_transfer_calibration.py | 111 ++++++++++++++---- docs/code-docs/source/affine-transfer.rst | 23 +++- .../test_affine_transfer_calibration.py | 91 ++++++++++++-- 3 files changed, 188 insertions(+), 37 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index fc9a3a6664df..cc60dcec2317 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -108,14 +108,21 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, fan_width: Optional[Union[int, Sequence[int]]] = None, fan_peers: Optional[Callable[[int, int], Sequence[int]]] = None, group: Optional[object] = None) -> Dict: - """Time local copies, every ordered process pair alone, and fans. + """Time local copies, process pairs one way and both ways, relays, and fans. Every process of ``group`` (the default group unless given) must call this. It returns the same dictionary on every process, with ``repeats`` samples per entry and no aggregation: - ``local``: a device-local copy on each process. - - ``peer``: each ordered pair with every other process idle, so that links through different - switches and sockets are each sampled. A sample is the slower of its two endpoints. + - ``peer``: each pair with every other process idle, so that links through different + switches and sockets are each sampled. A sample is the slower of its two endpoints. With + ``both_ways`` false, one ordered pair sends one way; with it true, the pair sends to each + other at once, as in colocated resharding, and each direction gets a sample labeled with + its own path, carrying the time until both endpoints had sent and received. + - ``relay``: every process receives from ``process - shift`` while sending to + ``process + shift``, for every shift, as the processes of a pipelined relay or an + all-gather do. A sample is one process's own time, labeled with the ``receive_path`` and + ``send_path`` it used, since that time covers both. - ``fan_out``: for every root and fan width, the root sends one message to each of its ``width`` peers at once (1 to N), while every other process is idle. - ``fan_in``: for every root and fan width, each of its peers sends one message to the root @@ -135,8 +142,9 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, behind one PCIe switch or across a socket; it must return the same peers on every process. Nodes are told apart by host name. - The pair sweep makes ``world_size * (world_size - 1) * len(sizes) * (warmup + repeats)`` - barriers, so keep ``sizes`` short on large jobs. Each process allocates + The pair and relay sweeps make + ``(1.5 * world_size + 1) * (world_size - 1) * len(sizes) * (warmup + repeats)`` barriers, + so keep ``sizes`` short on large jobs. Each process allocates ``(2 + max(widths)) * max(sizes)`` bytes of device memory at most, 2.25 GiB with the default width at 8 processes per node and 256 MiB messages. """ @@ -176,6 +184,8 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, device = torch.device(get_accelerator().current_device_name()) local_times: Dict[int, List[float]] = {} peer_times: Dict[tuple, List[float]] = {} + both_ways_times: Dict[tuple, List[float]] = {} + relay_times: Dict[tuple, List[float]] = {} fan_times: Dict[tuple, List[float]] = {} for size in sizes: send = torch.ones(size, dtype=torch.uint8, device=device) @@ -194,6 +204,21 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, if rank in (source, target): peer_times[(size, source, target)] = times[warmup:] + for first in range(world): + for second in range(first + 1, world): + other = {first: second, second: first}.get(rank) + to_processes = [other] if other is not None else [] + receives = [(recv, other)] if other is not None else [] + times = [_timed_exchange(send, to_processes, receives, group) for _ in range(warmup + repeats)] + if other is not None: + both_ways_times[(size, first, second)] = times[warmup:] + + for shift in range(1, world): + to_processes = [(rank + shift) % world] + receives = [(recv, (rank - shift) % world)] + times = [_timed_exchange(send, to_processes, receives, group) for _ in range(warmup + repeats)] + relay_times[(size, shift)] = times[warmup:] + for width in widths: for root in range(world): peers = peer_sets[(root, width)] @@ -214,9 +239,9 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, # Samples stay on their own process until every timing is done, so no collective runs inside a timed region. gathered = [None] * world - dist.all_gather_object(gathered, (local_times, peer_times, fan_times), group=group) + dist.all_gather_object(gathered, (local_times, peer_times, fan_times, both_ways_times, relay_times), group=group) - local, peer = [], [] + local, peer, relay = [], [], [] fans = {'fan_out': [], 'fan_in': []} for size in sizes: for process in range(world): @@ -231,9 +256,36 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'bytes': size, 'from_process': source, 'to_process': target, + 'both_ways': False, 'path': path_of(source, target), 'seconds': seconds }) + for first in range(world): + for second in range(first + 1, world): + key = (size, first, second) + seconds = [max(pair) for pair in zip(gathered[first][3][key], gathered[second][3][key])] + for source, target in ((first, second), (second, first)): + peer.append({ + 'bytes': size, + 'from_process': source, + 'to_process': target, + 'both_ways': True, + 'path': path_of(source, target), + 'seconds': list(seconds) + }) + for shift in range(1, world): + for process in range(world): + source = (process - shift) % world + target = (process + shift) % world + relay.append({ + 'bytes': size, + 'process': process, + 'from_process': source, + 'to_process': target, + 'receive_path': path_of(source, process), + 'send_path': path_of(process, target), + 'seconds': gathered[process][4][(size, shift)] + }) for width in widths: for root in range(world): peers = peer_sets[(root, width)] @@ -257,6 +309,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, 'warmup': warmup, 'local': local, 'peer': peer, + 'relay': relay, 'fan_widths': widths, 'fan_out': fans['fan_out'], 'fan_in': fans['fan_in'], @@ -304,10 +357,15 @@ def fit_links(calibration: Dict) -> Dict: single slow repeat does not move the line. Every fit holds ``alpha_seconds``, ``bytes_per_second``, ``max_relative_error`` and the ``sizes`` fitted. Returns: - - ``local`` and ``peer``: a fit per path label. - - ``peer_pairs``: a fit per ordered ``(from_process, to_process)`` pair, from the ``peer`` - samples. It keeps the sender and direction asymmetry that pooling by path label averages - away, as between cards behind PCIe switches. + - ``local`` and ``peer``: a fit per path label, ``peer`` from the one-way samples. + - ``peer_pairs``: a fit per ordered ``(from_process, to_process)`` pair, from the one-way + ``peer`` samples. It keeps the sender and direction asymmetry that pooling by path label + averages away, as between cards behind PCIe switches. + - ``peer_both_ways`` and ``peer_both_ways_pairs``: the same, from the ``both_ways`` samples, + i.e. the per-direction cost while the reverse direction is busy too. Compare with ``peer`` + and ``peer_pairs`` to see what a link loses when used both ways at once. + - ``relay``: a fit per ``(receive_path, send_path)``, from each process's time to receive one + message and send another at once while every process does the same. - ``fan_out`` and ``fan_in``: per fan, keyed by ``(root, peers)`` with the peers sorted, a fit per path label, from the peers' times, each under its own message's path. They give per-link cost while those peers share one sender or one receiver. @@ -328,19 +386,24 @@ def fit_links(calibration: Dict) -> Dict: for sample in calibration['local']: local.setdefault(sample['path'], {}).setdefault(sample['bytes'], []).extend(sample['seconds']) - peer: Dict[str, Dict[int, List[float]]] = {} - peer_pairs: Dict[Tuple[int, int], Dict[int, List[float]]] = {} - for sample in calibration['peer']: - peer.setdefault(sample['path'], {}).setdefault(sample['bytes'], []).extend(sample['seconds']) - pair = (sample['from_process'], sample['to_process']) - peer_pairs.setdefault(pair, {}).setdefault(sample['bytes'], []).extend(sample['seconds']) - - fits = { - 'schema': CALIBRATION_SCHEMA, - 'local': _fit_groups(local), - 'peer': _fit_groups(peer), - 'peer_pairs': _fit_groups(peer_pairs), - } + fits = {'schema': CALIBRATION_SCHEMA, 'local': _fit_groups(local)} + for both_ways, name in ((False, 'peer'), (True, 'peer_both_ways')): + by_path: Dict[str, Dict[int, List[float]]] = {} + by_pair: Dict[Tuple[int, int], Dict[int, List[float]]] = {} + for sample in calibration['peer']: + if sample['both_ways'] != both_ways: + continue + by_path.setdefault(sample['path'], {}).setdefault(sample['bytes'], []).extend(sample['seconds']) + pair = (sample['from_process'], sample['to_process']) + by_pair.setdefault(pair, {}).setdefault(sample['bytes'], []).extend(sample['seconds']) + fits[name] = _fit_groups(by_path) + fits[f'{name}_pairs'] = _fit_groups(by_pair) + + relay: Dict[Tuple[str, str], Dict[int, List[float]]] = {} + for sample in calibration['relay']: + paths = (sample['receive_path'], sample['send_path']) + relay.setdefault(paths, {}).setdefault(sample['bytes'], []).extend(sample['seconds']) + fits['relay'] = _fit_groups(relay) for kind, direction in (('fan_out', 'send'), ('fan_in', 'receive')): fanned: Dict[tuple, Dict[str, Dict[int, List[float]]]] = {} rooted: Dict[tuple, Dict[int, List[float]]] = {} diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index ba1f57e05aae..1edb4b218bd1 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -63,13 +63,22 @@ receives the same raw samples:: calibration = calibrate_links(path_of=node_path_of(processes_per_node=8), fan_width=[1, 2, 4, 7]) fits = fit_links(calibration) fits['peer_pairs'][(0, 1)] # the link from process 0 to process 1 alone + fits['peer_both_ways_pairs'][(0, 1)] # the same direction while 1 also sends to 0 + fits['relay'][('intra_node', 'inter_node')] # receiving within a node while sending out of it fits['fan_in'][(0, (1, 2, 3, 4))]['inter_node'] # per-link cost while 1-4 send to 0 at once fits['receive'][(0, (1, 2, 3, 4))] # process 0's aggregate rate receiving from 1-4 -Four patterns are sampled at every size, 4 KiB to 256 MiB by default: +Five patterns are sampled at every size, 4 KiB to 256 MiB by default: - ``local``: a device-local copy on each process. -- ``peer``: each ordered process pair alone (1 to 1). +- ``peer``: each process pair alone (1 to 1), one way, and both ways at once + (``both_ways``), as when a process sends and receives together in colocated + resharding. A two-way exchange gives a sample per direction, labelled with + that direction's path. +- ``relay``: every process receives from ``process - shift`` while sending to + ``process + shift``, for every shift, as in a pipelined relay or the + all-gather stage of one. Each sample is one process's time, labelled with + both its ``receive_path`` and its ``send_path``. - ``fan_out``: one root sends to ``width`` peers at once (1 to N). - ``fan_in``: ``width`` peers send to one root at once (N to 1), measuring receiver contention. @@ -87,7 +96,11 @@ labels only ``local`` and ``peer``; ``node_path_of`` splits ``peer`` into ``intra_node`` and ``inter_node``, and any callable can be used, for example one that tells NVLink from PCIe pairs. ``fit_links`` pools the samples per label and fits ``alpha + bytes / bandwidth`` to the median at each size, and -``peer_pairs`` fits each ordered pair alone. Fan fits are keyed by +``peer_pairs`` fits each ordered pair alone, both from one-way samples; +``peer_both_ways`` and ``peer_both_ways_pairs`` do the same for the two-way +samples, so comparing them with ``peer`` shows what a link loses per direction +when both directions are busy. ``relay`` is fitted per +``(receive_path, send_path)``. Fan fits are keyed by ``(root, peers)``, with the peers sorted; the width is ``len(peers)``. ``send`` and ``receive`` fit each root's own time against all the bytes it moved, giving the root's aggregate rate with those peers, which is what a plan's per-process @@ -107,8 +120,8 @@ fitting. On a uniform fabric, fits of one width can be pooled by Processes here are ranks of ``group``; pass the group the transfer runs on. A plan's source and target locations are mapped to processes by ``TransferEndpoints``, so translate through it before -joining a plan's messages with these labels. The pair sweep makes -``world_size * (world_size - 1)`` barriered samples per size and repeat, and each +joining a plan's messages with these labels. The pair and relay sweeps make +``(1.5 * world_size + 1) * (world_size - 1)`` barriered samples per size and repeat, and each 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 diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py index 494effe465ee..52a39d58f7ce 100644 --- a/tests/unit/checkpoint/test_affine_transfer_calibration.py +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -44,9 +44,19 @@ def seconds(path, size, slowdown=1.0): 'bytes': size, 'from_process': s, 'to_process': t, + 'both_ways': both_ways, 'path': path_of(s, t), 'seconds': seconds(path_of(s, t), size) - } for size in sizes for s in range(world) for t in range(world) if s != t], + } for size in sizes for s in range(world) for t in range(world) if s != t for both_ways in (False, True)], + 'relay': [{ + 'bytes': size, + 'process': p, + 'from_process': (p - shift) % world, + 'to_process': (p + shift) % world, + 'receive_path': path_of((p - shift) % world, p), + 'send_path': path_of(p, (p + shift) % world), + 'seconds': seconds(path_of(p, (p + shift) % world), size) + } for size in sizes for shift in range(1, world) for p in range(world)], **{ kind: [{ 'bytes': size, @@ -68,7 +78,8 @@ def test_fit_recovers_known_link_costs(): fits = fit_links(_synthetic_calibration(costs, sizes)) fan = (0, (1, )) # the synthetic fans have one peer, so a root moves one message per fan - checks = [(fits['local'][LOCAL], LOCAL), (fits['peer'][INTER_NODE], INTER_NODE)] + checks = [(fits['local'][LOCAL], LOCAL), (fits['peer'][INTER_NODE], INTER_NODE), + (fits['peer_both_ways'][INTER_NODE], INTER_NODE), (fits['relay'][(INTER_NODE, INTER_NODE)], INTER_NODE)] checks += [(fits[kind][fan][INTER_NODE], INTER_NODE) for kind in ('fan_out', 'fan_in')] checks += [(fits[direction][fan], INTER_NODE) for direction in ('send', 'receive')] for fit, path in checks: @@ -135,6 +146,49 @@ def test_peer_pair_fits_keep_each_direction(): assert fits['peer_pairs'][pair]['bytes_per_second'] == pytest.approx(expected, rel=1e-6) +def test_two_way_fits_are_kept_apart_from_one_way_fits(): + """Pooling two-way samples into ``peer`` would hide what a link loses per direction when both + directions are busy, which a policy pricing a colocated resharding needs. + """ + sizes = [4096, 1 << 20, 1 << 24] + alpha, one_way, both_ways = 1e-5, 20e9, 12e9 + calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), INTER_NODE: (alpha, one_way)}, sizes) + for sample in calibration['peer']: + if sample['both_ways']: + sample['seconds'] = [alpha + sample['bytes'] / both_ways] * 3 + + fits = fit_links(calibration) + assert fits['peer'][INTER_NODE]['bytes_per_second'] == pytest.approx(one_way, rel=1e-6) + assert fits['peer_both_ways'][INTER_NODE]['bytes_per_second'] == pytest.approx(both_ways, rel=1e-6) + for pair in ((0, 1), (1, 0)): + assert fits['peer_pairs'][pair]['bytes_per_second'] == pytest.approx(one_way, rel=1e-6) + assert fits['peer_both_ways_pairs'][pair]['bytes_per_second'] == pytest.approx(both_ways, rel=1e-6) + + +def test_relay_fits_are_keyed_by_receive_and_send_path(): + """A relay's time covers a receive and a send, so fitting it under either path alone would + mix processes that received over a slow link with ones that only sent over it. + """ + sizes = [4096, 1 << 20, 1 << 24] + alpha = 1e-5 + rate = {(INTRA_NODE, INTRA_NODE): 40e9, (INTRA_NODE, INTER_NODE): 15e9, (INTER_NODE, INTRA_NODE): 8e9} + calibration = _synthetic_calibration({LOCAL: (1e-6, 100e9), INTER_NODE: (alpha, 10e9)}, sizes) + calibration['relay'] = [{ + 'bytes': size, + 'process': 0, + 'from_process': 1, + 'to_process': 2, + 'receive_path': receive_path, + 'send_path': send_path, + 'seconds': [alpha + size / bandwidth] * 3, + } for size in sizes for (receive_path, send_path), bandwidth in rate.items()] + + fits = fit_links(calibration) + assert set(fits['relay']) == set(rate) + for paths, bandwidth in rate.items(): + assert fits['relay'][paths]['bytes_per_second'] == pytest.approx(bandwidth, rel=1e-6) + + def test_fit_rejects_unknown_schema_and_single_size(): with pytest.raises(ValueError): fit_links({'schema': CALIBRATION_SCHEMA + 1}) @@ -161,17 +215,28 @@ def test_every_path_is_sampled_and_labeled(self): assert result['world_size'] == world assert sorted((s['bytes'], s['process']) for s in result['local']) == sorted( (size, process) for size in sizes for process in range(world)) - assert sorted((s['bytes'], s['from_process'], s['to_process']) for s in result['peer']) == sorted( - (size, source, target) for size in sizes for source in range(world) for target in range(world) - if source != target) + every_ordered_pair = sorted((size, source, target) for size in sizes for source in range(world) + for target in range(world) if source != target) + for both_ways in (False, True): + assert sorted((s['bytes'], s['from_process'], s['to_process']) for s in result['peer'] + if s['both_ways'] == both_ways) == every_ordered_pair + assert sorted( + (s['bytes'], s['process'], s['from_process'], s['to_process']) for s in result['relay']) == sorted( + (size, process, (process - shift) % world, (process + shift) % world) for size in sizes + for shift in range(1, world) for process in range(world)) + + def path_between(source, target): + return INTRA_NODE if source // 2 == target // 2 else INTER_NODE for sample in result['local']: assert sample['path'] == LOCAL for sample in result['peer']: - expected = INTRA_NODE if sample['from_process'] // 2 == sample['to_process'] // 2 else INTER_NODE - assert sample['path'] == expected + assert sample['path'] == path_between(sample['from_process'], sample['to_process']) + for sample in result['relay']: + assert sample['receive_path'] == path_between(sample['from_process'], sample['process']) + assert sample['send_path'] == path_between(sample['process'], sample['to_process']) - samples = [s['seconds'] for s in result['local'] + result['peer']] + samples = [s['seconds'] for s in result['local'] + result['peer'] + result['relay']] for seconds in samples: assert len(seconds) == 3 assert all(value > 0 for value in seconds) @@ -190,6 +255,11 @@ def test_every_path_is_sampled_and_labeled(self): fits = fit_links(result) assert set(fits['local']) == {LOCAL} assert set(fits['peer']) == {INTRA_NODE, INTER_NODE} + assert set(fits['peer_both_ways']) == {INTRA_NODE, INTER_NODE} + assert set(fits['peer_both_ways_pairs']) == set(fits['peer_pairs']) + assert set(fits['relay']) == {(receive, send) + for receive in (INTRA_NODE, INTER_NODE) + for send in (INTRA_NODE, INTER_NODE)} - {(INTRA_NODE, INTRA_NODE)} every_fan = {(root, tuple(sorted(set(range(world)) - {root}))) for root in range(world)} assert set(fits['fan_out']) == set(fits['fan_in']) == set(fits['send']) == set(fits['receive']) == every_fan for kind in ('fan_out', 'fan_in'): @@ -229,6 +299,11 @@ def test_fans_label_each_message_by_its_direction(self): for sample in result['fan_in']: root = sample['root'] assert sample['paths'] == [f'{peer}->{root}' for peer in sample['peers']] + for sample in result['peer']: + assert sample['path'] == f'{sample["from_process"]}->{sample["to_process"]}' + for sample in result['relay']: + assert sample['receive_path'] == f'{sample["from_process"]}->{sample["process"]}' + assert sample['send_path'] == f'{sample["process"]}->{sample["to_process"]}' widths = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=[2, 1, 2]) assert widths['fan_widths'] == [1, 2] From 851ea68c11fded4abcbcb275698afab807954245 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Wed, 11 Nov 2026 15:11:03 +0000 Subject: [PATCH 09/16] Describe two-way peer fits as pair completion times Both directions of a both_ways sample carry the pair's completion time, so peer_both_ways_pairs[(a, b)] equals peer_both_ways_pairs[(b, a)]. Say so in fit_links and the docs, and compare against the slower of the two one-way fits. Keep the external-group executor test's assertion to one-way peer samples, since calibrate_links now also returns both_ways samples. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi (cherry picked from commit 57a47ff13126e1171a26c3968a39e857ffc465ec) --- deepspeed/checkpoint/affine_transfer_calibration.py | 8 +++++--- docs/code-docs/source/affine-transfer.rst | 8 +++++--- .../test_affine_transfer_executor_external_group.py | 3 ++- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index cc60dcec2317..b75994cd7608 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -361,9 +361,11 @@ def fit_links(calibration: Dict) -> Dict: - ``peer_pairs``: a fit per ordered ``(from_process, to_process)`` pair, from the one-way ``peer`` samples. It keeps the sender and direction asymmetry that pooling by path label averages away, as between cards behind PCIe switches. - - ``peer_both_ways`` and ``peer_both_ways_pairs``: the same, from the ``both_ways`` samples, - i.e. the per-direction cost while the reverse direction is busy too. Compare with ``peer`` - and ``peer_pairs`` to see what a link loses when used both ways at once. + - ``peer_both_ways`` and ``peer_both_ways_pairs``: the same, from the ``both_ways`` samples. + Both directions of a two-way sample carry the pair's completion time, so + ``peer_both_ways_pairs[(a, b)]`` equals ``peer_both_ways_pairs[(b, a)]``. To see what a + link loses when used both ways at once, compare it with the slower of the two one-way + ``peer_pairs`` fits, not with each direction's own. - ``relay``: a fit per ``(receive_path, send_path)``, from each process's time to receive one message and send another at once while every process does the same. - ``fan_out`` and ``fan_in``: per fan, keyed by ``(root, peers)`` with the peers sorted, a fit diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 1edb4b218bd1..b9079cd53070 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -63,7 +63,7 @@ receives the same raw samples:: calibration = calibrate_links(path_of=node_path_of(processes_per_node=8), fan_width=[1, 2, 4, 7]) fits = fit_links(calibration) fits['peer_pairs'][(0, 1)] # the link from process 0 to process 1 alone - fits['peer_both_ways_pairs'][(0, 1)] # the same direction while 1 also sends to 0 + fits['peer_both_ways_pairs'][(0, 1)] # the pair's completion time while 0 and 1 send to each other fits['relay'][('intra_node', 'inter_node')] # receiving within a node while sending out of it fits['fan_in'][(0, (1, 2, 3, 4))]['inter_node'] # per-link cost while 1-4 send to 0 at once fits['receive'][(0, (1, 2, 3, 4))] # process 0's aggregate rate receiving from 1-4 @@ -98,8 +98,10 @@ that tells NVLink from PCIe pairs. ``fit_links`` pools the samples per label and fits ``alpha + bytes / bandwidth`` to the median at each size, and ``peer_pairs`` fits each ordered pair alone, both from one-way samples; ``peer_both_ways`` and ``peer_both_ways_pairs`` do the same for the two-way -samples, so comparing them with ``peer`` shows what a link loses per direction -when both directions are busy. ``relay`` is fitted per +samples. Both directions of a two-way sample carry the pair's completion time, +so ``(a, b)`` and ``(b, a)`` fit the same; comparing them with the slower of the +two one-way ``peer_pairs`` fits shows what a link loses when both directions are +busy. ``relay`` is fitted per ``(receive_path, send_path)``. Fan fits are keyed by ``(root, peers)``, with the peers sorted; the width is ``len(peers)``. ``send`` and ``receive`` fit each root's own time against all the bytes it moved, giving diff --git a/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py b/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py index 8f7bf4a845ad..b9c81b1efff5 100644 --- a/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py +++ b/tests/unit/checkpoint/test_affine_transfer_executor_external_group.py @@ -66,7 +66,8 @@ def _worker(rank, port, tmp): del store assert not mismatched, mismatched assert calibration['world_size'] == 2 - assert sorted((sample['from_process'], sample['to_process']) for sample in calibration['peer']) == [(0, 1), (1, 0)] + assert sorted((sample['from_process'], sample['to_process']) for sample in calibration['peer'] + if not sample['both_ways']) == [(0, 1), (1, 0)] @pytest.mark.skipif(get_accelerator().device_name() != 'cpu', From d46533428fcb0e771eacc7f9f78e6bfbfb6d5442 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 12 Nov 2026 23:16:24 +0000 Subject: [PATCH 10/16] Label local samples by path_of and record the measured group's backend A path_of that tells local devices apart, as on a host with unlike accelerators, had every local copy labeled 'local' and pooled into one fit. Local samples now carry path_of(process, process) like every other sample. communication_backend recorded the accelerator's preferred backend, which need not be the one the measured group runs on. It now comes from the group itself, through a new deepspeed.comm.get_backend that wraps the backend's existing get_backend. Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/affine_transfer_calibration.py | 11 ++++++++--- deepspeed/comm/comm.py | 8 ++++++++ docs/code-docs/source/affine-transfer.rst | 2 +- .../checkpoint/test_affine_transfer_calibration.py | 11 +++++++++++ 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index b75994cd7608..f1a5ff950187 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -113,7 +113,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, Every process of ``group`` (the default group unless given) must call this. It returns the same dictionary on every process, with ``repeats`` samples per entry and no aggregation: - - ``local``: a device-local copy on each process. + - ``local``: a device-local copy on each process, labeled ``path_of(process, process)``. - ``peer``: each pair with every other process idle, so that links through different switches and sockets are each sampled. A sample is the slower of its two endpoints. With ``both_ways`` false, one ordered pair sends one way; with it true, the pair sends to each @@ -245,7 +245,12 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, fans = {'fan_out': [], 'fan_in': []} for size in sizes: for process in range(world): - local.append({'bytes': size, 'process': process, 'path': LOCAL, 'seconds': gathered[process][0][size]}) + local.append({ + 'bytes': size, + 'process': process, + 'path': path_of(process, process), + 'seconds': gathered[process][0][size] + }) for source in range(world): for target in range(world): if source == target: @@ -304,7 +309,7 @@ def calibrate_links(sizes: Sequence[int] = DEFAULT_SIZES, return { 'schema': CALIBRATION_SCHEMA, 'world_size': world, - 'communication_backend': get_accelerator().communication_backend_name(), + 'communication_backend': dist.get_backend(group), 'repeats': repeats, 'warmup': warmup, 'local': local, diff --git a/deepspeed/comm/comm.py b/deepspeed/comm/comm.py index 48d563b680d0..fd6180817739 100755 --- a/deepspeed/comm/comm.py +++ b/deepspeed/comm/comm.py @@ -786,6 +786,14 @@ def get_global_rank(group: Optional[Any] = None, group_rank: int = 0) -> int: return cdb.get_global_rank(group, group_rank) +def get_backend(group: Optional[Any] = None) -> str: + """Name of the backend that runs ``group``'s collectives, the default group's if none is given.""" + global cdb + assert cdb is not None and cdb.is_initialized( + ), 'DeepSpeed backend not set, please initialize it using init_process_group()' + return cdb.get_backend(group) + + def get_all_ranks_from_group(group=None): global cdb assert cdb is not None and cdb.is_initialized( diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index b9079cd53070..1b5c20d6ce14 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -70,7 +70,7 @@ receives the same raw samples:: Five patterns are sampled at every size, 4 KiB to 256 MiB by default: -- ``local``: a device-local copy on each process. +- ``local``: a device-local copy on each process, labeled ``path_of(process, process)``. - ``peer``: each process pair alone (1 to 1), one way, and both ways at once (``both_ways``), as when a process sends and receives together in colocated resharding. A two-way exchange gives a sample per direction, labelled with diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py index 52a39d58f7ce..6d62407f0e1f 100644 --- a/tests/unit/checkpoint/test_affine_transfer_calibration.py +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -265,6 +265,14 @@ def path_between(source, target): for kind in ('fan_out', 'fan_in'): assert all(set(by_path) == {INTRA_NODE, INTER_NODE} for by_path in fits[kind].values()) + def test_records_the_backend_it_measured(self): + get_accelerator().set_device(int(os.environ.get('LOCAL_RANK', dist.get_rank()))) + measured = get_accelerator().communication_backend_name() + # The accelerator's preferred backend is not necessarily the one the group runs on. + with patch.object(get_accelerator(), 'communication_backend_name', return_value='not-the-group-backend'): + result = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=0) + assert result['communication_backend'] == measured + @pytest.mark.parametrize('processes_per_node', [1, 2]) def test_default_fans_stay_within_a_node(self, processes_per_node): get_accelerator().set_device(int(os.environ.get('LOCAL_RANK', dist.get_rank()))) @@ -304,6 +312,9 @@ def test_fans_label_each_message_by_its_direction(self): for sample in result['relay']: assert sample['receive_path'] == f'{sample["from_process"]}->{sample["process"]}' assert sample['send_path'] == f'{sample["process"]}->{sample["to_process"]}' + # A path_of that tells devices apart must not have their local copies pooled into one fit. + for sample in result['local']: + assert sample['path'] == f'{sample["process"]}->{sample["process"]}' widths = calibrate_links(sizes=[4096], repeats=1, warmup=0, fan_width=[2, 1, 2]) assert widths['fan_widths'] == [1, 2] From f678c9d49c2f9d699f60ba12fdba425d79fa9178 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Fri, 13 Nov 2026 23:13:44 +0000 Subject: [PATCH 11/16] Bump the calibration schema for two-way and relay samples fit_links reads peer samples' both_ways and the raw relay list. A raw calibration saved before those existed still claimed schema 1, so it passed the schema check and then raised KeyError. Schema 2 makes fit_links refuse it with a clear error instead. Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/affine_transfer_calibration.py | 3 ++- tests/unit/checkpoint/test_affine_transfer_calibration.py | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/deepspeed/checkpoint/affine_transfer_calibration.py b/deepspeed/checkpoint/affine_transfer_calibration.py index f1a5ff950187..ce1d3e2f6440 100644 --- a/deepspeed/checkpoint/affine_transfer_calibration.py +++ b/deepspeed/checkpoint/affine_transfer_calibration.py @@ -32,7 +32,8 @@ 'node_path_of', 'calibrate_links', 'fit_links' ] -CALIBRATION_SCHEMA = 1 +# 2: peer samples carry both_ways, and the raw result has relay samples. +CALIBRATION_SCHEMA = 2 # 4 KiB to 256 MiB: small messages fix the per-message cost, and fast links reach line rate only # from about 64 MiB up. diff --git a/tests/unit/checkpoint/test_affine_transfer_calibration.py b/tests/unit/checkpoint/test_affine_transfer_calibration.py index 6d62407f0e1f..d9006c6ac5d6 100644 --- a/tests/unit/checkpoint/test_affine_transfer_calibration.py +++ b/tests/unit/checkpoint/test_affine_transfer_calibration.py @@ -192,6 +192,13 @@ def test_relay_fits_are_keyed_by_receive_and_send_path(): def test_fit_rejects_unknown_schema_and_single_size(): with pytest.raises(ValueError): fit_links({'schema': CALIBRATION_SCHEMA + 1}) + # A raw result saved before two-way and relay samples existed must be refused, not misread. + legacy = _synthetic_calibration({LOCAL: (1e-6, 1e9), INTER_NODE: (1e-6, 1e9)}, [4096, 1 << 20]) + legacy['schema'] = 1 + legacy['peer'] = [{k: v for k, v in sample.items() if k != 'both_ways'} for sample in legacy['peer']] + del legacy['relay'] + with pytest.raises(ValueError): + fit_links(legacy) with pytest.raises(ValueError): fit_links(_synthetic_calibration({LOCAL: (1e-6, 1e9), INTER_NODE: (1e-6, 1e9)}, [4096])) From be0485d35a31568e95fe5f8be17b450c6bbe0a42 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Sat, 31 Oct 2026 13:18:15 +0000 Subject: [PATCH 12/16] Analyze affine transfer batches before execution Add analyze_transfers/expected_stats/report_to_dict: a dry-run report of an execute_transfers batch (volume, size distributions, rounds under a StagingBudget, per-process load and staging, per-pair and per-path bytes), labelled with the same path_of hook as calibrate_links. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Jin, Youzhi (cherry picked from commit 1ac1de1b27acf819af8c1f9490cf8b668478ed0b) --- .../checkpoint/affine_transfer_analysis.py | 315 ++++++++++++++++++ docs/code-docs/source/affine-transfer.rst | 30 ++ .../test_affine_transfer_analysis.py | 127 +++++++ 3 files changed, 472 insertions(+) create mode 100644 deepspeed/checkpoint/affine_transfer_analysis.py create mode 100644 tests/unit/checkpoint/test_affine_transfer_analysis.py diff --git a/deepspeed/checkpoint/affine_transfer_analysis.py b/deepspeed/checkpoint/affine_transfer_analysis.py new file mode 100644 index 000000000000..224eb5491aca --- /dev/null +++ b/deepspeed/checkpoint/affine_transfer_analysis.py @@ -0,0 +1,315 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""Describe what a transfer batch will do before it runs, without deciding anything. + +The planner chooses segments and replicas, and the executor chooses chunks, rounds and staging. +This module only reads those outputs. It reports volume, granularity, per-process send and receive +load, the executor's schedule and staging under a ``StagingBudget``, and bytes per path class, so +that a plan can be compared with another, or priced with ``fit_links`` results, before it runs. + +Nothing here feeds back into a plan, ranks alternatives or models time. Processes are those of +``TransferEndpoints``; messages are labelled with the same ``path_of(from_process, to_process)`` +hook as ``calibrate_links``. +""" + +import json +import math +from dataclasses import asdict, dataclass, field +from typing import Callable, Dict, Optional, Sequence, Tuple + +from .affine_transfer import TransferPlan +from .affine_transfer_calibration import LOCAL, default_path_of +from .affine_transfer_executor import StagingBudget, TransferEndpoints, _packed_rounds, build_operations + +__all__ = [ + 'TransferMessage', 'ProcessReport', 'PlanReport', 'analyze_transfers', 'expected_stats', 'report_to_dict', + 'distribution' +] + +REPORT_SCHEMA = 1 + + +@dataclass(frozen=True) +class TransferMessage: + """One point-to-point payload the executor posts in one round.""" + round: int + from_process: int + to_process: int + nbytes: int + entries: int + packed_on_send: bool + unpacked_on_receive: bool + path: str + + +@dataclass(frozen=True) +class ProcessReport: + process: int + sent_bytes: int = 0 + received_bytes: int = 0 + local_copy_bytes: int = 0 + send_messages: int = 0 + receive_messages: int = 0 + rounds: int = 0 + send_peers: int = 0 + receive_peers: int = 0 + pack_bytes: int = 0 + unpack_bytes: int = 0 + staging_bytes: int = 0 + + +@dataclass(frozen=True) +class PlanReport: + element_size: int + bytes_per_peer: int + parameters: int + segments: int + chunks: int + logical_bytes: int + moved_bytes: int + local_copy_bytes: int + remote_bytes: int + rounds: int + processes: Tuple[ProcessReport, ...] + messages: Tuple[TransferMessage, ...] + segment_bytes: Tuple[int, ...] + chunk_bytes: Tuple[int, ...] + planner: Dict[str, int] = field(default_factory=dict) + + def process(self, process: int) -> ProcessReport: + for entry in self.processes: + if entry.process == process: + return entry + return ProcessReport(process) + + +def _is_packed(shape: Sequence[int], strides: Sequence[int]) -> bool: + """Whether a strided region is one run of elements in row-major order, as torch judges it.""" + expected = 1 + for extent, stride in zip(reversed(tuple(shape)), reversed(tuple(strides))): + if extent == 1: + continue + if stride != expected: + return False + expected *= extent + return True + + +def _chunk_is_packed(operation, source_side: bool) -> bool: + strides = operation.segment.source_strides if source_side else operation.segment.target_strides + return _is_packed(operation.chunk_shape, strides) + + +def analyze_transfers(plans: Sequence[TransferPlan], + endpoints: TransferEndpoints, + element_size: int, + budget: StagingBudget = StagingBudget(), + path_of: Optional[Callable[[int, int], str]] = None) -> PlanReport: + """Report one ``execute_transfers`` batch, given its plans in request order. + + The schedule comes from the executor's own ``build_operations`` and round packing, so the + counts match what each process will return in ``TransferStats``. + """ + if path_of is None: + path_of = default_path_of + + indexed = [] + schedules = {} + for item, plan in enumerate(plans): + identity = id(plan) + if identity not in schedules: + schedules[identity] = build_operations(plan, endpoints, budget, element_size) + indexed.extend((item, operation) for operation in schedules[identity]) + + local_copy = {} + by_pair: Dict[Tuple[int, int], list] = {} + for item, operation in indexed: + if operation.from_process == operation.to_process: + process = operation.from_process + local_copy[process] = local_copy.get(process, 0) + operation.payload_bytes + else: + pair = (operation.from_process, operation.to_process) + by_pair.setdefault(pair, []).append((item, operation)) + + max_elements = budget.bytes_per_peer // element_size + messages = [] + sent, received, send_count, receive_count = {}, {}, {}, {} + pack, unpack, send_peers, receive_peers = {}, {}, {}, {} + rounds_of, staging = {}, {} + for pair in sorted(by_pair): + from_process, to_process = pair + rounds = _packed_rounds(by_pair[pair], max_elements) + largest_packed_send = 0 + largest_unpacked_receive = 0 + for round_index, (entries, count) in enumerate(rounds): + nbytes = count * element_size + # The executor sends a view only when the round holds one packed region; otherwise it stages. + single = len(entries) == 1 + send_direct = single and _chunk_is_packed(entries[0][1], source_side=True) + receive_direct = single and _chunk_is_packed(entries[0][1], source_side=False) + messages.append( + TransferMessage(round=round_index, + from_process=from_process, + to_process=to_process, + nbytes=nbytes, + entries=len(entries), + packed_on_send=not send_direct, + unpacked_on_receive=not receive_direct, + path=path_of(from_process, to_process))) + if not send_direct: + pack[from_process] = pack.get(from_process, 0) + nbytes + largest_packed_send = max(largest_packed_send, nbytes) + if not receive_direct: + unpack[to_process] = unpack.get(to_process, 0) + nbytes + largest_unpacked_receive = max(largest_unpacked_receive, nbytes) + sent[from_process] = sent.get(from_process, 0) + nbytes + received[to_process] = received.get(to_process, 0) + nbytes + send_count[from_process] = send_count.get(from_process, 0) + len(rounds) + receive_count[to_process] = receive_count.get(to_process, 0) + len(rounds) + send_peers[from_process] = send_peers.get(from_process, 0) + 1 + receive_peers[to_process] = receive_peers.get(to_process, 0) + 1 + # A process runs as many rounds as its busiest peer queue, in either direction. + rounds_of[from_process] = max(rounds_of.get(from_process, 0), len(rounds)) + rounds_of[to_process] = max(rounds_of.get(to_process, 0), len(rounds)) + # One arena per peer and direction, sized by its largest staged round. + staging[from_process] = staging.get(from_process, 0) + largest_packed_send + staging[to_process] = staging.get(to_process, 0) + largest_unpacked_receive + + processes = set(endpoints.source.values()) | set(endpoints.target.values()) + process_reports = tuple( + ProcessReport(process=process, + sent_bytes=sent.get(process, 0), + received_bytes=received.get(process, 0), + local_copy_bytes=local_copy.get(process, 0), + send_messages=send_count.get(process, 0), + receive_messages=receive_count.get(process, 0), + rounds=rounds_of.get(process, 0), + send_peers=send_peers.get(process, 0), + receive_peers=receive_peers.get(process, 0), + pack_bytes=pack.get(process, 0), + unpack_bytes=unpack.get(process, 0), + staging_bytes=staging.get(process, 0)) for process in sorted(processes)) + + planner = {} + for plan in plans: + for name, value in asdict(plan.statistics).items(): + planner[name] = planner.get(name, 0) + value + + segment_bytes = tuple(segment.numel * element_size for plan in plans for segment in plan.segments) + remote_bytes = sum(sent.values()) + local_bytes = sum(local_copy.values()) + return PlanReport(element_size=element_size, + bytes_per_peer=budget.bytes_per_peer, + parameters=len(plans), + segments=len(segment_bytes), + chunks=len(indexed), + logical_bytes=sum(math.prod(plan.logical_shape) * element_size for plan in plans), + moved_bytes=sum(segment_bytes), + local_copy_bytes=local_bytes, + remote_bytes=remote_bytes, + rounds=max(rounds_of.values(), default=0), + processes=process_reports, + messages=tuple(messages), + segment_bytes=segment_bytes, + chunk_bytes=tuple(operation.payload_bytes for _, operation in indexed), + planner=planner) + + +def expected_stats(report: PlanReport, process: int) -> Dict[str, int]: + """The ``TransferStats`` fields ``process`` should return for the analyzed batch.""" + entry = report.process(process) + return { + 'segments': report.segments, + 'chunks': report.chunks, + 'rounds': entry.rounds, + 'local_copy_bytes': entry.local_copy_bytes, + 'sent_bytes': entry.sent_bytes, + 'received_bytes': entry.received_bytes, + } + + +def distribution(values: Sequence[float]) -> Dict[str, float]: + """Count, sum and order statistics, with nearest-rank percentiles.""" + ordered = sorted(values) + if not ordered: + return {'count': 0, 'sum': 0} + + def percentile(fraction): + index = max(0, math.ceil(fraction * len(ordered)) - 1) + return ordered[index] + + return { + 'count': len(ordered), + 'sum': sum(ordered), + 'min': ordered[0], + 'p50': percentile(0.5), + 'p90': percentile(0.9), + 'max': ordered[-1], + 'mean': sum(ordered) / len(ordered), + } + + +def _imbalance(values: Sequence[int]) -> Optional[float]: + """Busiest over mean; 1.0 is perfectly even. None when nothing moves.""" + total = sum(values) + if total == 0: + return None + return max(values) / (total / len(values)) + + +def report_to_dict(report: PlanReport, include_messages: bool = False) -> Dict[str, object]: + """A JSON-ready summary; ``include_messages`` adds the full per-round message list.""" + pairs: Dict[str, Dict[str, int]] = {} + paths: Dict[str, Dict[str, int]] = {} + for message in report.messages: + pair = pairs.setdefault(f'{message.from_process}->{message.to_process}', {'messages': 0, 'bytes': 0}) + pair['messages'] += 1 + pair['bytes'] += message.nbytes + path = paths.setdefault(message.path, {'messages': 0, 'bytes': 0}) + path['messages'] += 1 + path['bytes'] += message.nbytes + local_bytes = report.local_copy_bytes + if local_bytes: + local = paths.setdefault(LOCAL, {'messages': 0, 'bytes': 0}) + local['bytes'] += local_bytes + + sent = [entry.sent_bytes for entry in report.processes] + received = [entry.received_bytes for entry in report.processes] + staged_messages = sum(1 for message in report.messages if message.packed_on_send or message.unpacked_on_receive) + summary = { + 'schema': REPORT_SCHEMA, + 'element_size': report.element_size, + 'bytes_per_peer': report.bytes_per_peer, + 'volume': { + 'parameters': report.parameters, + 'logical_bytes': report.logical_bytes, + 'moved_bytes': report.moved_bytes, + 'local_copy_bytes': report.local_copy_bytes, + 'remote_bytes': report.remote_bytes, + }, + 'granularity': { + 'segments': distribution(report.segment_bytes), + 'chunks': distribution(report.chunk_bytes), + 'messages': distribution([message.nbytes for message in report.messages]), + 'staged_messages': staged_messages, + 'pack_bytes': sum(entry.pack_bytes for entry in report.processes), + 'unpack_bytes': sum(entry.unpack_bytes for entry in report.processes), + }, + 'schedule': { + 'rounds': report.rounds, + 'staging_bytes_max': max((entry.staging_bytes for entry in report.processes), default=0), + }, + 'balance': { + 'sent_imbalance': _imbalance(sent), + 'received_imbalance': _imbalance(received), + 'active_pairs': len(pairs), + }, + 'processes': [asdict(entry) for entry in report.processes], + 'pairs': pairs, + 'paths': paths, + 'planner': report.planner, + } + if include_messages: + summary['messages'] = [asdict(message) for message in report.messages] + # Round-trip once so callers get exactly what json.dump would write (string keys, plain types). + return json.loads(json.dumps(summary)) diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 317425bcbb79..0a825828eddb 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -189,3 +189,33 @@ 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. + +Analyzing a plan +---------------- + +``analyze_transfers`` reports what an ``execute_transfers`` batch will do, +without running it or communicating. It takes the same plans, endpoints, +element size and ``StagingBudget`` and replays the executor's own operation +building and round packing, so it can be called on one process, for example to +compare two candidate plans or budgets before choosing one:: + + from deepspeed.checkpoint.affine_transfer_analysis import (analyze_transfers, expected_stats, + report_to_dict) + from deepspeed.checkpoint.affine_transfer_calibration import node_path_of + from deepspeed.checkpoint.affine_transfer_executor import StagingBudget + + report = analyze_transfers(plans, endpoints, element_size=2, budget=StagingBudget(256 << 20), + path_of=node_path_of(processes_per_node=8)) + summary = report_to_dict(report) + +The report covers volume (logical, moved, local-copy and remote bytes), the +distribution of segment, chunk and message sizes, the number of rounds, every +process's sent and received bytes, peers, messages, pack and unpack bytes and +staging arena size, and bytes per process pair and per path label. Each message +is labelled with ``path_of(from_process, to_process)``, the same hook +``calibrate_links`` uses, so per-path totals can be priced with ``fit_links`` +results. ``expected_stats(report, process)`` gives the ``TransferStats`` that +process will return, which makes the prediction checkable after a run. + +The report only describes a plan. It does not choose replicas, rank plans or +estimate time; those decisions belong to the caller. diff --git a/tests/unit/checkpoint/test_affine_transfer_analysis.py b/tests/unit/checkpoint/test_affine_transfer_analysis.py new file mode 100644 index 000000000000..65901a47f1b5 --- /dev/null +++ b/tests/unit/checkpoint/test_affine_transfer_analysis.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +"""Transfer analysis is checked against hand-derived counts and against the executor's own stats.""" + +import math +import os +from dataclasses import asdict + +import pytest +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_transfer import plan_transfer +from deepspeed.checkpoint.affine_transfer_analysis import analyze_transfers, expected_stats, report_to_dict +from deepspeed.checkpoint.affine_transfer_calibration import INTRA_NODE, LOCAL, node_path_of +from deepspeed.checkpoint.affine_transfer_executor import (StagingBudget, TransferEndpoints, TransferRequest, + execute_transfers) +from unit.common import DistributedTest + +FP32 = 4 + + +def _uneven_handoff(): + """8 elements, sources [4, 4] on processes 0-1, targets [2, 6] on processes 2-3. + + By hand: target 0 takes source 0[0:2]; target 1 takes source 0[2:4] and source 1[0:4]. + With 2 elements per round, 1->3 needs two rounds and every other pair one. + """ + source = contiguous_split_map((8, ), [4, 4], 0) + target = contiguous_split_map((8, ), [2, 6], 0) + endpoints = TransferEndpoints(source={0: 0, 1: 1}, target={0: 2, 1: 3}) + return plan_transfer(target, source), endpoints + + +def test_volume_rounds_and_messages_match_hand_count(): + plan, endpoints = _uneven_handoff() + report = analyze_transfers([plan], endpoints, FP32, StagingBudget(2 * FP32)) + + assert (report.segments, report.chunks, report.rounds) == (3, 4, 2) + assert (report.moved_bytes, report.remote_bytes, report.local_copy_bytes) == (32, 32, 0) + by_process = {entry.process: entry for entry in report.processes} + assert (by_process[0].sent_bytes, by_process[0].send_messages, by_process[0].rounds) == (16, 2, 1) + assert (by_process[1].sent_bytes, by_process[1].send_messages, by_process[1].rounds) == (16, 2, 2) + assert (by_process[2].received_bytes, by_process[2].rounds) == (8, 1) + assert (by_process[3].received_bytes, by_process[3].receive_messages, by_process[3].receive_peers) == (24, 3, 2) + # One-dimensional slices are packed on both sides, so nothing is staged. + assert sum(entry.pack_bytes + entry.unpack_bytes + entry.staging_bytes for entry in report.processes) == 0 + + +def test_strided_source_is_packed_before_sending(): + """Rows to columns on two processes: each sends a 2x2 block that is strided in its source.""" + source = contiguous_split_map((4, 4), [2, 2], 0) + target = contiguous_split_map((4, 4), [2, 2], 1) + endpoints = TransferEndpoints(source={0: 0, 1: 1}, target={0: 0, 1: 1}) + report = analyze_transfers([plan_transfer(target, source)], endpoints, FP32) + + assert (report.local_copy_bytes, report.remote_bytes) == (32, 32) + for entry in report.processes: + assert (entry.pack_bytes, entry.unpack_bytes, entry.staging_bytes) == (16, 0, 16) + + +def test_shared_plan_counts_once_per_request(): + plan, endpoints = _uneven_handoff() + single = analyze_transfers([plan], endpoints, FP32, StagingBudget(2 * FP32)) + double = analyze_transfers([plan, plan], endpoints, FP32, StagingBudget(2 * FP32)) + assert (double.segments, double.chunks, double.remote_bytes) == (6, 8, 64) + # A larger batch packs into the same per-peer arenas, so it cannot need fewer rounds. + assert double.rounds >= single.rounds + + +def test_report_is_json_ready_and_labels_paths(): + """Rows to columns on two processes of one node: half is copied locally, half crosses the node.""" + source = contiguous_split_map((4, 4), [2, 2], 0) + target = contiguous_split_map((4, 4), [2, 2], 1) + endpoints = TransferEndpoints(source={0: 0, 1: 1}, target={0: 0, 1: 1}) + report = analyze_transfers([plan_transfer(target, source)], endpoints, FP32, path_of=node_path_of(2)) + summary = report_to_dict(report, include_messages=True) + assert summary['paths'] == {INTRA_NODE: {'messages': 2, 'bytes': 32}, LOCAL: {'messages': 0, 'bytes': 32}} + assert summary['pairs'] == {'0->1': {'messages': 1, 'bytes': 16}, '1->0': {'messages': 1, 'bytes': 16}} + assert len(summary['messages']) == len(report.messages) == 2 + + +def _join_transfer_group(): + if not dist.is_initialized(): + dist.init_distributed(dist_backend=get_accelerator().communication_backend_name(), init_method='env://') + local_rank = int(os.environ.get('LOCAL_RANK', dist.get_rank())) + get_accelerator().set_device(local_rank) + return torch.device(get_accelerator().current_device_name()) + + +@pytest.mark.skipif(get_accelerator().device_count() < 4, reason='requires four visible accelerator devices') +class TestPredictionMatchesExecutor(DistributedTest): + world_size = 4 + + @pytest.mark.parametrize('peer_elements', [3, 64]) + def test_expected_stats_equal_executor_stats(self, peer_elements): + """A batch of a strided and a replicated parameter, so staging, chunking and local copies all occur.""" + device = _join_transfer_group() + rank = dist.get_rank() + dtype = torch.float32 + endpoints = TransferEndpoints(source={0: 0, 1: 1, 2: 2, 3: 3}, target={0: 3, 1: 2, 2: 1, 3: 0}) + cases = [ + (contiguous_split_map((8, 8), [2, 2, 2, 2], 0), contiguous_split_map((8, 8), [2, 2, 2, 2], 1)), + (replicated_map((8, 4), 4), contiguous_split_map((8, 4), [1, 3, 2, 2], 0)), + ] + requests, plans = [], [] + for index, (source, target) in enumerate(cases): + numel = math.prod(source.logical_shape) + full = torch.arange(numel, dtype=dtype, device=device).reshape(source.logical_shape) + sources = { + location: source.extract(full, location).contiguous() + for location, process in endpoints.source.items() if process == rank + } + targets = { + location: torch.full(shape, float('nan'), dtype=dtype, device=device) + for location, shape in target.shard_shapes.items() if endpoints.target[location] == rank + } + plan = plan_transfer(target, source) + plans.append(plan) + requests.append(TransferRequest(f'param-{index}', plan, sources, targets)) + + budget = StagingBudget(peer_elements * 4) + stats = execute_transfers(requests, endpoints, dtype, budget) + report = analyze_transfers(plans, endpoints, 4, budget) + assert asdict(stats) == expected_stats(report, rank) From 1dfbbc4c2ee821c0b3233a749cbcb7c48b443553 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Fri, 13 Nov 2026 23:32:04 +0000 Subject: [PATCH 13/16] Read the analyzed schedule from schedule_transfers The analyzer rebuilt the executor's rounds with the private _packed_rounds and build_operations, and re-derived the direct-send rule and arena sizes, so staging_bytes could drift from what execute_transfers allocates. It now reads rounds, direct flags, arenas and local copies from #9027's public schedule_transfers. Per-chunk sizes are not part of that schedule, so the report keeps the chunk count and drops the chunk-size distribution. The summary also records process_numbering: processes are the transport-group ranks TransferEndpoints binds, which join with a calibration only when it measured the same group. Signed-off-by: Jin, Youzhi --- .../checkpoint/affine_transfer_analysis.py | 158 ++++++------------ docs/code-docs/source/affine-transfer.rst | 11 +- 2 files changed, 61 insertions(+), 108 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_analysis.py b/deepspeed/checkpoint/affine_transfer_analysis.py index 224eb5491aca..30443513a4c8 100644 --- a/deepspeed/checkpoint/affine_transfer_analysis.py +++ b/deepspeed/checkpoint/affine_transfer_analysis.py @@ -19,7 +19,7 @@ from .affine_transfer import TransferPlan from .affine_transfer_calibration import LOCAL, default_path_of -from .affine_transfer_executor import StagingBudget, TransferEndpoints, _packed_rounds, build_operations +from .affine_transfer_executor import StagingBudget, TransferEndpoints, schedule_transfers __all__ = [ 'TransferMessage', 'ProcessReport', 'PlanReport', 'analyze_transfers', 'expected_stats', 'report_to_dict', @@ -27,6 +27,8 @@ ] REPORT_SCHEMA = 1 +# Processes are the transport-group ranks TransferEndpoints binds, as in execute_transfers. +PROCESS_NUMBERING = 'transport_group_rank' @dataclass(frozen=True) @@ -73,7 +75,6 @@ class PlanReport: processes: Tuple[ProcessReport, ...] messages: Tuple[TransferMessage, ...] segment_bytes: Tuple[int, ...] - chunk_bytes: Tuple[int, ...] planner: Dict[str, int] = field(default_factory=dict) def process(self, process: int) -> ProcessReport: @@ -83,23 +84,6 @@ def process(self, process: int) -> ProcessReport: return ProcessReport(process) -def _is_packed(shape: Sequence[int], strides: Sequence[int]) -> bool: - """Whether a strided region is one run of elements in row-major order, as torch judges it.""" - expected = 1 - for extent, stride in zip(reversed(tuple(shape)), reversed(tuple(strides))): - if extent == 1: - continue - if stride != expected: - return False - expected *= extent - return True - - -def _chunk_is_packed(operation, source_side: bool) -> bool: - strides = operation.segment.source_strides if source_side else operation.segment.target_strides - return _is_packed(operation.chunk_shape, strides) - - def analyze_transfers(plans: Sequence[TransferPlan], endpoints: TransferEndpoints, element_size: int, @@ -107,88 +91,54 @@ def analyze_transfers(plans: Sequence[TransferPlan], path_of: Optional[Callable[[int, int], str]] = None) -> PlanReport: """Report one ``execute_transfers`` batch, given its plans in request order. - The schedule comes from the executor's own ``build_operations`` and round packing, so the - counts match what each process will return in ``TransferStats``. + The schedule comes from the executor's ``schedule_transfers``, so the counts match what each + process will return in ``TransferStats`` and the staging is what it will allocate. """ if path_of is None: path_of = default_path_of - indexed = [] - schedules = {} - for item, plan in enumerate(plans): - identity = id(plan) - if identity not in schedules: - schedules[identity] = build_operations(plan, endpoints, budget, element_size) - indexed.extend((item, operation) for operation in schedules[identity]) - - local_copy = {} - by_pair: Dict[Tuple[int, int], list] = {} - for item, operation in indexed: - if operation.from_process == operation.to_process: - process = operation.from_process - local_copy[process] = local_copy.get(process, 0) + operation.payload_bytes - else: - pair = (operation.from_process, operation.to_process) - by_pair.setdefault(pair, []).append((item, operation)) - - max_elements = budget.bytes_per_peer // element_size + schedules = schedule_transfers(plans, endpoints, budget, element_size) messages = [] - sent, received, send_count, receive_count = {}, {}, {}, {} - pack, unpack, send_peers, receive_peers = {}, {}, {}, {} - rounds_of, staging = {}, {} - for pair in sorted(by_pair): - from_process, to_process = pair - rounds = _packed_rounds(by_pair[pair], max_elements) - largest_packed_send = 0 - largest_unpacked_receive = 0 - for round_index, (entries, count) in enumerate(rounds): - nbytes = count * element_size - # The executor sends a view only when the round holds one packed region; otherwise it stages. - single = len(entries) == 1 - send_direct = single and _chunk_is_packed(entries[0][1], source_side=True) - receive_direct = single and _chunk_is_packed(entries[0][1], source_side=False) - messages.append( - TransferMessage(round=round_index, - from_process=from_process, - to_process=to_process, - nbytes=nbytes, - entries=len(entries), - packed_on_send=not send_direct, - unpacked_on_receive=not receive_direct, - path=path_of(from_process, to_process))) - if not send_direct: - pack[from_process] = pack.get(from_process, 0) + nbytes - largest_packed_send = max(largest_packed_send, nbytes) - if not receive_direct: - unpack[to_process] = unpack.get(to_process, 0) + nbytes - largest_unpacked_receive = max(largest_unpacked_receive, nbytes) - sent[from_process] = sent.get(from_process, 0) + nbytes - received[to_process] = received.get(to_process, 0) + nbytes - send_count[from_process] = send_count.get(from_process, 0) + len(rounds) - receive_count[to_process] = receive_count.get(to_process, 0) + len(rounds) - send_peers[from_process] = send_peers.get(from_process, 0) + 1 - receive_peers[to_process] = receive_peers.get(to_process, 0) + 1 - # A process runs as many rounds as its busiest peer queue, in either direction. - rounds_of[from_process] = max(rounds_of.get(from_process, 0), len(rounds)) - rounds_of[to_process] = max(rounds_of.get(to_process, 0), len(rounds)) - # One arena per peer and direction, sized by its largest staged round. - staging[from_process] = staging.get(from_process, 0) + largest_packed_send - staging[to_process] = staging.get(to_process, 0) + largest_unpacked_receive - - processes = set(endpoints.source.values()) | set(endpoints.target.values()) - process_reports = tuple( - ProcessReport(process=process, - sent_bytes=sent.get(process, 0), - received_bytes=received.get(process, 0), - local_copy_bytes=local_copy.get(process, 0), - send_messages=send_count.get(process, 0), - receive_messages=receive_count.get(process, 0), - rounds=rounds_of.get(process, 0), - send_peers=send_peers.get(process, 0), - receive_peers=receive_peers.get(process, 0), - pack_bytes=pack.get(process, 0), - unpack_bytes=unpack.get(process, 0), - staging_bytes=staging.get(process, 0)) for process in sorted(processes)) + for from_process, schedule in schedules.items(): + for to_process, sent_rounds in schedule.sends.items(): + received_rounds = schedules[to_process].receives[from_process] + for round_index, (sent, received) in enumerate(zip(sent_rounds, received_rounds)): + messages.append( + TransferMessage(round=round_index, + from_process=from_process, + to_process=to_process, + nbytes=sent.elements * element_size, + entries=sent.chunks, + packed_on_send=not sent.direct, + unpacked_on_receive=not received.direct, + path=path_of(from_process, to_process))) + + def total_bytes(rounds_by_peer, staged_only=False): + elements = 0 + for rounds in rounds_by_peer.values(): + elements += sum(entry.elements for entry in rounds if not (staged_only and entry.direct)) + return elements * element_size + + process_reports = [] + chunks = 0 + for process, schedule in schedules.items(): + arena_elements = sum(schedule.send_arena_elements.values()) + sum(schedule.receive_arena_elements.values()) + process_reports.append( + ProcessReport(process=process, + sent_bytes=total_bytes(schedule.sends), + received_bytes=total_bytes(schedule.receives), + local_copy_bytes=schedule.local_copy_elements * element_size, + send_messages=sum(len(rounds) for rounds in schedule.sends.values()), + receive_messages=sum(len(rounds) for rounds in schedule.receives.values()), + rounds=schedule.rounds, + send_peers=len(schedule.sends), + receive_peers=len(schedule.receives), + pack_bytes=total_bytes(schedule.sends, staged_only=True), + unpack_bytes=total_bytes(schedule.receives, staged_only=True), + staging_bytes=arena_elements * element_size)) + # Count each remote chunk once, on its sending side. + chunks += schedule.local_copy_chunks + chunks += sum(entry.chunks for rounds in schedule.sends.values() for entry in rounds) planner = {} for plan in plans: @@ -196,22 +146,19 @@ def analyze_transfers(plans: Sequence[TransferPlan], planner[name] = planner.get(name, 0) + value segment_bytes = tuple(segment.numel * element_size for plan in plans for segment in plan.segments) - remote_bytes = sum(sent.values()) - local_bytes = sum(local_copy.values()) return PlanReport(element_size=element_size, bytes_per_peer=budget.bytes_per_peer, parameters=len(plans), segments=len(segment_bytes), - chunks=len(indexed), + chunks=chunks, logical_bytes=sum(math.prod(plan.logical_shape) * element_size for plan in plans), moved_bytes=sum(segment_bytes), - local_copy_bytes=local_bytes, - remote_bytes=remote_bytes, - rounds=max(rounds_of.values(), default=0), - processes=process_reports, + local_copy_bytes=sum(entry.local_copy_bytes for entry in process_reports), + remote_bytes=sum(entry.sent_bytes for entry in process_reports), + rounds=max((entry.rounds for entry in process_reports), default=0), + processes=tuple(process_reports), messages=tuple(messages), segment_bytes=segment_bytes, - chunk_bytes=tuple(operation.payload_bytes for _, operation in indexed), planner=planner) @@ -278,6 +225,7 @@ def report_to_dict(report: PlanReport, include_messages: bool = False) -> Dict[s staged_messages = sum(1 for message in report.messages if message.packed_on_send or message.unpacked_on_receive) summary = { 'schema': REPORT_SCHEMA, + 'process_numbering': PROCESS_NUMBERING, 'element_size': report.element_size, 'bytes_per_peer': report.bytes_per_peer, 'volume': { @@ -289,7 +237,7 @@ def report_to_dict(report: PlanReport, include_messages: bool = False) -> Dict[s }, 'granularity': { 'segments': distribution(report.segment_bytes), - 'chunks': distribution(report.chunk_bytes), + 'chunks': report.chunks, 'messages': distribution([message.nbytes for message in report.messages]), 'staged_messages': staged_messages, 'pack_bytes': sum(entry.pack_bytes for entry in report.processes), diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 0a825828eddb..f5a8cc279d4d 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -195,8 +195,8 @@ Analyzing a plan ``analyze_transfers`` reports what an ``execute_transfers`` batch will do, without running it or communicating. It takes the same plans, endpoints, -element size and ``StagingBudget`` and replays the executor's own operation -building and round packing, so it can be called on one process, for example to +element size and ``StagingBudget`` and reads the schedule from +``schedule_transfers``, so it can be called on one process, for example to compare two candidate plans or budgets before choosing one:: from deepspeed.checkpoint.affine_transfer_analysis import (analyze_transfers, expected_stats, @@ -209,7 +209,7 @@ compare two candidate plans or budgets before choosing one:: summary = report_to_dict(report) The report covers volume (logical, moved, local-copy and remote bytes), the -distribution of segment, chunk and message sizes, the number of rounds, every +number of chunks, the distribution of segment and message sizes, the number of rounds, every process's sent and received bytes, peers, messages, pack and unpack bytes and staging arena size, and bytes per process pair and per path label. Each message is labelled with ``path_of(from_process, to_process)``, the same hook @@ -217,5 +217,10 @@ is labelled with ``path_of(from_process, to_process)``, the same hook results. ``expected_stats(report, process)`` gives the ``TransferStats`` that process will return, which makes the prediction checkable after a run. +Processes are the transport-group ranks ``TransferEndpoints`` binds, and the +summary records that as ``process_numbering``. Its pair and per-process figures +join with ``fit_links`` results only when ``calibrate_links`` measured the same +group, so pass the transfer's group to both. + The report only describes a plan. It does not choose replicas, rank plans or estimate time; those decisions belong to the caller. From d223b7a700036565948020d19f47a39bfe646b0a Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Wed, 18 Nov 2026 14:24:09 +0000 Subject: [PATCH 14/16] Label local copies with the analyzed path_of The path summary filed every local copy under 'local'. Record path_of(process, process) per process, as calibrate_links does, so the totals join with fit_links results for a custom classifier. Signed-off-by: Jin, Youzhi --- .../checkpoint/affine_transfer_analysis.py | 11 +++++--- docs/code-docs/source/affine-transfer.rst | 6 ++--- .../test_affine_transfer_analysis.py | 27 +++++++++++++++++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_analysis.py b/deepspeed/checkpoint/affine_transfer_analysis.py index 30443513a4c8..c2dc8e5ca230 100644 --- a/deepspeed/checkpoint/affine_transfer_analysis.py +++ b/deepspeed/checkpoint/affine_transfer_analysis.py @@ -50,6 +50,8 @@ class ProcessReport: sent_bytes: int = 0 received_bytes: int = 0 local_copy_bytes: int = 0 + # path_of(process, process), the label calibrate_links gives this process's local copies. + local_copy_path: str = LOCAL send_messages: int = 0 receive_messages: int = 0 rounds: int = 0 @@ -128,6 +130,7 @@ def total_bytes(rounds_by_peer, staged_only=False): sent_bytes=total_bytes(schedule.sends), received_bytes=total_bytes(schedule.receives), local_copy_bytes=schedule.local_copy_elements * element_size, + local_copy_path=path_of(process, process), send_messages=sum(len(rounds) for rounds in schedule.sends.values()), receive_messages=sum(len(rounds) for rounds in schedule.receives.values()), rounds=schedule.rounds, @@ -215,10 +218,10 @@ def report_to_dict(report: PlanReport, include_messages: bool = False) -> Dict[s path = paths.setdefault(message.path, {'messages': 0, 'bytes': 0}) path['messages'] += 1 path['bytes'] += message.nbytes - local_bytes = report.local_copy_bytes - if local_bytes: - local = paths.setdefault(LOCAL, {'messages': 0, 'bytes': 0}) - local['bytes'] += local_bytes + for entry in report.processes: + if entry.local_copy_bytes: + local = paths.setdefault(entry.local_copy_path, {'messages': 0, 'bytes': 0}) + local['bytes'] += entry.local_copy_bytes sent = [entry.sent_bytes for entry in report.processes] received = [entry.received_bytes for entry in report.processes] diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index 03fa07e5d1ca..fe1b965624a7 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -130,9 +130,9 @@ The report covers volume (logical, moved, local-copy and remote bytes), the number of chunks, the distribution of segment and message sizes, the number of rounds, every process's sent and received bytes, peers, messages, pack and unpack bytes and staging arena size, and bytes per process pair and per path label. Each message -is labelled with ``path_of(from_process, to_process)``, the same hook -``calibrate_links`` uses, so per-path totals can be priced with ``fit_links`` -results. ``expected_stats(report, process)`` gives the ``TransferStats`` that +is labelled with ``path_of(from_process, to_process)``, and each process's local +copies with ``path_of(process, process)``, the same hook ``calibrate_links`` +uses, so per-path totals can be priced with ``fit_links`` results. ``expected_stats(report, process)`` gives the ``TransferStats`` that process will return, which makes the prediction checkable after a run. Processes are the transport-group ranks ``TransferEndpoints`` binds, and the diff --git a/tests/unit/checkpoint/test_affine_transfer_analysis.py b/tests/unit/checkpoint/test_affine_transfer_analysis.py index 65901a47f1b5..5c8d07b83752 100644 --- a/tests/unit/checkpoint/test_affine_transfer_analysis.py +++ b/tests/unit/checkpoint/test_affine_transfer_analysis.py @@ -82,6 +82,33 @@ def test_report_is_json_ready_and_labels_paths(): assert len(summary['messages']) == len(report.messages) == 2 +def test_local_copies_use_the_custom_local_label(): + """A path_of that names each process's local copies, as calibrate_links records them.""" + source = contiguous_split_map((4, 4), [2, 2], 0) + target = contiguous_split_map((4, 4), [2, 2], 1) + endpoints = TransferEndpoints(source={0: 0, 1: 1}, target={0: 0, 1: 1}) + + def path_of(from_process, to_process): + return f'hbm{from_process}' if from_process == to_process else 'link' + + report = analyze_transfers([plan_transfer(target, source)], endpoints, FP32, path_of=path_of) + summary = report_to_dict(report) + assert summary['paths'] == { + 'link': { + 'messages': 2, + 'bytes': 32 + }, + 'hbm0': { + 'messages': 0, + 'bytes': 16 + }, + 'hbm1': { + 'messages': 0, + 'bytes': 16 + }, + } + + def _join_transfer_group(): if not dist.is_initialized(): dist.init_distributed(dist_backend=get_accelerator().communication_backend_name(), init_method='env://') From 9610b2f3bcad6e22c4406fa5640bf824d1aabe40 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Wed, 18 Nov 2026 15:13:09 +0000 Subject: [PATCH 15/16] Spell out the analysis invariants and keep empty distributions shaped Assert that both sides of a pair schedule the same rounds, note which expected_stats fields are batch-wide, require element_size to match the executed dtype, and give an empty distribution the same keys. Signed-off-by: Jin, Youzhi --- .../checkpoint/affine_transfer_analysis.py | 20 ++++++++++++++++--- .../test_affine_transfer_analysis.py | 11 ++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/deepspeed/checkpoint/affine_transfer_analysis.py b/deepspeed/checkpoint/affine_transfer_analysis.py index c2dc8e5ca230..bf2eb640ea74 100644 --- a/deepspeed/checkpoint/affine_transfer_analysis.py +++ b/deepspeed/checkpoint/affine_transfer_analysis.py @@ -95,6 +95,11 @@ def analyze_transfers(plans: Sequence[TransferPlan], The schedule comes from the executor's ``schedule_transfers``, so the counts match what each process will return in ``TransferStats`` and the staging is what it will allocate. + + ``element_size`` must be the element size of the tensors the batch will run on, which + ``execute_transfers`` takes from their dtype (``torch.empty((), dtype=dtype).element_size()``). + A different value is not detected: chunks, rounds and byte counts are then predicted for + another dtype. """ if path_of is None: path_of = default_path_of @@ -104,6 +109,8 @@ def analyze_transfers(plans: Sequence[TransferPlan], for from_process, schedule in schedules.items(): for to_process, sent_rounds in schedule.sends.items(): received_rounds = schedules[to_process].receives[from_process] + # Both sides split a pair's chunks into the same rounds, so the rounds pair up one to one. + assert len(sent_rounds) == len(received_rounds), (from_process, to_process) for round_index, (sent, received) in enumerate(zip(sent_rounds, received_rounds)): messages.append( TransferMessage(round=round_index, @@ -166,7 +173,11 @@ def total_bytes(rounds_by_peer, staged_only=False): def expected_stats(report: PlanReport, process: int) -> Dict[str, int]: - """The ``TransferStats`` fields ``process`` should return for the analyzed batch.""" + """The ``TransferStats`` fields ``process`` should return for the analyzed batch. + + ``segments`` and ``chunks`` count the whole batch, so every process returns the same values; + the other fields are that process's own. + """ entry = report.process(process) return { 'segments': report.segments, @@ -179,10 +190,13 @@ def expected_stats(report: PlanReport, process: int) -> Dict[str, int]: def distribution(values: Sequence[float]) -> Dict[str, float]: - """Count, sum and order statistics, with nearest-rank percentiles.""" + """Count, sum and order statistics, with nearest-rank percentiles. + + Empty input has the same keys, with ``None`` for the order statistics and the mean. + """ ordered = sorted(values) if not ordered: - return {'count': 0, 'sum': 0} + return {'count': 0, 'sum': 0, 'min': None, 'p50': None, 'p90': None, 'max': None, 'mean': None} def percentile(fraction): index = max(0, math.ceil(fraction * len(ordered)) - 1) diff --git a/tests/unit/checkpoint/test_affine_transfer_analysis.py b/tests/unit/checkpoint/test_affine_transfer_analysis.py index 5c8d07b83752..583f71a56375 100644 --- a/tests/unit/checkpoint/test_affine_transfer_analysis.py +++ b/tests/unit/checkpoint/test_affine_transfer_analysis.py @@ -3,6 +3,7 @@ """Transfer analysis is checked against hand-derived counts and against the executor's own stats.""" import math +import json import os from dataclasses import asdict @@ -82,6 +83,16 @@ def test_report_is_json_ready_and_labels_paths(): assert len(summary['messages']) == len(report.messages) == 2 +def test_empty_batch_summary_keeps_its_keys(): + endpoints = TransferEndpoints(source={0: 0, 1: 1}, target={0: 0, 1: 1}) + summary = report_to_dict(analyze_transfers([], endpoints, FP32)) + for name in ('segments', 'messages'): + stats = summary['granularity'][name] + assert set(stats) == {'count', 'sum', 'min', 'p50', 'p90', 'max', 'mean'} + assert stats['count'] == 0 and stats['max'] is None + json.dumps(summary) + + def test_local_copies_use_the_custom_local_label(): """A path_of that names each process's local copies, as calibrate_links records them.""" source = contiguous_split_map((4, 4), [2, 2], 0) From 46d754351532c19fdaee92052b6700e648f4e35b Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Sun, 22 Nov 2026 13:14:20 +0000 Subject: [PATCH 16/16] Note that local-copy predictions include copies run in place Signed-off-by: Jin, Youzhi --- .../checkpoint/affine_transfer_analysis.py | 8 ++++ docs/code-docs/source/affine-transfer.rst | 7 +++- .../test_affine_transfer_analysis.py | 38 +++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/deepspeed/checkpoint/affine_transfer_analysis.py b/deepspeed/checkpoint/affine_transfer_analysis.py index bf2eb640ea74..297cf4663c90 100644 --- a/deepspeed/checkpoint/affine_transfer_analysis.py +++ b/deepspeed/checkpoint/affine_transfer_analysis.py @@ -96,6 +96,11 @@ def analyze_transfers(plans: Sequence[TransferPlan], The schedule comes from the executor's ``schedule_transfers``, so the counts match what each process will return in ``TransferStats`` and the staging is what it will allocate. + Local-copy figures are the exception: the analysis sees no buffers, so they include copies that + ``execute_transfers`` drops as in place (source and target the same memory at the same strides), + which ``TransferStats.local_copy_bytes`` does not count. After a run, a smaller + ``local_copy_bytes`` is this known difference, not a prediction error. + ``element_size`` must be the element size of the tensors the batch will run on, which ``execute_transfers`` takes from their dtype (``torch.empty((), dtype=dtype).element_size()``). A different value is not detected: chunks, rounds and byte counts are then predicted for @@ -177,6 +182,9 @@ def expected_stats(report: PlanReport, process: int) -> Dict[str, int]: ``segments`` and ``chunks`` count the whole batch, so every process returns the same values; the other fields are that process's own. + + ``local_copy_bytes`` is an upper bound: it includes the local copies ``execute_transfers`` drops + as in place, which the returned ``TransferStats`` leaves out. The other fields are exact. """ entry = report.process(process) return { diff --git a/docs/code-docs/source/affine-transfer.rst b/docs/code-docs/source/affine-transfer.rst index fa1f6e64cd70..cc95e170948f 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -134,7 +134,12 @@ staging arena size, and bytes per process pair and per path label. Each message is labelled with ``path_of(from_process, to_process)``, and each process's local copies with ``path_of(process, process)``, the same hook ``calibrate_links`` uses, so per-path totals can be priced with ``fit_links`` results. ``expected_stats(report, process)`` gives the ``TransferStats`` that -process will return, which makes the prediction checkable after a run. +process will return, which makes the prediction checkable after a run. Every +field is exact except ``local_copy_bytes``, which is an upper bound: the report +sees no buffers, so it also counts local copies that ``execute_transfers`` drops +as in place (source and target the same memory at the same strides). A smaller +``local_copy_bytes`` after a run is that known difference, not a prediction +error. Processes are the transport-group ranks ``TransferEndpoints`` binds, and the summary records that as ``process_numbering``. Its pair and per-process figures diff --git a/tests/unit/checkpoint/test_affine_transfer_analysis.py b/tests/unit/checkpoint/test_affine_transfer_analysis.py index 583f71a56375..0b3762347f76 100644 --- a/tests/unit/checkpoint/test_affine_transfer_analysis.py +++ b/tests/unit/checkpoint/test_affine_transfer_analysis.py @@ -163,3 +163,41 @@ def test_expected_stats_equal_executor_stats(self, peer_elements): stats = execute_transfers(requests, endpoints, dtype, budget) report = analyze_transfers(plans, endpoints, 4, budget) assert asdict(stats) == expected_stats(report, rank) + + +@pytest.mark.skipif(get_accelerator().device_count() < 2, reason='requires two visible accelerator devices') +class TestPredictionWithInPlaceCopies(DistributedTest): + world_size = 2 + + def test_local_copy_bytes_over_count_by_the_in_place_bytes(self): + """Each process keeps its own shard of two parameters; one is moved in place, the other copied. + + The analysis counts both local copies, the executor only the one it runs. Every other field agrees. + """ + device = _join_transfer_group() + rank = dist.get_rank() + dtype = torch.float32 + split = contiguous_split_map((8, ), [4, 4], 0) + endpoints = TransferEndpoints(source={0: 0, 1: 1}, target={0: 0, 1: 1}) + plan = plan_transfer(split, split) + shard = torch.arange(4, dtype=dtype, device=device) + 4 * rank + other = torch.full((4, ), float('nan'), dtype=dtype, device=device) + requests = [ + TransferRequest('in-place', plan, {rank: shard}, {rank: shard}), + TransferRequest('copied', plan, {rank: shard.clone()}, {rank: other}), + ] + + stats = execute_transfers(requests, endpoints, dtype) + expected = expected_stats(analyze_transfers([plan, plan], endpoints, FP32), rank) + + in_place_bytes = shard.numel() * FP32 + assert expected['local_copy_bytes'] == 2 * in_place_bytes + assert expected['local_copy_bytes'] - stats.local_copy_bytes == in_place_bytes + assert { + key: value + for key, value in asdict(stats).items() if key != 'local_copy_bytes' + } == { + key: value + for key, value in expected.items() if key != 'local_copy_bytes' + } + assert torch.equal(other, shard)