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
gpt_params(50257, 1024, 768, 12) gives per_layer 7087872 and total 124439808.
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.
Rule: 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.