Skip to content

ZeRO-1/2 gradient accumulation: close the executable test gaps from #8957 - #3

Open
kritikagarg wants to merge 1 commit into
masterfrom
test/8957-zero12-grad-accum-coverage
Open

kritikagarg wants to merge 1 commit into
masterfrom
test/8957-zero12-grad-accum-coverage

Conversation

@kritikagarg

Copy link
Copy Markdown
Owner

Addresses deepspeedai#8957 (ZeRO-1/2 gradient accumulation: remaining test coverage).

Review PR against my own fork — not submitted upstream. DRAFT: work in progress.

Status

This is an in-progress snapshot, pushed while the authoring agent is still running its test suite. Nothing here has been verified yet — no confirmed test run, no pre-commit check, no teeth-check. Do not review for correctness yet; it will be force-updated with the verified commit when testing completes.

Currently +490 lines across:

  • tests/unit/v1/zero/test_zero2_offload_multi_backward.py
  • tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py

Context

deepspeedai#8957 is a maintainer-authored checklist of missing test coverage, a follow-up to PR deepspeedai#8949 ("ZeRO-1/2: preserve gradients across request boundaries until step"), which is merged. It is test-only work — no production code should change.

Known environment limitation (important for judging the evidence)

This work was prepared on a CPU-only aarch64 box, 2 cores, with no C++ compiler. Consequently DeepSpeedCPUAdam, fused_adam and deepspeed_shm_comm cannot be JIT-built.

That matters a lot here: deepspeedai#8957's checklist is largely about CPU-offload gradient accumulation, and CPU offload requires DeepSpeedCPUAdam. So a meaningful share of the checklist is not executable in this environment at all, regardless of whether the tests are written correctly. Expect the final report to separate:

  • items proven by an actual run here, from
  • items written but only runnable on a machine that can build cpu_adam.

AI assistance

AI assistance (Claude Code) was used to write these tests. Per AGENTS.md, a human must read every changed line and add the DCO Signed-off-by before anything goes upstream — no sign-off has been added, and this is explicitly not upstream-ready.

Issue deepspeedai#8957 lists checks still missing after deepspeedai#8949. These are the ones that
can be executed and can actually fail on a CPU-only host with two ranks.

tests/unit/v1/zero/test_zero2_offload_multi_backward.py adds five two-rank
end-to-end tests over a padded, rank-split parameter group (3 + 6 gradient
elements padded to 12, so rank 1 owns its fragment at a non-zero source
offset behind three padding elements):

- late first use of a parameter in a multi-request window, including an
  overlap_comm variant,
- a non-finite window followed by finite windows with fp32 accumulation,
- clipping and Inf detection for a parameter that only ever contributes on a
  non-boundary backward,
- fractional contributions (1 and 1/256) whose sum bf16 cannot hold, so the
  configured accumulation dtype is observable,
- managed_gradient_accumulation=false with several backwards per step().

Every gradient and update is checked against an independently derived
reference: the sum-loss gradient of a bias-free linear layer is the input
column sums, the update comes from plain torch SGD, and the clipped update
from torch.nn.utils.clip_grad_norm_. No assertion uses the sibling
offload/non-offload path as its oracle.

tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py previously only checked
that the host-partition norm moved between micro-steps. It now also checks the
accumulated gradient against the analytic micro-batch sum, which a wrong
accumulation magnitude cannot pass.

ZeRO-1 with overlap_comm is excluded from the new matrix: it returns a
different wrong gradient for each half of the split parameter on its own, a
reduction defect that needs its own report.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kritikagarg

Copy link
Copy Markdown
Owner Author

PR Summary — deepspeedai#8957: ZeRO-1/2 gradient accumulation test coverage

Issue deepspeedai/DeepSpeed#8957
Branch test/8957-zero12-grad-accum-coverage
Commit 062c4615 — unverified WIP snapshot
Diff 2 test files, +490 / −0
Difficulty Beginner (test-only; no production code)
Status 🚧 IN PROGRESS. Authoring agent still running. No confirmed test run, no pre-commit, no teeth-check.

⚠️ This document describes work in flight. Results are not yet established — nothing below should be read as a validated outcome. It will be rewritten when the agent reports.


What the issue asks for

deepspeedai#8957 is a maintainer-authored checklist of test gaps left over from PR #8949 ("ZeRO-1/2: preserve gradients across request boundaries until step"), which is merged. It is pure test work — no runtime change should appear in this diff.

The issue also criticises the existing tests on three specific grounds, which constrain how the new ones must be written:

