|
| 1 | +# mypy: allow-untyped-defs |
| 2 | +import warnings |
| 3 | +import weakref |
| 4 | +from typing import Callable, Optional, Set |
| 5 | + |
| 6 | +import torch |
| 7 | +from torch.autograd.graph import register_multi_grad_hook |
| 8 | +from torch.nn.modules.module import ( |
| 9 | + register_module_forward_hook, |
| 10 | + register_module_forward_pre_hook, |
| 11 | +) |
| 12 | +from torch.utils._pytree import tree_flatten |
| 13 | + |
| 14 | + |
| 15 | +__all__ = ["ModTracker"] |
| 16 | + |
| 17 | + |
| 18 | +class ModTracker: |
| 19 | + """ |
| 20 | + ``ModTracker`` is a context manager that tracks the nn.Module hierarchy during execution |
| 21 | + so that other system can query which Module is currently being executed (or its backward is being |
| 22 | + executed). |
| 23 | +
|
| 24 | + You can access the ``parents`` attribute on this context manager to get the set of all the |
| 25 | + Modules currently being executed via their fqn (fully qualified name, also used as the key within |
| 26 | + the state_dict). |
| 27 | + You can access the ``is_bw`` attribute to know if you are currently running in backward or not. |
| 28 | +
|
| 29 | + Note that ``parents`` is never empty and always contains the "Global" key. The ``is_bw`` flag |
| 30 | + will remain ``True`` after the forward until another Module is executed. If you need it to be |
| 31 | + more accurate, please submit an issue requesting this. Adding a map from fqn to the module instance |
| 32 | + is possible but not done yet, please submit an issue requesting this if you need it. |
| 33 | +
|
| 34 | + Example usage |
| 35 | +
|
| 36 | + .. code-block:: python |
| 37 | +
|
| 38 | + mod = torch.nn.Linear(2, 2) |
| 39 | +
|
| 40 | + with ModTracker() as tracker: |
| 41 | + # Access anything during the forward pass |
| 42 | + def my_linear(m1, m2, bias): |
| 43 | + print(f"Current modules: {tracker.parents}") |
| 44 | + return torch.mm(m1, m2.t()) + bias |
| 45 | + torch.nn.functional.linear = my_linear |
| 46 | +
|
| 47 | + mod(torch.rand(2, 2)) |
| 48 | +
|
| 49 | + """ |
| 50 | + |
| 51 | + parents: Set[str] |
| 52 | + """ |
| 53 | + A Set containing the fqn for each module currently running their forward |
| 54 | + """ |
| 55 | + |
| 56 | + def __init__(self): |
| 57 | + self.parents = {"Global"} |
| 58 | + self._known_modules: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() |
| 59 | + self._seen_modules: weakref.WeakSet = weakref.WeakSet() |
| 60 | + self._has_callback = False |
| 61 | + self._user_pre_fw_hook = None |
| 62 | + self._user_post_fw_hook = None |
| 63 | + self._user_pre_bw_hook = None |
| 64 | + self._user_post_bw_hook = None |
| 65 | + |
| 66 | + def _maybe_set_engine_callback(self): |
| 67 | + # This assumes no concurrent calls to backward |
| 68 | + if self._has_callback: |
| 69 | + return |
| 70 | + |
| 71 | + def callback(): |
| 72 | + self.parents = {"Global"} |
| 73 | + self._has_callback = False |
| 74 | + |
| 75 | + torch.autograd.Variable._execution_engine.queue_callback(callback) |
| 76 | + self._has_callback = True |
| 77 | + |
| 78 | + @property |
| 79 | + def is_bw(self): |
| 80 | + """ |
| 81 | + A boolean marking if this is currently running during the backward pass or not |
| 82 | + """ |
| 83 | + return torch._C._current_graph_task_id() != -1 |
| 84 | + |
| 85 | + def get_known_fqn(self, mod): |
| 86 | + """ |
| 87 | + Return the fqn for the given module if it is known to the ``ModTracker``, otherwise ``None``. |
| 88 | + """ |
| 89 | + return self._known_modules.get(mod, None) |
| 90 | + |
| 91 | + def register_user_hooks( |
| 92 | + self, |
| 93 | + pre_fw_hook: Optional[Callable] = None, |
| 94 | + post_fw_hook: Optional[Callable] = None, |
| 95 | + pre_bw_hook: Optional[Callable] = None, |
| 96 | + post_bw_hook: Optional[Callable] = None, |
| 97 | + ): |
| 98 | + """ |
| 99 | + Registers user-specified hooks to be called before/after the forward/backward pass for each |
| 100 | + module tracked by the ``ModTracker``. One or more can be ``None``. |
| 101 | + Args: |
| 102 | + pre_fw_hook (Callable, optional): A hook to be called before the forward pass for the |
| 103 | + module. It should have the following signature: |
| 104 | + pre_fw_hook (module, input) -> None |
| 105 | + post_fw_hook (Callable, optional): A hook to be called after the forward pass for the |
| 106 | + module. It should have the following signature: |
| 107 | + post_fw_hook (module, input, output) -> None |
| 108 | + pre_bw_hook (Callable, optional): A multi-grad hook to be called on all the outputs of |
| 109 | + the module that require gradients. It should have the following signature: |
| 110 | + pre_bw_hook (module, grad_output) -> None |
| 111 | + post_bw_hook (Callable, optional): A multi-grad hook to be called on all the inputs of |
| 112 | + the module that require gradients. It should have the following signature: |
| 113 | + post_bw_hook (module, grad_input) -> None |
| 114 | + Raises: |
| 115 | + AssertionError: If a new hook is provided when one is already registered. |
| 116 | + Note: |
| 117 | + If the module is not alive during the backward pass, the pre_bw_hook and post_bw_hook will |
| 118 | + will receive None as the module argument. |
| 119 | + The module fqn will be present in the ``parents`` attribute when each of the hooks is called. |
| 120 | + Hooks are intended to be used as markers only not to modify the inputs/outputs. |
| 121 | + """ |
| 122 | + |
| 123 | + def set_hook(hook, user_hook, hook_name): |
| 124 | + if hook is not None and user_hook is not None: |
| 125 | + raise AssertionError( |
| 126 | + f"Only one {hook_name} can be registered at a time" |
| 127 | + f" Clear the existing hook by calling ``clear_user_hooks`` before registering a new one" |
| 128 | + ) |
| 129 | + return hook |
| 130 | + |
| 131 | + self._user_pre_fw_hook = set_hook( |
| 132 | + pre_fw_hook, self._user_pre_fw_hook, "pre_fw_hook" |
| 133 | + ) |
| 134 | + self._user_post_fw_hook = set_hook( |
| 135 | + post_fw_hook, self._user_post_fw_hook, "post_fw_hook" |
| 136 | + ) |
| 137 | + self._user_pre_bw_hook = set_hook( |
| 138 | + pre_bw_hook, self._user_pre_bw_hook, "pre_bw_hook" |
| 139 | + ) |
| 140 | + self._user_post_bw_hook = set_hook( |
| 141 | + post_bw_hook, self._user_post_bw_hook, "post_bw_hook" |
| 142 | + ) |
| 143 | + |
| 144 | + def clear_user_hooks(self): |
| 145 | + """ |
| 146 | + Clears the user specified hooks registered with ``register_user_hooks`` |
| 147 | + """ |
| 148 | + self._user_pre_fw_hook = None |
| 149 | + self._user_post_fw_hook = None |
| 150 | + self._user_pre_bw_hook = None |
| 151 | + self._user_post_bw_hook = None |
| 152 | + |
| 153 | + def _get_mod_name(self, mod): |
| 154 | + if mod not in self._known_modules: |
| 155 | + self._known_modules[mod] = type(mod).__name__ |
| 156 | + mod_name = self._known_modules[mod] |
| 157 | + if mod not in self._seen_modules: |
| 158 | + for name, submod in mod.named_children(): |
| 159 | + self._known_modules[submod] = f"{mod_name}.{name}" |
| 160 | + self._get_mod_name(submod) |
| 161 | + self._seen_modules.add(mod) |
| 162 | + return mod_name |
| 163 | + |
| 164 | + def _get_append_fn(self, w_mod, name, is_bw): |
| 165 | + def fn(*args): |
| 166 | + if is_bw: |
| 167 | + self._maybe_set_engine_callback() |
| 168 | + if name in self.parents and not self.is_bw: |
| 169 | + |
| 170 | + def custom_formatwarning(msg, category, filename, lineno, line=None): |
| 171 | + return f"{filename}:{lineno}: {category.__name__}: {msg} \n" |
| 172 | + |
| 173 | + warnings.formatwarning = custom_formatwarning |
| 174 | + warnings.warn( |
| 175 | + "The module hierarchy tracking maybe be messed up." |
| 176 | + " Please file a bug to PyTorch, if it is the case." |
| 177 | + ) |
| 178 | + self.parents.add(name) |
| 179 | + |
| 180 | + if self._user_pre_bw_hook is not None and is_bw: |
| 181 | + self._user_pre_bw_hook(w_mod(), args) |
| 182 | + |
| 183 | + return fn |
| 184 | + |
| 185 | + def _get_pop_fn(self, w_mod, name, is_bw): |
| 186 | + def fn(*args): |
| 187 | + if self._user_post_bw_hook is not None and is_bw: |
| 188 | + self._user_post_bw_hook(w_mod(), args) |
| 189 | + |
| 190 | + if name in self.parents: |
| 191 | + self.parents.remove(name) |
| 192 | + elif not is_bw: |
| 193 | + # Due to some input/output not requiring gradients, we cannot enforce |
| 194 | + # proper nesting in backward |
| 195 | + raise RuntimeError( |
| 196 | + "The Module hierarchy tracking is wrong. Report a bug to PyTorch" |
| 197 | + ) |
| 198 | + |
| 199 | + return fn |
| 200 | + |
| 201 | + def _fw_pre_hook(self, mod, input): |
| 202 | + name = self._get_mod_name(mod) |
| 203 | + w_mod = weakref.ref(mod) |
| 204 | + self._get_append_fn(w_mod, name, False)() |
| 205 | + if self._user_pre_fw_hook is not None: |
| 206 | + self._user_pre_fw_hook(mod, input) |
| 207 | + args, _ = tree_flatten(input) |
| 208 | + tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad] |
| 209 | + if not self.is_bw and tensors: |
| 210 | + register_multi_grad_hook(tensors, self._get_pop_fn(w_mod, name, True)) |
| 211 | + |
| 212 | + def _fw_post_hook(self, mod, input, output): |
| 213 | + name = self._get_mod_name(mod) |
| 214 | + w_mod = weakref.ref(mod) |
| 215 | + if self._user_post_fw_hook is not None: |
| 216 | + self._user_post_fw_hook(mod, input, output) |
| 217 | + self._get_pop_fn(w_mod, name, False)() |
| 218 | + args, _ = tree_flatten(output) |
| 219 | + tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad] |
| 220 | + if not self.is_bw and tensors: |
| 221 | + register_multi_grad_hook(tensors, self._get_append_fn(w_mod, name, True)) |
| 222 | + |
| 223 | + def __enter__(self): |
| 224 | + self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook) |
| 225 | + self._fw_post_handle = register_module_forward_hook( |
| 226 | + self._fw_post_hook, always_call=True |
| 227 | + ) |
| 228 | + return self |
| 229 | + |
| 230 | + def __exit__(self, *args): |
| 231 | + self._fw_pre_handle.remove() |
| 232 | + self._fw_post_handle.remove() |
0 commit comments