406. Count the parameters of a GPT-2 style model
Why it matters Parameter counts drive memory planning, FLOPs estimates and checkpoint sizes.
Before training, you should know where the parameters live: embeddings, attention, MLP, norms and the output head.
Write gpt_params(vocab, ctx, d, n_layers, tie=True, ff_mult=4). The model has token embeddings (vocab x d), learned positions (ctx x d), and per layer: two LayerNorms (gain and bias each, d values), a fused QKV linear d -> 3d with bias, an output projection d -> d with bias, and an MLP d -> ff_mult*d -> d with biases. After the last layer there is one more LayerNorm. The output head is vocab x d with no bias and is skipped when tie is True. Return a dict of ints with keys "embedding" (tokens plus positions), "per_layer", "head" and "total".
def gpt_params(vocab, ctx, d, n_layers, tie=True, ff_mult=4)Example 1
Input: gpt_params(50257, 1024, 768, 12)
Output: per_layer 7087872 and total 124439808
Example 2
Input: vocab = 10, ctx = 4, d = 2, n_layers = 1
Output: {'embedding': 28, 'per_layer': 74, 'head': 0, 'total': 106}
Example 3
Input: vocab = 100, ctx = 8, d = 16, n_layers = 2, ff_mult = 2
Output: {'embedding': 1728, 'per_layer': 2224, 'head': 0, 'total': 6208}
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Write each piece as a formula in d and add them up.
Hint 2
Linear a -> b with bias has a*b + b parameters.
Hint 3
A LayerNorm has 2d parameters.
Hint 4
Tying shares the head with the token embedding.
Common mistakes
- Counting the tied head twice.
- Forgetting the final LayerNorm or the biases.
Understand the idea
Counting parameters is bookkeeping: list every weight matrix, multiply its sides, add the biases. A linear layer from a to b has a*b weights and b biases.
Tiny config: vocab 10, context 4, width 2, one layer. Embeddings: 10*2 + 4*2 = 28. One layer: norms 4*2 = 8; QKV 2*6 + 6 = 18; projection 2*2 + 2 = 6; MLP 2*8 + 8 + 8*2 + 2 = 42; sum 74. Final norm 4. Tied head adds 0, so the total is 28 + 74 + 4 = 106.
total = V*d + ctx*d + L*(4d + 3d^2 + 3d + d^2 + d + 2*m*d^2 + m*d + d) + 2d + (0 if tied else V*d), with m = ff_mult
For GPT-2 small (V = 50257, ctx 1024, d 768, 12 layers) this gives 124,439,808, the familiar "124M". Notice that roughly 12 d^2 per layer dominates, which is why FLOPs and memory are often estimated from L * 12 * d^2.