Skip to content

Clear stale offload scratch before restoring low-precision gradients - #8728

Merged
sfc-gh-truwase merged 3 commits into
deepspeedai:masterfrom
adenzhou1350:codex/clear-low-precision-offload-scratch
Nov 5, 2026
Merged

sfc-gh-truwase merged 3 commits into
deepspeedai:masterfrom
adenzhou1350:codex/clear-low-precision-offload-scratch

Conversation

@adenzhou1350

@adenzhou1350 adenzhou1350 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

With unmanaged gradient accumulation, ZeRO-2 CPU offload and BF16/FP16 master weights, a genuinely overflowing step can cause the next entirely finite step to be skipped.

_restore_cpu_offload_grad_to_gpu copies only the locally owned fragment into a shared scratch tensor for low-precision masters. The norm and optimizer-buffer consumers read that fragment, but the overflow tracker reads the entire restored gradient. NaNs left in the unowned region by another parameter group can therefore set local_overflow for a finite window.

Change

Clear the destination view before the partial copy. The FP32-master full-copy path is unchanged.

The regression uses the public Engine training loop with two parameter groups (12 and 8 elements) and DP=2. It first produces a real NaN step, then requires two finite steps to update both parameters. All parameters participate in every step; the test does not fabricate optimizer state or poison scratch storage directly. It covers BF16/FP16 with both low-precision and FP32 masters.

Validation

  • Historical device-validation base: c687df79653459d08c0c6fada6d124971d966662. The device results below belong to that original revision, not the new merge head.
  • Two NVIDIA B300 GPUs; Python 3.12.13, Torch 2.11.0+cu130, CUDA 13.0; actual CPUAdam extension.
  • On unmodified master, the added BF16 and FP16 low-precision-master cases fail at finite step did not update large; both FP32-master controls pass.
  • With this change, all four registered distributed regression cases pass.
  • Official pre-commit run --files passes with the unchanged repository configuration and pinned hooks on Linux/Python 3.12.
  • The original module's two CPU-accumulator cases pass. Its other eight cases require the no-offload GPU FusedAdam comparison and could not run successfully in this environment: extension compilation fails on missing cusparse.h. They are not claimed as passing.

This is a correctness fix, not a performance or convergence claim.

Merge refresh (2026-11-03): merged upstream master dc046b15d7a58f6c8dacba435508b52b1ebc620c as 8efca4cd5bfb0af39822ed1c69272743eecdb787. The test-file conflict was resolved by retaining the upstream request-boundary tests and the original overflow-recovery test plus its CPUAdamBuilder import. All upstream test definitions and the original overflow test retain identical ASTs; the production fix is unchanged. Relative to the merged master, the PR remains two files with 63 added lines. Exact repository changed-file pre-commit checks passed on Linux/Python 3.12.3 for the committed tree, with no hook edits; syntax and git diff --check passed. Distributed/GPU tests were not rerun for this merge, and hosted CI for the new head is tracked separately from the historical results above.

AI assistance was used for this conflict refresh and validation; the submitting human reviewed the merge diff before the signed-off push.

Current-head hosted CI: the DCO app check and Modal test collection succeeded; three Modal execution/smoke checks were skipped. Five GitHub Actions workflows (Formatting, python, cpu-torch-latest, nv-pre-compile-ops, and DCO / required) currently report action_required with zero jobs, pending upstream approval. These are admission gates, not executed test failures; no retry has been requested.

banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 2, 2026
…epspeedai#8949)

Additionally to deepspeedai#8749
another precision issue

Porting this from @seanbell's
Snowflake-AI-Research/Arctic-Platform#371


**An accumulation boundary is not necessarily an optimizer step.** A
caller can finish several requests with
`engine.set_gradient_accumulation_boundary(True)` while delaying
`engine.step()` until all requests have contributed. ZeRO-1/2 must
retain every request's gradients until that update and must not carry a
previous update's gradients into the next one.

