Fix memory leak in engine and zero optimizer #9034
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
delock
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: afterdestroy(),delandgc.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_Optimizerleak 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 andfirst_dataloader_checkstay 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 neverpops 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 thatwraps the same model.
3. Class-level
functools.lru_cacheonPartitionedParameterCoordinator.__params_to_release: the cache keys onselfand is never cleared, so it keeps every coordinator and its modules alive. The cache is now created perinstance in
__init__, with the same key and the same never-invalidated behavior.4.
p._z3_optimizer(stage3.py): cleared indestroy()when it points at this optimizer.5.
lp._zero_optimizer(stage_1_and_2.py, ZeRO-1/2 with CPU offload): deleted indestroy()when it points atthis optimizer.
6. Second teardown at garbage collection (
engine.py): once 1-5 make a destroyed engine collectable,DeepSpeedEngine.__del__would rundestroy()again. If a newer engine already wraps the same model, that secondteardown resets the newer engine's
_hp_mapping(ZeRO-1/2 andBF16_Optimizer:safe_get_full_fp32_paramthenreturns zeros) and its
FWD_MODULE_STACKentry.destroy()now marks the engine, and__del__skips engines thatwere destroyed explicitly. Repeated explicit
destroy()calls still run in full, astest_destroy_unpin.pyrequires.
7.
lp._hp_grad(bf16_optimizer.py):BF16_Optimizerpoints every parameter at a view of its flat fp32gradient 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 andwith CPU offload, plus
BF16_Optimizer(ZeRO-1, bf16,grad_accum_dtype: fp32). Each case checks, while the model iskept, that the destroyed engine and optimizer are collected and that no parameter still holds the
BF16_Optimizergradient 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
Memory per create/destroy cycle (2 ranks, rank 0,
Sequentialof 16Linear(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.