Fix GPU memory leak in ModelPruning when reused across multiple fit() calls
While using ModelPruning with lottery ticket hypothesis in an iterative training loop (multiple trainer.fit() calls with the same callback), I noticed GPU memory growing until OOM.
Root cause
The setup() method deep-copies the original modules to preserve weights for lottery ticket hypothesis reset:
self._original_layers.setdefault(id_, _LayerRef(data=deepcopy(module), names=[]))
deepcopy(module) copies all parameters on the GPU. When setup() is called again on the next trainer.fit(), the old dict is overwritten but the GPU tensors may linger in CUDA memory until the Python GC eventually runs — and by then, it's too late.
Fix
Two changes:
-
Move copies to CPU in
setup()— the original parameter data is only needed for_copy_param(), which already doessrc.data.to(dst.device)when restoring weights. Keeping them on CPU is safe and avoids GPU memory pressure. -
Clean up in
on_train_end— setself._original_layers = Noneto eagerly release references, giving the GC a clear signal.
Before/After
Before: GPU memory accumulates linearly with number of fit() calls when lottery ticket hypothesis is enabled.
After: Original layer copies live on CPU, and are explicitly released after training ends.
Closes #8542
Hi @ethanwharris @tchaton @justusschock, just checking whether this PR is on the right track. CI is green and I’m happy to adjust the approach if you prefer a different fix.
Closing this out since there has been no maintainer response in over a month. The patch is still valid if there is interest later; happy to reopen or rebase it then.