Skip to content

ZeRO-3: copy offloaded master weights back to the device through pinned buffer - #8840

Merged
pengdurice merged 7 commits into
deepspeedai:masterfrom
pengdurice:peng-fix-zero3-offload-pinned-copy-v2
Oct 30, 2026
Merged

pengdurice merged 7 commits into
deepspeedai:masterfrom
pengdurice:peng-fix-zero3-offload-pinned-copy-v2

Conversation

@pengdurice

@pengdurice pengdurice commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

ZeRO-3: pin the offloaded master weights and cast them on the device when copying them back

Part of: #8672 (Q4 2026 roadmap), "Enable training of large scale models".

Summary

With offload_optimizer.device: cpu, ZeRO-3 copies each sub-group's updated float32 master partition back to the
device as bf16 after every step.

  • pin_memory: true (the default since fix(zero3): async grad offload + pinned offload buffers by default #8207) pins the float32 gradient partitions. It does not pin the master
    partitions, so this copy reads pageable host memory.
  • The copy is also a cast. A blocking copy_ from float32 into bf16 casts on the CPU into a new pageable tensor and
    copies from that at a few GB/s.

This PR follows ZeRO-1/2 and #5301:

  • with pin_memory: true, each CPU master partition is pinned when it is created, as ZeRO-1/2 does;
  • the copy-back moves the pinned float32 master to the device and casts it there, in pieces of 2**26 elements, so the
    device temporary is one piece (0.25 GiB) instead of a whole sub-group.

Results:

  • Qwen2.5-32B, 8 H200, whole optimizer on the CPU: 12.08 s to 9.42 s per step (-22.0%), same peak device memory,
    same losses (the new unit test compares the parameters bitwise).
  • Host memory: the master partitions are already in host memory and become pinned. PyTorch's pinned allocator rounds
    each allocation up to a power of two: a 1e9-element sub-group (3.73 GiB in float32) reserves 4.00 GiB.

Duplicate check

Searched issues and PRs on 2026-10-13 ("offload pinned fp32 partition", "zero3 offload pin_memory copy",
"fp32_partitioned_groups_flat", "offload ratio pinned", "pageable offload"). Related, not duplicates: #8207 (merged:
pinned the ZeRO-3 gradient offload buffers, default pin_memory: true; master partitions unchanged), #8256 (merged:
routes pin sites through get_accelerator().pin_memory(); this PR uses the same accelerator calls), #8618 (closed:
a CPU-offload benchmark).

