Skip to content

ZeRO-1/2: one CPU-offload accumulator per group; zero idle gradients - #9018

Merged
sfc-gh-truwase merged 1 commit into
masterfrom
truwase/zero-request-boundary-grads
Nov 9, 2026
Merged

sfc-gh-truwase merged 1 commit into
masterfrom
truwase/zero-request-boundary-grads

Conversation

@sfc-gh-truwase

@sfc-gh-truwase sfc-gh-truwase commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Lazy accumulator complexity. ZeRO-1/2: preserve gradients across request boundaries until step #8949 stores CPU-offload gradient sums in 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.
  • Stale-gradient leak ([BUG] ZeRO-1/2 CPU offload reapplies stale FP32 gradients for unused parameters #8991). reset_cpu_buffers did 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

  • One host accumulator per partition group, sized to the partition, in the bit16 dtype, pinned when cpu_offload_pin_memory is set. Each parameter uses a fixed slice at its dest_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.
  • Restore clears the scratch tensor before copying this rank's fragment.
  • The group buffers are unpinned with the other offload buffers.
  • reset_cpu_buffers zeros each FP32 partition gradient after the step, after overflow, and on reset.
  • set_norm_for_param_grad is 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-reduces local_overflow across 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

Validation

CPU unit tests

Hardware: 1x Intel Xeon Platinum 8488C (96 logical CPUs), no GPU. Python 3.12.12, PyTorch 2.9.1+cu130.

python -m pytest -q tests/unit/v1/zero/test_zero2_gradient_safety.py \
  tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py

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, and test_zero2_offload_multi_backward.py (includes #8728's test) run with LOCAL_SIZE=2: 87 passed, 2 skipped.

#8728's regression test, TestZero2OffloadOverflowRecovery::test_finite_step_after_overflow (two CPU ranks via LOCAL_SIZE=2, BF16 and FP16, low-precision and FP32 masters), passes 4/4 on this branch. With the zero_() in _restore_cpu_offload_grad_to_gpu removed, all 4 cases fail with finite 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 against torch.optim.Adam; all four fail with the reset_cpu_buffers zeroing removed. test_single_boundary_offload_avoids_auxiliary_storage_and_copy checks that a boundary-only step allocates no host accumulator.

python -m pytest -q tests/unit/runtime/zenflow \
  tests/unit/runtime/zero/test_zero1_optimizer_fastpath.py \
  tests/unit/runtime/half_precision/test_zero_grad_norm_overflow.py

97 passed, 42 skipped.

pre-commit run --files passed 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 same reset_cpu_buffers zeroing, 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. bwd is total backward time per optimizer step; iter is 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:

Model GPUs GAS bwd iter
Qwen3-4B 1 1 +4.4% +0.2%
Qwen3-4B 1 4 +2.1% +1.2%
Qwen3-4B 2 1 -0.4% +2.0%
Qwen3-4B 2 4 -0.1% +1.4%
Qwen3-4B 4 1 -0.7% -0.3%
Qwen3-4B 4 4 -0.7% -3.5%
Qwen3-4B 8 1 -1.2% -1.6%
Qwen3-4B 8 4 -1.3% -0.4%
Qwen3.5-4B 1 1 +0.6% +0.7%
Qwen3.5-4B 1 4 -0.3% -1.0%
Qwen3.5-4B 2 1 +2.5% +0.4%
Qwen3.5-4B 2 4 +1.4% +0.9%
Qwen3.5-4B 4 1 +1.0% +0.1%
Qwen3.5-4B 4 4 -0.4% -1.8%
Qwen3.5-4B 8 1 +1.3% -0.0%
Qwen3.5-4B 8 4 -9.0% +0.0%

Sequence length 2048:

Model GPUs GAS bwd iter
Qwen3-4B 1 1 +4.6% +1.8%
Qwen3-4B 1 4 +2.4% +1.3%
Qwen3-4B 2 1 +0.7% +1.9%
Qwen3-4B 2 4 -0.4% +0.1%
Qwen3-4B 4 1 -1.1% +0.4%
Qwen3-4B 4 4 -0.7% -2.1%
Qwen3-4B 8 1 -0.5% -3.0%
Qwen3-4B 8 4 -0.8% -4.0%
Qwen3.5-4B 1 1 -0.5% -0.1%
Qwen3.5-4B 1 4 -0.6% -1.3%
Qwen3.5-4B 2 1 +2.1% -1.7%
Qwen3.5-4B 2 4 +0.5% -0.9%
Qwen3.5-4B 4 1 +1.3% +1.9%
Qwen3.5-4B 4 4 -0.3% -0.9%
Qwen3.5-4B 8 1 +0.6% -0.7%
Qwen3.5-4B 8 4 -8.8% -0.6%
  • Peak GPU allocated and reserved memory: identical in all 32 pairs.
  • Pinned host memory (peak GiB, baseline → this PR, sequence length 512):
Model GPUs GAS=1 GAS=4
Qwen3-4B 1 41.0 → 41.0 51.6 → 49.0
Qwen3-4B 2 21.0 → 21.0 26.3 → 25.0
Qwen3-4B 4 11.0 → 11.0 13.6 → 13.0
Qwen3-4B 8 6.0 → 6.0 7.3 → 7.0
Qwen3.5-4B 1 42.0 → 42.0 53.9 → 50.0
Qwen3.5-4B 2 22.0 → 22.0 28.1 → 26.0
Qwen3.5-4B 4 12.0 → 12.0 15.2 → 14.0
Qwen3.5-4B 8 7.0 → 7.0 9.0 → 8.0

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_buffers only clears norms, and it was not checked for the same leak. ZenFlow inherits reset_cpu_buffers and 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.

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>
@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-05T14:05:41.080508Z 35d84df PR opened
ℹ️ 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.

@sfc-gh-truwase
sfc-gh-truwase requested a review from stas00 November 5, 2026 14:46
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 5, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 5, 2026
@xylian86
xylian86 added this pull request to the merge queue Nov 6, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 6, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 6, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 6, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 7, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 9, 2026
Merged via the queue into master with commit a4c989b Nov 9, 2026
21 of 23 checks passed
@sfc-gh-truwase
sfc-gh-truwase deleted the truwase/zero-request-boundary-grads branch November 9, 2026 03:15
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 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>
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] ZeRO-1/2 CPU offload reapplies stale FP32 gradients for unused parameters

3 participants