flowchart LR
    C1["existing tests call optimizer<br/>helpers on a <b>partial object</b>"] --> R1["→ drive real engine APIs instead"]
    C2["existing tests use the <b>sibling path</b><br/>as the oracle"] --> R2["→ anchor to an <b>independent</b><br/>summed-loss reference"]
    C3["existing tests set only <b>one</b><br/>accumulation boundary"] --> R3["→ several boundaries before one step()"]
    style R1 fill:#1b5e20,color:#fff
    style R2 fill:#1b5e20,color:#fff
    style R3 fill:#1b5e20,color:#fff
Loading

Checklist from the issue

# Item Runnable in this sandbox?
1 Several set_gradient_accumulation_boundary(True) calls before one step(), vs independent summed-loss reference likely yes
2 Two-parameter late first use, source_offset > 0, partition padding likely yes
3 Compact FP32 accumulation after overflow, then a later finite window likely yes
4 Clipping / Inf detection for a param used only on a non-boundary microbatch likely yes
5 Multi-rank split parameters world_size=2 only
6 Fractional BF16/FP16 values so master-dtype conversion is visible likely yes
7 Reentrant checkpointing, managed_gradient_accumulation=false unclear
8 overlap_comm stream ordering; ZenFlow overlap_step loop ❌ needs streams/accelerator
9 Direct gradient-equality checks likely yes

⚠️ The structural problem with validating this issue here

This is the single most important caveat, and it is a bad pairing between the issue and the machine — my fault in selecting it, not the agent's.

flowchart TD
    I["#8957 checklist is largely about<br/><b>ZeRO-1/2 CPU-offload</b> grad accumulation"]
    I --> NEED["CPU offload requires<br/><b>DeepSpeedCPUAdam</b>"]
    NEED --> JIT["DeepSpeedCPUAdam is JIT-compiled<br/>from C++/CUDA sources at runtime"]
    JIT --> NOCC["❌ <b>this box has no C++ compiler</b><br/>(also aarch64; cpu_adam uses x86 SIMD)"]
    NOCC --> FAIL["RuntimeError: DeepSpeedCPUAdam requires<br/>the cpu_adam op, which failed to build"]
    FAIL --> CONC["⇒ offload checklist items are<br/><b>not executable here at all</b>,<br/>however correctly written"]
    style NOCC fill:#8e1e1e,color:#fff
    style FAIL fill:#8e1e1e,color:#fff
    style CONC fill:#5d4037,color:#fff
Loading

Related environment blockers the agent is working around:

Component Status Workaround in use
cpu_adam ❌ cannot build use "torch_adam": true where the test allows
fused_adam ❌ cannot build avoid
deepspeed_shm_comm ❌ cannot build DS_TEST_DISABLE_SHM=1 → plain gloo

Consequence for review: the final report must separate items proven by an actual run here from items written but only runnable where cpu_adam builds. The second group may well be larger. Pass counts alone will overstate the coverage.

Why it is taking a long time

Not a hang — measured directly:

  • 2 physical cores, ~1 GB free RAM
  • torch defaults to 2 intra-op threads per process; each DistributedTest spawns 2 ranks → ~4 threads on 2 cores (2× oversubscription)
  • the agent runs one test at a time, each under its own timeout, so CPU arrives in bursts separated by decision gaps
  • 9 checklist items × (write → run → interpret) on that hardware

Verification status

