class
RemovableHandle
RemovableHandle(hooks: dict[int, object], key: int, extra_sets: tuple[set[int], ...] = ())Lightweight handle returned by every register_*_hook call.
Holds a reference to the dict (or set) that owns the registered hook
plus the unique key under which it lives. Calling remove
deregisters the hook — subsequent forward / backward / load-state-dict
passes will skip it. Also supports the context manager protocol so
hooks can be scoped to a with block.
Parameters
hooksdict[int, object]The hook registry dict (e.g.
_GLOBAL_FORWARD_HOOKS) whose
entry should be removed when remove is called.keyintUnique hook identifier returned by
_next_hook_id().extra_setstuple[set[int], ...]= ()Auxiliary sets (e.g. for "always-called" hooks) from which the
same key should also be discarded on removal.
Notes
The handle does NOT own the hook callable — it only knows where to
delete the registration. Holding a handle therefore prevents nothing
on its own; once remove is called the hook stops firing
regardless of any references the caller still holds.
Examples
>>> import lucid
>>> import lucid.nn as nn
>>> from lucid.nn import hooks
>>> model, x = nn.Linear(3, 2), lucid.zeros((1, 3))
>>> def my_hook(mod, inputs):
... print(f'about to call {type(mod).__name__}')
>>> h = hooks.register_module_forward_pre_hook(my_hook)
>>> _ = model(x)
about to call Linear
>>> h.remove() # explicit deregistration
>>> _ = model(x) # silent: the hook is gone
>>>
>>> # Or via context manager for scoped activation:
>>> with hooks.register_module_forward_pre_hook(my_hook):
... _ = model(x) # hook fires here
about to call Linear
>>> _ = model(x) # auto-removed on context exitUsed by 2
Constructors
1Instance methods
1Dunder methods
2__enter__()Enter the with block; return self for binding via as.
Exit the with block, auto-removing the hook registration.