Repository navigation
Description
I have observed about numel * 28 bytes cpu memory requirements for doing z2+optim cpu offload.
Here is the mapping out of current cpu memory allocations when offload_optimizer.device: cpu is used with zero: stage 2
Ideally it should be numel * 16 bytes (4 bytes per master weights, grad, 2x optim states).
The total of cpu memory allocation happen in 2 parts deepspeed.initialize + first step call - I'm going to break it down into each per param allocation.
part 1: deepspeed.initialize
- master weights 4 bytes - kosher
- intermediary H2D copy buffer (for speed) - 2 bytes (half precision) - seems we can't avoid this one
- related to above - 2 byte pinned memory overhead - fixed it here zero stage 1-2: don't pin memory if not configured #7689
- initialize_optimizer_states - creates 4 bytes for grads - kosher
total 10 bytes per param (after the fix in item 3)
we confirmed empirically that's the case.
part 2: first step
- 8 bytes for optim states - kosher
- unscale_and_clip_grads - adds 4 bytes - but we think it's peak cpu memory - because grad.data.mul_(1. / combined_scale) shouldn't allocate more memory other than for a temp buffer in pytorch - it doesn't appear to be a temp buffer not released by linux cpu memory - because the next allocation doesn't re-use it and allocates its own full sized tensor
- self.ds_opt_adam.adam_update for some reason allocates 4 bytes more
total: 16 bytes per param
grand total: 26 bytes
plus additional ~2 bytes I still don't have an account for
Details:
- this leaks 4 bytes per param (inside the first
stepcall)
for grad in grad_groups_flat:
# checking cpu memory before and after the next call shows an additional fp32
# allocation on the first call of unscale_and_clip_grads, on subsequent calls it's stable
grad.data.mul_(1. / combined_scale) #
I even tried to move it to gpu do the mul there and move back to cpu I still get the leak.
rank = torch.distributed.get_rank()
device = torch.device(f"cuda:{rank}")
t = 1. / combined_scale
see_memory_usage(f"before", force=True)
grad = grad.to(device)
t = t.to(device)
see_memory_usage(f"after to cuda", force=True)
grad.mul_(t)
see_memory_usage(f"after mul_", force=True)
grad = grad.cpu()
see_memory_usage(f"after to cpu", force=True)
and the memory is (the first row is cuda, the second is cpu):
before
MA 9.36 GB Max_MA 9.36 GB CA 12.05 GB Max_CA 12 GB
CPU Virtual Memory: used = 135.32 GB, percent = 6.8%
after to cuda
MA 21.36 GB Max_MA 21.36 GB CA 24.05 GB Max_CA 24 GB
CPU Virtual Memory: used = 135.33 GB, percent = 6.8%
after mul_
MA 21.36 GB Max_MA 21.36 GB CA 24.05 GB Max_CA 24 GB
CPU Virtual Memory: used = 135.33 GB, percent = 6.8%
after to cpu
MA 9.36 GB Max_MA 21.36 GB CA 24.05 GB Max_CA 24 GB
CPU Virtual Memory: used = 147.38 GB, percent = 7.4%
so you can see 12GB lost (3 layers out of 48)
the leak happens only in the first step
and it's not reclaimable - the next allocation doesn't re-use it
- cpu adam has some weird issue of allocating 4 bytes per param the first time
self.ds_opt_adam.adam_updateis called - even though if one looks at the cpp code there is no 4 bytes allocation there and if it's a temp buffer - it's not it sticks through - validated with getting cpu-oom with Qwen3-Next-80B - if I disable the update the cpu oom goes away
cc: @tjruwase - added the summary above, but I have to move on - perhaps someone else will get a chance to solve at least one of the two 4 bytes per param leaks. At 80B param model - that's 640GB of CPU memory wasted.
Activity
[-]Tracking excessive memory usage in z2 cpu offload[/-][+]Tracking excessive cpu memory usage in z2 cpu offload[/+]xylian86 commentedon Nov 29, 2025
@stas00
This is the buffer used to transfer FP32 parameters (CPU) to BF16/FP16 parameters (GPU) by casting on the CPU and then copying. DeepSpeed explicitly allocate this buffer to avoid fragmentation.
Although we can’t get rid of it entirely, it might be possible to tile it: allocate a fixed-size buffer (smaller) and then cast + transfer parameters sequentially through that buffer.
For Part2:
I did not observe the
unscale_and_clip_grads - adds 4 bytesorself.ds_opt_adam.adam_update for some reason allocates 4 bytes moreissues you mentioned on my side.I tested with Llama 8B, and after the first iteration the CPU memory usage is about 155 GB (~20×).
Tested with
torch==2.10.0.dev20251124+cu128and the latest DeepSpeed version.fix(zero): use float scalar in unscale_and_clip_grads to avoid CPU al…
fix(cpu-adam): skip .contiguous() copy for already-contiguous tensors (…
fix(cpu-adam): call malloc_trim after first step to release CPU alloc…
test: add regression tests for CPU offload memory leaks (deepspeedai#…
fix(zero-offload): reduce CPU memory leaks in ZeRO-2 optimizer offload (
fix(zero-offload): mitigate CPU RSS waste on ZeRO-2 optimizer offload
fix(zero-offload): mitigate CPU RSS waste on ZeRO-2 optimizer offload
delock commentedon Jul 14, 2026
Could not reproduce the two 4 bytes/param leaks on torch 2.12.1 + DeepSpeed master tip
I tried to reproduce both claimed leaks across three test scales — a synthetic single-tensor test, a 6-layer MLP (403M params), and a real Qwen2.5-1.5B-Instruct model — on both DP=1 and DP=2. RSS was measured via
/proc/self/statmat each phase.Environment
0.19.3+429e2ad2), post-PR zero stage 1-2: don't pin memory if not configured #7689offload_optimizer: cpu,pin_memory: falseBug #1 —
unscale_and_clip_gradsleak: not reproducedTested
grad.data.mul_(1. / combined_scale)with three variants on a 100M-element fp32 CPU tensor:mul_operand typeclip_grad > 0path)unscale_and_clipcode pathNo measurable allocation beyond noise (< 0.01 B/param) in any variant.
Bug #2 —
adam_updateleak: not reproducedopt.step()(lazy Adam state init +adam_update)opt.step()adam_update(states pre-allocated)The first-step delta is exactly 8 B/param (2 × fp32 Adam states), with no extra allocation from the C++
adam_updatecall.End-to-end results
DP=2 per-rank results are symmetric (19.84 vs 19.85 B/param) with zero growth on the 2nd step.
Semantic byte breakdown
The measured ~19 B/param decomposes as follows:
ds.initializestage_1_and_2.py:484ds.initializestage_1_and_2.py:491ds.initializestage_1_and_2.py:812exp_avg)step()cpu_adam.py:151exp_avg_sq)step()cpu_adam.py:154accumulated_grads_in_cpustage_1_and_2.py:1396temp_grad_buffer_for_cpu_offloadds.initializestage_1_and_2.py:575The two variable components are sized to
param.numel()per parameter (grad accum) andlargest_param_numel(temp buffer), so their per-param contribution varies with model architecture. They are legitimate implementation overhead, not leaks — they do not grow on subsequent steps.Conclusion
The total CPU RSS is consistently ~19 B/param across all configurations. The theoretical floor is 18 (4 fp32 weights + 4 fp32 grads + 4 momentum + 4 variance + 2 bf16 copy-back buffer), and the ~1 B/param excess is fully accounted for by grad accumulation buffers. No trace of the two 4 B/param leaks described above.
The ~28 B/param originally reported may be specific to an older PyTorch version's CPU allocator behavior or a different measurement methodology (e.g., multi-process shared-library RSS inflation). Happy to run additional tests if there's a specific configuration that triggers the issue.
stas00 commentedon Jul 14, 2026
That's good to hear, thank you both for validating the latest versions not seem to have the issue anymore. I don't currently have a way to re-test it easily.
I should have done a better job documenting the specific env I measured the problem in, but I can probably reverse engineer it to whatever were the stable versions when I made this issue.
stas00 commentedon Jul 14, 2026
I see this now closed PR #8132 was also trying to do some fixing.
alanhuangyoo commentedon Sep 1, 2026
Measured your part-2 item 2 in isolation, since
grad.data.mul_(1. / combined_scale)being anin-place op made it the odd one out. It does not appear to be the source — ruling it out so the
search can narrow.
200M-element fp32 tensor (800 MB), CPU RSS around the call only:
+1.5 MB is noise at this size; a second fp32 copy would show as +800 MB. So the multiply itself
allocates nothing in either form the code can reach.
The third line is the interesting one.
combined_scaleis built fromtotal_norm:so it is a tensor, and on whatever device
total_normcame back on. If that is the acceleratorwhile the offloaded grads are on CPU, this line raises rather than allocating — which it does not
in practice, so
total_normmust already be CPU-side on the offload path. Worth confirming thatholds for every path into
unscale_and_clip_gradsrather than by construction, but either way itis not a silent allocation.
That leaves your item 3 (
ds_opt_adam.adam_update) as the remaining unexplained 4 bytes. Happyto measure that one the same way if it would help — I have GPUs and can run the offload path
end to end.