Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
3ba2b6c
Calibrate affine transfer links per path, including fan-out and fan-in
jinyouzhi Oct 31, 2026
3f16eff
Calibrate fans at several widths and fit each process's send and rece…
Achyuthan-S Nov 2, 2026
fc62c0b
Key fan fits by peer set; add per-pair fits, fan_peers, group and a n…
jinyouzhi Nov 3, 2026
83284ab
Drop the card model from the calibration docs example
jinyouzhi Nov 3, 2026
11e311e
add docsing for fit_links return
jinyouzhi Nov 4, 2026
d7e1838
Fit concurrent links only from processes whose send and receive share…
jinyouzhi Nov 5, 2026
f3102ed
Drop the concurrent calibration pattern
jinyouzhi Nov 5, 2026
f27d566
Measure pairs both ways and relays
jinyouzhi Nov 6, 2026
851ea68
Describe two-way peer fits as pair completion times
jinyouzhi Nov 11, 2026
d465334
Label local samples by path_of and record the measured group's backend
jinyouzhi Nov 12, 2026
f678c9d
Bump the calibration schema for two-way and relay samples
jinyouzhi Nov 13, 2026
8d1c797
Merge remote-tracking branch 'origin/master' into affine-link-calibra…
jinyouzhi Nov 16, 2026
be0485d
Analyze affine transfer batches before execution
jinyouzhi Oct 31, 2026
1dfbbc4
Read the analyzed schedule from schedule_transfers
jinyouzhi Nov 13, 2026
66f6889
Merge branch 'master' into affine-transfer-analysis
jinyouzhi Nov 17, 2026
9ede0b1
Merge branch 'master' into affine-transfer-analysis
jinyouzhi Nov 18, 2026
d223b7a
Label local copies with the analyzed path_of
jinyouzhi Nov 18, 2026
9610b2f
Spell out the analysis invariants and keep empty distributions shaped
jinyouzhi Nov 18, 2026
5b0bc50
Merge branch 'master' into affine-transfer-analysis
delock Nov 22, 2026
46d7543
Note that local-copy predictions include copies run in place
jinyouzhi Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
288 changes: 288 additions & 0 deletions deepspeed/checkpoint/affine_transfer_analysis.py
Original file line number Diff line number Diff line change
@@ -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))
40 changes: 40 additions & 0 deletions docs/code-docs/source/affine-transfer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------

Expand Down
Loading
Loading