pytorch-lightning icon indicating copy to clipboard operation
pytorch-lightning copied to clipboard

Fix GPU memory leak in ModelPruning when reused across multiple fit() calls

Open goingforstudying-ctrl opened this issue 5 months ago • 1 comments

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:

  1. Move copies to CPU in setup() — the original parameter data is only needed for _copy_param(), which already does src.data.to(dst.device) when restoring weights. Keeping them on CPU is safe and avoids GPU memory pressure.

  2. Clean up in on_train_end — set self._original_layers = None to 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

goingforstudying-ctrl avatar Jun 07 '26 05:06 goingforstudying-ctrl

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.

goingforstudying-ctrl avatar Jun 23 '26 14:06 goingforstudying-ctrl

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.

goingforstudying-ctrl avatar Aug 02 '26 08:08 goingforstudying-ctrl