This fixes both non-offloaded and CPU-offloaded optimizer paths in
`deepspeed/runtime/zero/stage_1_and_2.py`, without changing
configuration defaults or adding an application-side workaround.

## Root Cause And Fix

- Non-offloaded optimizers cleared `all_grad_tensors` at every boundary,
discarding earlier requests before `step()`. Retain the accumulated
tensors until the existing step cleanup. When the separate
`param.grad_accum` tensor is cumulative, keep the existing reread
behavior so reentrant checkpoint phases do not double-count gradients.
- CPU-offloaded optimizers with FP32 master weights skipped refreshing
the persistent host accumulator on a step's first backward when that
backward was also a boundary. A subsequent request could then add the
previous step's stored gradients. Track each parameter's participation
in the current update window instead of relying on the global
`micro_step_id`. A first non-boundary contribution refreshes the host
accumulator; a first boundary contribution uses only the existing
optimizer-partition copy. If another backward follows before `step()`,
recover the previous locally owned partition fragment in the
accumulation dtype, then allocate or refresh the auxiliary host
accumulator. Never reuse a prior update's sum.

**A single-backward update needs no auxiliary allocation or copy.**
`_offload_partition_only_param_ids` records FP32-master parameters whose
current sum lives only in the optimizer partition. Explicit finalization
leaves those already-current gradients intact. `step()` clears both
participation sets before either a successful update or an overflow
return. Multiple backwards still need an auxiliary accumulator once the
second contribution arrives; this change does not claim a speedup for
that workload.

**Low-precision masters use a shared buffer instead of the separate
FP32-master accumulator.** Their CPU accumulator is a view of the
optimizer partition's gradient buffer. On a parameter's first use at a
boundary, the existing boundary copy initializes that shared buffer
directly, so a second host copy is unnecessary. Register the view and
the parameter's participation even when skipping the extra copy; later
backwards accumulate into the current window and explicit finalization
can restore the shared gradient. A first non-boundary use still
initializes the accumulator through the offload helper.

