torch.nn.ModuleRegistrationHook
export type ModuleRegistrationHook = (
module: Module,
name: string,
submodule: Module | null
) => Module | null | void;Hook called when a submodule is registered in a module.
ModuleRegistrationHook is triggered when add_module() is called on a module (i.e., when assigning a submodule as a property). Can inspect or modify the submodule being registered.
Signature:
(module: Module, name: string, submodule: Module | null) => Module | null | voidParameters:
module: The parent modulename: Property name for the submodule (e.g., 'layer1')submodule: The module being registered (or null to unregister)
Return Value:
- Return a modified module to change what gets registered
- Return null to prevent registration
- Return void to register unchanged
Use Cases:
- Monitor module hierarchy construction
- Wrap or modify submodules (e.g., add logging)
- Validate module compatibility
- Implement module factory patterns
- Track architecture changes
Examples
const hook: ModuleRegistrationHook = (module, name, submodule) => {
if (submodule) {
console.log(`Adding ${submodule.constructor.name} as ${name}`);
}
return; // Register as-is
};
torch.nn.register_module_registration_hook(hook);