v9.1.1
Menu

Count Model Parameters

mediumPROModelingPyTorch ModelingPytorch

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

Input
in_features=10, hidden_features=20, out_features=5
Output
{'total_params': 325, 'layer1_params': 220, 'layer2_params': 105}
Reasoning
  • Inputs: in_features=10 is the input vector size, hidden_features=20 is the width of the hidden layer, and out_features=5 is the number of outputs. The network maps 10→20→510 \to 20 \to 5, with ReLU in between.
  • Layer 1: a linear map from 10 inputs to 20 outputs holds a 20×1020 \times 10 weight matrix plus one bias per output, so 10⋅20+20=200+20=22010 \cdot 20 + 20 = 200 + 20 = 220 parameters.
  • Layer 2: the same rule from 20 inputs to 5 outputs gives a 5×205 \times 20 weight matrix plus 5 biases: 20⋅5+5=100+5=10520 \cdot 5 + 5 = 100 + 5 = 105.
  • ReLU is a fixed elementwise function max⁡(0,x)\max(0, x) with nothing to learn, so it contributes 0.
  • Output: the total is 220+105=325220 + 105 = 325, giving {'total_params': 325, 'layer1_params': 220, 'layer2_params': 105}. All three values are plain integers.
  • Notice that the hidden width appears in both layers, so the count grows roughly as (in+out)×hidden(\text{in} + \text{out}) \times \text{hidden}: for 784→128→10784 \to 128 \to 10 the first layer alone is 100480100480.

Constraints

  • Linear layer params = in_features * out_features + out_features (bias)
  • Use param.numel() to count elements

Learn this in

More from Pytorch

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.