torch.nn.RemovableHandle
class RemovableHandlenew RemovableHandle(hooks_list: Set<unknown>, hook: unknown)
- readonly
id(number) - – Gets the current number of hooks in the registry (debugging). Returns the size of the hook set at the time this property is accessed. Useful for debugging but not typically used in application code. Note: This returns the size of the hook container, not a unique ID. It may change as other hooks are added/removed.
Handle for managing a registered hook.
RemovableHandle is returned by all register_*_hook() functions. It allows
you to unregister a previously registered hook, effectively removing it from
being called during computation. Useful for temporary hooks or cleanup.
Key Features:
- Idempotent: Calling remove() multiple times is safe
- Lightweight: Just references the hook and its container
- Non-blocking: Removal is immediate and synchronous
Typical Usage:
// Register a hook and get a handle
const handle = module.register_forward_hook(myHook);
// Later: remove the hook
handle.remove();
// Hook is no longer called after removal
module.forward(input); // myHook not invoked- Idempotent: Safe to call remove() multiple times
- Immediate: Removal takes effect immediately
- Non-blocking: remove() is synchronous
- One-time: Each handle is tied to one hook registration
Examples
// Temporary debugging hook
const handle = model.register_forward_hook((m, input, output) => {
console.log('Forward pass');
});
// Do work...
model.forward(data); // Logs "Forward pass"
// Clean up when done
handle.remove();
model.forward(data); // No log output
// Safe to remove multiple times
handle.remove(); // No error
// Multiple hooks
const h1 = model.register_forward_hook(hook1);
const h2 = model.register_forward_hook(hook2);
h1.remove(); // Remove first hook, h2 still active
model.forward(x); // Only hook2 called
h2.remove(); // Clean up second hook
model.forward(x); // No hooks called