Check Status
Tests written ~490 lines across 2 files
Confirmed test run ❌ not yet
pre-commit ❌ not yet
Teeth-check (fails without deepspeedai#8949 behaviour) ❌ not yet
Items proven vs. unprovable, itemised ❌ pending report

Not done

  • No DCO Signed-off-by.
  • Not submitted upstream. Fork PR is a draft deliberately.

@kritikagarg
kritikagarg force-pushed the test/8957-zero12-grad-accum-coverage branch from 062c461 to b4368e3 Compare November 22, 2026 04:57
@kritikagarg
kritikagarg marked this pull request as ready for review November 22, 2026 05:01
@kritikagarg kritikagarg changed the title [DRAFT] ZeRO-1/2 gradient accumulation: remaining test coverage (#8957) ZeRO-1/2 gradient accumulation: close the executable test gaps from #8957 Nov 22, 2026
@kritikagarg

Copy link
Copy Markdown
Owner Author

✅ Verified — replaces the draft notice above

PR Summary — deepspeedai#8957: ZeRO-1/2 gradient accumulation test coverage

Issue deepspeedai/DeepSpeed#8957
Branch test/8957-zero12-grad-accum-coverage
Commit b4368e31
Diff 2 test files, +490 / −0 — no source changes
Difficulty Beginner scope, demanding execution
Status ✅ 42 new cases pass. Teeth-check proven across 9 mutations. Independently re-verified.

What was built

Six new tests closing the executable portion of deepspeedai#8957's checklist. Every end-to-end test runs over a two-rank, padded, rank-split parameter group built from SplitProjectionModel — Linear(3,1) + Linear(3,2) = 9 gradient elements, which ZeRO pads to 12:

flowchart TD
    M["SplitProjectionModel<br/>first.weight: 3 elems · second.weight: 6 elems<br/>total 9 → <b>padded to 12</b>"]
    M --> R0["<b>rank 0</b> partition (size 6)<br/>grad_position {0:[0,0,0,3], 1:[0,0,3,3]}<br/>owns all of first.weight<br/>+ first half of second.weight"]
    M --> R1["<b>rank 1</b> partition (size 6)<br/>grad_position {1:[0,3,0,3]}<br/><b>source_offset = 3 > 0</b><br/>behind <b>3 padding elements</b><br/>owns NO fragment of first.weight"]
    R0 --> W["⇒ exercises split params, non-zero source offset,<br/>padding, and a param absent from a rank"]
    R1 --> W
    style R1 fill:#5d4037,color:#fff
    style W fill:#1b5e20,color:#fff
Loading

The oracle is analytic, not the sibling path

This was the issue's central complaint about existing coverage. Every assertion anchors to an independently derived reference:

flowchart LR
    A["sum-loss gradient of a<br/>bias-free Linear =<br/><b>input column sums</b><br/><i>(calculus)</i>"] --> AS["gradient assertions"]
    B["<b>torch.optim.SGD</b><br/>on fp32 copies"] --> BS["update assertions"]
    C["<b>torch.nn.utils<br/>.clip_grad_norm_</b>"] --> CS["clipped-update assertions"]
    D["L2 norm of the independent<br/>gradient vs public<br/><b>engine.get_global_grad_norm()</b>"] --> DS["norm assertions"]
    style A fill:#1b5e20,color:#fff
Loading

Fixture inputs are eighths, so every per-backward gradient and every partial sum is exact in bf16 (numerator < 256). That allows rtol=0, atol=0 — no loosened thresholds anywhere.

Checklist disposition

# Item Outcome
1 Multi-boundary vs summed-loss reference ✅ already closed in-tree by deepspeedai#8949's final commit
2, 5 Late first use, source_offset > 0, padding; multi-rank split params ✅ test_late_first_use_in_padded_split_partition — 12 cases
3 Compact FP32 accumulation after overflow, later finite window ✅ test_compact_fp32_accumulation_recovers_after_overflow — 4 cases
4 Clipping + Inf detection for non-boundary-only param ✅ test_nonboundary_only_parameter_reaches_norm_and_overflow — 16 cases
6 Fractional values so master-dtype conversion is visible ✅ test_fractional_contributions_keep_configured_accumulation_dtype — 2 cases
7a managed_gradient_accumulation=false ✅ test_unmanaged_accumulation_sums_every_backward — 8 cases
7b Reentrant checkpointing ✅ already closed in-tree
9 Direct gradient equality ✅ TestZero2CPUOffloadGradAccumValue — 2 cases
8a overlap_comm functional ⚠️ folded in as a stage-2 matrix axis — no stream-ordering claim
8b overlap_comm stream ordering ❌ impossible — CPU accelerator streams are no-ops
8c ZenFlow overlap_step loop ❌ not runnable — see below

Teeth-check — 9 mutations, each caught

Source was mutated one line at a time, then restored. Highlights:

Mutation Caught by
pre-deepspeedai#8949 unconditional all_grad_tensors[i] = None late_first_use[bf16-device-optimizer-*]
pre-deepspeedai#8949 micro_step_id > 0 host-accum gating late_first_use[bf16-cpu-offload-2]
overflow branch leaves gradients resident compact_fp32_accumulation_recovers[device-optimizer-2]
_publish_unpublished_offload_grads() removed nonboundary_only[clipping-…] and [inf-detection-…] — both halves bite
norm recording removed (gradient still published) global grad norm 2.604 excludes the non-boundary-only parameter (expected 3.584)
compact partition built in model dtype fractional_contributions[fp32]
epilogue add_ → copy_ unmanaged_accumulation[bf16-device-optimizer-2]
add_(dest_buffer, alpha=2) — double counting only the new value test; old norm test passes

I re-ran that last one independently — it is the key result

TestZero2CPUOffloadGradAccumNorm::test[None]              PASSED   ← pre-existing test misses it
TestZero2CPUOffloadGradAccumValue::...reference[None]      FAILED   ← new test catches it
1 failed, 3 passed

This is exactly the defect class deepspeedai#8957 complained about: the old test asserts only that the host-partition norm changes, which any wrong-magnitude accumulation satisfies.

Also self-discriminating without any mutation: fractional_contributions asserts different values for its two parametrizations — 1.00390625 for fp32 accumulation vs 1.0 for bf16 (the window adds 1 + 1/256; each term is exact in bf16, the sum is not). Both pass, so the configured dtype demonstrably changes the observable result and the test cannot be vacuous.

Verified results

Run Result
42 new two-rank cases 42 passed in 75.39s (agent) — 42 passed in 86.05s (my independent re-run)
test_zero_cpu_offload_grad_accum.py (old + new) 4 passed in 9.35s
All 3 affected files together 10 failed / 122 passed / 12 skipped

⚠️ The 10 failures are pre-existing, not introduced. All sit in the untouched TestZeroOffloadMultiBackward class, all are RuntimeError: Error building extension 'fused_adam' — no C++ compiler on this host. Confirmed by stashing the diff and re-running on pristine 7681845b: identical 10 failures.

🔴 Incidental finding — possible real bug, needs its own issue

Found on unmutated master 7681845b. With stage: 1 + overlap_comm: true, bf16, 2 gloo ranks, and a parameter whose first contribution is a non-boundary backward, the two halves of a split parameter get different wrong sums:

stage=1 overlap=False  second.weight  got [2.75, 3.25, 3.0, 2.75, 3.25, 3.0]  ✅ correct
stage=1 overlap=True   second.weight  got [2.25, 2.75, 2.5, 3.25, 3.75, 3.5]  ❌ row 0 low by 0.5, row 1 high by 0.5
stage=2 overlap=True   second.weight  got [2.75, 3.25, 3.0, 2.75, 3.25, 3.0]  ✅ correct

first.weight is correct in all three. Nothing in engine.py forbids overlap_comm at stage 1 (except with managed_gradient_accumulation=False), so this is either a genuine reduction defect or an undocumented unsupported combination. The agent correctly excluded it from the committed matrix ([(1,False),(2,False),(2,True)]) with an in-file comment rather than committing a failing test. Reproducer at /tmp/ds_probe/p2.py. Needs a human decision.

Corrections to my briefing — the agent was right

Item I told it Reality
PR deepspeedai#9018 closed/unmerged merged 2026-11-09
PR deepspeedai#9044 closed/unmerged merged 2026-11-11
DistributedTest(world_size=2) works here ❌ skips — CPU accelerator reports device_count()==1
deepspeedai#8957 checklist currency current filed 2026-10-30, 3 days before deepspeedai#8949 merged; items already closed in-tree

It triaged against the current code rather than the issue snapshot, and launched its own ranks via torch.multiprocessing.start_processes(start_method="forkserver") — matching the already-merged test_multiple_request_boundaries_before_step.

Sandbox workarounds — local only, NOT committed

Artifact Purpose
/tmp/ds_site/sitecustomize.py marks deepspeed_shm_comm incompatible → gloo fallback (op can't JIT-build without a compiler)
/tmp/ds_probe/* layout probe, mutation scripts, reproducers, pristine source backup

Both module paths (op_builder.cpu.comm and deepspeed.ops.op_builder.cpu.comm) must be patched — they are distinct module objects when the repo root is on sys.path.

Not validated

GPU/CUDA of any kind · FP16 end to end · CPUAdam and fp16/bf16_master_weights_and_grads (op won't build) · overlap_comm stream ordering · ZenFlow overlap_step (the in-tree ZenFlow suite returns immediately on CPU, so its 57 "passing" tests execute no training at all; a direct two-rank attempt died in gloo process-group setup) · overlap_comm at stage 1 (see finding above) · ZeRO-3 · NVMe · vendor accelerators · world_size > 2 · TP/PP/EP/SP.

No convergence/throughput/memory numbers — correctly N/A, since this adds tests only and changes no numerics.

Hardware: CPU only, aarch64, 2 cores, no accelerator, gloo, torch 2.15.0+cpu, Python 3.13.18, 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.

1 participant