Repository navigation
ZeRO-1/2: one CPU-offload accumulator per group; zero idle gradients - #9018
Merged
Merged
Conversation
buffers allocated on first use. FP32 masters get owned buffers sized to the whole parameter; low-precision masters get aliased views of the partition gradient. Every reader branches on which kind it holds, the buffers are never unpinned, and the restore path leaves stale scratch data that the overflow scan reads. Replace the dict with one host buffer per partition group, sized to the partition and indexed by the same dest_offset as the FP32 partition. It is allocated on the first non-boundary accumulation, so boundary-only (GAS=1) training pins no extra host memory. Low-precision masters keep accumulating in the partition gradient. The buffers are unpinned with the other offload buffers, and restore clears the scratch tensor before copying this rank's fragment. Also fix a stale-gradient leak (#8991): reset_cpu_buffers now zeros each FP32 partition gradient, so a parameter that is idle in the next window does not have its previous gradient applied again by the optimizer. Remove set_norm_for_param_grad, which has no callers. Co-authored-by: Cursor <cursoragent@cursor.com> Signed-off-by: Olatunji Ruwase <tunji.ruwase@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
sfc-gh-truwase
requested review from
loadams,
tjruwase and
tohtana
as code owners
November 5, 2026 14:02
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
stas00
approved these changes
Nov 5, 2026
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 5, 2026
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 5, 2026
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 6, 2026
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 6, 2026
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 7, 2026
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 11, 2026
…sts (deepspeedai#9044) ## Summary Follow-up to deepspeedai#9018 (merged as `a4c989b7`). With CPU offload, the compact partition-sized accumulator (used for fp32 accumulation on a 16-bit model) now publishes to the host partition gradient at each request boundary and is freed between requests when the host copy can restore it exactly. - The device partition is freed after the boundary copy only if the host gradient restores the running sum bit for bit (same dtype, or an fp32 host holding bf16/fp16 values). The next backward in the same optimizer window restores it. Otherwise (for example bf16 masters with fp32 accumulation) it stays resident until `step()`. - The gate for the compact buffer is unchanged from before this series: fp32 accumulation on a 16-bit model, in the stages and offload modes that already used it (including stage 1 with offload). Muon groups keep the host accumulator. The default bf16/fp16 accumulation keeps the per-parameter path, so no partition-sized device buffer is added for it. - Overflow is now checked on the value cast to the host gradient dtype. With fp16 master weights and fp32 accumulation, an fp32 sum above the fp16 range used to pass the check and become inf on the host; it now skips the step. - Legacy host path: gradients that a non-boundary backward left only in the host accumulator are published at the next boundary (`_publish_unpublished_offload_grads`). - `config.py` is unchanged: fp32 accumulation with fp16/bf16 master weights is not rejected, as before. - New option `zero_optimization.retain_gpu_grad_partition_until_step` (default `false`). The default frees the fp32 gradient partition from GPU memory between requests. Set it to `true` to keep the partition in GPU memory until `step()`; GPU memory use between requests then rises by one partition per rank. With `true`, memory returns to the base level and the backward returns to base timing (Qwen3-4B stage 2, 1 GPU: 455 ms vs base 474 ms; synthetic: 14.4 ms vs 14.1 ms). Step time is unchanged. Test: `test_zero_offload_accum_precision.py::TestZeroOffloadReleaseOption` checks residency per boundary and that the final weights match in both settings. **Unsupported: bf16 master weights with fp32 gradient accumulation.** The host gradient is bf16 and cannot hold the fp32 sum, so the GPU partition is not released between requests in that case. It is also rounded once to bf16 when copied to the host (see below). ## Test plan - CPU: `test_zero2_gradient_safety.py`, `test_zero_cpu_offload_grad_accum.py`, `test_zero2_offload_multi_backward.py`: 88 passed, 12 skipped. New `test_zero_offload_accum_precision.py`: 10 passed. - B200 (4 GPUs), final commit `9960ecb7`: targeted offload suites (gradient safety, grad-accum norm, multi-backward, coalesced grad reduction, config dict) gave 227 passed, 28 warnings; the autoep gradient-parity file gave 18 passed, 2 skipped. - B200 (4 GPUs), new `test_multiple_request_boundaries_host_accumulator` and `test_fp16_host_gradient_overflow_skips_step`: pass. With the pre-fix overflow check restored in a scratch copy, the fp32 case of the overflow test fails. - B200 device-memory probe (single GPU, ZeRO-2 CPU offload, synthetic 134M-parameter bf16 stack of eight 4096x4096 linears, 3 optimizer windows, 4 backwards per window each marked as a request boundary, one `step()` per window). Values are MB of `torch.cuda.memory_allocated` after each request backward, and the per-window `max_memory_allocated`: | masters / accumulation | base `a4c989b7`: between requests | this PR `9960ecb7`: between requests | window peak, base / this PR | | --- | --- | --- | --- | | fp32 / fp32 | 816 | 304 | 2090 / 2090 | | bf16 / fp32 (unsupported) | 816 | 816 | 2090 / 2090 | | fp32 / bf16 (default) | 304 | 304 | 1386 / 1386 | The 512 MB saving between requests is the fp32 partition of this model. The in-window peak is unchanged, because the partition is still built within a window. Stage 1 and other model sizes were not measured. ## Test changes - `test_zero2_gradient_safety.py`: stubs pin the legacy host path with a comment; they bypass the reduction that fills the compact buffer. - `test_zero_cpu_offload_grad_accum.py`: the norm assertion reads the device partition sum, or the host gradient once the partition has been freed, and runs with and without fp32 accumulation. It checks every norm is above zero. - `test_zero2_offload_multi_backward.py`: adds a host-accumulator request-boundary test (exact gradient checks; fails if the publish call is disabled) and `test_fp16_host_gradient_overflow_skips_step`. - `test_zero_offload_accum_precision.py` (new): window-sum precision for stage x master x accumulation using micro-step gradients that are exact in bf16, and `safe_set_full_grad` residency behavior. See below. ## Measured precision and residency (not claims about production) Window sum over 16 micro-steps, relative max error against the exact sum, read before `step()`: | stage | masters | accumulation | error | notes | | --- | --- | --- | --- | --- | | 2 | fp32 | fp32 | 0 | the supported exact case | | 2 | fp32 | bf16 | 6.2e-3 | per-step bf16 accumulation | | 2 | bf16 | fp32 | 2.4e-3 | unsupported: one rounding to the bf16 host gradient | | 2 | bf16 | bf16 | 6.2e-3 | | | 1 | fp32 | fp32 | 2.4e-3 | the window sum is copied into the reduction bucket of the communication dtype (bf16 here) and rounded once before the all-reduce; identical on base | | 1 | fp32 | bf16 | 6.2e-3 | | | 1 | bf16 | fp32 | 2.4e-3 | | | 1 | bf16 | bf16 | 6.2e-3 | | The base commit gives the same table, so this PR does not change precision for these cells. Why stage 1 fp32/fp32 is 2.4e-3 and stage 2 fp32/fp32 is 0: stage 2 reduces each micro-step gradient into the fp32 partition. These micro-step values are exact in bf16, so every reduction is exact and the fp32 sum is exact. Stage 1 keeps the window sum in fp32 (`grad_accum`), but at the boundary it copies that sum into the reduction bucket, which has the communication dtype (bf16 in this test, since the model is bf16). The sum is therefore rounded once to bf16 before the all-reduce. Stage 1 is not changed by this PR. A fp32 reduction for stage 1 would remove the rounding at twice the communication volume; it is not in this PR. `safe_set_full_grad` between backwards in one window: - A value set while the GPU partition is resident (after the first backward of a window) is overwritten at the boundary; it is not kept. - A value set after a boundary has freed the partition (fp32 masters) is kept, and the next backward accumulates onto it exactly. ## Stage-1 memory, step time, multi-rank, and Qwen3-4B Same request-boundary probe as above (every backward is a boundary, then `step()`), comparing base `a4c989b7` to this PR. Times are median after the first window. Memory is `torch.cuda.memory_allocated` after a boundary backward, on rank 0. **Synthetic 134M-parameter stack (eight 4096x4096 linears), 1 GPU.** Between-request memory for fp32 masters + fp32 accumulation drops from 816 MB to 304 MB on both stage 1 and stage 2. Window peak is unchanged (stage 1: 3492 MB; stage 2: 2090 MB). Default bf16 accumulation stays at 304 MB. Unsupported bf16 masters + fp32 accumulation stays at 816 MB. Median `step()` is 26 ms on both trees. Median backward for the released fp32-accumulation path is about 10 ms slower on this stack (15→25 ms on stage 1, 14→24 ms on stage 2), which is the host copy plus restore on the next request. On Qwen3-4B the same path is much slower per backward: 474→733 ms (stage 2, 1 GPU), 496→785 ms (stage 1, 1 GPU), 483→687 ms (stage 2, 2 GPUs). This is the cost of releasing the partition. `zero_optimization.retain_gpu_grad_partition_until_step: true` removes it, at the price of keeping one fp32 partition resident (see the Summary). **Same stack, 2 GPUs, fp32 masters + fp32 accumulation.** Each rank's partition is half the model (256 MB of fp32). Stage 2 between-request memory drops from 560 MB to 304 MB; stage 1 from 2468 MB to 2212 MB. Window peaks are unchanged. Median `step()` is 127–135 ms on both trees. **Qwen3-4B (random-init from the published config, 4.02B parameters, seq 512, 4 request-boundary backwards per window), fp32 masters.** | stage / GPUs / accumulation | base between (MB) | this PR between (MB) | window peak base / this PR (MB) | median step ms base / this PR | | --- | --- | --- | --- | --- | | 2 / 1 / bf16 (default) | 8431 | 8431 | 13251 / 13251 | 3923 / 3782 | | 2 / 1 / fp32 | 23775 | 8431 | 29187 / 29187 | 3966 / 3984 | | 1 / 1 / bf16 | 8431 | 8431 | 19142 / 19142 | 3899 / 3793 | | 1 / 1 / fp32 | 23775 | 8431 | 42182 / 42017 | 3889 / 3929 | | 2 / 2 / bf16 | 8431 | 8431 | 13251 / 13251 | 16767 / 16375 | | 2 / 2 / fp32 | 16103 | 8431 | 20923 / 20024 | 16176 / 15781 | On 1 GPU the released fp32 partition is about 15.3 GB (4.02e9 × 4 bytes). On 2 GPUs it is about 7.7 GB per rank. Default bf16 accumulation is unchanged. `step()` is within a few percent of base. This is a request-boundary microbenchmark, not a full SFT job. ## Remaining limits - No full production training job (loss curve, tokens/s over many steps) was run. - ZeRO-1 offload with bf16/fp16 masters: fp32 accumulation does accumulate in fp32 on the device, but the window sum is rounded once when copied to the bf16 host gradient (table above; identical on base). ## Known follow-ups (not in this PR) - PCIe traffic optimization (deferred deliberately). - Stage 1 rounds the window sum to 16 bits at reduction (pre-existing). --------- Signed-off-by: Olatunji Ruwase <tunji.ruwase@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Replacement for #8964, which was closed after an accidental force-push of an unrelated commit onto this branch. GitHub will not reopen #8964 after that rewrite. Follow-up to #8949 (merged as dc046b1). Fixes #8991.
This replaces the earlier content of this PR (accumulating every backward in the optimizer's FP32 partition gradient). That approach was dropped: its extra complexity was not worth its gains. This version keeps #8949's design and makes two narrow changes: preallocate the CPU-offload accumulator per partition group instead of lazily per parameter, and fix the stale-gradient leak.
Problem
accumulated_grads_in_cpu, a dict keyed by parameter id and filled on first use. FP32 masters get owned buffers sized to the whole parameter; low-precision masters get aliased views of the partition gradient, created in two places. Accumulate, copy-back, and restore each branch on which kind they hold (about ten branches across four functions). The pinned buffers are never unpinned, and the low-precision restore leaves stale data in a shared scratch tensor that the overflow scan reads.reset_cpu_buffersdid not zero the FP32 partition gradient. A trainable parameter that receives no gradient in the next window kept its previous slice, and Adam applied it again.Fix
cpu_offload_pin_memoryis set. Each parameter uses a fixed slice at itsdest_offset, the same layout as the FP32 partition. The buffer is allocated on the first non-boundary accumulation, so boundary-only training (GAS=1) pins no extra host memory. Low-precision masters keep accumulating in the partition gradient._get_cpu_offload_accumulator_slice()is the only place that picks the buffer. The per-parameter dict, both alias sites, and the full-parameter versus fragment branching are removed.reset_cpu_bufferszeros each FP32 partition gradient after the step, after overflow, and on reset.set_norm_for_param_gradis removed; it has no callers.No config or API changes.
Overflow detection
Restore now zeros the non-owned part of the restored gradient, where #8949 kept this rank's local pre-reduction values. Skip-step behavior does not change: each reduced fragment is checked by the rank that owns it, and
has_overflow()MAX-reduceslocal_overflowacross the data-parallel and model-parallel groups. A multi-rank test with an inf in a non-owned region was not run.Not a duplicate
zero_()in_restore_cpu_offload_grad_to_gputhat this PR includes. This PR is rebased onto master (b62afa8) after Clear stale offload scratch before restoring low-precision gradients #8728 landed. The one conflict was in_restore_cpu_offload_grad_to_gpu; the resolution keeps this PR's version (unconditionalzero_()on the scratch, then the fragment copy from_get_cpu_offload_accumulator_slice).Validation
CPU unit tests
Hardware: 1x Intel Xeon Platinum 8488C (96 logical CPUs), no GPU. Python 3.12.12, PyTorch 2.9.1+cu130.
57 passed, 2 skipped (the two CUDA stream tests).
After rebasing onto master b62afa8,
test_zero2_gradient_safety.py,test_zero_cpu_offload_grad_accum.py, andtest_zero2_offload_multi_backward.py(includes #8728's test) run withLOCAL_SIZE=2: 87 passed, 2 skipped.#8728's regression test,
TestZero2OffloadOverflowRecovery::test_finite_step_after_overflow(two CPU ranks viaLOCAL_SIZE=2, BF16 and FP16, low-precision and FP32 masters), passes 4/4 on this branch. With thezero_()in_restore_cpu_offload_grad_to_gpuremoved, all 4 cases fail withfinite step did not update large. The new leak tests (test_idle_parameter_window_does_not_reuse_previous_gradient,test_idle_parameter_stays_zero_beside_active_neighbor, FP32 and BF16 masters) compare againsttorch.optim.Adam; all four fail with thereset_cpu_bufferszeroing removed.test_single_boundary_offload_avoids_auxiliary_storage_and_copychecks that a boundary-only step allocates no host accumulator.97 passed, 42 skipped.
pre-commit run --filespassed on the three changed files.GPU memory and throughput
Hardware: 8x NVIDIA H200 (141 GiB), PyTorch 2.14.0+cu130, CUDA 13.0 (driver version not recorded). Qwen3-4B and Qwen3.5-4B, ZeRO-2, bf16, CPU optimizer offload with pinned memory,
torch.optim.Adam, GAS 1 and 4, sequence length 512 and 2048, 1 warmup and the median of 2 measured iterations, at 1, 2, 4, and 8 GPUs. Baseline is #8949 plus the samereset_cpu_bufferszeroing, so these numbers isolate the accumulator change. The measured tree differs from this commit only in comments and tests.All 16 runs passed (64 rows). Change vs. baseline (#8949 plus the same partition-gradient zeroing), in percent. Negative means faster.
bwdis total backward time per optimizer step;iteris forward + backward + step.Across all rows, iteration time moves between -4.0% and +2.0%. Backward moves within ±2.5% in every row except Qwen3.5-4B at 8 GPUs with GAS=4, which is 9.0% faster at sequence length 512 and 8.8% faster at 2048. Both sequence lengths show it, but this sweep does not explain the cause.
Sequence length 512:
Sequence length 2048:
Host RSS moves with pinned memory. No convergence run was performed.
Compatibility matrix
Validated: ZeRO-1 and ZeRO-2 with CPU optimizer offload, FP32 and BF16 (low-precision) masters, bf16 parameters, managed gradient accumulation (GAS 1 and 4), 1 to 8 GPUs data parallel (GPU sweep is ZeRO-2 only), and the ZenFlow and ZeRO-1 fast-path unit tests above.
Not validated: FP16 loss scaling, NVMe offload, ZeRO-3, pipeline, tensor, sequence, or expert parallelism, gradient clipping, checkpoint load in the middle of a window, and convergence. The GPU sweep never takes a non-boundary step at GAS=1, so the first-use allocation in unmanaged mode is covered only by CPU tests. The cost of zeroing the full FP32 partition each step was not measured on its own, because the baseline includes the same zeroing.
ZeRO-3 is unchanged: its
reset_cpu_buffersonly clears norms, and it was not checked for the same leak. ZenFlow inheritsreset_cpu_buffersand so gets the new zeroing; its unit tests pass.AI assistance was used to write, review, and measure this change. The submitting human needs to review every changed line before sign-off.