Hook¶
- class Hook(prehook: Callable | None = None, posthook: Callable | None = None, *, prehook_kwargs: dict[str, Any] | None = None, posthook_kwargs: dict[str, Any] | None = None, train_update: bool = True, eval_update: bool = True)[source]¶
Bases:
objectProvides and manages forward hook and prehook functionality.
Hook provides functionality to register and deregister itself as forward hook with a
Moduleobject. This is performed usingregister_forward_hook()to register itself as a forward hook and it manages the returned RemovableHandle to deregister itself.- Parameters:
prehook (Callable | None, optional) – function to call before hooked module’s
forward(). Defaults toNone.posthook (Callable | None, optional) – function to call after hooked module’s
forward(). Defaults toNone.prehook_kwargs (dict[str, Any] | None, optional) – keyword arguments passed to
register_forward_pre_hook(). Defaults toNone.posthook_kwargs (dict[str, Any] | None, optional) – keyword arguments passed to
register_forward_hook(). Defaults toNone.train_update (bool, optional) – if the hooks should be run when hooked module is in train mode. Defaults to
True.eval_update (bool, optional) – if the hooks should be run when hooked module is in eval mode. Defaults to
True.
Note
If not
None, the signature of the prehook must be of the following form.hook(module, args) -> None or modified input
Or, if
with_kwargsis passed as a keyword argument.hook(module, args, kwargs) -> None or modified input
See
register_forward_pre_hook()for further information.Note
If not
None, the signature of the posthook must be of the following form.hook(module, args, output) -> None or modified output
Or, if
with_kwargsis passed as a keyword argument.hook(module, args, kwargs, output) -> None or modified output
See
register_forward_hook()for further information.- Raises:
RuntimeError – at least one of
prehookandposthookmust not be None.
- deregister() None[source]¶
Deregisters the hook as a forward hook and/or prehook.
If the
Hookis not registered, this is still safe to call.