Remove Hooks and Verify Cleanup
Problem Statement
Demonstrate proper hook lifecycle: register, use, and remove hooks.
Background
Hooks that aren't removed can cause memory leaks and unexpected behavior. Always store the handle returned by register_forward_hook and call handle.remove().
Your Task
The starter code creates a layer and a mutable counter. Register a forward hook that counts how many times the layer is called. After the first 3 forward passes, remove the hook. The test verifies the counter stops incrementing after hook removal.
Output Format
Returns a dictionary with "count_before_remove", "count_after_remove", and "hook_removed".
Example
None
{'count_before_remove': 3, 'count_after_remove': 3, 'hook_removed': True}- The function
hook_cleanup_test()initializes a counter list[0]and registers a forward hook that increments the counter by 1 each time it fires. - The input
[[1.0, 2.0, 3.0]]is run through the model 3 times, causing the hook to fire 3 times and incrementing the counter to . - After recording the counter as
count_before_remove, the hook is removed, and the input is run 2 more times without the hook firing, leaving the counter unchanged at . - The function records the counter as
count_after_removeand returns a dict withcount_before_removeandcount_after_removeboth equal to , andhook_removedset toTruesince the counts are equal.
Constraints
- Use hook handle.remove() to unregister
- Verify hook no longer fires after removal
- Use a mutable counter