diff --git a/deepspeed/checkpoint/affine_transfer_analysis.py b/deepspeed/checkpoint/affine_transfer_analysis.py new file mode 100644 index 000000000000..297cf4663c90 --- /dev/null +++ b/deepspeed/checkpoint/affine_transfer_analysis.py @@ -0,0 +1,288 @@ +# 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, schedule_transfers + +__all__ = [ + 'TransferMessage', 'ProcessReport', 'PlanReport', 'analyze_transfers', 'expected_stats', 'report_to_dict', + 'distribution' +] + +REPORT_SCHEMA = 1 +# Processes are the transport-group ranks TransferEndpoints binds, as in execute_transfers. +PROCESS_NUMBERING = 'transport_group_rank' + + +@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 + # 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 + 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, ...] + 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 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 ``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 + another dtype. + """ + if path_of is None: + path_of = default_path_of + + schedules = schedule_transfers(plans, endpoints, budget, element_size) + messages = [] + 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, + 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, + 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, + 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: + 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) + return PlanReport(element_size=element_size, + bytes_per_peer=budget.bytes_per_peer, + parameters=len(plans), + segments=len(segment_bytes), + chunks=chunks, + logical_bytes=sum(math.prod(plan.logical_shape) * element_size for plan in plans), + moved_bytes=sum(segment_bytes), + 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, + planner=planner) + + +def expected_stats(report: PlanReport, process: int) -> Dict[str, int]: + """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. + + ``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 { + '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. + + 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, 'min': None, 'p50': None, 'p90': None, 'max': None, 'mean': None} + + 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 + 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] + 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': { + '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': 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), + '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 ab6a89354660..cc95e170948f 100644 --- a/docs/code-docs/source/affine-transfer.rst +++ b/docs/code-docs/source/affine-transfer.rst @@ -109,6 +109,46 @@ round count that ``TransferStats.rounds`` reports. ``execute_transfers`` builds its rounds and arenas from the same computation, so the two cannot drift apart. The schedule follows the current transport described above and changes with it. +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 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, + 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 +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)``, 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. 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 +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. + Calibrating links ----------------- 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..0b3762347f76 --- /dev/null +++ b/tests/unit/checkpoint/test_affine_transfer_analysis.py @@ -0,0 +1,203 @@ +# 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 json +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 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) + 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://') + 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) + + +@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)