class

RemovableHandle

RemovableHandle(hooks_list: list[Callable[..., object]], hook: Callable[..., object])
source

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 remove whenever the hook is no longer needed.
  • RAII — bind the handle in a with block; 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 callable
The underlying registry list owned by the tensor; on remove the hook is dropped from this list.
hookcallable
The exact callable to remove. Identity (is) is used for matching.

Attributes

_hooks_listlist of callable
The registry list (private).
_hookcallable
The registered hook (private).

Notes

The post-backward hook contract is

xˉh(xˉ),\bar x \leftarrow h(\bar x),

where xˉ=L/x\bar x = \partial \mathcal{L} / \partial x is the accumulated gradient and hh is the user-supplied hook. A hook returning None leaves xˉ\bar x 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)

dunder

__init__

None
__init__(hooks_list: list[Callable[..., object]], hook: Callable[..., object])
source

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

fn

remove

None
remove()
source

Remove the hook from the tensor.

dunder

__enter__

RemovableHandle
__enter__()
source

Enter the context. Returns self so the value can be bound via with ... as.

dunder

__exit__

None
__exit__(args: object = ())
source

Exit the context, restoring any state that was modified on entry.