Repository navigation
ZeRO-1: reduce the fp32 accumulation window in fp32, not the comm dtype - #2
kritikagarg wants to merge 1 commit into
Conversation
With ZeRO-1, a 16-bit model and `data_types.grad_accum_dtype: "fp32"`, the gradient window is summed in fp32 in `param.grad_accum` and the IPG bucket is allocated in fp32 (`_gradient_reduction_buffer_dtype`, `setup_buckets`), so the copy into the bucket is exact. The boundary reduction then casts the bucket to `communication_data_type` -- bf16/fp16, inferred from the precision mode -- in `DeepSpeedZeroOptimizer.allreduce_bucket` and `gradient_reduction_w_predivide`, so the fp32 window sum is rounded once to 16 bits on the way into the all-reduce and the requested accumulation precision is discarded. ZeRO-2 reduces every micro-step in the model dtype and accumulates into an fp32 partition afterwards, so for inputs exact in the model dtype its window sum is exact; ZeRO-1's was not. Resolve the reduction dtype where the inference already lives: when `communication_data_type` is unset, ZeRO stage 1 with fp32 accumulation on a 16-bit model reduces in the accumulation dtype. An explicitly configured `communication_data_type` keeps its current meaning and is the documented way to keep the narrower reduction. ZeRO-2, ZeRO-3, the autocast per-parameter comm dtype path and every configuration without a `grad_accum_dtype` override are untouched. All-reduce bytes double for this configuration. ZeRO-1 reduces once per accumulation window rather than once per micro-step, so the cost is bounded, but it is a visible change. Fixes deepspeedai#9047 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
PR Summary — deepspeedai#9047: ZeRO-1 rounds the fp32 accumulation window to the comm dtype
The defectWith ZeRO-1 + a 16-bit model + flowchart TD
subgraph z1["ZeRO-1 — BEFORE (buggy)"]
direction TB
M1["micro-step 1..N<br/>grad in bf16"] --> GA["param.grad_accum<br/><b>fp32</b> — window sum<br/>(use_grad_accum_attribute)"]
GA --> IPG["IPG bucket<br/><b>fp32</b><br/>(_gradient_reduction_buffer_dtype)<br/>✅ lossless copy"]
IPG --> CAST["<b>cast to communication_data_type</b><br/>= bf16, <i>inferred</i> from precision mode<br/>allreduce_bucket / gradient_reduction_w_predivide"]
CAST --> RED["all_reduce in bf16"]
RED --> BACK["copy_ back into fp32 bucket"]
BACK --> ERR["❌ rel err 2.4e-3<br/>precision already lost"]
end
style CAST fill:#8e1e1e,color:#fff
style ERR fill:#8e1e1e,color:#fff
style IPG fill:#1b5e20,color:#fff
Why ZeRO-2 is immune — it never holds an fp32 value that needs reducing: flowchart TD
subgraph z2["ZeRO-2 — correct by construction"]
direction TB
N1["micro-step k<br/>grad in bf16"] --> R2["reduce-scatter <b>per micro-step</b><br/>in model dtype (bf16)"]
R2 --> ACC["add into <b>fp32</b> partition<br/><i>after</i> the reduction"]
ACC --> OK2["✅ rel err 0<br/>only the rounding<br/>the user accepted"]
end
style OK2 fill:#1b5e20,color:#fff
Root cause in one sentence: the engine infers the communication dtype purely from parameter precision and never considers accumulation precision — even for the one stage whose reduction input is the accumulator. The fix — resolve the reduction dtype where the inference lives
flowchart TD
S(["_configure_zero_optimizer()"]) --> Q1{"communication_data_type<br/>explicitly set in config?"}
Q1 -->|yes| E1["return it unchanged<br/><i>user's deliberate bandwidth choice —<br/>also the escape hatch to old behavior</i>"]
Q1 -->|"no (inferred)"| Q2{"stage == 1 ?"}
Q2 -->|no| E2["return inferred 16-bit<br/><i>stage 2/3 input is already 16-bit;<br/>promoting costs bandwidth, buys nothing</i>"]
Q2 -->|yes| Q3{"model_dtype != fp32<br/><b>and</b><br/>grad_accum_dtype == fp32 ?"}
Q3 -->|no| E3["return inferred<br/><i>narrower accum can never<br/>demote a wider comm dtype</i>"]
Q3 -->|yes| FIX["<b>return fp32</b><br/>✅ window sum survives the reduction"]
style FIX fill:#1b5e20,color:#fff
style E1 fill:#37474f,color:#fff
Why
|
| Rule | Promote only when communication_data_type was inferred. Explicit values pass through untouched. |
| Default | On by default, not opt-in — a documented combination silently not doing what it says is a correctness bug, not a feature flag. |
| Escape hatch | communication_data_type: "bf16" restores the old bytes on the wire. Documented in config-json.md. |
| Cost accepted | All-reduce bytes double for this config. ZeRO-1 reduces once per accumulation window, not per micro-step, so it amortizes over gradient_accumulation_steps. |
Measured results
16 micro-steps of gradients exactly representable in the model dtype; float64 closed-form oracle; window sum read via safe_get_full_grad before step().
| model | stage | accum | offload | comm dtype | before | after |
|---|---|---|---|---|---|---|
| bf16 | 1 | fp32 | cpu | inferred | 2.355e-03 |
0 |
| fp16 | 1 | fp32 | — | inferred | 2.944e-04 |
0 |
| fp16 | 1 | fp32 | cpu | inferred | 2.944e-04 |
0 |
| fp16 | 1 | fp32 | — | fp16 explicit |
2.944e-04 |
2.944e-04 (by design) |
| bf16/fp16 | 1 | default | —/cpu | inferred | 6.18e-03/8.83e-04 |
unchanged |
| bf16/fp16 | 2 | fp32 | —/cpu | inferred | 0 |
0 (still 16-bit) |
| bf16/fp16 | 3 | fp32 | — | inferred | 0 |
0 (still 16-bit) |
Independently reproduced at world_size=2 over gloo with rank-distinct data and an exact-mean oracle.
Teeth-check — the test actually fails without the fix
# BEFORE (engine.py change stashed, test kept)
FAILED ...TestZeroDenseAccumReductionDtype::test_fp32_accumulation_window_sum_is_exact[1]
AssertionError: stage 1 fp32 accumulation lost precision: 2.944e-04
1 failed, 2 passed
# AFTER
3 passed
Re-run independently by me: 3 passed in 9.53s.
No regressions
| Suite | Before | After | Failure-set delta |
|---|---|---|---|
| Set A (9 ZeRO/bf16 files) | 33 failed / 100 passed | 32 failed / 101 passed | only the new stage-1 test flips |
Set B (grad_accum_dtype/comm dtype files) |
75 failed / 55 passed | 74 failed / 56 passed | only the new stage-1 test flips |
fused_adam/cpu_adam cannot JIT-build. Identical before and after.
Sibling-path audit (required by AGENTS.md)
flowchart TD
CFG["bf16 model + grad_accum_dtype: fp32 + ZeRO stage 1"] --> Q{"CPU offload?"}
Q -->|"yes"| ZO["DeepSpeedZeroOptimizer<br/>stage_1_and_2.py"]
Q -->|"no"| BO["<b>BF16_Optimizer</b><br/>engine.py:2405-2410 routes here"]
ZO --> F["✅ FIXED by this PR"]
BO --> NF["❌ <b>SAME BUG, NOT FIXED</b><br/>DeepSpeedEngine.allreduce_bucket<br/>engine.py:3939-3945<br/>measured 2.4e-3 / 2.8e-3"]
style F fill:#1b5e20,color:#fff
style NF fill:#8e1e1e,color:#fff
| Path | Shares defect? | Notes |
|---|---|---|
| ZeRO-2 | No | Reduction input already 16-bit. Verified exact before & after. |
| ZeRO-3 | No | Already promotes to fp32 for fp32-kept params (stage3.py:1763-1768). Verified. |
FP16_Optimizer / FP16_UnfusedOptimizer |
N/A | Without ZeRO, _do_optimizer_sanity_check rejects model_dtype != grad_accum_dtype. |
BF16_Optimizer + engine allreduce_bucket |
YES — out of scope | See diagram. Needs its own issue. |
| Autocast per-param comm dtype | Inert | That path ignores self.communication_data_type entirely. |
| MoE expert groups | Not special-cased | Share the fp32 IPG bucket → same dtype. Deliberate deviation from issue text. Untested. |
| ZenFlow | Inherits via shared constructor | Not separately validated. |
⚠️ Read this before merging: a reader of "deepspeedai#9047 is fixed" would reasonably assume ZeRO-1 + fp32 accum is now exact everywhere. It is not —bf16without CPU offload still rounds, because that config never reaches the ZeRO optimizer at all. This must be stated in the issue thread.
Relationship to deepspeedai#9044
#9044 is merged (2026-11-11) and is an ancestor of this branch's base. deepspeedai#9047 was filed while reviewing it; the stage-1 error is pre-existing, not a regression from deepspeedai#9044. This PR touches nothing deepspeedai#9044 touched and reuses its test file rather than adding a new one.
Gaps — must be closed by a human before upstream submission
| Gap | Why it matters |
|---|---|
| No GPU, no NCCL, no device collective | Every reduction here went through gloo on CPU. The dtype change has never run on real accelerator comms. |
| No convergence / throughput / peak-memory numbers | This is a numerics and bandwidth change; AGENTS.md requires them. The issue's "B200 all-reduce + step-time check" item is open. |
| Tightened assertion never executed | The strengthened TestZeroOffloadAccumPrecision needs DeepSpeedCPUAdam, unbuildable here. Equivalent case covered only by standalone script. |
| Not run | test_zero.py, MoE, ZenFlow, PP/TP/SP, reduce_scatter: false, overlap_comm: true, NVMe offload. |
Hardware for every number above: CPU-only, aarch64, 2 cores, no accelerator, gloo, torch 2.15.0+cpu, Python 3.13, no C++ compiler.
Not done
- No DCO
Signed-off-by— a human must read every line and attest. - Not submitted upstream.
Fixes deepspeedai#9047.
Review PR against my own fork — not submitted upstream.
What
With ZeRO stage 1, a 16-bit model and
data_types.grad_accum_dtype: "fp32", the gradient window is summed in fp32 inparam.grad_accumand the IPG bucket is allocated in fp32, so the copy into the bucket is lossless. The boundary reduction then casts that bucket tocommunication_data_type— bf16/fp16, inferred from the precision mode — inDeepSpeedZeroOptimizer.allreduce_bucketandgradient_reduction_w_predivide. The fp32 window sum is rounded once to 16 bits on the way into the collective, discarding exactly the precisiongrad_accum_dtype: fp32was configured to buy.ZeRO-2 is unaffected by construction: it reduces each micro-step in the model dtype and accumulates into the fp32 partition afterwards.
This resolves the reduction dtype at the single ZeRO-1/2 optimizer construction site in
DeepSpeedEngine.deepspeed/runtime/zero/stage_1_and_2.pyis not touched.Why in
engine.pyrather thanstage_1_and_2.pyThe optimizer cannot distinguish an inferred comm dtype from an explicitly configured one —
DeepSpeedEngine.communication_data_typeresolvesNoneinto a concrete dtype before handing it over. The explicit-vs-inferred distinction only exists in the engine. Fixing it there also keeps a file flagged as very-large-blast-radius core runtime byte-for-byte unchanged.Design decision
Promotion applies only when
communication_data_typewas inferred. An explicitbf16/fp16/fp32is passed through untouched — that setting is a deliberate bandwidth choice, and it is the documented way to keep the previous narrower reduction. The condition is narrow: stage 1 only, and only when accumulation is fp32 while the model dtype is not.Cost: all-reduce bytes double for this configuration. ZeRO-1 reduces once per accumulation window rather than per micro-step, so the extra bytes amortize over
gradient_accumulation_steps.Sibling-path audit (per
AGENTS.md)stage3.py:1763-1768). Verified.FP16_Optimizer/FP16_UnfusedOptimizer_do_optimizer_sanity_checkrejectsmodel_dtype != grad_accum_dtype.BF16_Optimizer+DeepSpeedEngine.allreduce_bucketbf16+ fp32 accum + stage 1 takes when CPU offload is off (engine.py routes it toBF16_Optimizer). Measured 2.4e-3 at 1 rank, 2.8e-3 at 2 ranks — unchanged by this PR. Needs a separate issue.self.communication_data_typeentirely.Relationship to deepspeedai#9044
deepspeedai#9044 ("ZeRO-2 CPU offload: accumulate in the compact partition between requests") is merged (2026-11-11) and is an ancestor of the base commit here. deepspeedai#9047 was filed while reviewing it; the stage-1 error is pre-existing, not a regression from deepspeedai#9044. This PR changes nothing deepspeedai#9044 touched and reuses its
test_zero_offload_accum_precision.pyfor coverage rather than adding a new file.Tests run, and the hardware
CPU-only sandbox, aarch64, 2 cores, no accelerator, gloo, torch 2.15.0+cpu, Python 3.13. No GPU, no NCCL, no C++ compiler.
Surrounding ZeRO/bf16 suites, before vs after: set A
33 failed/100 passed→32 failed/101 passed; set B75 failed/55 passed→74 failed/56 passed. The single flip in each is the new stage-1 test; no new failures. All remaining failures are environmental — no C++ compiler, sofused_adam/cpu_adamcannot JIT-build; identical before and after.Standalone numerics check (16 micro-steps of values exact in the model dtype, float64 oracle, window sum read before
step()):fp16explicitCompatibility matrix: NOT validated — must be run before merging
AGENTS.mdexpects them. The issue's "B200 all-reduce/step-time check" item is open.TestZeroOffloadAccumPrecisionwas never executed — it needsDeepSpeedCPUAdam, unbuildable here. Equivalent cell covered only by standalone script.test_zero.py, MoE, ZenFlow, PP/TP/SP,reduce_scatter: false,overlap_comm: true, NVMe offload: not run.AI assistance
AI assistance (Claude Code) was used for the diagnosis, patch, tests and this description. Per
AGENTS.mda human must review every line and supply the missing GPU/convergence evidence plus the DCOSigned-off-by— no sign-off has been added.