Count the parameters of an MLP
Why it matters Estimating parameter count is the first step of every GPU memory budget.
Before training anything, know how big it is.
Write mlp_params(sizes, bias=True). sizes lists layer widths from input to output, for example [784, 128, 10]. Each consecutive pair (a, b) is a dense layer with a * b weights plus b biases if bias is True. Return the total.
def mlp_params(sizes, bias=True)Example
mlp_params([784, 128, 10]) is 784*128 + 128 + 128*10 + 10 = 101770.
Understand the idea
Knowing how many parameters a model has tells you its memory cost before you train it. In a multilayer perceptron, every pair of neighbouring layers is a dense layer: each input unit connects to each output unit with one weight, and each output unit has one bias. Worked example: sizes = [10, 5, 3]. Layer 1 has 10 * 5 = 50 weights and 5 biases. Layer 2 has 5 * 3 = 15 weights and 3 biases. Total = 50 + 5 + 15 + 3 = 73. With bias=False the total is 50 + 15 = 65. Rule: for every consecutive pair (a, b) in sizes, add a * b, plus b if bias is True. The bias count follows the output width b, not the input width a. A list with one size has no layers, so the answer is 0. Used in: sizing models to fit GPU memory, estimating checkpoint size (parameters times bytes per parameter), and reading model cards that quote parameter counts for LLMs.