fn

register_module_forward_pre_hook

RemovableHandle
register_module_forward_pre_hook(hook: Callable[..., object], with_kwargs: bool = False)
source

Register a global pre-forward hook fired on every Module.__call__.

The hook is invoked before the wrapped module's forward method runs. It receives the module instance and the positional inputs (and, optionally, the keyword inputs) and may return a tuple that replaces the positional inputs for the upcoming forward pass — useful for automatic input normalisation, logging, or shape validation.

Parameters

hookCallable
The pre-hook function. Signature:
  • hook(module, inputs) -> None | tuple (default)
  • hook(module, inputs, kwargs) -> None | tuple (with_kwargs=True)
Returning None leaves the inputs untouched; returning a non-None tuple replaces the positional inputs.
with_kwargsbool= False
If True, the hook also receives the kwargs dict and may replace it (return (new_inputs, new_kwargs)). Default False for compatibility with reference-framework idioms.

Returns

RemovableHandle

Handle whose RemovableHandle.remove deregisters the hook.

Notes

Global hooks fire for every Module instance. For per-module hooks use Module.register_forward_pre_hook instead. The order of hook execution is registration order (FIFO).

Examples

>>> from lucid.nn.hooks import register_module_forward_pre_hook
>>> def log_call(mod, inputs):
...     print(f'{type(mod).__name__}({inputs[0].shape})')
>>> handle = register_module_forward_pre_hook(log_call)
>>> # ... forward passes trigger the log ...
>>> handle.remove()