Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/2.5] ModuleTracker: Add explicit garbage collection #1661

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions torch/utils/module_tracker.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# mypy: allow-untyped-defs
import logging
import weakref
from typing import Set
from typing import List, Set, TYPE_CHECKING

import torch
from torch.autograd.graph import register_multi_grad_hook
Expand All @@ -12,6 +12,10 @@
from torch.utils._pytree import tree_flatten


if TYPE_CHECKING:
from torch.utils.hooks import RemovableHandle


logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -61,6 +65,7 @@ def __init__(self) -> None:
self._known_modules: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
self._seen_modules: weakref.WeakSet = weakref.WeakSet()
self._has_callback = False
self._hooks: List[RemovableHandle] = []

def _maybe_set_engine_callback(self):
# This assumes no concurrent calls to backward
Expand Down Expand Up @@ -126,7 +131,9 @@ def _fw_pre_hook(self, mod, input):
args, _ = tree_flatten(input)
tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
if tensors:
register_multi_grad_hook(tensors, self._get_pop_fn(name, True))
self._hooks.append(
register_multi_grad_hook(tensors, self._get_pop_fn(name, True))
)

def _fw_post_hook(self, mod, input, output):
name = self._get_mod_name(mod)
Expand All @@ -135,7 +142,9 @@ def _fw_post_hook(self, mod, input, output):
args, _ = tree_flatten(output)
tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
if tensors:
register_multi_grad_hook(tensors, self._get_append_fn(name, True))
self._hooks.append(
register_multi_grad_hook(tensors, self._get_append_fn(name, True))
)

def __enter__(self):
self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook)
Expand All @@ -145,3 +154,6 @@ def __enter__(self):
def __exit__(self, *args):
self._fw_pre_handle.remove()
self._fw_post_handle.remove()
for hook in self._hooks:
hook.remove()
self._hooks.clear()