PIXELBANKv9.1.0
Menu

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:

Input:
None
Output:
{'count_before_remove': 3, 'count_after_remove': 3, 'hook_removed': True}
Reasoning:
  • 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 33.
  • 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 33.
  • The function records the counter as count_after_remove and returns a dict with count_before_remove and count_after_remove both equal to 33, and hook_removed set to True since the counts are equal.

Constraints:

  • Use hook handle.remove() to unregister
  • Verify hook no longer fires after removal
  • Use a mutable counter
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Remove Hooks and Verify Cleanup - Easy | PixelBank