RemovableHandle
RemovableHandle(hooks_list: list[Callable[..., object]], hook: Callable[..., object])Handle returned by lucid.Tensor.register_hook.
A RemovableHandle keeps a reference to the list of hooks
attached to a tensor's gradient and to the specific callable
that was just registered, providing two ways to take the hook
back off:
- Imperative — call
removewhenever the hook is no longer needed. - RAII — bind the handle in a
withblock; the hook is automatically removed when control leaves the block.
This class is distinct from
lucid.nn.hooks.RemovableHandle: that one manages
forward/backward hooks on lucid.nn.Module, whereas
this one operates on the per-tensor hooks dispatched from
lucid.Tensor.backward after the gradient has been
accumulated.
Parameters
hooks_listlist of callableremove the hook is dropped from this list.hookcallableis) is used
for matching.Attributes
_hooks_listlist of callable_hookcallableNotes
The post-backward hook contract is
where is
the accumulated gradient and is the user-supplied
hook. A hook returning None leaves
unchanged; returning a tensor replaces it.
remove is idempotent — calling it twice is harmless.
Examples
>>> import lucid
>>> x = lucid.tensor([1.0, 2.0], requires_grad=True)
>>> handle = x.register_hook(lambda g: print('grad =', g))
>>> (x * x).sum().backward()
>>> handle.remove()
As a context manager:
>>> with x.register_hook(lambda g: g * 2) as h:
... (x * x).sum().backward()Methods (4)
__init__
→None__init__(hooks_list: list[Callable[..., object]], hook: Callable[..., object])Initialise the instance. See the class docstring for parameter semantics.
remove
→Noneremove()Remove the hook from the tensor.
__enter__
→RemovableHandle__enter__()Enter the context. Returns self so the value can be bound via with ... as.
__exit__
→None__exit__(args: object = ())Exit the context, restoring any state that was modified on entry.