PIXELBANKv9.1.0
Menu

Register Backward Hook to Capture Gradients

Problem Statement

Use a backward hook to capture gradients flowing through a specific layer.

Background

module.register_full_backward_hook(hook_fn) captures gradients during the backward pass. The hook receives (module, grad_input, grad_output).

Your Task

The starter code creates a model and grad_data dict. Use a backward hook to capture the gradients flowing through the second Linear layer during backpropagation. Store both grad_input and grad_output, and clean up the hook afterward.

Output Format

Returns a dictionary with "grad_output_shape", "grad_input_shapes", and "num_grad_inputs".

Example:

Input:
None
Output:
{'grad_output_shape': [1, 1], 'grad_input_shapes': [[1, 4], [1, 1], [1]], 'num_grad_inputs': 3}
Reasoning:
  • The backward_hook_test function creates a neural network with two linear layers and a ReLU activation function, then registers a full backward hook on the second linear layer.
  • When the input [[1.0, 2.0, 3.0]] is passed through the network, the output is computed and the mean squared error (MSE) loss is calculated with respect to the target [[1.0]].
  • During the backward pass, the hook is triggered, capturing the gradients flowing through the second linear layer: grad_input contains the gradients of the loss with respect to the layer's input and parameters, while grad_output contains the gradients of the loss with respect to the layer's output.
  • The hook stores the shapes of grad_output and grad_input, which are then returned as a dictionary: grad_output has shape [1,1][1, 1], grad_input has shapes [1,4][1, 4], [1,1][1, 1], and [1][1] (corresponding to the layer's input, weight, and bias, respectively), and there are 33 non-None entries in grad_input.

Constraints:

  • Use register_full_backward_hook
  • Capture grad_input and grad_output
  • Hook on the second Linear layer
solution.py

Test Results

0/0
Run code to see test results.
Register Backward Hook to Capture Gradients - Medium | PixelBank