← Back to Pull requests

[AffineIR] Fused copies, symmetric-memory window and staging release for prepared affine transfers #9118

Open
jinyouzhi opened this pull request with 1995 lines diff across 7 files
View on GitHub
jinyouzhi jinyouzhi commented on Nov 18, 2026 10:44 UTC
Author

Stacked on #9094, which is itself rebased on #9093 (RFC #9026, step after "prepare once, run per step"). Until both merge, only the last four commits belong to this PR:

  • [checkpoint] Fused region copies for prepared affine transfers

  • [comm] Expose symmetric-memory rendezvous and peer tensors

  • [checkpoint] Copy window shards in place and release staging between runs

  • [checkpoint] Check window copies for aliases and keep 16-byte elements off the tile kernel
  • As agreed with @0z5a on #9026, the fused copy and the window transport share one PR and one copy-table format. copy_ stays the default everywhere.

    What changes

    Fused copies (opt-in copier=)

  • prepare_transfers(..., copier=fused_copies) replaces each round's pack, unpack and local-copy lists with a single Triton kernel launch (copy_tiles). The kernel reads a table of addresses, strides and extents for each region.

  • sequential_copies (one copy_ per view) is the default and keeps current behaviour.

  • fused_copies falls back to copy_ for views it cannot tile, for elements that are not 1, 2, 4 or 8 bytes (complex128), for host tensors, and when Triton is unavailable.

  • The kernel uses only generic Triton ops. The same code runs on CUDA and on XPU (Triton XPU backend). Triton is imported lazily, so CPU workers never touch a device driver.

  • The copier is built inside _agree. If building it fails, every process refuses the batch.
  • Symmetric-memory window (opt-in window=)

  • deepspeed.comm gains symm_mem_rendezvous and symm_mem_peer_tensor, so torch.distributed stays behind deepspeed/comm.

  • Tensors placed in a TransferWindow are copied directly into or out of the peer's window, pull or push, and skip the staged rounds.

  • Window copies use the same copier as the staged lists.

  • TransferStats.mapped_bytes reports how many bytes went through the window.

  • The window layout is part of the agreed fingerprint, so mismatched placements refuse the batch on every process.

  • Window copies take part in the region-level alias check from #9093: a pulled or pushed target counts as a write, a pulled or pushed source as a read on the process that owns it.

  • Each window gets an identity and its member ranks when it is built. A window built over another group, or different windows on different processes, refuse the batch on every process.

  • Window memory is never sent or received in place. NCCL leaves send/recv undefined when one side's buffer is registered and the peer's is not, so a staged region in any live window (passed or not) goes through the plain arena.

  • The handle keeps the window alive. Without check, a run with window copies starts with a group barrier, so peers never read a shard its owner is still writing.

  • Every process must pass the same window, or none. A window passed on only some processes, or a failure while building it, hangs instead of refusing; the docstring and the docs say so.

  • Available on execute_transfer, execute_transfers and prepare_transfers.
  • Staging lifecycle

  • PreparedTransfer.release_staging() frees the staging arenas, round views and copier tables between runs, for example during training steps.

  • A process may release on its own; the next run() re-stages them. With check=True, a failure while re-staging refuses on every process.
  • Why this is not a duplicate

    #9094 adds the prepared handle with copy_ only. This PR is the follow-up proposed in #9026 §5: the fused copy, the window transport and release_staging(). No other open PR touches affine_transfer_executor.py beyond #9094.

    Tests

    pytest tests/unit/checkpoint/test_affine_transfer_executor.py
    

    | Platform | Result |
    |---|---|
    | CPU, gloo (DS_ACCELERATOR=cpu), current head | 94 passed, 27 skipped (window and Triton tests need a GPU) |
    | 4× Intel Arc Pro B70, xe driver (kernel 6.19.10), torch 2.14.0.dev20260804+xpu, triton 3.8.0 (xpu), xccl, current head | all pass at 2 and 4 processes |
    | 4× NVIDIA L20, torch 2.14.1+cu130, NCCL 2.30.7, current head | 125 passed |

    New tests:

  • every copy list goes through the copier;

  • fused copies match copy_ for every region shape (strided, transposed, misaligned, 0-d, empty);

  • window transfers for each placement × copier, prepared and one-shot;

  • schedules leave window copies out of the rounds;

  • a released handle stages again on its next run (2 and 4 processes);

  • fused copies for complex64 and complex128;

  • a window region written on one process while a peer reads it is refused (pull and push, prepared and one-shot);

  • one process may release on its own; a process that cannot stage again stops every process with check=True;

  • different windows on different processes are refused;

  • a window shard that is not passed as window= is staged, never sent in place (fails without the fix);

  • fused copies of empty and single-element regions.
  • Performance

    Workload: Qwen3-4B, 398 bf16 tensors. 2-D weights move from a row split to a column split over N processes, and 1-D weights move between shifted even splits. Each cell is the median of 5 warm PreparedTransfer.run() calls in ms (lower is better); copy_ vs fused_copies.

    8× Arc Pro B70 (cards 8–15, xccl):

    | N | staging | copy_ | fused | Δ |
    |---|---|---|---|---|
    | 2 | 8 MiB | 162.6 | 171.6 | +5.5% |
    | 2 | 64 MiB | 123.7 | 124.2 | +0.5% |
    | 4 | 8 MiB | 164.9 | 165.0 | 0.0% |
    | 4 | 64 MiB | 137.6 | 136.7 | −0.7% |
    | 8 | 8 MiB | 103.2 | 99.6 | −3.6% |
    | 8 | 64 MiB | 109.0 | 104.7 | −4.0% |

    4× L20:

    | N | staging | copy_ | fused | Δ |
    |---|---|---|---|---|
    | 2 | 64 MiB | 103.5 | 102.1 | −1.4% |
    | 4 | 8 MiB | 84.4 | 81.5 | −3.4% |
    | 4 | 64 MiB | 86.1 | 80.4 | −6.6% |

  • The fused copy helps more as N grows, because each round has more regions. At N=2 the runs are dominated by communication, and on B70 the 8 MiB case is slightly slower.

  • prepare_transfers with fused_copies costs an extra 50–75 ms once, to build the tables and compile the kernel. This is why copy_ stays the default.

  • Window transport, run() median at 64 MiB staging:
  • | Platform | N | staged | window pull | window push |
    |---|---|---|---|---|
    | L20 | 4 | 83.6 | 83.8 | 79.2 |
    | B70 | 2 | 123.7 | 90.5 | 98.3 |

  • Peak memory: release_staging() frees all staging buffers between runs. Without it, memory use is the same as #9094.
  • Compatibility

  • Only the affine checkpoint transfer path changes, and every new feature is opt-in. ZeRO stages, offload and the engine are untouched.

  • Tested with bf16 only. Multi-node runs and the window across nodes were not tested. The window needs torch.distributed._symmetric_memory.
  • AI assistance was used for this change.

    Diff: 1995 lines (+1883 / -112) across 7 files Reviewer: jinyouzhi Review duration: 20942m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.66) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.66 · 1995 lines diff across 7 files
    0.66
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.93 · 5 substantive comment(s)
    0.93
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    84%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    10 items
    jinyouzhi jinyouzhi commented on Nov 20, 2026 16:27 UTC
    Author

    Thanks for the review. Rebased onto the current #9094 (on #9093) and addressed each point in 95e799dd4:

    1. 16-byte elements. fused_copies now sends any element size outside {1, 2, 4, 8} to copy_, and the kernel asserts ELEMENT == 8 in the last branch. The fused test covers complex64 and complex128; complex128 fails without the fix.
    2. Window copies and region aliases. _validate_aliases also takes the window operations of this process: a pulled/pushed target counts as a write, a pulled/pushed source as a read. New 2-process test: each rank's source shard and a target the peer writes are the same window tensor; every process refuses with "a source and a target overlap" and the shard is unchanged (pull/push × prepared/one-shot). The four cases do not raise without the fix.
    3. Partial window / construction failure. Documented in TransferWindow and in the docs: pass the same window on every process or none.
    4. release_staging. Relaxed the docstring: a process may release on its own; use check=True if re-allocation can fail. Added a test for that.
    5. check=True restage failure. New test: the last rank fails to re-stage, every process raises "could not allocate the released staging", targets are unchanged, and the next run succeeds.
    6. PR body. Fixed the pytest line.

    CPU (gloo): 94 passed, 27 skipped. 4× B70 (xccl): all pass at 2 and 4 processes.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 26, 2026 06:47 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"2725eb4d2ea167529290755747f2feffeab6c14d","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

    <details>
    <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

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

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-26T07:02:45.398233Z">2026-11-26T07:02:45.398233Z</relative-time> | 2725eb4 | Draft marked ready |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    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.

    </details>

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 26, 2026 07:02 UTC
    Code Review
    deepspeed/checkpoint/affine_transfer_executor.py:1
    @@ -587,84 +898,396 @@ def execute_transfers(requests: Sequence[TransferRequest],
             for plan in plans:
                 if id(plan) not in digests:
                     digests[id(plan)] = plan_digest(plan, endpoints, budget, element_size)
    +        if window is not None and initialized and (len(window.members) != world_size
    +                                                   or window.members[rank] != dist.get_rank()):
    +            raise AffineTransferExecutionError('the window was created over a different group than the transfer')
    +        # Which window, which shards lie in it and who copies decide what each process does, so ranks must
    +        # agree on them.
    +        mapping = None if window is None else (window.identity, window.members, window.direction,
    +                                               tuple(sorted(offsets.items())))
             fingerprint = (3, str(dtype), budget.bytes_per_peer, tuple(sorted(endpoints.source.items())),
                            tuple(sorted(endpoints.target.items())),
    -                       tuple((request.key, digests[id(request.plan)]) for request in requests))
    +                       tuple((request.key, digests[id(request.plan)]) for request in requests), mapping)
             digest = zlib.crc32(repr(fingerprint).encode())
    +        window_locations = None if window is None else _window_locations(requests, offsets)
             # The same computation as schedule_transfers, so what it reports is what runs here.
    -        lane = _lanes(indexed, [rank], budget.bytes_per_peer // element_size)[rank]
    -        local_copies, recv_rounds, send_rounds = lane.local_copies, lane.recv_rounds, lane.send_rounds
    -        if aliased:
    -            local_copies = _validate_aliases(requests, lane, element_size)
    -        recv_direct = {
    -            peer: [
    -                _direct_payload(entries, requests, dtype, False) if direct else None
    -                for (entries, _), direct in zip(rounds, lane.recv_direct[peer])
    -            ]
    -            for peer, rounds in recv_rounds.items()
    -        }
    -        send_direct = {
    -            peer: [
    -                _direct_payload(entries, requests, dtype, True) if direct else None
    -                for (entries, _), direct in zip(rounds, lane.send_direct[peer])
    -            ]
    -            for peer, rounds in send_rounds.items()
    -        }
    -        recv_arenas = {peer: torch.empty(size, dtype=dtype, device=device) for peer, size in lane.recv_arena.items()}
    -        send_arenas = {peer: torch.empty(size, dtype=dtype, device=device) for peer, size in lane.send_arena.items()}
    +        paused = _collector_paused() if keep else contextlib.nullcontext()
    +        with paused:
    +            lane = _lanes(indexed, [rank], budget.bytes_per_peer // element_size, window_locations,
    +                          _registered_locations(requests))[rank]
    +            # A local copy whose source and target are the same memory moves nothing. It is dropped here,
    +            # before the agreement, for a one-shot move and for every run of a prepared handle.
    +            if aliased:
    +                window_operations = [] if window_locations is None else [
    +                    (item, operation) for item, operation in indexed
    +                    if rank in (operation.from_process, operation.to_process)
    +                    and _mapped_direction(item, operation, window_locations, window.direction) is not None
    +                ]
    +                copies = _validate_aliases(requests, lane, element_size, rank, window_operations)
    +            else:
    +                copies = lane.local_copies
    +            recv_arenas = {
    +                peer: torch.empty(size, dtype=dtype, device=device)
    +                for peer, size in lane.recv_arena.items()
    +            }
    +            send_arenas = {
    +                peer: torch.empty(size, dtype=dtype, device=device)
    +                for peer, size in lane.send_arena.items()
    +            }
    +            mapped, mapped_bytes, mapped_total = _mapped_share(indexed, window_locations, window, rank)
    +            if keep:
    +                rounds = list(_round_views(lane, recv_arenas, send_arenas, requests, dtype))
    +                local_copies = tuple(_local_copy_views(copies, requests, dtype))
    +                mapped_copies = tuple(_mapped_copy_views(mapped, requests, offsets, window, dtype))
    +                layout = _buffer_layout(requests)
    +                if copier is None:
    +                    from .affine_transfer_copy import sequential_copies as copier
    +                # Built here so that a copier failing on one process refuses the batch on every process.
    +                packs, unpacks = _round_copiers(rounds, copier)
    +                local_copy = copier([(target, source) for target, source, _ in local_copies])
    +                # A peer's window is device memory mapped into this process, so the same table format covers
    +                # copies whose destination or source lies in it.
    +                if mapped_copies:
    +                    mapped_copy = copier(mapped_copies)
         except (ValueError, TypeError, KeyError, AttributeError, RuntimeError, OverflowError, MemoryError) as caught:

    <sub><sub>!P1 Badge</sub></sub> Fold all copier build failures into collective rejection

    When a user-supplied copier raises an exception not in this whitelist (for example AssertionError or OSError) on just one rank while _round_copiers/copier(...) is being built, that rank exits _agree before the decision all-gather while the other ranks block in it. PreparedTransfer.run repeats the same narrow catch when rebuilding after release_staging, so the documented collective-refusal behavior also fails there; catch ordinary Exception from the copier boundary and turn it into the shared rejected/failed flag.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 26, 2026 07:02 UTC
    Code Review
    deepspeed/checkpoint/affine_transfer_executor.py:1
    @@ -533,15 +744,103 @@ def execute_transfers(requests: Sequence[TransferRequest],
                           endpoints: TransferEndpoints,
                           dtype: torch.dtype,
                           budget: StagingBudget = StagingBudget(),
    -                      group: Optional[object] = None) -> TransferStats:
    +                      group: Optional[object] = None,
    +                      window: Optional[TransferWindow] = None) -> TransferStats:
         """Move a frozen parameter batch with collective preflight and bounded peer messages.
     
         Each direction stages at most ``bytes_per_peer`` per active peer. All requests and staging
         allocations are checked before payload, including read/write aliases between parameters.
         The caller stream's final unpack and local copies complete before this function returns.
    +    With a ``window`` (the same one on every process), operations touching window shards are copied
    +    in place and the call ends with a group barrier, so no peer reads or writes them after return.
    +    A batch moved repeatedly can be prepared once with ``prepare_transfers`` instead.
    +    """
    +    agreed = _agree(requests, endpoints, dtype, budget, group, keep=False, window=window)
    +    lane = agreed.lane
    +    # Nothing outlives this call, so each round's views are built when the move reaches it, while the
    +    # round before may still be in flight, instead of all of them before the first byte moves.
    +    rounds = _round_views(lane, agreed.recv_arenas, agreed.send_arenas, requests, dtype)
    +    local_copies = _local_copy_views(agreed.copies, requests, dtype)
    +    mapped_copies = _mapped_copy_views(agreed.mapped, requests, agreed.offsets, window, dtype)

    <sub><sub>!P1 Badge</sub></sub> Resolve one-shot peer mappings before moving data

    _mapped_copy_views is a generator, so in the one-shot execute_transfers(..., window=...) path this line does not call TransferWindow.peer until _run_mapped, after _run_rounds has already sent data and written staged/local targets. If peer-tensor construction fails on only one process (for example a backend cannot map that peer/dtype), that process raises outside _agree while the others wait at the final window barrier, and the advertised preflight/no-write rejection is lost. Materialize these views during agreement, as the prepared path does.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 26, 2026 07:02 UTC
    Code Review
    deepspeed/checkpoint/affine_transfer_executor.py:1
    @@ -508,13 +717,15 @@ def schedule_transfers(plans: Sequence[TransferPlan],
             for segment in plan.segments:
                 if segment.source_rank not in endpoints.source or segment.target_rank not in endpoints.target:
                     raise AffineTransferExecutionError(f'{segment!r} names a location with no endpoint binding')
    +    if window_locations is not None and len(window_locations) != len(plans):
    +        raise AffineTransferExecutionError('window_locations must name one pair of location sets per plan')
         indexed = _indexed_operations(plans, endpoints, budget, element_size)
         named = set(endpoints.source.values()) | set(endpoints.target.values())
         if process is not None and process not in named:
             raise AffineTransferExecutionError(f'process {process} is not named by the endpoints')
         processes = sorted(named) if process is None else [process]
         schedules = {}
    -    for member, lane in _lanes(indexed, processes, budget.bytes_per_peer // element_size).items():
    +    for member, lane in _lanes(indexed, processes, budget.bytes_per_peer // element_size, window_locations).items():

    <sub><sub>!P2 Badge</sub></sub> Account for registered buffers in reported schedules

    When a request buffer belongs to any live TransferWindow that is not passed as window, _agree supplies _registered_locations(requests) to _lanes so that side is staged rather than used as a direct NCCL buffer, but schedule_transfers calls _lanes here with registered=None. The public schedule therefore reports direct=True and no arena even though execution allocates and uses an arena; window_locations cannot represent this because it removes those operations as mapped copies. Add a registered-location input/state so memory and cost policies see the schedule that actually runs.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 26, 2026 07:02 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 2725eb4d2e

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    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".

    </details>

    jinyouzhi jinyouzhi commented on code on Nov 27, 2026 19:51 UTC
    Code Review
    deepspeed/checkpoint/affine_transfer_executor.py:1
    @@ -587,84 +898,396 @@ def execute_transfers(requests: Sequence[TransferRequest],
             for plan in plans:
                 if id(plan) not in digests:
                     digests[id(plan)] = plan_digest(plan, endpoints, budget, element_size)
    +        if window is not None and initialized and (len(window.members) != world_size
    +                                                   or window.members[rank] != dist.get_rank()):
    +            raise AffineTransferExecutionError('the window was created over a different group than the transfer')
    +        # Which window, which shards lie in it and who copies decide what each process does, so ranks must
    +        # agree on them.
    +        mapping = None if window is None else (window.identity, window.members, window.direction,
    +                                               tuple(sorted(offsets.items())))
             fingerprint = (3, str(dtype), budget.bytes_per_peer, tuple(sorted(endpoints.source.items())),
                            tuple(sorted(endpoints.target.items())),
    -                       tuple((request.key, digests[id(request.plan)]) for request in requests))
    +                       tuple((request.key, digests[id(request.plan)]) for request in requests), mapping)
             digest = zlib.crc32(repr(fingerprint).encode())
    +        window_locations = None if window is None else _window_locations(requests, offsets)
             # The same computation as schedule_transfers, so what it reports is what runs here.
    -        lane = _lanes(indexed, [rank], budget.bytes_per_peer // element_size)[rank]
    -        local_copies, recv_rounds, send_rounds = lane.local_copies, lane.recv_rounds, lane.send_rounds
    -        if aliased:
    -            local_copies = _validate_aliases(requests, lane, element_size)
    -        recv_direct = {
    -            peer: [
    -                _direct_payload(entries, requests, dtype, False) if direct else None
    -                for (entries, _), direct in zip(rounds, lane.recv_direct[peer])
    -            ]
    -            for peer, rounds in recv_rounds.items()
    -        }
    -        send_direct = {
    -            peer: [
    -                _direct_payload(entries, requests, dtype, True) if direct else None
    -                for (entries, _), direct in zip(rounds, lane.send_direct[peer])
    -            ]
    -            for peer, rounds in send_rounds.items()
    -        }
    -        recv_arenas = {peer: torch.empty(size, dtype=dtype, device=device) for peer, size in lane.recv_arena.items()}
    -        send_arenas = {peer: torch.empty(size, dtype=dtype, device=device) for peer, size in lane.send_arena.items()}
    +        paused = _collector_paused() if keep else contextlib.nullcontext()
    +        with paused:
    +            lane = _lanes(indexed, [rank], budget.bytes_per_peer // element_size, window_locations,
    +                          _registered_locations(requests))[rank]
    +            # A local copy whose source and target are the same memory moves nothing. It is dropped here,
    +            # before the agreement, for a one-shot move and for every run of a prepared handle.
    +            if aliased:
    +                window_operations = [] if window_locations is None else [
    +                    (item, operation) for item, operation in indexed
    +                    if rank in (operation.from_process, operation.to_process)
    +                    and _mapped_direction(item, operation, window_locations, window.direction) is not None
    +                ]
    +                copies = _validate_aliases(requests, lane, element_size, rank, window_operations)
    +            else:
    +                copies = lane.local_copies
    +            recv_arenas = {
    +                peer: torch.empty(size, dtype=dtype, device=device)
    +                for peer, size in lane.recv_arena.items()
    +            }
    +            send_arenas = {
    +                peer: torch.empty(size, dtype=dtype, device=device)
    +                for peer, size in lane.send_arena.items()
    +            }
    +            mapped, mapped_bytes, mapped_total = _mapped_share(indexed, window_locations, window, rank)
    +            if keep:
    +                rounds = list(_round_views(lane, recv_arenas, send_arenas, requests, dtype))
    +                local_copies = tuple(_local_copy_views(copies, requests, dtype))
    +                mapped_copies = tuple(_mapped_copy_views(mapped, requests, offsets, window, dtype))
    +                layout = _buffer_layout(requests)
    +                if copier is None:
    +                    from .affine_transfer_copy import sequential_copies as copier
    +                # Built here so that a copier failing on one process refuses the batch on every process.
    +                packs, unpacks = _round_copiers(rounds, copier)
    +                local_copy = copier([(target, source) for target, source, _ in local_copies])
    +                # A peer's window is device memory mapped into this process, so the same table format covers
    +                # copies whose destination or source lies in it.
    +                if mapped_copies:
    +                    mapped_copy = copier(mapped_copies)
         except (ValueError, TypeError, KeyError, AttributeError, RuntimeError, OverflowError, MemoryError) as caught:

    Fixed in 3eb069b6a and 70f40973b. Caller copiers are wrapped with _safe_copier, and both _agree and PreparedTransfer.run (when restaging after release_staging) now catch Exception so any build or restaging failure folds into the collective refusal. Added multi-rank regressions for AssertionError and OSError across both prepare_transfers and release_staging rebuilds.

    jinyouzhi jinyouzhi commented on code on Nov 27, 2026 19:51 UTC
    Code Review
    deepspeed/checkpoint/affine_transfer_executor.py:1
    @@ -533,15 +744,103 @@ def execute_transfers(requests: Sequence[TransferRequest],
                           endpoints: TransferEndpoints,
                           dtype: torch.dtype,
                           budget: StagingBudget = StagingBudget(),
    -                      group: Optional[object] = None) -> TransferStats:
    +                      group: Optional[object] = None,
    +                      window: Optional[TransferWindow] = None) -> TransferStats:
         """Move a frozen parameter batch with collective preflight and bounded peer messages.
     
         Each direction stages at most ``bytes_per_peer`` per active peer. All requests and staging
         allocations are checked before payload, including read/write aliases between parameters.
         The caller stream's final unpack and local copies complete before this function returns.
    +    With a ``window`` (the same one on every process), operations touching window shards are copied
    +    in place and the call ends with a group barrier, so no peer reads or writes them after return.
    +    A batch moved repeatedly can be prepared once with ``prepare_transfers`` instead.
    +    """
    +    agreed = _agree(requests, endpoints, dtype, budget, group, keep=False, window=window)
    +    lane = agreed.lane
    +    # Nothing outlives this call, so each round's views are built when the move reaches it, while the
    +    # round before may still be in flight, instead of all of them before the first byte moves.
    +    rounds = _round_views(lane, agreed.recv_arenas, agreed.send_arenas, requests, dtype)
    +    local_copies = _local_copy_views(agreed.copies, requests, dtype)
    +    mapped_copies = _mapped_copy_views(agreed.mapped, requests, agreed.offsets, window, dtype)

    Fixed in 3eb069b6a and 70f40973b. _agree now materializes both _local_copy_views and _mapped_copy_views during agreement for the one-shot path as well, and catches Exception so a rank-local TransferWindow.peer failure of any kind refuses the batch collectively before any data moves (test_a_one_shot_refuses_whole_before_data_moves_when_a_map_fails_on_one_rank).

    jinyouzhi jinyouzhi commented on code on Nov 27, 2026 19:51 UTC
    Code Review
    deepspeed/checkpoint/affine_transfer_executor.py:1
    @@ -508,13 +717,15 @@ def schedule_transfers(plans: Sequence[TransferPlan],
             for segment in plan.segments:
                 if segment.source_rank not in endpoints.source or segment.target_rank not in endpoints.target:
                     raise AffineTransferExecutionError(f'{segment!r} names a location with no endpoint binding')
    +    if window_locations is not None and len(window_locations) != len(plans):
    +        raise AffineTransferExecutionError('window_locations must name one pair of location sets per plan')
         indexed = _indexed_operations(plans, endpoints, budget, element_size)
         named = set(endpoints.source.values()) | set(endpoints.target.values())
         if process is not None and process not in named:
             raise AffineTransferExecutionError(f'process {process} is not named by the endpoints')
         processes = sorted(named) if process is None else [process]
         schedules = {}
    -    for member, lane in _lanes(indexed, processes, budget.bytes_per_peer // element_size).items():
    +    for member, lane in _lanes(indexed, processes, budget.bytes_per_peer // element_size, window_locations).items():

    Fixed in 3eb069b6a. schedule_transfers now accepts per-process window_registered locations and forwards them to _lanes, reporting direct=False and the staging arena size whenever a round touches registered window memory (test_schedule_stages_a_round_that_starts_in_a_registered_window).

    Reviewers
    Assignees
    jinyouzhi jinyouzhi
    Labels
    risk: low confidence: 84.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 65.8% (HIGH) · Higher = larger blast radius
    65.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.9% · Lower = rushed or shallow review
    84.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 10.0% · Safe to merge
    10.0%