← Back to Pull requests

Complete ZeRO-3 serial checkpoint handoff for universal loads and rank boundaries #8898

Open
Levius-Fubuki opened this pull request with 157 lines diff across 3 files
View on GitHub
Levius-Fubuki Levius-Fubuki commented on Oct 24, 2026 00:53 UTC
Author

Fix ZeRO-3 serial checkpoint token handoff for valid Universal Checkpoint loads and non-default DP groups. Universal loading currently receives a token without forwarding it; legacy loading can use a DP-group rank as a global destination and can cross a local launcher boundary.

Use the shared handoff helper for legacy and universal loaders, forward to the next global rank, and stop at the launcher-local boundary. Legacy temporary checkpoint state is released before the send. No public signature, checkpoint format, or training arithmetic changes.

This is independent of #8897's rejection regression. Merged #8891 supplies DP-size preflight; this PR retains that implementation and fixes successful loads. #8892's neighboring restoration changes remain separate.

Published follow-up on 2026-10-30 (36246fed), integrating master 9148ab22 in the existing PR branch:

  • Capture accelerator device count before deleting launcher metadata in the fallback test, avoiding a CPU runner changing its inferred local size during the load.

  • Add a four-rank legacy checkpoint round trip using DP groups [0,2] / [1,3] and model groups [0,1] / [2,3]. It verifies exact model weights, FP32 masters, Adam moments/counters and engine step after restore, then compares the next loss and actual parameter update against uninterrupted training.

  • The four-process MPU topology exercises checkpoint group/rank addressing with SimpleModel; it is not a tensor-parallel model-training or multi-node validation claim.
  • Validation: Apple M3, macOS 15.1 ARM64, Python 3.12.13, torch 2.14.1, CPU/Gloo:

    DS_ACCELERATOR=cpu CUDA_VISIBLE_DEVICES=0,1,2,3 LOCAL_SIZE=4 GLOO_SOCKET_IFNAME=lo0 OMP_NUM_THREADS=1 PYTHONPATH=.:tests python -m pytest --forked tests/unit/checkpoint/test_universal_checkpoint.py::TestZeRO3SerialUniversalCheckpoint tests/unit/checkpoint/test_zero_optimizer.py::TestZeROCheckpoint::test_serial_checkpoint_with_launcher_topology tests/unit/checkpoint/test_zero_optimizer.py::TestZeROCheckpoint::test_serial_checkpoint_with_nondefault_dp_groups --torch_ver=2.14.1 -q
    

    9 passed: four Universal Checkpoint cases, four launcher/fallback cases, and the four-rank non-default-DP round trip. All applicable changed-file pre-commit hooks pass.

    Negative control: reverting only the helper's token-destination rank to the DP-group rank makes the four-process regression hang. The pytest timeout plugin reports a timeout/internal error at 25 seconds, and the external process-group deadline terminates the run at 75 seconds (exit 124). This is a timeout observation, not an ordinary assertion failure. The production helper was restored in finally; the exact four-process test then passes again.

    Historical validation on the original revision: 2×RTX 3090 24 GiB, driver 580.105.08, Python 3.12.3, torch 2.12.1+cu130, CUDA 13.0, NCCL 2.29.7; nine targeted cases passed, and the unchanged baseline reproduced Universal serial timeout and invalid global destination. A separate four-rank CPU reproducer exposed the legacy self-send. Those GPU results predate #8891 and do not validate this local integration/follow-up.

    Real CUDA/NCCL reruns of the updated tests, actual multi-node, four-GPU TP/DP, MoE, NVMe and vendor accelerators remain unvalidated. No throughput, convergence or peak-memory improvement is claimed. Arbitrary I/O/rank failures and recovery protocols are outside this patch.

    AI assistance (OpenAI Codex) was used for investigation, implementation and validation. The submitting human confirmed reviewing the final diff and running the relevant tests, and authorized DCO sign-off and publication of 36246fed.

    Diff: 157 lines (+152 / -5) across 3 files Reviewer: Levius-Fubuki Review duration: 57534m
    All Vouch review confidence checks passed
    Residual risk 0.12 = Change Risk (0.57) × (1 − Review Confidence (0.79)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 157 lines diff across 3 files
    0.57
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.94 · 5 substantive comment(s)
    0.94
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    79%
    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.303
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    10 items
    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 24, 2026 00:53 UTC
    Reviewer

    Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

    An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 24, 2026 00:53 UTC
    Bot

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

    Codex Review Summary

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

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ⚠️ Failed <relative-time datetime="2026-10-27T01:46:51.226282Z">2026-10-27T01:46:51.226282Z</relative-time><br/>We couldn’t complete this review. Comment @codex review to try again. | c084f27 | Manual request |

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

    Levius-Fubuki Levius-Fubuki commented on Oct 27, 2026 01:45 UTC
    Author

    @codex review

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 27, 2026 01:46 UTC
    Bot

    Codex Review: Something went wrong. Try again later by commenting “@codex review”.

    An unknown error occurred
    

    <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".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    Copilot Copilot commented on code on Oct 29, 2026 05:29 UTC
    Code Review
    tests/unit/checkpoint/test_zero_optimizer.py:1
    @@ -46,6 +46,44 @@ def test_pipeline_checkpoint_loading(self, tmpdir, zero_stage):
     
             checkpoint_correctness_verification(config_dict, models, hidden_dim, tmpdir, load_module_only=True)
     
    +    @pytest.mark.parametrize("local_size_variable",
    +                             ["LOCAL_WORLD_SIZE", "LOCAL_SIZE", "OMPI_COMM_WORLD_LOCAL_SIZE", None])
    +    def test_serial_checkpoint_with_launcher_topology(self, tmpdir, monkeypatch, local_size_variable):
    +        config = {
    +            "train_micro_batch_size_per_gpu": 1,
    +            "optimizer": {
    +                "type": "Adam",
    +                "params": {
    +                    "torch_adam": True
    +                }
    +            },
    +            "zero_optimization": {
    +                "stage": 3,
    +                "pipeline_loading_checkpoint": True
    +            },
    +        }
    +        model = SimpleModel(10, empty_grad=False)
    +        saved, _, _, _ = deepspeed.initialize(config=config, model=model, model_parameters=model.parameters())
    +        for batch in random_dataloader(model=saved,
    +                                       total_samples=2,
    +                                       hidden_dim=10,
    +                                       device=saved.device,
    +                                       dtype=torch.float32):
    +            saved.backward(saved(batch[0], batch[1]))
    +            saved.step()
    +        saved.save_checkpoint(tmpdir, tag="serial")
    +        model = SimpleModel(10, empty_grad=False)
    +        loaded, _, _, _ = deepspeed.initialize(config=config, model=model, model_parameters=model.parameters())
    +        # Change launcher metadata after device setup: this still uses single-host GPU transport.
    +        for name in ["LOCAL_WORLD_SIZE", "LOCAL_SIZE", "OMPI_COMM_WORLD_LOCAL_SIZE"]:
    +            monkeypatch.delenv(name, raising=False)
    +        if local_size_variable is not None:
    +            monkeypatch.setenv("LOCAL_RANK", "0")
    +            monkeypatch.setenv(local_size_variable, "1")

    The None case hangs on a single-NUMA-node CPU runner: deleting LOCAL_SIZE changes CPU_Accelerator.device_count() from the harness's two processes to one NUMA node. The handoff then skips rank 0's send while rank 1 remains blocked in the engine's receive. Capture the accelerator count before clearing launcher metadata and preserve that value for the fallback case.

    Copilot Copilot commented on code on Oct 29, 2026 05:29 UTC
    Code Review
    deepspeed/runtime/zero/stage3.py:1
    @@ -3632,18 +3634,26 @@ def load_state_dict(self,
                 # delete the temp state_dict_list variable to save memory, then trigger
                 # the next rank's loading
                 if load_serial is not None:
    -                load_serial += 1
                     rank = dist.get_rank(group=self.dp_process_group)
    -                local_rank = dist.get_local_rank()
                     del state_dict_list[rank]
    -                rank_end = dist.get_world_size() - 1
    -                if local_rank != rank_end:
    -                    dist.send(tensor=load_serial, dst=rank + 1)
    +                self._notify_next_checkpoint_rank(load_serial)
     
                 if len(self.persistent_parameters) > 0:
                     self.persistent_parameters[0].partition(self.persistent_parameters)
                     # self.persistent_parameters[0].all_gather(self.persistent_parameters) # this will be done in checkpoint_event_epilogue() so remove it to prevent double all_gather
     
    +    def _notify_next_checkpoint_rank(self, load_serial):
    +        if load_serial is None:
    +            return
    +        local_world_size = os.environ.get("LOCAL_WORLD_SIZE",
    +                                          os.environ.get("LOCAL_SIZE", os.environ.get("OMPI_COMM_WORLD_LOCAL_SIZE")))
    +        if local_world_size is None:
    +            local_world_size = get_accelerator().device_count()
    +        rank = dist.get_rank()

    Neither new regression uses a non-default DP group, so DP-group ranks equal global ranks throughout the committed tests. Reverting this line to dist.get_rank(group=self.dp_process_group) would therefore leave those tests passing while reintroducing the self-send/wrong-destination failure this PR fixes. Please add the reported four-rank/two-DP-group legacy round trip as an integration regression that checks completion and restored model/optimizer state.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 29, 2026 05:29 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    The fallback regression hangs on single-NUMA-node CPU runners, and the tests lack non-default DP-group coverage needed to catch the original self-send/wrong-destination failure.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Preserve accelerator count when clearing launcher metadata · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Add four-rank multi-DP-group legacy round-trip regression · New

  • </details>

    <sub>Review effort: Balanced</sub>

    Levius-Fubuki Levius-Fubuki commented on code on Oct 30, 2026 02:34 UTC
    Code Review
    tests/unit/checkpoint/test_zero_optimizer.py:1
    @@ -46,6 +46,44 @@ def test_pipeline_checkpoint_loading(self, tmpdir, zero_stage):
     
             checkpoint_correctness_verification(config_dict, models, hidden_dim, tmpdir, load_module_only=True)
     
    +    @pytest.mark.parametrize("local_size_variable",
    +                             ["LOCAL_WORLD_SIZE", "LOCAL_SIZE", "OMPI_COMM_WORLD_LOCAL_SIZE", None])
    +    def test_serial_checkpoint_with_launcher_topology(self, tmpdir, monkeypatch, local_size_variable):
    +        config = {
    +            "train_micro_batch_size_per_gpu": 1,
    +            "optimizer": {
    +                "type": "Adam",
    +                "params": {
    +                    "torch_adam": True
    +                }
    +            },
    +            "zero_optimization": {
    +                "stage": 3,
    +                "pipeline_loading_checkpoint": True
    +            },
    +        }
    +        model = SimpleModel(10, empty_grad=False)
    +        saved, _, _, _ = deepspeed.initialize(config=config, model=model, model_parameters=model.parameters())
    +        for batch in random_dataloader(model=saved,
    +                                       total_samples=2,
    +                                       hidden_dim=10,
    +                                       device=saved.device,
    +                                       dtype=torch.float32):
    +            saved.backward(saved(batch[0], batch[1]))
    +            saved.step()
    +        saved.save_checkpoint(tmpdir, tag="serial")
    +        model = SimpleModel(10, empty_grad=False)
    +        loaded, _, _, _ = deepspeed.initialize(config=config, model=model, model_parameters=model.parameters())
    +        # Change launcher metadata after device setup: this still uses single-host GPU transport.
    +        for name in ["LOCAL_WORLD_SIZE", "LOCAL_SIZE", "OMPI_COMM_WORLD_LOCAL_SIZE"]:
    +            monkeypatch.delenv(name, raising=False)
    +        if local_size_variable is not None:
    +            monkeypatch.setenv("LOCAL_RANK", "0")
    +            monkeypatch.setenv(local_size_variable, "1")

    Thank you for pointing this out. Fixed in 36246fed: the accelerator device count is captured before clearing launcher metadata and preserved for the fallback case.

    All four launcher/fallback cases pass on Apple M3 CPU/Gloo. The full updated serial/universal selection, including the four-process non-default-DP regression, reports 9 passed; changed-file pre-commit checks pass (macOS 15.1 ARM64, Python 3.12.13, torch 2.14.1).

    The follow-up is now pushed and the PR description has been updated. No new CUDA/NCCL validation is claimed. Thank you for catching this.

    Levius-Fubuki Levius-Fubuki commented on code on Oct 30, 2026 02:35 UTC
    Code Review
    deepspeed/runtime/zero/stage3.py:1
    @@ -3632,18 +3634,26 @@ def load_state_dict(self,
                 # delete the temp state_dict_list variable to save memory, then trigger
                 # the next rank's loading
                 if load_serial is not None:
    -                load_serial += 1
                     rank = dist.get_rank(group=self.dp_process_group)
    -                local_rank = dist.get_local_rank()
                     del state_dict_list[rank]
    -                rank_end = dist.get_world_size() - 1
    -                if local_rank != rank_end:
    -                    dist.send(tensor=load_serial, dst=rank + 1)
    +                self._notify_next_checkpoint_rank(load_serial)
     
                 if len(self.persistent_parameters) > 0:
                     self.persistent_parameters[0].partition(self.persistent_parameters)
                     # self.persistent_parameters[0].all_gather(self.persistent_parameters) # this will be done in checkpoint_event_epilogue() so remove it to prevent double all_gather
     
    +    def _notify_next_checkpoint_rank(self, load_serial):
    +        if load_serial is None:
    +            return
    +        local_world_size = os.environ.get("LOCAL_WORLD_SIZE",
    +                                          os.environ.get("LOCAL_SIZE", os.environ.get("OMPI_COMM_WORLD_LOCAL_SIZE")))
    +        if local_world_size is None:
    +            local_world_size = get_accelerator().device_count()
    +        rank = dist.get_rank()

    Thank you for the suggestion. Added in 36246fed: a real four-process legacy round-trip regression uses DP groups [0,2] / [1,3], where group ranks differ from global ranks. It checks exact restored model weights, FP32 masters, Adam moments/counters and engine step, then compares the next loss and actual parameter update against uninterrupted training.

    The test passes on Apple M3 CPU/Gloo. Reverting only the token destination to the DP-group rank reproduces a hang; after restoring the helper, the same test passes again. The full serial/universal selection reports 9 passed, with changed-file pre-commit checks passing (macOS 15.1 ARM64, Python 3.12.13, torch 2.14.1).

    The MPU topology exercises checkpoint addressing with SimpleModel; it is not full tensor-parallel-model or multi-node validation. The follow-up is now pushed, and no new CUDA/NCCL run is claimed. Thank you for helping strengthen the regression coverage.

    Reviewers
    Assignees
    Levius-Fubuki Levius-Fubuki
    Labels
    risk: low confidence: 79.2% 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: 57.2% (MEDIUM) · Higher = larger blast radius
    57.2%
    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: 79.2% · Lower = rushed or shallow review
    79.2%
    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: 11.9% · Safe to merge
    11.9%