Gradient Flow Analysis
Problem Statement
Analyze gradient flow through a deep network to detect vanishing or exploding gradients.
Background
In deep networks, gradients can vanish (approach 0) or explode (grow huge) as they flow backward through layers. Monitoring gradient norms per layer helps diagnose training issues.
Your Task
The starter code creates a 5-layer Sigmoid network, runs a forward pass, and calls backward. Compute the L2 gradient norm for each layer's weights to analyze how gradients flow through the network.
The rest (vanishing detection, min/max) is handled by the pre-filled code.
Output Format
Returns a dictionary with "grad_norms" (list of 5), "vanishing", "max_norm", and "min_norm".
Example
None
{'grad_norms': [0.000149, 0.000411, 0.001311, 0.004769, 0.059498], 'vanishing': True, 'max_norm': 0.059498, 'min_norm': 0.000149}- The function
gradient_flow_test()starts by seeding the random number generator withtorch.manual_seed(42)to ensure reproducibility. - A 5-layer network is created with
nn.Linear(4, 4)layers and Sigmoid activations, then the inputtorch.ones(1, 4)and targettorch.zeros(1, 4)are used to compute the MSE loss. - The
backward()function is called to compute the gradients, and for each Linear layer, the L2 norm of the weight gradients is calculated as , where is the gradient element, resulting in the list of gradient norms:[0.000149, 0.000411, 0.001311, 0.004769, 0.059498]. - The function then determines if the gradients are vanishing by checking if the last layer's gradient norm is less than
0.01times the first layer's gradient norm, resulting invanishingbeingTrue, and calculates the maximum and minimum gradient norms across layers.
Constraints
- 5 Linear(4,4) layers with Sigmoid activation
- Monitor weight gradient norms per layer
- Detect vanishing gradients