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]_GLOBAL_FORWARD_HOOKS) whose
entry should be removed when remove is called.keyint_next_hook_id().extra_setstuple[set[int], ...]= ()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 exitMethods (4)
__init__
→None__init__(hooks: dict[int, object], key: int, extra_sets: tuple[set[int], ...] = ())Initialise the handle. See the class docstring for parameter semantics.
remove
→Noneremove()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)).
__enter__
→RemovableHandle__enter__()Enter the with block; return self for binding via as.
__exit__
→None__exit__(args: object = ())Exit the with block, auto-removing the hook registration.