← Back to Pull requests

Fix memory leak in engine and zero optimizer #9034

Closed
unknown closed this pull request without merging on Nov 09, 2026 14:28 UTC
View on GitHub
unknown unknown commented on Nov 08, 2026 05:43 UTC
Author

Fixes #7204 (ZeRO-3 + CPU offload, host RAM grows every time the engine is destroyed and re-initialized).

Problem


engine.destroy() does not release the engine: after destroy(), del and gc.collect(), the engine and its optimizer stay reachable, so every re-initialization causes memory leak. Each create → train → destroy() → del → gc.collect() cycle leaks the whole engine and optimizer: about 2 GiB of GPU memory per cycle on the repro model below, or about 4 GiB of host RAM per cycle with CPU offload (the #7204 setup).
ZeRO-3 leaks even when the caller drops the model. ZeRO-0/1/2 and BF16_Optimizer leak when the caller keeps the model,
as HF Trainer does. This PR removes the references that keep a destroyed engine alive, so its memory is freed while the caller still holds the model.

Root cause and fixes

A referrer-chain search from the destroyed engine back to GC roots found references 1-5. Items 6 and 7 came from the
re-wrap and other-optimizer checks under Validation.

1. Engine forward hooks (engine.py): the forward pre/post hooks and first_dataloader_check stay registered on the model. destroy() now removes them, after _deactivate_deepcompile(), which re-registers the forward hooks.
2. FWD_MODULE_STACK (parameter_offload.py): ZeRO-3 pushes the top module onto this process-wide list and never
pops it. DeepSpeedZeRoOffload.destroy() now removes its entry, at most once per instance
(_has_fwd_stack_entry), so destroying a replaced engine a second time cannot remove the entry of a newer engine that
wraps the same model.
3. Class-level functools.lru_cache on PartitionedParameterCoordinator.__params_to_release: the cache keys on
self and is never cleared, so it keeps every coordinator and its modules alive. The cache is now created per
instance in __init__, with the same key and the same never-invalidated behavior.
4. p._z3_optimizer (stage3.py): cleared in destroy() when it points at this optimizer.
5. lp._zero_optimizer (stage_1_and_2.py, ZeRO-1/2 with CPU offload): deleted in destroy() when it points at
this optimizer.
6. Second teardown at garbage collection (engine.py): once 1-5 make a destroyed engine collectable,
DeepSpeedEngine.__del__ would run destroy() again. If a newer engine already wraps the same model, that second
teardown resets the newer engine's _hp_mapping (ZeRO-1/2 and BF16_Optimizer: safe_get_full_fp32_param then
returns zeros) and its FWD_MODULE_STACK entry. destroy() now marks the engine, and __del__ skips engines that
were destroyed explicitly. Repeated explicit destroy() calls still run in full, as test_destroy_unpin.py
requires.
7. lp._hp_grad (bf16_optimizer.py): BF16_Optimizer points every parameter at a view of its flat fp32
gradient buffer, so a kept model pins the whole buffer (2x the bf16 model size). destroy() now clears it.

Test

tests/unit/v1/zero/test_zero.py::TestDestroyReleasesEngine, world_size = 1, 7 cases: ZeRO-1/2/3, each without and
with CPU offload, plus BF16_Optimizer (ZeRO-1, bf16, grad_accum_dtype: fp32). Each case checks, while the model is
kept, that the destroyed engine and optimizer are collected and that no parameter still holds the BF16_Optimizer
gradient buffer; that collecting a destroyed engine after a new engine wraps the model leaves the new engine's fp32
parameters unchanged; and that the model is collected once the last engine is destroyed.

Validation


cd tests && CUDA_VISIBLE_DEVICES=0 python -m pytest --forked unit/v1/zero/test_zero.py::TestDestroyReleasesEngine

Memory per create/destroy cycle (2 ranks, rank 0, Sequential of 16 Linear(4096, 4096), bf16, torch AdamW, 4 cycles;
growth = (cycle 4 - cycle 1) / 3; "kept" = the caller keeps every model, as HF Trainer does):

| Scenario | Before | After |
|---|---|---|
| ZeRO-3, model dropped | +2048.6 MiB GPU | 0 |
| ZeRO-3 + CPU offload, model dropped (#7204) | +4097.2 MiB host RSS | +0.4 MiB RSS |
| ZeRO-3, model kept | +2048.6 MiB GPU | +256.2 MiB (the kept bf16 partition) |
| ZeRO-3 + zero.Init, model kept | +2048.6 MiB GPU | +256.2 MiB |
| ZeRO-3 + CPU offload, model kept | +4097.3 MiB RSS | +512.9 MiB RSS (the kept pinned partition, rounded up to a power of two by torch's host allocator) |
| ZeRO-2, model kept | +2048.5 MiB GPU | +512.1 MiB (the kept bf16 model) |
| ZeRO-2 + CPU offload, model kept | +544.1 MiB GPU, +3616.6 MiB RSS | +512.1 MiB GPU, RSS flat |
| ZeRO-1, model kept | +2048.5 MiB GPU | +512.1 MiB |
| ZeRO-0 (FP16_UnfusedOptimizer, bf16), model kept | +3584.9 MiB GPU | +512.1 MiB |
| FP16_Optimizer (fused Adam, fp16), model kept | +3584.9 MiB GPU | +512.1 MiB |
| BF16_Optimizer, model kept | +3072.8 MiB GPU | +512.1 MiB |
| ZeRO-2, model dropped (control) | 0 | 0 |

After the fix no destroyed engine or optimizer stays alive in any scenario. ZeRO-1/2/3 with fp32 gradient accumulation
also keep only the model. The memory numbers were measured before the last commit, which changes only a repeated
destroy().

AI assistance

This change was developed with AI assistance (GitHub Copilot CLI). I reviewed every changed line and ran the tests.

Diff: 650 lines (+487 / -163) across 8 files Reviewer: delock Review duration: 1965m
All Vouch review confidence checks passed
Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
0.52
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
0.17
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
56%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.388
Shallow Review Depth shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #9034"
general weight: 0.35
Reviewers
Assignees
Unassigned
Labels
risk: low confidence: 56.8% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 52% (MEDIUM) · Higher = larger blast radius
52%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 56.8% · Lower = rushed or shallow review
56.8%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 22.5% · Safe to merge
22.5%