Skip to content

ZeRO-1: reduce the fp32 accumulation window in fp32, not the comm dtype - #2

Open
kritikagarg wants to merge 1 commit into
masterfrom
fix/9047-zero1-fp32-accum-comm-dtype
Open

kritikagarg wants to merge 1 commit into
masterfrom
fix/9047-zero1-fp32-accum-comm-dtype

Conversation

@kritikagarg

Copy link
Copy Markdown
Owner

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 in param.grad_accum and the IPG bucket is allocated in fp32, so the copy into the bucket is lossless. The boundary reduction then casts that bucket to communication_data_type — bf16/fp16, inferred from the precision mode — in DeepSpeedZeroOptimizer.allreduce_bucket and gradient_reduction_w_predivide. The fp32 window sum is rounded once to 16 bits on the way into the collective, discarding exactly the precision grad_accum_dtype: fp32 was 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.py is not touched.

Why in engine.py rather than stage_1_and_2.py

The optimizer cannot distinguish an inferred comm dtype from an explicitly configured one — DeepSpeedEngine.communication_data_type resolves None into 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_type was inferred. An explicit bf16/fp16/fp32 is 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)

Path Result
ZeRO-2 Does not share the defect; reduction input already 16-bit. Verified exact before and after.
ZeRO-3 Does not share it, and 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 + DeepSpeedEngine.allreduce_bucket Shares the defect; deliberately out of scope. This is the path bf16 + fp32 accum + stage 1 takes when CPU offload is off (engine.py routes it to BF16_Optimizer). Measured 2.4e-3 at 1 rank, 2.8e-3 at 2 ranks — unchanged by this PR. Needs a separate issue.
ZenFlow Inherits the new resolution via the shared constructor; not separately validated.
Autocast per-param comm dtype Inert — that path ignores self.communication_data_type entirely.
MoE expert groups Not special-cased; they share the fp32 IPG bucket and get the same dtype. Deliberate deviation from the issue text. Not exercised by any test.

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.py for 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.

cd tests && python3.13 -m pytest -p no:randomly -q \
  "unit/v1/zero/test_zero_offload_accum_precision.py::TestZeroDenseAccumReductionDtype"
# before fix: 1 failed, 2 passed
#   AssertionError: stage 1 fp32 accumulation lost precision: 2.944e-04
# after  fix: 3 passed

Surrounding ZeRO/bf16 suites, before vs after: set A 33 failed/100 passed → 32 failed/101 passed; set B 75 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, so fused_adam/cpu_adam cannot 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()):

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 — fp16 explicit 2.944e-04 2.944e-04 (by design)
bf16/fp16 2 fp32 —/cpu inferred 0 0 (still 16-bit)
bf16/fp16 3 fp32 — inferred 0 0 (still 16-bit)

Compatibility matrix: NOT validated — must be run before merging

  • No GPU, no NCCL, no real device collective. Every reduction went through gloo on CPU.
  • No convergence, throughput, or peak-memory numbers. This is a numerics and bandwidth change, so AGENTS.md expects them. The issue's "B200 all-reduce/step-time check" item is open.
  • The tightened assertion in TestZeroOffloadAccumPrecision was never executed — it needs DeepSpeedCPUAdam, 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.md a human must review every line and supply the missing GPU/convergence evidence plus the DCO Signed-off-by — no sign-off has been added.

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>
@kritikagarg

Copy link
Copy Markdown
Owner Author

PR Summary — deepspeedai#9047: ZeRO-1 rounds the fp32 accumulation window to the comm dtype

Issue deepspeedai/DeepSpeed#9047
Branch fix/9047-zero1-fp32-accum-comm-dtype
Commit 3605f177
Diff 3 files, +104 / −6 (engine.py, config-json.md, one test file)
Difficulty Medium
Status Bug reproduced, fix implemented, regression test proven to have teeth. Missing GPU/convergence evidence.

The defect

With ZeRO-1 + a 16-bit model + grad_accum_dtype: fp32, the whole accumulation window is summed in fp32 — then rounded once to bf16/fp16 immediately before the all-reduce. The extra precision the config asked for is discarded at reduction time.

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
Loading

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
Loading

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

deepspeed/runtime/zero/stage_1_and_2.py is not touched (core runtime, very large blast radius per pr-checklist §1.1). Instead the dtype is decided at the single ZeRO-1/2 construction site in engine.py:

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
Loading

Why engine.py and not stage_1_and_2.py

The optimizer cannot distinguish an inferred comm dtype from an explicitly configured one — DeepSpeedEngine.communication_data_type resolves None into a concrete dtype before handing it over. That distinction exists only in the engine. Fixing it there also leaves core ZeRO byte-for-byte unchanged and needs no new constructor parameter.

Design decision and its cost

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

⚠️ All remaining failures are environmental — this box has no C++ compiler, so 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
Loading
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 — bf16 without 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.

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 with fp32 grad accumulation rounds the window sum to the communication dtype

1 participant