Repository navigation
Preserve FP32 folded gradients through FP32 accumulation - #8920
Levius-Fubuki wants to merge 1 commit into
Conversation
Signed-off-by: levius <2114377220@qq.com>
0z5a
left a comment
There was a problem hiding this comment.
Read at 05e16530.
This looks right to me. The correction marker lives on the parameter, not on the gradient tensor, so correcting a temporary fp32 copy and mirroring it back into lp.grad keeps the marker contract. The TP reduction was already done in fp32 on master: reduce_autoep_folding_gradient upcasts bf16 gradients before the all-reduce, then rounds back. So the communication volume is unchanged, and the only difference is that the fp32 accumulator now gets the unrounded value.
On CPU (gloo), test_autoep_autotp_bf16_folding_parity.py passes at this head (13 tests). With the same test file on master, all 8 new cases fail, off by 0.0039 or 0.0078 (the bf16 rounding step), and the 5 existing cases still pass.
One nit, inline.
| param_name=self.param_names.get(lp)) | ||
| # Retained LP gradients must still agree with their correction marker. | ||
| if grad is not lp.grad: | ||
| lp.grad.copy_(grad) |
There was a problem hiding this comment.
The copy-back is unconditional. It's wasted in two common cases. Under immediate_grad_update, accumulate_hp_grads_and_remove_lp sets lp.grad = None right after this call. For parameters whose folding strategy is SKIP, grad holds the unchanged value. apply_folding_correction_to_grad_buffer returns the strategy, so the copy could be skipped there, and also when the caller is about to drop lp.grad.
…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 <tunji.ruwase@snowflake.com> Co-authored-by: Cursor <cursoragent@cursor.com>
Fixes #8913.
With BF16 AutoEP/AutoTP folding and FP32 accumulation,
_update_hp_gradcurrently rounds the FP32 folding result through BF16 before adding it to the FP32 accumulator. Apply the existing folding correction to temporary FP32 staging and accumulate it directly. Mirror the corrected value into retained BF16 gradients so the existing correction marker and boundary reducer keep their current contract. No new persistent buffer or marker lifecycle is introduced; BF16-only accumulation is unchanged.On upstream bf222a2, two exact BF16 inputs (1 and 1.0078125) should average to 1.00390625 in FP32; the new two-rank regression fails with absolute error 0.00390625. Device validation: 2 x NVIDIA GeForce RTX 3090 24 GB, driver 580.105.08, torch 2.12.1+cu130, CUDA 13.0, NCCL 2.29.7, Python 3.12.3.
Validation:
The same new engine test fails on the unmodified optimizer with explicit FP32 communication. Changed-file pre-commit, syntax and diff checks pass. Independent spec/code reviews found no remaining issue. A two-rank NCCL boundary microbenchmark with 1,048,576 elements, 10 warmups and 40 timed calls records 6 MiB → 4 MiB temporary peak allocation per rank and preserves the exact FP32 midpoint; measured medians are about 0.85–0.87 ms baseline and 0.82–0.83 ms fixed. This is an operator-boundary measurement, not end-to-end model throughput. New tests use real NCCL reductions and real BF16 ZeRO 1 TP2/DP1 training, analytic gradients and clipped-SGD master updates, both accumulation modes, GAS 1/2, and two optimizer steps. An auxiliary sharded parameter keeps norm contributions nonempty, so this change has no dependency on #8912.
The non-immediate GAS>1 correction-marker limitation already present upstream is outside this change. Later microbatches in that test use equal rank inputs to isolate this precision boundary; arbitrary unequal later gradients remain unvalidated. Full AutoEP MoE model conversion, TP2/EP2/DP2 four-rank execution, other wrappers/accelerators, production convergence and performance remain unvalidated. Existing ZeRO 1/2/3 and engine buffer paths were inspected; this PR changes only the dedicated BF16 accumulation boundary.
Duplicate check: no open PR found for this FP32 staging fix. Merged #8654 manages gradient release/correction marker cleanup; open #8823 changes expert clipping; neither preserves this FP32 folding boundary.
AI assistance (OpenAI Codex) was used for investigation, implementation and device tests. The human submitter confirmed manual diff review and test-result verification and authorized submission. Device tests above were executed on the requested server with Codex; no additional human test execution is asserted.
Local recheck on 2026-10-28, unchanged head
05e16530: Apple M3/macOS ARM64, Python 3.12.13, torch 2.14.1, CPU/Gloo. The complete folding-parity file above reports 13 passed withDEEPSPEED_RUN_H100_TESTS=1; all applicable changed-file pre-commit hooks pass. This is CPU distributed validation, not an H100 or new CUDA/NCCL run. The non-immediate GAS>1 correction-marker limitation described above remains outside this change. Keeping this PR in draft while the author's ready-PR limit is reached.