v9.1.1
Menu

Initialize Only Specific Layer Types

mediumPROWeight InitializationPyTorch Advanced

Problem Statement

Apply different initialization strategies to different layer types in a model.

Background

Different layer types benefit from different initialization. Linear layers with ReLU need Kaiming init, while BatchNorm layers are typically initialized to scale=1, shift=0.

Your Task

The starter code creates a model with Linear and BatchNorm layers. Define an initialization function that applies appropriate initialization for each layer type: Kaiming for Linear layers and standard init for BatchNorm layers. Apply it to the model.

The verification code is pre-filled.

Output Format

Returns a dictionary with "linear_bias_sum", "bn_weight_all_ones", "bn_bias_all_zeros", "num_linear", and "num_bn".

Example

Input
None
Output
{'linear_bias_sum': 0.0, 'bn_weight_all_ones': True, 'bn_bias_all_zeros': True, 'num_linear': 3, 'num_bn': 2}
Reasoning
  • Input: none. The model is fixed: three Linear layers (4→84 \to 8, 8→48 \to 4, 4→24 \to 2) with BatchNorm layers over 88 and 44 features between them, so num_linear is 33 and num_bn is 22.
  • Linear layers: Kaiming (He) init for ReLU draws each weight from N(0,σ2)\mathcal{N}(0, \sigma^2) with σ=2/fan-in\sigma = \sqrt{2 / \text{fan-in}}, i.e. 2/4≈0.707\sqrt{2/4} \approx 0.707 for the first and last layers and 2/8=0.5\sqrt{2/8} = 0.5 for the middle one. Biases are 00.
  • Bias sum: there are 8+4+2=148 + 4 + 2 = 14 bias values, all 00, so linear_bias_sum is 0.00.0.
  • BatchNorm layers: the scale γ\gamma is 11 and the shift β\beta is 00 for all 8+4=128 + 4 = 12 features, so bn_weight_all_ones and bn_bias_all_zeros are both True.
  • Notice: a freshly built BatchNorm already has γ=1\gamma = 1, β=0\beta = 0, so those flags are True even without init. The bias sum is the real check: default Linear biases are random and sum to about 0.60070.6007 here, so 0.00.0 proves your init ran.

Constraints

  • Different init for Linear vs BatchNorm
  • Linear: kaiming_normal_ weights, zeros_ bias
  • BatchNorm: ones_ weight, zeros_ bias

More from PyTorch Advanced

PRO

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

Sign in to run your code against the test cases.