PIXELBANKv9.1.0
Menu

Modify Activations with Forward Hook

Problem Statement

Use a forward hook to modify activations by clamping them to a range.

Background

Forward hooks can not only inspect but also modify layer outputs by returning a new tensor. If the hook returns a value, it replaces the layer's output.

Your Task

The starter code runs the model once without a hook. Use a forward hook to clamp the first layer's output to [-0.5, 0.5]. Compare the model's output with and without the hook, and clean up the hook afterward.

Output Format

Returns a dictionary with "output_without", "output_with", and "outputs_differ".

Example:

Input:
None
Output:
{'output_without': [-0.1207, -1.3901], 'output_with': [-0.2228, -0.7854], 'outputs_differ': True}
Reasoning:
  • The function modify_hook_test() starts by seeding the random number generator with torch.manual_seed(42) to ensure reproducibility.
  • It creates a neural network model nn.Sequential(nn.Linear(3, 4), nn.Linear(4, 2)) and runs the input [[1.0, 2.0, 3.0]] through the model without a hook, storing the output as output_without.
  • A forward hook is then registered on the first layer, which clamps the output to the range [−0.5,0.5][-0.5, 0.5] using the clamp function, and the same input is run through the model with the hook, storing the output as output_with.
  • The function returns a dictionary containing output_without and output_with as flat lists rounded to 4 decimals, as well as a boolean outputs_differ indicating whether the two outputs are different, which in this case is True due to the clamping effect of the hook.

Constraints:

  • Hook must clamp to [-0.5, 0.5]
  • Hook must return the modified tensor
  • Compare outputs with and without hook
🔒

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.