Skip to content

[checkpoint] Batch replica selection for affine transfer plans - #8936

Merged
delock merged 3 commits into
deepspeedai:masterfrom
0z5a:replica-batch-policy-20261028
Nov 12, 2026
Merged

delock merged 3 commits into
deepspeedai:masterfrom
0z5a:replica-batch-policy-20261028

Conversation

@0z5a

@0z5a 0z5a commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Implements the planner side of #8935. It does not close the issue: the cost-aware policies are the policy layer under #8252.

What it adds

  • plan_transfers(pairs, limits, *, source_processes, target_processes, element_size, min_split_bytes, replica_policy) in deepspeed/checkpoint/affine_transfer.py. It plans every parameter of one sync and calls one replica policy with every request at once.
  • ReplicaRequest and ReplicaPart.
    • A request names the parameter, the target location, the region and its validated holders. When the caller passes the location→process mappings, it also names the processes behind them.
    • Regions with a single holder are included, so a policy sees load it cannot move.
    • Requests arrive in a fixed order: parameter, then target location, then origin.
  • An answer is either a holder location, or ReplicaParts that cut the region along axis 0.
  • The planner checks every answer before it emits any segment, and raises InvalidReplicaPolicyError otherwise:
    • one answer per request;
    • only validated holders;
    • parts that tile the request exactly along axis 0;
    • part fields that are not iterable coordinates, rather than a raw TypeError;
    • with min_split_bytes, every part of a split is at least that large;
    • the parts of one parameter stay within PlanBudget.max_pair_checks, checked from the answer's length before the parts are expanded.
  • deepspeed/checkpoint/affine_replica_policy.py holds three policies:
    • first_holder: what plan_transfer does by default.
    • local_first_least_loaded: the plan_transfers default. It takes a holder in the target's own process first, then the sending process with the fewest bytes assigned so far in this batch. Ties go to the lowest location, and it never splits.
    • per_request(selector): runs an existing replica_selector as a batch policy.

Review follow-up (commit 773ddfd3)

What it does not change
plan_transfer behaves exactly as before; it shares its validation and emission steps with plan_transfers. AutoEP's plan_expert_transfer and its docs are untouched.

Decisions from #8935

  • One sync per batch.
  • Only axis-0 splits for now. Other split shapes are refused, so widening later is an additive change.
  • Plain location→process mappings rather than TransferEndpoints, so the planner does not import the executor.
  • Policies live in their own module.
  • The per-request adapter stays.

min_split_bytes comes from my last comment on #8935 and has not been agreed yet. It is optional and off by default. The process_node mapping proposed there is deferred.

Tests
tests/unit/checkpoint/test_affine_replica_policy.py, CPU only:

  • Random policies over 24 seeds, including random splits across holders, on five parameters: whole replicas, a partly replicated fused block, a vector and a scalar. Every plan writes each target element exactly once and matches extract. This is the check that matches the "Any consistent plan is exact" theorem of the correctness draft for Define affine IR for checkpointing #8252.
  • first_holder and per_request reproduce plan_transfer's plans exactly.
  • The default policy:
    • copies locally when it can;
    • balances load, counting single-holder load;
    • never assumes a local copy without mappings.
  • Refused answers:
    • holders that are not candidates;
    • bools, floats, None and strings;
    • gaps, overlaps and parts outside the region;
    • cuts along axis 1, empty parts and parts with the wrong number of axes;
    • non-iterable part fields;
    • the wrong number of answers;
    • splits under min_split_bytes, and more parts than the budget allows, including parts accumulated across requests.
  • The maps are validated before the policy runs.
  • The pair budget is decided from the answer's length before the planner reads its parts.

With DS_ACCELERATOR=cpu on macOS arm64 (Python 3.11, torch 2.15.0), the new file passes (65 tests) together with test_affine_transfer_plan.py, test_autoep_affine.py and test_affine_shard_map.py (306 passed), and tests/unit/v1/moe/test_autoep_unit.py (which covers plan_expert_transfer) together with test_autoep_affine_universal.py pass too (215 passed, 8 skipped). yapf 0.43.0, flake8 5.0.4, codespell, the license check and the other pre-commit hooks are clean. The five rejection/budget tests added here fail on the previous planner and pass now.

How it fits with other PRs

Scope, compatibility and AI assistance
Only the CPU planning interface, its tests and its documentation change: no training-loop, GPU, ZeRO, offload or precision path is touched, so no compatibility-matrix cell or on-device serving check is affected, and none was run. AI assistance was used: the initial implementation was co-authored with Claude Opus 5.5, this review follow-up was prepared with an AI coding agent, and the submitter reviewed every changed line and ran the tests above.

cc @Achyuthan-S @delock

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T09:59:49.703718Z 24881a4 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 24881a444e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

return _emit(prepared, choices, budget)


