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.

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplemlp_params([784, 128, 10])
  • Sample 2: no biasmlp_params([10, 20, 30, 1], bias=False)
  • Test 3: one layermlp_params([3, 1])
  • Test 4: transformer ffnmlp_params([4096, 16384, 4096])