class

RemovableHandle

RemovableHandle(hooks: dict[int, object], key: int, extra_sets: tuple[set[int], ...] = ())
source

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.
keyint
Unique 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

>>> from lucid.nn import hooks
>>> def my_hook(mod, inputs):
...     print(f'about to call {type(mod).__name__}')
>>> h = hooks.register_module_forward_pre_hook(my_hook)
>>> # ... forward passes print the message ...
>>> h.remove()                    # explicit deregistration
>>>
>>> # Or via context manager for scoped activation:
>>> with hooks.register_module_forward_pre_hook(my_hook):
...     model(x)                  # hook fires here
>>> # hook auto-removed on context exit

Methods (4)

dunder

__init__

None
__init__(hooks: dict[int, object], key: int, extra_sets: tuple[set[int], ...] = ())
source

Initialise the handle. See the class docstring for parameter semantics.

fn

remove

None
remove()
source

Deregister the hook this handle refers to.

Pops the hook entry from the owning registry dict and discards the key from any auxiliary sets. Idempotent — calling remove a second time is a no-op (pop(..., None)).

dunder

__enter__

RemovableHandle
__enter__()
source

Enter the with block; return self for binding via as.

dunder

__exit__

None
__exit__(args: object = ())
source

Exit the with block, auto-removing the hook registration.