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
None
{'output_without': [-0.1207, -1.3901], 'output_with': [-0.2228, -0.7854], 'outputs_differ': True}- The function
modify_hook_test()starts by seeding the random number generator withtorch.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 asoutput_without. - A forward hook is then registered on the first layer, which clamps the output to the range using the
clampfunction, and the same input is run through the model with the hook, storing the output asoutput_with. - The function returns a dictionary containing
output_withoutandoutput_withas flat lists rounded to 4 decimals, as well as a booleanoutputs_differindicating whether the two outputs are different, which in this case isTruedue 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