Initialize Only Specific Layer Types
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
None
{'linear_bias_sum': 0.0, 'bn_weight_all_ones': True, 'bn_bias_all_zeros': True, 'num_linear': 3, 'num_bn': 2}- Input: none. The model is fixed: three Linear layers (, , ) with BatchNorm layers over and features between them, so
num_linearis andnum_bnis . - Linear layers: Kaiming (He) init for ReLU draws each weight from with , i.e. for the first and last layers and for the middle one. Biases are .
- Bias sum: there are bias values, all , so
linear_bias_sumis . - BatchNorm layers: the scale is and the shift is for all features, so
bn_weight_all_onesandbn_bias_all_zerosare bothTrue. - Notice: a freshly built BatchNorm already has , , so those flags are
Trueeven without init. The bias sum is the real check: default Linear biases are random and sum to about here, so proves your init ran.
Constraints
- Different init for Linear vs BatchNorm
- Linear: kaiming_normal_ weights, zeros_ bias
- BatchNorm: ones_ weight, zeros_ bias