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
None
{'grad_output_shape': [1, 1], 'grad_input_shapes': [[1, 4], [1, 1], [1]], 'num_grad_inputs': 3}- The
backward_hook_testfunction 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_inputcontains the gradients of the loss with respect to the layer's input and parameters, whilegrad_outputcontains the gradients of the loss with respect to the layer's output. - The hook stores the shapes of
grad_outputandgrad_input, which are then returned as a dictionary:grad_outputhas shape ,grad_inputhas shapes , , and (corresponding to the layer's input, weight, and bias, respectively), and there are non-None entries ingrad_input.
Constraints
- Use register_full_backward_hook
- Capture grad_input and grad_output
- Hook on the second Linear layer