These changes address the [stale-gradient first-use
review](deepspeedai#8949 (comment)),
the [low-precision boundary-handling
clarification](deepspeedai#8949 (comment)),
and the subsequent single-backward allocation/copy concern. The code
names `first_use` and `boundary` explicitly and distinguishes
shared-buffer accumulation from the lazily allocated FP32-master
accumulator.

**This complements DeepSpeed
[deepspeedai#8749](deepspeedai#8749), rather than
replacing its precision fix.** deepspeedai#8749 preserves FP32 partition gradients,
including CPU offload. The remaining defect concerns the lifetime of
accumulated gradients when model and accumulation dtypes match.
[Arctic-Platform
deepspeedai#371](Snowflake-AI-Research/Arctic-Platform#371)
motivated the native DeepSpeed repair; AP-specific hooks are not needed
by this change.

## Regression Coverage

The existing `tests/unit/v1/zero/test_zero2_offload_multi_backward.py`
now includes a 16-case, two-rank integration matrix:

| Axis | Cases |
| --- | --- |
| ZeRO stage | 1, 2 |
| Optimizer placement | Non-offloaded, CPU offload |
| BF16 model gradient accumulation | BF16, FP32 |
| Activation checkpointing | Disabled, reentrant |

**Each case checks independently derived gradients and actual parameter
updates.** Two independent linear projections exercise partition
ownership; analytical input-column sums supply the gradient reference
and ordinary PyTorch SGD supplies the update reference. Binary-exact
fixture values allow zero-tolerance assertions without loosening
numerical thresholds.

Eight successive update windows cover a multi-call request, a zero-loss
request followed by useful work, consecutive single-call requests, mixed
request lengths, a boundary-first request followed by a multi-backward
request, a fresh single backward after earlier updates, and two
conditional-participation windows. Each projection is absent from the
first backward of one window, then contributes repeatedly after having
participated in the preceding update. The integration tests compare
actual consecutive-single-backward updates; a separate storage
regression checks the resource contract.

The existing gradient-safety suite also checks first use after another
parameter's backward, with FP32 and BF16 master buffers and
boundary/non-boundary first contributions. It checks the summed gradient
and actual Adam update against an independent PyTorch optimizer,
including a boundary-only overflow after an earlier update has allocated
the auxiliary buffer. Additional controls check repeated finalization,
partial partition ownership, BF16 accumulation rounding, pending
pageable-source copies, and no additional storage or copy for
consecutive single-boundary updates. These storage-level tests bypass
the ZeRO constructor; they do not claim CPUAdam integration coverage for
BF16 master weights.

## Validation

**All reported execution was on CPU, not on GPU.** Hardware: one visible
Intel Xeon Platinum 8488C socket, 96 logical CPUs; two CPU/Gloo ranks
for distributed cases; no GPU or accelerator driver used. Software:
PyTorch `2.9.1+cu130`, DeepSpeed `0.19.8+0fe2dfcc7`, Python from
`/home/yak/miniconda3/envs/dev/bin/python`. The CUDA-enabled PyTorch
build does not constitute CUDA hardware validation.

| Test | Result |
| --- | --- |
| Plain request-boundary matrix before the original source fix | 4
BF16-accumulation failures, 4 FP32-accumulation passes |
| Delayed-participation offload regressions before the review fix | 2
BF16-accumulation failures, 2 FP32-accumulation passes |
| First-use storage regressions before the review fix | 4 failures
(FP32/BF16 masters, boundary/non-boundary first use); 4
ordinary-accumulation controls passed |
| Single-boundary allocation/copy regression before the lazy fix | 1
FP32-master failure; 9 other storage controls passed |
| Complete request-boundary/checkpoint matrix after the lazy fix | 16
passed |
| Existing multi-backward/offload controls after the lazy fix | 10
passed |
| Gradient-safety suite after the lazy fix, including overflow | 52
passed, 2 CUDA-only skips |
| Temporary CPU storage-lifetime and allocation/copy probes | 6 passed |

The repository suites total 78 passes and 2 CUDA-only skips; the
temporary probes add 6 passes. The integration matrix completed in 88.91
seconds, native optimizer controls in 105.38 seconds, the final
gradient-safety rerun in 8.63 seconds, and the final temporary probes in
2.51 seconds. These are test durations, not training-throughput
measurements.

New matrix command, from the DeepSpeed checkout:

```bash
DS_ACCELERATOR=cpu PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 \
  /home/yak/miniconda3/envs/dev/bin/python -m pytest -sv \
  tests/unit/v1/zero/test_zero2_offload_multi_backward.py \
  -k multiple_request_boundaries --tb=short --color=no
```

The existing optimizer controls initially timed out with optional
shared-memory communication enabled. They passed using real Gloo with
only that optional communication extension disabled. The temporary test
launcher contains:

```python
import sys
import deepspeed.ops
import pytest

deepspeed.ops.__compatible_ops__["deepspeed_shm
```

```bash
DS_ACCELERATOR=cpu PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 \
  /home/yak/miniconda3/envs/dev/bin/python \
  /tmp/codex-01a13767-deepspeed-gloo-tests.py -sv \
  tests/unit/v1/zero/test_zero2_offload_multi_backward.py \
  -k TestZeroOffloadMultiBackward --tb=short --color=no

DS_ACCELERATOR=cpu PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 \
  /home/yak/miniconda3/envs/dev/bin/python -m pytest -sv \
  tests/unit/v1/zero/test_zero2_gradient_safety.py --tb=short --color=no
```

The configured pre-commit hooks passed for all three changed Python
files and this local description, including YAPF, flake8, license, and
accelerator/distributed-import checks. The first run applied YAPF's
required wrapping to the new tests; the second run passed without
modifications. `git diff --check` passed.

## Single-Backward Allocation And Copy Control

**The lazy fix restores the original single-boundary resource behavior
in a CPU-only fixture.** For a fresh FP32-master optimizer with
1,048,576 BF16 gradient values, 12 single-boundary calls produced the
following counts. The original base is `8d4f29c75`; the eager review-fix
head is `7e00e1a8e`. The fixture resets per-update participation between
calls and measures persistent auxiliary tensor storage and `copy_`
operations, not process peak memory or GPU transfers.

| Revision | Auxiliary host bytes | Copies per boundary call |
| --- | ---: | ---: |
| Original base | 0 | 1 |
| Eager review fix | 2,097,152 | 2 |
| Lazy fix | 0 | 1 |

BF16-master controls remain at zero auxiliary bytes and one copy per
call in all three revisions. A buffer allocated by an earlier
multi-backward update remains available for reuse, but a later
single-boundary update does not refresh that stale buffer. The
repository regression
`test_single_boundary_offload_avoids_auxiliary_storage_and_copy` checks
the no-extra-storage/copy contract and actual consecutive Adam updates.

The larger allocation/copy comparison and four ordinary success/overflow
storage-lifetime controls were run with the temporary probe
`/tmp/codex-01a13767-pr8949-additional-feedback.py`:

```bash
DS_ACCELERATOR=cpu PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 PYTHONPATH=.:tests \
  /home/yak/miniconda3/envs/dev/bin/python \
  /tmp/codex-01a13767-pr8949-additional-feedback.py
```

Synthetic CPU timings are not evidence of accelerator throughput. No
end-to-end speedup is claimed.

## Compatibility And Remaining Validation

**The CPU runs validate optimizer-placement logic, not physical GPU
optimizer placement or GPU-to-CPU transfers.** The regression is also
enabled on hosts with at least two CUDA devices, but GPU execution
remains required before claiming on-device coverage. FP16, CPUAdam
integration with low-precision master weights, NVMe offload, vendor
accelerators, and tensor/pipeline/expert/sequence parallelism were not
validated by the new matrix. BF16 master-buffer behavior was validated
only in the gradient-safety fixture described above.

Static sibling inspection found that ZeRO-3 refreshes the first
microstep's partition buffer and that the BF16 optimizer retains
accumulation until its update or explicit zeroing. This PR changes
neither implementation. Conditional participation after the first
microstep was not validated for ZeRO-3; the inspected code is not
evidence that every sibling accumulation case is correct.

Full-model convergence, throughput, and peak-memory measurements were
not performed. Only the fixture's auxiliary-allocation and copy-count
reductions above are established. GPU transfer cost and performance for
repeated-backward workloads remain unmeasured.

## Related Work And Submission

Public open-PR searches for `gradient accumulation`, `stale gradients`,
and `8749 in:body`, plus the deepspeedai#8749 discussion, were checked on October
29, 2026. No competing request-boundary fix was identified. Related
[deepspeedai#8728](deepspeedai#8728) clears
unowned offload scratch for low-precision masters;
[deepspeedai#8856](deepspeedai#8856) repairs the
BF16 full-gradient setter. Neither supplies this per-parameter
request-lifetime fix. Repeat the duplicate check before opening another
PR.

AI assistance was used. A human submitter must review every changed
line, run the relevant accelerator tests, and provide any required
sign-off. This is the local description for existing PR deepspeedai#8949, excluded
from the source commit; GitHub PR text is not edited by this task.

---------

Signed-off-by: Stas Bekman <[email protected]>
Co-authored-by: Sean Bell <[email protected]>
@adenzhou1350

adenzhou1350 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Merged upstream master dc046b15 in signed-off commit 8efca4cd5bfb after human review of the conflict resolution. Both the new upstream request-boundary suite and the existing overflow-recovery test are retained; the production repair is unchanged.

Both PR-authored files passed the exact repository pre-commit checks on Linux/Python 3.12.3 for this committed tree, plus syntax and diff checks. I did not rerun the distributed/GPU cases for this merge; the original B300 results remain historical evidence. The PR description now separates those results from the new head. AI-assisted conflict refresh.

Current-head hosted CI: the DCO app check and Modal test collection succeeded; three Modal execution/smoke checks were skipped. Five GitHub Actions workflows (Formatting, python, cpu-torch-latest, nv-pre-compile-ops, and DCO / required) currently report action_required with zero jobs, pending upstream approval. These are admission gates, not executed test failures; no retry has been requested.

@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 4, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 4, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Nov 5, 2026
Merged via the queue into deepspeedai:master with commit 0d0aa30 Nov 5, 2026
15 checks passed
xylian86 pushed a commit to xylian86/DeepSpeed that referenced this pull request Nov 7, 2026
…deepspeedai#9020)

## CI: drop the abandoned deepspeed-kernels from the dev requirements

### Problem

When Modal has no GPU within 600 s, `modal-torch-latest` falls back to
AWS. Since deepspeedai#8950 (merged 2026-11-04) that fallback has failed 6 times
out of 6 with `AwsControllerError: AWS prepare failed with exit code 1`,
and no tests ran. Five were merge-queue entries whose PRs were not at
fault (deepspeedai#8985 twice, deepspeedai#8728, deepspeedai#8612, deepspeedai#8842); one was the scheduled run on
master. Examples:
-
https://github.com/deepspeedai/DeepSpeed/actions/runs/41940811586/job/126960989358
-
https://github.com/deepspeedai/DeepSpeed/actions/runs/42061411246/job/127364012408

### Cause

deepspeedai#8950 added `python -m pip check` after "install candidate DeepSpeed" in
`build_remote_commands`. On the AWS environment (uv venv, CPython
3.12.14) it exits 1 with:

```
deepspeed-kernels 0.0.1.dev1698255861 is not supported on this platform
```

`deepspeed-kernels` comes from `requirements/requirements-dev.txt`. Its
only file on PyPI (last release 2023-10-25) is named
`deepspeed_kernels-0.0.1.dev1698255861-py3-none-manylinux1_x86_64.whl`,
but the `WHEEL` file inside it says `Tag: cp38-cp38-linux_x86_64`. pip
installs by the file name (any Python 3) and `pip check` checks the
internal tag (Python 3.8 only). To see the tag:

```
pip download deepspeed-kernels==0.0.1.dev1698255861 --no-deps -d /tmp/dk && unzip -p /tmp/dk/*.whl '*.dist-info/WHEEL'
```

The job logs never show this line: the prepare output is cut at 24,000
characters of stdout (`SSM_INLINE_STDOUT_CHARS`), and the complete
output is fetched only when the test phase fails. I found it by running
the same prepare commands outside CI.

(The Modal sandbox runs the same `pip check` and prints `No broken
requirements found.` with the same package; I could not find out why it
passes there.)

### Change

| Where | What |
|---|---|
| `requirements/requirements-dev.txt` | Remove `deepspeed-kernels`,
which is no longer maintained. |
| `ci/torch_latest.py`: `_emit_ssm_output` | Fetch the complete output
tail for a failed `prepare` phase too, not only `test`, so the next
prepare failure shows its error in the job log. |
| `ci/test_torch_latest.py` | One test for the prepare tail; the fake
AWS CLI returns the prepare output for prepare-phase S3 keys. |

`pip check` itself is unchanged (as deepspeedai#8950 wrote it). The first version
of this PR exempted the `deepspeed-kernels` line instead; following
review, the package is removed rather than exempted.

No active CI job uses `deepspeed-kernels`:
- the inference-v2 kernel tests are deselected by `tests/pytest.ini`
(`not inference_v2_ops`); the only workflow that selected them
(`nv-a6000.yml`) is disabled;
- `nv-pre-compile-ops` builds with `DS_BUILD_CUTLASS_OPS=0
DS_BUILD_RAGGED_DEVICE_OPS=0`;
- it was the only reason `cmake` was installed, and nothing else in
`ci/`, `tests/` or the workflows uses `cmake`.

Not removed: `op_builder/ragged_ops.py` and
`op_builder/inference_cutlass_builder.py` link prebuilt libraries from
the package (`-lblockedflash`, `-ldeepspeedft`) to build the
inference-v2 ragged kernels and CUTLASS MoE / mixed GEMM. Inference v2
is not deprecated (deepspeedai#8489), and DeepSpeed-MII (0.3.3) still installs
`deepspeed-kernels` as a dependency, so those builders keep working for
its users.

The AWS prepare installs the requirements of the candidate commit, so
this change also applies to its own merge-queue run.

### Duplicate check

Searched open PRs and issues on 2026-11-05 for "deepspeed-kernels", "pip
check", "AWS prepare failed" and "capacity fallback": none addresses
this. deepspeedai#8950 added the check; deepspeedai#8921 moved the AWS fallback to Python
3.12.

### Tests

Hardware: CPU only (CI controller code and requirements; no GPU path
changed). Intel Xeon Platinum 8375C, Ubuntu 22.04.5, CPython 3.12.14,
pip 26.3, pytest 8.3.5.

| Command | Result |
|---|---|
| `python ci/test_torch_latest.py` | 50/50 passed (49 existing + 1 new)
|
| `python ci/test_tests_fetcher.py` | 27/27 passed |
| `pre-commit run --files ci/torch_latest.py ci/test_torch_latest.py
requirements/requirements-dev.txt` | all hooks pass |
| the new test against the master version of `ci/` | fails (the prepare
log ends at "AWS prepare failed with exit code 1" without the late line)
|
| the AWS prepare commands rerun from scratch outside CI with this
`requirements-dev.txt` (uv 0.12.7, CPython 3.12.14, the three
requirements files, torch 2.10.0 cu128 pin, Transformers `main`,
DeepSpeed master) | RERUN_RESULT |

`test_aws_prepare_failure_emits_bounded_s3_tail`: a failed prepare whose
output exceeds the inline limit prints the tail, including the last
line, read from the prepare-phase S3 key.

Not run: the real AWS fallback (needs the CI's AWS credentials) and the
Modal sandbox. No workflow runs `ci/test_torch_latest.py`; I ran it by
hand.

### Compatibility

CI and development requirements only. No DeepSpeed runtime code changes,
so no ZeRO stage, offload, precision or parallelism cell is affected.
Users who build the inference-v2 ragged or CUTLASS ops from a source
checkout now install `deepspeed-kernels` themselves (DeepSpeed-MII does
this).

### AI assistance

This change, its tests and this description were prepared with AI
assistance (Claude), which also ran the tests above.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: pengdurice <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 9, 2026
…eepspeedai#9018)

Replacement for deepspeedai#8964, which was closed after an accidental force-push
of an unrelated commit onto this branch. GitHub will not reopen deepspeedai#8964
after that rewrite. Follow-up to deepspeedai#8949 (merged as dc046b1). Fixes
deepspeedai#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 deepspeedai#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.** deepspeedai#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 (deepspeedai#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
deepspeedai#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

- deepspeedai#8949 (merged): this builds on it.
- deepspeedai#8991 (open issue): the leak this fixes.
- deepspeedai#8728 (merged as 0d0aa30): clears stale offload scratch before
restoring low-precision gradients. Its change is the same `zero_()` in
`_restore_cpu_offload_grad_to_gpu` that this PR includes. This PR is
rebased onto master (b62afa8) after deepspeedai#8728 landed. The one conflict was
in `_restore_cpu_offload_grad_to_gpu`; the resolution keeps this PR's
version (unconditional `zero_()` on the scratch, then the fragment copy
from `_get_cpu_offload_accumulator_slice`).
- deepspeedai#8920 (open): FP32 folded-gradient accumulation. Unrelated.
- deepspeedai#8957 (open issue): remaining test coverage. Not required for this
change.

## Validation

### CPU unit tests

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

```bash
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 deepspeedai#8728's test) run with
`LOCAL_SIZE=2`: 87 passed, 2 skipped.

deepspeedai#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.

```bash
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 deepspeedai#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 (deepspeedai#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.

Signed-off-by: Olatunji Ruwase <[email protected]>
Co-authored-by: Cursor <[email protected]>
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 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.

3 participants