PIXELBANKv9.1.0
Menu

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:

Input:
None
Output:
{'grad_norms': [0.000149, 0.000411, 0.001311, 0.004769, 0.059498], 'vanishing': True, 'max_norm': 0.059498, 'min_norm': 0.000149}
Reasoning:
  • The function gradient_flow_test() starts by seeding the random number generator with torch.manual_seed(42) to ensure reproducibility.
  • A 5-layer network is created with nn.Linear(4, 4) layers and Sigmoid activations, then the input torch.ones(1, 4) and target torch.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 ∑i=1ngi2\sqrt{\sum_{i=1}^{n} g_i^2}, where gig_i is the ithi^{th} 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.01 times the first layer's gradient norm, resulting in vanishing being True, 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
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.