Count Model Parameters
Problem Statement
Count the total number of trainable parameters in a neural network.
Background
Understanding model size is important for deployment and memory planning. Each layer's parameters include weights and biases, and the total determines the model's capacity and memory footprint.
Your Task
Write a function count_parameters(in_features, hidden_features, out_features) that builds a two-layer network (with ReLU) and returns a breakdown of its trainable parameters.
Output Format
Return a dictionary with keys: "total_params" (int), "layer1_params" (int), "layer2_params" (int).
Example:
in_features=10, hidden_features=20, out_features=5
{'total_params': 325, 'layer1_params': 220, 'layer2_params': 105}Layer1: 1020+20=220, Layer2: 205+5=105, Total: 325
Constraints:
- Linear layer params = in_features * out_features + out_features (bias)
- Use param.numel() to count elements
1. Background Knowledge
Neural network parameters are the learnable weights and biases in layers that are optimized during training. In PyTorch, nn.Linear(in_features, out_features) creates a layer with:
- Weight matrix: \mathbf{W} \in \mathbb{R}^{\text{out_features}Γ\text{in_features}} β \text{in_features}Γ\text{out_features} parameters
- Bias vector: \mathbf{b} \in \mathbb{R}^{\text{out_features}} β \text{out_features} parameters
- Total: \text{in_features}Γ\text{out_features}+\text{out_features}
Trainable parameters have requires_grad=True (default for nn.Linear). ReLU activations have 0 parameters as they are fixed functions: f(x)=max(0,x).
Key PyTorch methods:
for name, param in model.named_parameters():
if param.requires_grad:
count = param.numel() # Total elements in tensor
Sample calculation: For Linear(10β20) + Linear(20β5):
- Layer 1: 10Γ20+20=220
- Layer 2: 20Γ5+5=105
- Total: 325 trainable parameters
2. Algorithm Approach
Direct iteration over parameters (most reliable):
1. Build model: Sequential(Linear1 β ReLU β Linear2)
2. Iterate model.named_parameters()
3. For each param: if requires_grad, add param.numel()
4. Track layer-specific counts using name filtering
Mathematical formulation: Let L1β=\text{Linear}(ninβ,nhβ), L2β=\text{Linear}(nhβ,noutβ)
params(L_i) = n_{prev} Γ n_i + n_i
total_params = params(L_1) + params(L_2)
Alternative: sum(p.numel() for p in model.parameters() if p.requires_grad)
3. Step-by-Step Strategy
def count_parameters(in_features, hidden_features, out_features):
# Step 1: Create model
model = nn.Sequential(
nn.Linear(in_features, hidden_features),
nn.ReLU(),
nn.Linear(hidden_features, out_features)
)
# Step 2: Initialize counters
total = 0
layer1 = 0
layer2 = 0
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
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.