PIXELBANKv9.1.0
Menu

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:

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:
  • The function selective_init_test() seeds the random number generator with torch.manual_seed(42) to ensure reproducibility.
  • It creates a model with three nn.Linear layers and two nn.BatchNorm1d layers, then applies the specified initialization strategies: Kaiming normal for nn.Linear weights, zeros for nn.Linear biases, ones for nn.BatchNorm1d weights, and zeros for nn.BatchNorm1d biases.
  • The function calculates the sum of all nn.Linear biases, which are initialized to zeros, resulting in a sum of 0.00.0.
  • It counts the number of nn.Linear and nn.BatchNorm1d layers, finding 33 and 22 respectively, and checks that all nn.BatchNorm1d weights are 1.01.0 and all biases are 0.00.0, resulting in the output dictionary with the specified values.

Constraints:

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

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.