Skip to content

Tracking excessive cpu memory usage in z2 cpu offload #7693

Open

Description

@stas00

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

  1. master weights 4 bytes - kosher
  2. intermediary H2D copy buffer (for speed) - 2 bytes (half precision) - seems we can't avoid this one
  3. related to above - 2 byte pinned memory overhead - fixed it here zero stage 1-2: don't pin memory if not configured #7689
  4. 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

  1. 8 bytes for optim states - kosher
  2. 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
  3. 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 step call)
        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_update is 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

  1. changed the title [-]Tracking excessive memory usage in z2 cpu offload[/-] [+]Tracking excessive cpu memory usage in z2 cpu offload[/+] on Nov 14, 2025
  2. xylian86 commented on Nov 29, 2025

    @xylian86
    Collaborator

    @stas00

    intermediary H2D copy buffer (for speed) - 2 bytes (half precision) - seems we can't avoid this one

    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 bytes or self.ds_opt_adam.adam_update for some reason allocates 4 bytes more issues you mentioned on my side.

    I tested with Llama 8B, and after the first iteration the CPU memory usage is about 155 GB (~20×).

    # ds_config
      "zero_optimization": {
        "stage": 2,
        "overlap_comm": true,
        "offload_optimizer": {
          "device": "cpu",
          "pin_memory": true
        }
    

    Tested with torch==2.10.0.dev20251124+cu128 and the latest DeepSpeed version.

  3. delock commented on Jul 14, 2026

    @delock
    Collaborator

    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/statm at each phase.

    Environment

    • GPU: 1–2 × NVIDIA RTX 5090
    • CPU RAM: 90–180 GB
    • torch: 2.12.1+cu130
    • DeepSpeed: master tip (0.19.3+429e2ad2), post-PR zero stage 1-2: don't pin memory if not configured #7689
    • Model: Qwen2.5-1.5B-Instruct (1.54B params), bf16, AdamW, ZeRO-2 + offload_optimizer: cpu, pin_memory: false

    Bug #1 — unscale_and_clip_grads leak: not reproduced

    Tested grad.data.mul_(1. / combined_scale) with three variants on a 100M-element fp32 CPU tensor:

    mul_ operand type 1st call delta 2nd call delta
    Python float (scalar path) +0.00 B/param +0.00 B/param
    0-dim CPU tensor (clip_grad > 0 path) +0.00 B/param +0.00 B/param
    Exact unscale_and_clip code path +0.01 B/param +0.00 B/param

    No measurable allocation beyond noise (< 0.01 B/param) in any variant.

    Bug #2 — adam_update leak: not reproduced

    Operation Delta
    1st opt.step() (lazy Adam state init + adam_update) +8.00 B/param
    2nd opt.step() +0.00 B/param
    Direct C++ adam_update (states pre-allocated) +0.01 B/param

    The first-step delta is exactly 8 B/param (2 × fp32 Adam states), with no extra allocation from the C++ adam_update call.

    End-to-end results

    Test Model DP Params/rank Measured B/param
    Synthetic single 100M tensor 1 100M 18.0
    Simple MLP 6-layer, dim=8192 1 403M 19.7
    Qwen2.5-1.5B real HF model 1 1.54B 18.9
    Qwen2.5-1.5B real HF model 2 772M 19.8 (rank 0) / 19.9 (rank 1)

    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:

    Bytes Buffer dtype Allocated in Code
    4 fp32 master weights fp32 ds.initialize stage_1_and_2.py:484
    2 bf16 copy-back buffer bf16 ds.initialize stage_1_and_2.py:491
    4 fp32 gradients fp32 ds.initialize stage_1_and_2.py:812
    4 Adam momentum (exp_avg) fp32 1st step() cpu_adam.py:151
    4 Adam variance (exp_avg_sq) fp32 1st step() cpu_adam.py:154
    18 subtotal (always present)
    ~0.5–1.5 accumulated_grads_in_cpu bf16 1st backward stage_1_and_2.py:1396
    ~0.1–0.3 temp_grad_buffer_for_cpu_offload bf16 ds.initialize stage_1_and_2.py:575
    ~19 measured total

    The two variable components are sized to param.numel() per parameter (grad accum) and largest_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.

  4. stas00 commented on Jul 14, 2026

    @stas00
    CollaboratorAuthor

    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.

  5. stas00 commented on Jul 14, 2026

    @stas00
    CollaboratorAuthor

    I see this now closed PR #8132 was also trying to do some fixing.

  6. alanhuangyoo commented on Sep 1, 2026

    @alanhuangyoo
    Contributor

    Measured your part-2 item 2 in isolation, since grad.data.mul_(1. / combined_scale) being an
    in-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:

    scale = python float            RSS  1289.4 -> 1290.9 MB    +1.5 MB
    scale = CPU 0-dim tensor        RSS  1291.0 -> 1292.5 MB    +1.5 MB
    scale = CUDA 0-dim tensor       RuntimeError: Expected all tensors to be on the same device
    

    +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_scale is built from total_norm:

    clip = ((total_norm / self.loss_scale) + 1e-6) / self.clip_grad
    clip = torch.clamp(clip, min=1.0)
    combined_scale = clip * self.loss_scale

    so it is a tensor, and on whatever device total_norm came back on. If that is the accelerator
    while the offloaded grads are on CPU, this line raises rather than allocating — which it does not
    in practice, so total_norm must already be CPU-side on the offload path. Worth confirming that
    holds for every path into unscale_and_clip_grads rather than by construction, but either way it
    is not a silent allocation.

    That leaves your item 3 (ds_opt_adam.adam_update) as the remaining unexplained 4 bytes. Happy
    to measure that one the same way if it would help — I have GPUs and can run the offload path
    end to end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions