v9.1.1
Menu

Register Forward Hook to Capture Activations

easyFREEHooksPyTorch Advanced

Problem Statement

Use a forward hook to capture intermediate activations from a hidden layer.

Background

module.register_forward_hook(hook_fn) lets you inspect outputs of any layer without modifying the model. The hook function receives (module, input, output).

Your Task

The starter code creates a 3-layer model and an activations dict. Use a forward hook to capture the output of the first layer during a forward pass. Store the captured activation in the provided dict and remember to clean up the hook afterward.

Output Format

Returns a dictionary with "activation_shape", "activation_values", and "final_output".

Example

Input
None
Output
{'activation_shape': [1, 4], 'activation_values': [1.4206, 0.7051, 2.2023, 0.8228], 'final_output': [-0.2042, -0.7735]}
Reasoning
  • Input: none. The seed fixes every weight of the 3→4→23 \to 4 \to 2 network, and the forward pass uses the single row x=[1,2,3]x = [1, 2, 3], a 1×31 \times 3 batch of one sample.
  • First layer: h=xW1⊤+b1h = x W_1^\top + b_1, a 1×41 \times 4 result. Its first entry is 0.4414⋅1+0.4792⋅2−0.1353⋅3+0.4266≈1.42060.4414 \cdot 1 + 0.4792 \cdot 2 - 0.1353 \cdot 3 + 0.4266 \approx 1.4206; the other three give 0.70510.7051, 2.20232.2023, 0.82280.8228. That row is the captured activation, shape [1, 4].
  • Rest of the network: ReLU zeroes negatives, but all four entries are positive, so they pass unchanged. The second layer maps them to y=ReLU(h)W2⊤+b2=[−0.2042,−0.7735]y = \mathrm{ReLU}(h) W_2^\top + b_2 = [-0.2042, -0.7735].
  • Output: the shape, the four rounded activations, and the two final values.
  • Notice that the activation is taken straight out of the first layer, before ReLU: had any hih_i been negative, the captured value would still be negative even though the next layer sees 00.

Constraints

  • Use register_forward_hook
  • Hook captures output of first Linear layer
  • Do not modify the model architecture

Learn this in

More from PyTorch Advanced

solution.py

Test results

Sign in to run your code against the test cases.