Sibling path: ZeRO-1/2 pins its master partitions
(stage_1_and_2.py#L563-L575).
#5301 added the pinning and copied the pinned master to the device before the cast; ZeRO-1/2 now casts into a pinned
bf16 buffer of each partition's size instead
(#L3093-L3096).
This PR uses #5301's form, which needs no second pinned buffer.

Root cause

What offload_optimizer.pin_memory: true pins in ZeRO-3 on master, checked at runtime on the earlier version of this
PR, which pins the same buffers as master (one GPU, bf16, DeepSpeedCPUAdam, after deepspeed.initialize and after one
step):

Buffer Where Pinned
fp16_partitioned_groups_flat (bf16 parameter partitions) device (device memory)
fp32_partitioned_groups_flat[i].grad (float32 gradient partitions) host yes (stage3.py#L1339-L1340)
fp32_partitioned_groups_flat (float32 master partitions) host no
Adam exp_avg, exp_avg_sq host no

With offload_param, fp16_partitioned_groups_flat is on the host and already pinned: it is a view of
param_groups_fp16_flat_cpu_memory (stage3.py#L906).

_create_fp32_partitions builds each CPU master partition with .to('cpu', dtype=...) and .clone().detach()
(stage3.py#L1157-L1160),
which gives pageable memory. After the CPU optimizer step, _reassign_or_swap_out_partitioned_parameters runs
fp16_flat.data.copy_(fp32_flat.data): a blocking copy from CPU float32 to device bf16, which PyTorch does by casting
on the CPU into a new pageable bf16 tensor of the whole partition, copying it from pageable memory and synchronizing.

Found in a profile (MiniMax-M3, first 8 layers, 8 H200, 75% of the optimizer on the CPU, rank 0): 13 bare
aten::copy_ host-to-device copies of 576 MiB per step from pageable memory, at 3-7 GB/s, 1,648 ms per step.

The change (deepspeed/runtime/zero/stage3.py, 43 added, 4 removed lines)

Where What
_create_fp32_partitions with offload_optimizer.pin_memory, pins each CPU master partition after clone().detach() (get_accelerator().pin_memory)
_reassign_or_swap_out_partitioned_parameters uses the new copy for a master pinned there whose destination is on the device; every other case keeps dst.copy_(src): pin_memory false, sub-groups kept on the device (ratio < 1), NVMe-swapped sub-groups
new _copy_pinned_master_to_device(dst, src) per piece of 2**26 elements: src[piece].to(device, non_blocking=True), then dst[piece].copy_(...), which casts on the device; at the end, records an event and waits for it
new _master_pinned_at_construction(sub_group_id) the condition above (pinned, on the CPU, not NVMe-swapped); also used by _unpin_offload_buffers
__init__, _unpin_offload_buffers the piece size; release of the pinned masters (matters under DS_PIN_MEMORY_BACKEND=native)

Design notes:

  • Why the cast moves to the device: pinning alone does not make the copy faster. A blocking copy_ from pinned
    float32 into bf16 still casts on the CPU into a new pageable tensor (136.2 ms against 136.5 ms from pageable memory,
    300M elements, in an earlier measurement on the same setup).

  • Why pieces: .to(device) of a whole sub-group makes a float32 device temporary of the sub-group's size,
    3.73 GiB at the default sub_group_size of 1e9. Pieces of 2**26 elements keep it at 0.25 GiB at the same speed.

    Measured on one H200, torch 2.8.0, 12 CPU threads, copying one partition back into its bf16 device partition:

    Copy back 300M elements 1e9 elements Extra device memory at 1e9
    copy_ from pageable float32 (master) 132.6 ms 483.3 ms 0
    pinned float32, .to(device), then copy_ (fix pagable h2d memcpy #5301) 22.1 ms 73.6 ms 3.73 GiB
    the same in pieces of 2**26 elements (this PR) 22.1 ms 73.7 ms 0.25 GiB
    earlier version of this PR: two pinned 2**26-element bf16 staging buffers 19.4 ms 73.6 ms 0
  • Same values: the device cast rounds to nearest even, as the CPU cast does. The new test compares the trained
    parameters bitwise against pin_memory: false.

  • Stream order: the pieces go on the current stream. The final wait keeps what callers had before: the partition
    is on the device when the function returns. The next forward's parameter all-gathers run on their own stream, and
    that stream does not wait for the main stream.

  • Host synchronization: one wait per sub-group, at the end of its copy. The old path also blocked for the whole
    copy.

Measured

Qwen2.5-32B (all 64 layers, real weights), 1 node of 8 H200 (143,771 MiB, driver 580.126.09), torch 2.8.0+cu126.
Settings:

  • ZeRO-3 with offload_optimizer: {device: cpu, pin_memory: true};
  • float32 master weights and Adam states, DeepSpeedCPUAdam with 12 threads per rank;
  • bf16, one 8,192-token PG-19 sequence per GPU, activation checkpointing, lr 1e-6;
  • mean of steps 3-8; one run per column; all runs in one job on the same node.
master 0f8c9d7f1 earlier version of this PR (staging buffers) this PR
step time 12.08 s 10.20 s 9.42 s
step time with wall_clock_breakdown 11.96 s - 9.42 s
rank 0: forward / backward 1.19 / 3.71 s - 1.19 / 3.67 s
rank 0: step / of which the sub-group loop (optimizer_step) 7.06 / 6.05 s - 4.56 / 3.52 s
peak device memory (rank 0) 34.66 GB 34.66 GB 34.66 GB
loss at steps 1 / 2 / 8 0.022649 / 0.976290 / 1.746374 0.022649 / 0.976256 / 1.746135 0.022649 / 0.976285 / 1.746306

The losses differ from step 2 by run-to-run variation: two master runs differ by as much (step 2 is 0.976235 with
wall_clock_breakdown and 0.976290 without it). The flash-attention backward adds with atomics. The bitwise check is
the unit test below.

This version is faster than the earlier one in training (9.42 against 10.20 s), although the two copies take the
same time alone at 1e9 elements. A likely reason, not measured: the earlier version cast on the CPU, which the CPU
optimizer of all 8 ranks on the node also uses; this version casts on the device.

Earlier version of this PR (staging buffers) on MiniMax-M3 (DeepSpeed master + unmerged MiniMax-M3 model code: #8658, #8652)

Settings for both: ZeRO-3 + AutoEP (expert parallel 8), real weights, each 65,536-token sequence split over 4 GPUs,
65% of the optimizer on the CPU (offload_optimizer.ratio 0.65), float32 master + Adam.

  • 4 nodes x 8 H200, all 60 layers, same nodes, back to back: 126.9 s without, 123.9 s with
    (mean of steps 3-10); peak device memory 132.4 GB in both.
  • 1 node, first 8 layers: 14.09 s without, 12.46 s with; losses equal at every printed step.

These were not repeated with this version.

Tests

Updated: TestZero3OffloadPinnedCopyBack in tests/unit/v1/zero/test_zero.py (2 ranks, ratio 1.0 and 0.5,
sub_group_size 20,000 so partial offload has sub-groups on both sides).

  • It trains 3 steps with pin_memory: false (direct copy) and with pin_memory: true, and requires the gathered
    parameters to be bitwise equal.
  • It requires every CPU master partition to be pinned with pin_memory: true, and none with pin_memory: false.
  • It requires that the pinned run used the new copy. Otherwise the test would compare the direct copy with itself.
  • The piece size is set to 1,000 elements, so each sub-group is copied in many pieces.

Commands, from tests/, on 1 node of 8 H200 (143,771 MiB, driver 580.126.09), torch 2.8.0+cu126, pytest 9.1.1:

# master 0f8c9d7f1 + only the new test: 2 failed, AttributeError: no attribute '_copy_pinned_master_to_device'
# master + this PR:
pytest unit/v1/zero/test_zero.py -k TestZero3OffloadPinnedCopyBack        # 2 passed
pytest unit/v1/zero/test_zero.py unit/v1/zero/test_zero_user_backward.py unit/v1/pin_memory/ \
    -k "offload or Offload or pin or Pin"                                  # 61 passed, 1 skipped (torch_npu)
pytest unit/v1/zero/test_offload_states.py                                 # 128 passed
pytest unit/runtime/zero/test_zero_offloadpp.py unit/v1/pin_memory/        # 47 passed, 1 skipped (torch_npu)

The test is in tests/unit/v1, so PR CI selects it: the modal-torch-latest selector (ci/tests_fetcher.py)
picked tests/unit/v1/zero/test_zero.py for the earlier version, which changes the same two files.

Compatibility

Cell Validated
ZeRO-3, CPU optimizer offload, pin_memory true, whole optimizer on the CPU yes: new test (ratio 1.0); Qwen2.5-32B
ZeRO-3, partial offload (ratio < 1) yes: new test (ratio 0.5). MiniMax-M3 on 1 and 4 nodes with the earlier version only
ZeRO-3, pin_memory false unchanged path (not pinned, direct copy); the new test's reference
bf16 yes. fp16: not run (same path; the device cast also rounds to nearest even)
ZeRO-3, NVMe optimizer offload not run. Unchanged: NVMe-swapped sub-groups are not pinned here and keep the direct copy
ZeRO-3 + ZenFlow, DS_PIN_MEMORY_BACKEND=native not run
ZeRO-1/2 not affected
Accelerators other than CUDA not run; only get_accelerator() calls are used (pin_memory, is_pinned, Event, unpin_memory)

No config, checkpoint format or public API change.

AI assistance

This change, its tests and this description were prepared with AI assistance (Claude).

…ed buffers

Signed-off-by: pengdurice <pengduhit@gmail.com>
@0z5a 0z5a mentioned this pull request Oct 18, 2026
@pengdurice
pengdurice marked this pull request as ready for review October 20, 2026 21:01
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T21:11:59.347603Z f8d5502 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@delock
delock self-requested a review October 23, 2026 08:07
model, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config_dict)


@pytest.mark.skipif(not get_accelerator().is_bf16_supported(), reason="bf16 is not supported on this accelerator")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suppose we run v1 tests on CPU, then these tests should be skipped on CPU because offload is not a CPU scenario.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great catch, added a line to skip cpu below (similar to what TestZero3DictFwd does it);-)

@delock

delock commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

Hi @pengdurice , thanks for your PR. I have left my comments.

Signed-off-by: pengdurice <pengduhit@gmail.com>
@delock
delock added this pull request to the merge queue Oct 23, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 23, 2026
# fp32_partitioned_groups are aliases. Calling tensor.data.copy_ will not trigger any copy in that case.
self.fp16_partitioned_groups_flat[sub_group_id].data.copy_(
self.fp32_partitioned_groups_flat[sub_group_id].data)
dst = self.fp16_partitioned_groups_flat[sub_group_id].data

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pengdurice can you confirm why self.fp16_partitioned_groups_flat and self.fp32_partitioned_groups_flat are not pinned at construction if pin_memory option is selected

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @sfc-gh-truwase , thank you for the review. For self.fp16_partitioned_groups_flat, it is on the GPU unless offloading parameters are on, so pinning doesn't apply here. For self.fp32_partitioned_groups_flat, it is indeed pinned, but during copying back to the GPU, it uses an pageable memory by PyTorch which is the inefficient part. So, this PR creates two fixed sized pinned buffer. LMK if that's clear. Thank you!

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I recommend mirroring #5301: when offload_optimizer.pin_memory is enabled, pin the final CPU FP32 master partition at construction—after clone().detach()—and explicitly transfer it to the accelerator before the low-precision copy. This is simpler and consistent with ZeRO-1/2 semantics, though it accepts model-scale pinned memory.

One correction: the linked initialization code pins fp32_partitioned_groups_flat[i].grad, not its .data. The flat FP32 master weight currently remains pageable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, @sfc-gh-truwase thanks for the review, I just redid the code to match #5301. Also thank you for the comment of the master weights are not pinned. this is also implemented in the current version. (also sorry for the mis-understanding of the code base where I thought the master was already pinned)Thank you!

…vice when copying back

Signed-off-by: pengdurice <pengduhit@gmail.com>
@delock

delock commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Hi @sfc-gh-truwase if you have no further comments I'll help merge this PR, thanks!

Comment thread deepspeed/runtime/zero/stage3.py Resolved
Comment thread deepspeed/runtime/zero/stage3.py Resolved
pengdurice and others added 2 commits October 30, 2026 20:32
Co-authored-by: Olatunji Ruwase <tunji.ruwase@snowflake.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
…ice), as deepspeedai#5301

Signed-off-by: pengdurice <pengduhit@gmail.com>
@pengdurice
pengdurice force-pushed the peng-fix-zero3-offload-pinned-copy-v2 branch from f57752e to 1e8e783 Compare October 30, 2026 20:32
@pengdurice
pengdurice added this pull request to the merge queue Oct 30, 2026
Merged via the queue into deepspeedai:master with commit c6291b7 Oct 30, 2026
15 checks passed
@pengdurice
pengdurice deleted the peng-fix-zero3-offload-pinned-copy-v2 branch October 30, 2026 22:14
pengdurice added a commit to pengdurice/DeepSpeed that referenced this pull request Nov 7, 2026
…PU Adam step

Rebuilt on master after deepspeedai#8840 was merged. Review changes: step_pieces is replaced by DeepSpeedCPUAdam.step(grad_scale=..., bf16_copy=...), so the Optimizer.step hooks run. The scale factor of a fused step is applied later to the gradients that the next window does not overwrite, and before every fp32-gradient read, so parameters and gradients stay bitwise equal to master when a parameter gets no gradient. grad_scale_supported() is false on RVV. The copy-back test skips on the CPU accelerator. New tests for fp16 overflow, pin_memory off and unused layers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: pengdurice <pengduhit@gmail.com>
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 13, 2026
# ZeRO-3 CPU offload: apply the clip factor and write the bf16 copy
inside the CPU Adam pass

**Builds on:** deepspeedai#8840 (merged).
**Part of:** deepspeedai#8672 (Q4 2026 roadmap), "Enable training of large scale
models".

## Summary

With the optimizer offloaded to the CPU, ZeRO-3's step on master makes
three passes over every CPU sub-group:

1. multiply every fp32 gradient by the clip and loss-scale factor in
place (`grad.mul_`), even when the factor is 1;
2. run `DeepSpeedCPUAdam` (reads gradients, parameters and both moments;
writes parameters and both moments);
3. copy the fp32 master to the device and cast it there to bf16 (deepspeedai#8840):
twice the bytes of the bf16 result over
PCIe, into an fp32 device temporary the size of the sub-group (3.73 GiB
at the default `sub_group_size` of 1e9).

This PR folds 1 and 3 into 2. The CPU Adam kernel multiplies each
gradient by the factor as it loads it. With
`pin_memory` on and a bf16 device partition, it also writes the bf16
copy of each updated piece into one of two pinned
buffers, and the buffer is copied to the device while the next piece is
updated. Parameters after training, and
gradients read after `step()`, are bitwise equal to master.

## The change

| File | Lines | What |
|---|---|---|
| `csrc/includes/cpu_adam.h` | +74 -1 | `_grad_scale`, `_params_copy`,
`set_grad_scale`, `set_params_copy`, `params_copy_for`: the step
multiplies each loaded gradient by the factor and, when a copy buffer is
set, stores the updated parameter in bf16 there |
| `csrc/includes/sve.h` | +4 -1 | the SVE path takes the factor |
| `csrc/adam/cpu_adam_impl.cpp` | +131 | `ds_adam_step_scaled`,
`ds_adam_step_scaled_copy`, `ds_adam_copy_supported`,
`ds_adam_grad_scale_supported`, `ds_adam_block_numel` |
| `csrc/adam/cpu_adam.cpp` | +17 | bindings `adam_update_scaled`,
`adam_update_scaled_copy`, `adam_copy_supported`,
`adam_grad_scale_supported`, `adam_block_numel` |
| `deepspeed/ops/adam/cpu_adam.py` | +62 -4 | `step(closure=None,
grad_scale=1.0, bf16_copy=None)`: `bf16_copy=(piece_numel, before_piece,
after_piece)` updates each parameter piece by piece; `before_piece`
returns the bf16 buffer for the piece and `after_piece` starts its copy.
The piece size is rounded down to a multiple of the kernel's widest
vector block (128 floats with AVX512), so every element takes the vector
path. `copy_supported()`, `grad_scale_supported()` |
| `deepspeed/runtime/zero/stage3.py` | +143 -10 |
`_grad_scale_for_cpu_adam` passes the factor to CPU Adam instead of
`mul_` for CPU sub-groups; `_cpu_adam_step_and_copy_back` runs the
pieces into two pinned bf16 buffers of 2^26 elements, waits for the
previous copy out of a buffer before refilling it, and waits for the
last piece before returning (the next forward's all-gathers do not wait
for this stream); `_apply_deferred_grad_scale` (below) |
| `tests/unit/ops/adam/test_cpu_adam.py` | +106 | kernel tests below |
| `tests/unit/v1/zero/test_zero.py` | +218 | ZeRO-3 tests below;
`TestZero3OffloadPinnedCopyBack` turns off the fused copy-back |

**Gradients that are not overwritten.** On master the offloaded fp32
gradient buffer is not cleared between steps.
A parameter that gets no gradient in a window (a skipped branch, an
expert with no tokens) keeps its older gradient,
the step reads it again, and the in-place `mul_` multiplies it by every
step's factor. Because the fused step does not
write the scaled gradient back, each fused sub-group records its factor.
At the start of the next `step()` (before the
overflow check), the slices that the new window did not overwrite are
multiplied by it, which is the multiply master
did. Every function that reads or sets offloaded fp32 gradients
(`safe_get_full_grad`, `safe_get_local_grad`, the set
functions, `get_fp32_grad_partitions`,
`update_fp32_grad_for_param_vectorized`) applies a recorded factor
first. When
every parameter gets a gradient, this multiplies nothing.

**Where the fused path runs.** The clip factor is fused for CPU
sub-groups with float32 gradients and master weights,
with DeepSpeed's bf16 or fp16 (including the dynamic loss scale) and
`pin_memory` on or off. It is not used with a
torch GradScaler, ZenFlow, NVMe offload or Muon, or on the RVV build
(its kernel has no factor;
`grad_scale_supported()` is false). The bf16 copy also needs
`pin_memory` on, a bf16 device partition and a CPU Adam
build with a bf16 store (AVX512, NEON and the scalar loop; AVX2, SVE and
RVV keep the copy of deepspeedai#8840). SuperOffload
overrides `step()` and is not affected. No configuration key changes.

## Measured

Qwen2.5-32B, real weights, PG-19 rows of 8,192 tokens, 1 node x 8 H200,
ZeRO-3, all of the optimizer offloaded to the
CPU (`pin_memory` on), fp32 Adam states, bf16, activation checkpointing,
12 OpenMP threads per rank. Master and this PR
alternate in one job on the same node; each run is 2 warm-up and 6
measured steps, and the time is the mean of the 6.

| Run | Master | This PR | Change |
|---|---|---|---|
| 1 | 9.445 s per step | 9.077 s | −3.9% |
| 2 | 9.544 s | 9.213 s | −3.5% |
| 3, with `wall_clock_breakdown` | 9.910 s | 9.532 s | −3.8% |

- Losses: equal at step 1 (0.022649) in all six runs. From step 2 they
differ in the 4th to 6th digit, by as much as
the two master runs differ from each other (step 8: master 1.746211,
1.746275, 1.746414; this PR 1.746454,
  1.746391, 1.746197).
- `optimizer_step` timer (rank 0, run 3, mean of the measured steps):
4414 ms on master, 4281 ms with this PR. It varies
between steps from 4125 to 4686 ms on master and from 3737 to 4719 ms
with this PR.
- Peak device memory during a step: 34,658,109,952 bytes in all six
runs. In this configuration the fp32 device
  temporary of master's copy-back does not set the peak.
- Pinned host memory: the two bf16 buffers add 256 MiB per rank,
allocated at the first fused copy-back.

Earlier measurement, on the first version of this PR stacked on the
first version of deepspeedai#8840 (master 5f266e2, before
deepspeedai#8840 dropped its staging buffers): GLM-5.2, real weights, 65,536-token
rows, 1 node x 8 H200, first 8 layers, 20% of
the optimizer on the GPU: 15.95 s per step before, 14.61-14.67 s with
both halves fused; 8 nodes x 8 H200, all 78
layers: 147.16 s before, 143.61 s after.

## Tests

| Test | Checks |
|---|---|
| `test_cpu_adam_grad_scale_matches_scaling_in_place` |
`step(grad_scale=f)` gives bitwise the parameters and moments of
`grad.mul_(f)` then `step()` |
| `test_cpu_adam_bf16_copy_matches_step` | `step(bf16_copy=...)` with
pieces of 1,000 elements (not a multiple of the vector block) and
524,289-element tensors gives bitwise the result of one `step()`, and
the bf16 copies equal `param.to(torch.bfloat16)` |
| `test_cpu_adam_bf16_copy_runs_step_hooks` | `step(bf16_copy=...)` runs
the optimizer's step pre- and post-hooks, and a torch `StepLR` built on
it gives no "`lr_scheduler.step()` before `optimizer.step()`" warning |
| `TestZero3CpuAdamGradScale` (2 ranks; clip 1e-3 and 1e6; ratio 1.0 and
0.5; `pin_memory` on and off) | ZeRO-3 with CPU offload: parameters
after 3 steps, and gradients read with `safe_get_full_grad` after them,
bitwise equal to the in-place path; the fused path ran; factor below 1
when clipping, 1 otherwise |
| `TestZero3CpuAdamCopyBack` (2 ranks; ratio 1.0 and 0.5; skipped on the
CPU accelerator) | pieces of 1,000 elements reuse both buffers many
times per step; parameters bitwise equal to the separate passes; the
fused copy-back ran |
| `TestZero3CpuAdamUnusedLayer` (2 ranks; `pin_memory` on and off) | a
layer used only in step 0: every sub-group takes the fused path, and
parameters and gradients after 3 steps are bitwise equal to the in-place
path |
| `TestZero3CpuAdamFp16Overflow` (2 ranks) | fp16 with a dynamic loss
scale and an inf loss in step 0: the step is skipped and the loss scale
lowered on both paths, and the parameters after the later fused steps
are bitwise equal |

`TestZero3CpuAdamUnusedLayer` fails if the recorded factor is dropped
without the multiply: the unused layer's
parameters then differ by up to 9.766e-04, and the gradients read after
the last step by up to 5.429e-01 (2 H200;
4.961e-01 on the CPU accelerator with 2 ranks); the other layers'
parameters stay bitwise equal.

`TestZero3OffloadPinnedCopyBack` (from deepspeedai#8840) counts the calls of
deepspeedai#8840's copy. It now turns off the fused copy-back,
because on AVX512 every bf16 CPU sub-group would take it; the fused
copy-back is tested by `TestZero3CpuAdamCopyBack`.

Hardware: 1 node of 8 NVIDIA H200 (driver 580.126.09), Intel Xeon
Platinum 8488C (AVX512), torch 2.8.0+cu126,
pytest 9.1.1:

```
pytest unit/ops/adam/test_cpu_adam.py                                   # 138 passed, 5 skipped
pytest unit/v1/zero/test_zero.py                                        # 120 passed, 1 skipped, 3 failed (*)
pytest unit/v1/zero/test_zero.py::TestZero3OffloadPinnedCopyBack \
       unit/v1/zero/test_zero.py::TestZero3CpuAdam*  (4 classes)        # 15 passed, after the fix (*)
pytest unit/v1/zero/test_invalid_grad_norm.py                           # 18 passed
pytest unit/runtime/zero/test_zero_offloadpp.py unit/v1/pin_memory/     # 53 passed, 1 skipped
pytest unit/runtime/zenflow/test_zf.py                                  # 95 passed
```

(*) The 3 failures were in the tests: `TestZero3OffloadPinnedCopyBack`
[1.0] and [0.5] (above), and
`TestZero3CpuAdamFp16Overflow`, which expected the first overflow to
lower the loss scale although the default
`hysteresis` is 2; it now sets `hysteresis: 1`. Only test files changed
after that run.

After merging master `af5198984` into the branch (it brings deepspeedai#8974, which
changes `cpu_adam.py`), on the same hardware:
`test_cpu_adam.py`, `test_invalid_grad_norm.py` and the five ZeRO-3
classes above: 177 passed, 5 skipped.

The 5 skips in `test_cpu_adam.py` are the file's own fp16 cases. CPU
accelerator (`DS_ACCELERATOR=cpu`, 2 ranks,
gloo): `test_cpu_adam.py`, `test_invalid_grad_norm.py` and the five
ZeRO-3 classes: 160 passed, 16 skipped (fp16 and
copies to a device). `pre-commit run --files` passes on every changed
file.

## Compatibility

| Cell | Validated |
|---|---|
| ZeRO-3, CPU optimizer offload, bf16, `pin_memory` on and off, all of
the optimizer on the CPU (ratio 1.0) and half (0.5) | yes (tests;
Qwen2.5-32B on 1 node) |
| fp16 with a dynamic loss scale, including an overflow step | yes
(test) |
| Parameters without a gradient in a step | yes (test) |
| AVX512 build (Intel Xeon Platinum 8488C, the H200 nodes) | yes |
| NEON / SVE builds, AVX2-only CPUs | no (AVX2 and SVE have no bf16
store in this kernel, so `copy_supported()` is false and the copy keeps
the path of deepspeedai#8840; the clip factor is fused on every build except RVV) |
| RVV | no; `grad_scale_supported()` is false there, so both halves keep
the master path |
| GradScaler, NVMe offload, ZenFlow, Muon, SuperOffload | path unchanged
by design |
| ZeRO-1 / ZeRO-2 | not touched |

## Related pull requests

- deepspeedai#8719 (ReFlow) also fuses the gradient scaling into its CPU kernels
and writes bf16 parameters without a separate
pass, in separate kernels with asynchronous scheduling. This PR puts the
two synchronous parts into the default
`DeepSpeedCPUAdam` path and does not schedule anything asynchronously,
so it does not depend on deepspeedai#8719 or replace it.
- deepspeedai#8981 zeroes the gradients of parameters that got none in a window.
All of its writes to the offloaded fp32 gradients
go through `_offload_grad_partition_at_boundary`, which records them
here, so with both PRs every slice is overwritten
in each window and the deferred multiply does no work. The two PRs edit
neighbouring lines in `stage3.py`.
- deepspeedai#8970 changes `unscale_and_clip_grads` for bf16/fp16 gradients only;
the fused path is fp32 only. Textual conflict of
two lines (this PR moves the factor computation into
`_combined_grad_scale`).

## AI assistance

This change, its tests and this description were prepared with AI
assistance (Claude).

---------

Signed-off-by: pengdurice <pengduhit@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 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.

4 participants