Selective Parameter Freezing
Problem Statement
Freeze specific layers of a model while keeping others trainable.
Background
In transfer learning, you often freeze pretrained layers and only train the top layers. You can freeze parameters by setting requires_grad = False.
Your Task
The starter code creates a 2-layer model. Freeze layer1's parameters so they don't update during training, then count the total, trainable, and frozen parameters in the model.
Output Format
Returns a dictionary with "total_params", "trainable_params", "frozen_params", and "layer1_frozen".
Example
None
{'total_params': 58, 'trainable_params': 18, 'frozen_params': 40, 'layer1_frozen': True}- The model is created with
nn.Sequentialcontaining two linear layers:nn.Linear(4, 8)(layer1) andnn.Linear(8, 2)(layer2). - Layer1 has parameters (weights and bias), and layer2 has parameters, making a total of parameters.
- By setting
requires_grad=Falseon layer1's parameters, all 40 parameters in layer1 are frozen, leaving 18 parameters in layer2 trainable. - The function then returns a dictionary with the total parameter count (58), trainable parameter count (18), frozen parameter count (40), and a boolean indicating that all layer1 parameters are frozen (True).
Constraints
- Use nn.Sequential with named layers
- Freeze by setting requires_grad = False
- Count parameters using .numel()