def plan_transfers(pairs: Mapping[str, Tuple[ParamAffineMap, ParamAffineMap]],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Document the new batch planning API

For downstream users adopting plan_transfers, this patch exposes the entry point in __all__ plus a new callback/split protocol and default selection behavior, but adds no user documentation; the existing AutoEP docs only explain plan_expert_transfer and the old per-request replica_selector, so there is no supported reference for the process mappings, element sizes, split constraints, or policy answers. Add the required documentation alongside the feature.

AGENTS.md reference: AGENTS.md:L71-L71

Useful? React with 👍 / 👎.

Comment thread deepspeed/checkpoint/affine_transfer.py Outdated
if type(part.source_location) is not int or part.source_location not in holders:
raise InvalidReplicaPolicyError(f'{where}: location {part.source_location!r} is not a validated '
f'holder {sorted(holders)}')
origin, shape = tuple(part.logical_origin), tuple(part.shape)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate part fields before tuple conversion

When a custom policy returns a ReplicaPart whose logical_origin or shape is non-iterable (for example None), these tuple(...) calls raise a raw TypeError. The function's new contract says every invalid answer raises InvalidReplicaPolicyError; callers that catch AffineTransferError to reject a policy or fall back will instead abort, so convert and validate these fields under the policy-error path.

Useful? React with 👍 / 👎.

Comment thread deepspeed/checkpoint/affine_transfer.py Outdated
Comment on lines +664 to +667
parts = _resolve(request, item, answer, min_split_bytes, element_size)
choices[name][index] = parts
parts_per_name[name] += len(parts)
if parts_per_name[name] > budget.max_pair_checks:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce split budgets before materializing parts

When a custom policy accidentally returns a very large split for one request, _resolve materializes every LogicalBox and sorts the full answer before this cumulative check runs. Consequently even a tiny max_pair_checks does not bound planner work or memory, so a malformed policy can cause a large allocation or OOM before it is rejected; enforce the remaining per-parameter allowance while or before resolving the answer.

Useful? React with 👍 / 👎.

@Achyuthan-S Achyuthan-S left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this from the policy side, since the cost-aware policy will sit on this interface. It has what that policy needs:

  • Each request carries its bytes, the target process and every candidate's process.
  • The whole sync arrives in one call, in a fixed order, so a policy can balance load over all of it, including the single-holder load it can't move.

The topology and the calibration (#8966's fit_links) can live inside the policy, so I agree the process_node mapping can stay out of the planner. The refactor keeps plan_transfer's selection and emission as they were, and local_first_least_loaded does what its docstring says.

Checked on CPU:

  • At 24881a4: test_affine_replica_policy.py, test_affine_transfer_plan.py and test_affine_shard_map.py pass (251).
  • Merged with current master (after #8809, #8885 and #8975), the merge is clean, and the planner, executor, AutoEP and ZeRO-affine tests pass together (583 passed, 8 skipped).

A few small things:

  1. Codex's first P2 is real: a ReplicaPart with logical_origin=None raises a raw TypeError (I checked), not InvalidReplicaPolicyError. The second is minor: the policy's answer is already in memory by then, so checking len(answer) against the remaining max_pair_checks allowance before _resolve only saves the planner's own work on a malformed split. It's still cheap to add.
  2. Docs: #8809 has landed, so the plan_transfers section can go into affine-transfer.rst now.
  3. A note for policy authors: every rank has to return the same answers. #8809's schedule digest already refuses mismatched plans ("ranks disagree about the transfer schedule"), so this fails loudly. Still, one line in the docstring saying that cost inputs should come from data every rank shares, such as fit_links on the gathered calibration, would help.
  4. The test docstring cites "Theorem 3 of the proof draft". In the PDF I posted it's Theorem 4, "Any consistent plan is exact". Citing it by name would survive renumbering.

LGTM from the policy side. The first part of 1 is worth doing before merge, and the rest is up to you.

0z5a and others added 2 commits November 5, 2026 19:59
Add plan_transfers, which plans every parameter of one sync and hands a
replica policy every request at once, as agreed in deepspeedai#8935. The policy
returns a holder location per request, or splits a request along axis 0
across validated holders. The planner checks every answer before it
emits a segment: one answer per request, only validated holders, and
parts that tile the request exactly. So a policy decides where data is
read from, never what arrives.

Requests name map locations and, when the caller passes the
location-to-process mappings, the processes behind them, so a policy can
tell a local copy from a transfer. element_size turns elements into bytes
and min_split_bytes bounds every part of a split.

Policies live in affine_replica_policy.py: first_holder (plan_transfer's
default), local_first_least_loaded (the plan_transfers default) and
per_request, which runs an existing replica_selector as a batch policy.
plan_transfer itself is unchanged; it now shares its validation and
emission steps with plan_transfers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de>
A ReplicaPart whose logical_origin or shape is not iterable is now refused
with InvalidReplicaPolicyError instead of raising a raw TypeError, and an
answer with more parts than the remaining max_pair_checks allowance is
refused on its length before _resolve expands it. The pair budget now raises
InvalidReplicaPolicyError as well, so every refused answer uses the error the
planner documents.

Document plan_transfers, the request and answer protocol, the process
mappings, element sizes (one entry per parameter), split constraints and the
built-in policies in affine-transfer.rst, and tell policy authors that answers
must agree across ranks, so cost inputs must come from data every rank shares.
Cite the deepspeedai#8252 theorem "Any consistent plan is exact" by name instead of by
number.

Tests: the rejected-answer cases include non-iterable part fields,
test_the_pair_budget_is_checked_before_the_parts_are_read pins that the planner
decides from len(answer) without reading the parts, and both budget tests pin
the policy error, including parts accumulated across requests. All five fail on
the previous planner. On macOS arm64 CPU (Python 3.11, torch 2.15.0),
test_affine_replica_policy.py passes (65 tests), the four affine checkpoint
suites pass together (306), and the AutoEP unit suites pass (215 passed,
8 skipped). pre-commit (yapf, flake8, codespell, license) is clean.

Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de>
@0z5a
0z5a force-pushed the replica-batch-policy-20261028 branch from 24881a4 to 773ddfd Compare November 5, 2026 19:09
@0z5a

0z5a commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@Achyuthan-S thanks — all four are in 773ddfd3 (branch rebased on current master, after #8809, #8885 and #8975):

  1. A ReplicaPart whose logical_origin or shape is not iterable now raises InvalidReplicaPolicyError; the pair budget uses the same class, so every refused answer uses the documented one. The budget is decided from len(answer) before _resolve expands the parts, and it still accumulates across requests. The tests pin both (test_the_pair_budget_is_checked_before_the_parts_are_read, test_parts_count_against_the_budget_across_requests); the five rejection/budget cases fail on the previous planner.
  2. plan_transfers is documented in docs/code-docs/source/affine-transfer.rst: the request/answer protocol, source_processes/target_processes, element_size (one entry per parameter), the axis-0 split and min_split_bytes constraints, the policy error, and the three built-in policies.
  3. The plan_transfers and affine_replica_policy docstrings now say answers must agree on every rank, so cost inputs must come from data every rank shares (for example fit_links on the gathered calibration, [AffineIR] Calibrate affine transfer links per path (Plan analysis & calibration Part-2) #8966), and quote the executor's "ranks disagree about the transfer schedule (batch schedule)".
  4. The test docstring cites "Any consistent plan is exact" by name.

Validation on macOS arm64 CPU (Python 3.11, torch 2.15.0): 65 tests in the new file, 306 across the four affine checkpoint suites, and 215 passed / 8 skipped for the AutoEP suites; pre-commit (yapf, flake8, codespell, license) is clean. No GPU path is touched.

@Achyuthan-S

Copy link
Copy Markdown
Contributor

Re-checked 773ddfd: all four are in.

  • A ReplicaPart with a non-iterable logical_origin or shape now raises InvalidReplicaPolicyError, since the tuple(...) conversion is guarded. The pair budget is decided from len(answer) before _resolve, and the budget tests pass.
  • plan_transfers is documented in affine-transfer.rst, the docstrings say answers must agree on every rank, and the test cites "Any consistent plan is exact" by name.

I merged the branch with current master: the merge is clean, and the planner, replica-policy, shard-map, ZeRO-affine, AutoEP-affine and executor suites (including the external-group test) pass together on CPU, with 383 passed. LGTM from the policy side. The cost-aware policy will build directly on this interface.

@delock
delock enabled auto-merge November 12, 2026 03:55
@delock
delock added this pull request to the merge queue Nov 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 12, 2026
@delock
delock added this pull request to the merge queue Nov 12, 2026
Merged via the queue into deepspeedai:master with commit 2d02194 Nov 12, 2026
18 checks passed
LiRunGuo added a commit to LiRunGuo/DeepSpeed that referenced this pull request Nov 12, 2026
); shards given at each sync follow offload/reload

Signed-off-by: RunguoLi <li19107254665@gmail.com>
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 14, 2026
…omparisons (deepspeedai#9011)

**Stacked on deepspeedai#9010** (only the last two commits are new here; I will
rebase after deepspeedai#9010 merges).

`_validate_holders` compared every piece with every other piece,
`_sources` compared every source region with every other region, and
`_shards_tile` compared each rank's pieces pairwise by shard address.
Planning time therefore grew quadratically with the number of pieces,
and a map with 1024 pieces already exceeded the default
`max_pair_checks`.

When no rank repeats a box and distinct boxes do not overlap, a rank
covers a box exactly when it holds that very box, so the holders of each
box can be read from a table. This PR adds `boxes_disjoint` to
`affine_geometry`. It sweeps along the axis whose box origins vary most
and compares each box only with the boxes still open where it starts.
The same sweep proves that a rank's pieces tile its shard when they are
disjoint by address and fill it (suggested by 0z5a in review). Maps that
fail the fast checks fall back to the original pairwise walk, which
names the offending piece, so error messages are unchanged, and maps
that pass no longer hit the per-rank `len(held)**2` budget.

The sweep counts its comparisons against `max_pair_checks` too
(suggested by Achyuthan-S in review). A disjoint layout can keep every
box open for the whole sweep: for example, h full-height one-column
boxes plus 2h one-element boxes beside them. When the sweep runs out of
budget it reports "not shown disjoint". It compares at most n·(n−1)/2
pairs, so running out implies n² > `max_pair_checks`, and the pairwise
fallback refuses at once. With 4,095 such pieces, planning went from
19.2 s to a budget refusal in 0.6 s.

Planning time (8 ranks with interleaved rows, re-sharded to 8 row
shards, 64 columns; ms, single CPU process):

| pieces | before | holders/sources only | + shard addresses (this PR) |
|---|---|---|---|
| 256 | 211 | 15 | 7 |
| 512 | 827 | 46 | 15 |
| 1024 | 3278 (refused by default budget) | 156 | 33 |
| 2048 | 12926 | 569 | 76 |
| 4096 | 50469 | 2227 | 235 |

Tests:
- Randomized oracle over 200 seeds: plans and errors match the pairwise
walk, including replicas split at different points, overlapping pieces
and wrong holder lists.
- `boxes_disjoint` is checked against an all-pairs reference over 100
seeds.
- Mutation check: the tests catch dropped intersections and wrong holder
sets.
- A rank holding 1024 pieces plans under the default `max_pair_checks`
(refused before this change).
- The always-open layout above plans correctly under the default budget
and is refused with `max_pair_checks` just below its sweep cost. Without
the sweep budget, that test plans instead of refusing.
- `tests/unit/checkpoint -k affine` passes on 8× NVIDIA L20 (645
passed). At 12663c3 on CPU (`DS_ACCELERATOR=cpu`, 4 ranks): 642 passed,
5 skipped.

The remaining near-quadratic steps, the source × target join and
`_covers_union`, overlap with deepspeedai#8936 and will follow after it lands;
segment merging in `_coalesce` has its own `max_merge_checks` budget and
will follow separately.

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 15, 2026
deepspeedai#9027)

## Why

A replica policy (deepspeedai#8936) or cost model (deepspeedai#8252) needs to know what a
batch will cost before running it: messages per peer, rounds, and
staging memory. deepspeedai#8967 builds that report today by importing the
executor's private `_packed_rounds` and `build_operations`. It then
re-derives the in-place decision and the arena sizing, so its numbers
would drift silently whenever the executor's staging changes. It asked
for a public API instead.

## What

`schedule_transfers(plans, endpoints, budget, element_size,
process=None)` in `affine_transfer_executor` returns, for one process or
for every process the endpoints name, the `ProcessSchedule` that
`execute_transfers` would run. It uses no buffers and no communication:
- the rounds per peer and direction (`ScheduledRound`: elements, chunks,
and whether the round is sent or received in place);
- the staging arena each peer direction allocates;
- the local copies;
- the round count that `TransferStats.rounds` reports.

`execute_transfers` now builds its rounds and arenas from the same
private computation, so the report and the run cannot disagree. The
in-place decision is made from geometry rather than from the buffer.
`_region` is an `as_strided` view of a packed shard, so it is contiguous
exactly when `(chunk_shape, strides)` is row-major packed, ignoring
extent-1 axes.

Unchanged:
- `plan_digest`, the batch fingerprint and `TransferStats`, so mixed
versions still agree on the schedule;
- `build_operations` and `_packed_rounds`, which keep their names and
signatures until deepspeedai#8967 switches.

## Tests

- `test_schedule_is_what_the_executor_runs` (2 and 4 ranks; mixed packed
and strided regions with 16-element messages) checks:
- rounds, sent, received and local-copy bytes against the executor's
`TransferStats`;
  - that both sides of every message agree;
  - the arena sizes;
  - that the batch exercises both the in-place and the staged path.
- `test_packed_regions_are_exactly_the_contiguous_views` compares the
geometric rule with `Tensor.is_contiguous` over 2000 random shapes and
strides, including extent-1 axes.
- A single-process case covers local-only batches and the argument
checks.
- Forcing every round to be staged, or dropping the extent-1 exception,
makes these tests fail.

On macOS arm64 CPU (Python 3.12, torch 2.15.0):
- The executor, external-group, planner and shard-map suites pass (263).
- All other affine checkpoint tests pass, except the four
`TestAffineUniversalCheckpointResume` cases, which fail the same way on
master in this environment (uninstalled package version).
- With deepspeedai#8967 merged on top, its analysis tests pass unchanged (59
together with the executor suite).
- pre-commit is clean.

This merges cleanly with deepspeedai#8936, deepspeedai#9010 and deepspeedai#9011. With deepspeedai#8966 and deepspeedai#8967
the only conflict is that both append a section to
`affine-transfer.rst`.

---------

Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
jinyouzhi added a commit to jinyouzhi/DeepSpeed that referenced this pull request Nov 17, 2026
…calibration Part-2) (deepspeedai#8966)

## Calibrate affine transfer links per path

Stacked on deepspeedai#8809 only for its docs page (`affine-transfer.rst`); the
module itself needs nothing beyond master. Until deepspeedai#8809 merges, please
review only the commits after the deepspeedai#8809 merge.

### Why
A replica policy or cost model choosing between plans (deepspeedai#8252,
deepspeedai#8935/deepspeedai#8936) needs link costs measured on the machine it runs on.
Executor measurements show that round count and receiver sharing
dominate sync time, so per-pair numbers are not enough on their own;
this PR also measures 1→N and N→1.

### What
`deepspeed/checkpoint/affine_transfer_calibration.py`:
- `calibrate_links(sizes, repeats, warmup, path_of, fan_width,
fan_peers, group)`: collective over `group` (the default group unless
given). Returns the same raw samples on every process, with no
aggregation, for:
  - `local` copy;
  - `peer` (each ordered pair alone);
  - `fan_out` (1→N);
  - `fan_in` (N→1, receiver contention).
  
  Sizes run from 4 KiB to 256 MiB by default.
- Each message is labelled by `path_of(from_process, to_process)`.
`default_path_of` gives `local`/`peer`; `node_path_of(n)` gives
`intra_node`/`inter_node`; any callable works.
- `fit_links(calibration)`: per-path `alpha + bytes / bandwidth`, fitted
to the per-size medians; `peer_pairs` per ordered pair; fans keyed by
`(root, peers)`, with `send`/`receive` giving each root's aggregate
rate.

Weight transfers are one-way (a training process sends, a rollout
process receives), so no pattern has a process send and receive at once.

It measures only. It does not plan, select replicas, or change the
planner or executor.

### Example (one node, 8 devices, default sizes)
| pattern | B70 xccl: alpha (µs) / GB/s | L20 nccl (PCIe): alpha (µs) /
GB/s | H20 nccl (NVLink): alpha (µs) / GB/s |
|---|---|---|---|
| local | 73 / 359 | 16 / 1534* | 9 / 1881 |
| peer | 301 / 28.2 | 72 / 25.3 | 54 / 275 |
| fan_out (7 peers) | 531 / 3.4 | 141 / 3.6 | 88 / 49.6 |
| fan_in (7 peers) | 670 / 2.6 | 56 / 3.8 | 46 / 54.5 |
| run time | 88 s | 34 s | 13 s |

\* poor linear fit (max relative error 0.77); small copies are
cache-resident.

### Multi-node (2 × 8 H20, RoCE 8 × 200 Gb/s per node,
`node_path_of(8)`, 16 processes)
| pattern | alpha (µs) / GB/s | max rel. error |
|---|---|---|
| peer, intra_node | 57 / 53.8 | 0.07 |
| peer, inter_node | 97 / 16.6 (pairs 14.0–24.5) | 0.50 |
| fan_in, 7 intra-node peers: root receive | 94.6 GB/s | |
| fan_out, 8 cross-node peers: root send | 62.1 GB/s median (33–78 over
roots) | |
| run time | 72 s (+111 s for cross-node fans of width 1/4/8) | |

- The same NVLink pair measured 275 GB/s in the 8-process group and 54
GB/s in the 16-process group over RoCE (105 GB/s with NCCL over TCP), so
calibrate on the group and communication settings the transfer uses.

### Tests
`tests/unit/checkpoint/test_affine_transfer_calibration.py`:
- fit on synthetic data with known link costs, per-pair and per-peer-set
fits;
- schema and argument checks;
- 4-rank runs checking completeness, sample counts, and fan path
direction with an asymmetric `path_of`.

10 passed on 8× B70 (xccl). `pytest tests/unit/checkpoint/ -k affine`:
344 passed, 1 skipped on 8× H20 with torch 2.13.0+cu129 / NCCL 2.29.7
and with torch 2.9.1+cu129 / NCCL 2.29.7. Mutation check: flipping the
fan_in label direction fails a test. Cross-node runs used NCCL 2.29.7 on
both nodes (torch 2.13.0 and 2.9.1).

AI assistance (GitHub Copilot) was used for the multi-node runs and this
description; I reviewed the changes and the results.

### Follow-ups
- Sampled pairs for large worlds.
- Joining the samples to a plan's messages (analysis PR, stacked on this
one and deepspeedai#8809).

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Signed-off-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
Signed-off-by: iLeGend <824040212@qq.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 23, 2026
…lysis & calibration Part-1) (deepspeedai#8967)

## Analyze affine transfer batches before execution

Builds on deepspeedai#8809 (executor) and deepspeedai#8966 (calibration path labels), both
merged.

### Why
Plans that move the same bytes can differ a lot in time (up to 1.75× on
8× B70 between replica choices), and executor measurements show that the
round count under a `StagingBudget` dominates sync time. A policy
(deepspeedai#8935/deepspeedai#8936) or cost model (deepspeedai#8252) needs these facts before it runs a
plan.

### What
`deepspeed/checkpoint/affine_transfer_analysis.py`:
- `analyze_transfers(plans, endpoints, element_size, budget, path_of)`
is a pure function with no communication. It reads the schedule from the
executor's public `schedule_transfers`, so it reports what
`execute_transfers` will run:
  - volume;
  - segment, chunk and message size distributions;
  - rounds;
- per process: sent/received bytes, peers, messages, pack/unpack bytes,
staging arena;
  - per-pair and per-path bytes.
- `expected_stats(report, process)` predicts that process's
`TransferStats`.
- `report_to_dict` returns a JSON-ready summary.
- Messages use the same `path_of` labels as `calibrate_links`, so
per-path totals can be priced with `fit_links`.

It does not choose replicas, rank plans, or model time.

### Tests
- Hand-counted rounds and bytes on an uneven handoff.
- Staging of strided sources.
- A batch with a shared plan.
- Path and pair labels in the JSON summary.
- 4 ranks: `expected_stats` == the executor's `TransferStats`, for a
strided and a replicated parameter under budgets of 3 and 64 elements.
- 2 ranks: on a batch with an in-place local copy, the predicted
`local_copy_bytes` exceeds the executor's by exactly the in-place bytes,
and every other field matches.

Results:
- CPU (gloo): 7 passed; the two 4-rank tests need four devices and are
skipped.
- 4× Intel Arc Pro B70 (xccl): the 2-rank and 4-rank tests pass.
- 4× L20 (nccl): all passed before the in-place test was added; not
re-run since.

Mutation checks (dropping the receiver's round count, or the local bytes
in the path summary) are caught.

### Follow-up
- `expected_stats(...)['local_copy_bytes']` is an upper bound. The
analysis 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); `TransferStats.local_copy_bytes` does not. The
docstrings and `affine-transfer.rst` state this, and the 2-rank test
pins the difference. Making this field exact would need the analysis to
know which copies are in place, for example by passing the buffers or
the in-place copies to `analyze_transfers`. That is left for a
follow-up.

---------

Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
Signed-off-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
Signed-off-by: iLeGend <824040212@qq.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 23, 2026
…peedai#9052)

Refs deepspeedai#9026 (open question 8), deepspeedai#9045.

### Why

A rollout replica that changes placement can often keep a
tensor-parallel shard that is still current, while the trainer's ZeRO-3
partitions hold the whole parameter. `plan_transfer` can read a block
from any of its holders only if the source map's blocks are equal or
disjoint and each block lists every holder. A map that simply lists both
layouts' pieces breaks both rules, since a partition can start or end
inside a row of the shard. So today the planner refuses it, and deepspeedai#9045
falls back to its own planner for these weights.

### What

- `union_affine_maps(maps)` in `deepspeed/checkpoint/affine.py` returns
one map of a parameter that several layouts hold at once.
- Each piece is cut at the edges of every block held over it, in any
layout (replicas within one layout may store a region whole or in
parts), and each cut piece lists the holders from every layout.
- A cut keeps the piece's strides and moves its offsets, so every
location still stores exactly what it did.
- Layouts use disjoint locations, one per buffer. `TransferEndpoints`
already lets several locations map to one process.
  - More than two layouts are merged pairwise.
- Blocks are taken in order of their first row, and each is compared
only with the parts that still reach into its rows; a piece is cut
against only the parts that start in its rows. That keeps the work close
to linear in the number of partitions (see Cost).
- Layouts that contradict each other raise `InvalidMapError`, and a
piece that is not an axis-aligned block raises `UnsupportedLayoutError`:
the planner's types for the same problems, so a caller that falls back
on `AffineTransferError` catches these too.
- `subtract` moves unchanged from `affine_transfer._subtract` into
`affine_geometry`, the module deepspeedai#9010 added for shared box arithmetic. The
planner imports it under its old name.
- Spec §10.8 and a section in `affine-transfer.rst`, after the
replica-policy section from deepspeedai#8936.

### Scope

Cuts along rows and along columns are both planned. A ZeRO-3 block of
several rows cut at a column edge keeps its row-major strides and its
partition's offset, so it is not dense in its flat shard; the planner
reads such shards since @0z5a's deepspeedai#9070.

### Cost

@jinyouzhi measured the first version growing with the square of the
number of ZeRO-3 partitions. `union_affine_maps` on a (4096, 4096)
parameter's ZeRO-3 partitions plus another layout, macOS arm64 CPU
(before = the previous version):

| Other layout | 200 partitions | 1000 partitions |
| --- | --- | --- |
| 8-way row split | 1.93 s → 0.03 s | 48.0 s → 0.18 s |
| 8-way column split | 11.0 s → 0.26 s | 1.3 s (34k pieces) |
| whole replica | 1.91 s → 0.03 s | 0.18 s |

A column split is the slowest case left, because each of its blocks
spans every row.

A union is cut at every layout's edges, so it can exceed the default
`PlanBudget` (4,096 pieces per map). `plan_transfer` on the same unions,
into a row-split and a column-split TP8 target (the same for both unless
noted):

| Partitions + other layout | Pieces | Default `PlanBudget()` |
`max_pieces_per_map=1 << 16` |
| --- | --- | --- | --- |
| 200 + 8-way row | 1,196 | planned | planned |
| 200 + 8-way column | 6,782 | refused (pieces) | planned |
| 1000 + 8-way row | 5,996 | refused (pieces) | planned |
| 1000 + 8-way column | 33,976 | refused (pieces) | into rows: planned
(2.3 s); into columns: refused at `max_merge_checks` (262,144), planned
(3.5 s) with `max_merge_checks` and `max_pair_checks` raised as well |

The docs now show the budget next to the call (thanks @delock).

### Tests

`test_affine_transfer_plan.py`:
- A surviving row shard plus ZeRO-3 partitions, in 4 configurations
(uneven TP sizes, one or two surviving ranks, 1 to 5 partitions),
planned into a row-split and a column-split target. Checked:
- each element's holders are exactly the union of both layouts' holders;
  - every location extracts what its own layout says;
  - every plan reproduces `extract` exactly;
  - the surviving shard is read.
- Three layouts merged in all six orders: the same holders, and exact
plans.
- A column cut, in 3 configurations (one or two surviving column shards,
2 to 7 partitions): holders, and exact plans into a row-split and a
column-split target that read the surviving shard. With deepspeedai#9070's planner
change reverted, 2 of the 3 are refused.
- A layout whose replicas store a block whole and in two halves, merged
with ZeRO-3 partitions: holders, and an exact plan into a column-split
target.
- Refusals, with the planner's error types: no maps, a location in both
layouts, different shapes, a transposed piece that is not a block, and a
row-major run that wraps into the next row.

`test_affine_transfer_executor.py`: on 2 ranks, one process holds a
ZeRO-3 partition and a surviving row shard under two locations. The plan
runs through `execute_transfer`, and every target shard equals
`extract`.

Not merging the holders, dropping the part of a block that a later block
doesn't overlap, or leaving the destination offset unmoved makes 9 of
these 11 tests fail. Setting a part aside one row too early, or ending
the search for the parts under a piece one row short, makes 6 and 7 of
them fail.

### Validation

The fifth commit changes only the spec and `affine-transfer.rst`: the
column cut is planned since deepspeedai#9070, and the example passes a `PlanBudget`
sized for a union.

Rebased on master c00a7f6, after deepspeedai#9070 and deepspeedai#9093 merged. The only
conflict was in `test_affine_transfer_executor.py`, where this PR and
deepspeedai#9093 added test classes at the same place; both are kept. The three
earlier commits are otherwise unchanged (`git range-diff`), and a fourth
extends the column-cut test to plan. macOS arm64 CPU, Python 3.9.6,
torch 2.8.0, gloo (`DS_ACCELERATOR=cpu LOCAL_SIZE=4`):
- All nine affine test files: 959 passed (master c00a7f6: 948 passed).
- yapf 0.43.0 and flake8 5.0.4 pass on the changed files.
- 300 random unions of ZeRO-3 partitions (1 to 8) and surviving column
shards (2 to 4 way, random widths, any non-empty subset), each planned
into a row split and a column split: all 600 plans are exact, and all
read a surviving shard.

On GPU: 4× A100-SXM4-40GB (NVLink), driver 595.71.05, torch
2.12.1+cu130, NCCL 2.29.7, Python 3.12.11, with `pytest --forked` over
the six `test_affine_*.py` files and `test_zero_affine.py`: this branch
905 passed and 1 skipped (master c00a7f6: 894 passed and 1 skipped),
so the 11 new tests also pass over NCCL.

Earlier, rebased on master 97aa3c1, after deepspeedai#9039 renamed the geometry
imports. The only conflicts were those imports and
`affine_geometry.__all__`; `subtract` now sits with master's unaliased
imports. macOS arm64 CPU, Python 3.9.6, torch 2.8.0, gloo
(`DS_ACCELERATOR=cpu LOCAL_SIZE=4`):
- All nine affine test files: 933 passed (master 97aa3c1: 924 passed).
- yapf 0.43.0 and flake8 5.0.4 pass on the changed files.
- Against the previous version, on 6,000 random unions of two or three
layouts (ZeRO-3 partitions, row and column splits, replicas, any subset
of surviving shards): identical pieces, the same holders for every
element, the same shard at every location, and the same refusals.

The runs below are from before that rebase and the cost change.

Earlier, rebased on master 892ed83, which includes deepspeedai#9011. The code and
test changes are the same as before the rebase; the only conflicts were
additions next to deepspeedai#9011's (`subtract` next to `boxes_disjoint` in
`affine_geometry.py`, and the imports). macOS arm64 CPU, Python 3.9.6,
torch 2.8.0, gloo (`DS_ACCELERATOR=cpu LOCAL_SIZE=4`):
- All eight affine test files: 715 passed (master 892ed83: 706
passed).
- yapf and flake8 pass on the files the rebase touched.

On master 988b2e3, before that rebase (with deepspeedai#9010 and deepspeedai#8936):
- All eight affine test files, then including deepspeedai#8936's
`test_affine_replica_policy.py`: 412 passed.
- The four union configurations above, planned through deepspeedai#8936's
`plan_transfers` with `local_first_least_loaded` and with `first_holder`
into both targets: all 16 plans reproduce `extract` exactly.
- Against the previous commit (110ff4b, before the two fixes from
review), on random layouts: 300 unions with a row-split surviving shard,
300 with a column-split one, and 300 of three or four layouts. Every
element has the same holders, and every plan into a row- or column-split
target has the same outcome as before: exact, except 82 of the
column-split cases, which both commits refuse (the column cut under
Scope).
- pre-commit passes on the changed files.

Before the rebase, on f9fe4df with deepspeedai#9010 applied:
- All seven affine test files: 346 passed.
- With deepspeedai#9011 on top: 648 passed. The only conflicts were adjacent
additions: import lines and appended definitions.
- 300 random two-layout cases (uneven TP sizes, any subset of surviving
ranks, 1 to 6 partitions):
  - holders and map-level exactness hold in every case;
  - cuts along rows: 137 of 137 planned and exact;
- cuts along columns: 79 planned and exact, and 84 refused by the
current planner.
- 300 random unions of three or four layouts, merged in random order:
all planned and exact.

On GPU, also before the rebase: 4× A100-SXM4-40GB (NVLink), driver
595.71.05, torch 2.12.1+cu130, NCCL 2.29.7, Python 3.12.11, with `pytest
--forked` over six of the affine test files (all but
`test_autoep_affine_universal.py`):
- master (8a6b53f): 317 passed, 1 skipped;
- this branch: 325 passed, 1 skipped, so the 8 new tests also pass over
NCCL, including the executor test.
- The one skip is the external-group test that runs only on the CPU
accelerator.

cc @0z5a @LiRunGuo @jinyouzhi

---------

Signed-off-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 23, 2026
deepspeedai#9145)

Refs deepspeedai#9026 (the cost model), deepspeedai#8252, deepspeedai#8935.

### Why

Plans that move the same data can differ in time by several times. Which
holder each target reads and the staging budget are free choices, and
the planner guarantees an exact result whichever is picked. In the runs
below, the default (the planner's first holder, the larger budget) is up
to 76% slower than the fastest candidate. A replica policy (deepspeedai#8935,
deepspeedai#8936), a two-stage relay (deepspeedai#9074) or a weight sync (deepspeedai#9045) needs a way
to compare candidates before running one. deepspeedai#8967 reports what a batch
moves and states that it does not model time; deepspeedai#8966 measures link rates.
This adds the step between them: a time estimate per candidate, and the
choice.

### What

`deepspeed/checkpoint/affine_transfer_cost.py`, which is not imported by
`import deepspeed`:
- `TransferCostModel(route, capacity, seconds_per_call,
seconds_per_round, seconds_per_region)`: one machine's calibrated costs.
`route(sender, receiver)` names the resources a message occupies;
`capacity` gives bytes per second per resource kind. Capacities must be
positive and finite, and the costs non-negative and finite.
- `node_route(nodes, intra_node)`: across nodes, the sender's
`network_send` and the receiver's `network_receive`; within a node, each
GPU's own link (`device_send`, `device_receive`, as on NVSwitch) or the
link between the two GPUs (`device_pair`, NVLink).
- `estimate_seconds(stages, model)`: each stage is one
`execute_transfers` call, and stages run one after another. A call's
rounds come from `schedule_transfers`, so the estimate prices the rounds
that `execute_transfers` will run. A round takes its most loaded
resource's bytes over that resource's capacity, plus
`seconds_per_round`. Copy launches, `seconds_per_region` for each staged
or local region of the busiest process, overlap the bytes, so a call
takes `seconds_per_call + max(rounds, launches)`. Rounds sent or
received in place launch no copy.
- `cheapest(candidates, model)`: estimates every candidate and returns
the cheapest name with every estimate. A tie goes to the name that sorts
first, so ranks given the same model and candidates choose the same
plan. The model must be built from data every rank shares.
- A section in `affine-transfer.rst`.

Not priced: a plan's one-time preparation (deepspeedai#9094), and overlap between
stages.

### Tests

`tests/unit/checkpoint/test_affine_transfer_cost.py`, single process.
Each expected time is computed in the test from the bytes and the given
capacities:
- A round takes its busiest resource, whether the sender's or the
receivers' side binds.
- Two resources in one round bind on their own (the mixed incast of RFC
deepspeedai#9026).
- Copy launches overlap the bytes; local copies count as regions; rounds
sent and received in place do not.
- The GH200 capacities of RFC deepspeedai#9026 give its model rows for direct (4 ×
8 GiB / 68.4 GB/s) and sharded (8 GiB / 23.4 GB/s), and the relay
through deepspeedai#8936's `local_first_least_loaded` is chosen.
- A tie goes to the first name.
- Refusals: a routed resource with no capacity, a process with no node,
a zero capacity, an unknown intra-node kind, no candidates.

Each of these changes to the module makes at least one test fail: adding
the resources instead of taking the busiest (3 fail), adding launches to
the bytes (1), counting in-place rounds as regions (1), counting each
message on both sides (2), dropping `seconds_per_round` (1), and
breaking ties toward the last name (1).

### Validation

macOS arm64 CPU, Python 3.9.6, torch 2.8.0, on master c00a7f6: the 6
tests pass; yapf 0.43.0 and flake8 5.0.4 pass on the new files.

On GPU, with this exact module file on master e35282b: 4 GPUs of an
8-GPU node, on two machines, driver 595.71.05, torch 2.12.1+cu130, NCCL
2.29.7:
- 4× A100-SXM4-40GB (NV12), AMD EPYC 7763;
- 4× H200 (NV18), Intel Xeon Platinum 8558.

On each, the 6 tests pass. Then a ranking test: 5 moves, each run as 2
to 4 candidate plans that deliver the same bf16 data and differ only in
the holders read or the staging budget (16 plans). Each plan's time is
the median of 7 runs after 3 warmups, from a barrier to the end of the
call, slowest process. The first run of every plan was checked exact
against the maps. The model was fitted on each machine from 8
calibration transfers only: one pair at 64 MiB, 256 MiB and 1 GiB in one
round and 1 GiB at 64 and 8 MiB budgets, a 1 GiB fan-out to three, a
fan-in of three times 1 GiB, and a gather of 2048 pieces of 4 KiB. The
candidates were fixed, and their times kept out of view, until the fit
was done. Regret is the chosen plan's time over the fastest measured:

| Move | Candidates | A100: model | A100: default | H200: model | H200:
default |
| --- | --- | --- | --- | --- | --- |
| 1 GiB held on 2 GPUs, into row halves on the other 2 | first holder or
one each, 16/64 MiB budget | 0% | 56.7% | 0% | 38.6% |
| DP2 × TP2 into TP4 (1 GiB) | first holder, local, local then the other
| 0.3% | 4.1% | 1.4% | 5.1% |
| Ring of 512 MiB blocks | budget 8/16/32/64 MiB | 0% | 0% | 0% | 0% |
| Rows to columns over 4 GPUs | budget 4/16/32 MiB | 0% | 0% | 0% | 0% |
| 16 weights of 64 MiB held on 2 GPUs, into row quarters on 4 | first
holder or split | 0% | 76.4% | 0% | 76.3% |

The estimates rank plans; they are not times. Against the measured times
of these 16 plans they range from 62% under to 15% over on the A100 node
(5 of 16 within 15%), and from 57% under to 5% under on the H200 node (3
of 16). Rerunning the scoring with the module on master c00a7f6 gives
byte-identical output on both machines.

Not validated:
- Across nodes: the `network_send` and `network_receive` terms are
checked only against the published GH200 numbers in the unit test; no
multi-node run here.
- Other accelerators: the module is pure Python over
`schedule_transfers` and calls no device or collective, but it was
calibrated only on these two NVIDIA machines.
- Turning `calibrate_links` (deepspeedai#8966) fits into these capacities is left
to the caller.

The module does not change any training, checkpoint or ZeRO code path,
so no ZeRO stage, offload, precision or parallelism setting is affected.

Signed-off-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com>
Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants