Lesson 4.4: Initialisation, parameter counts and shapes
Read a transformer's shapes, count its parameters exactly, and start it well: check the loss at step 0, scale the residual layers and test on one batch.
By the end of this lesson you will be able to write down the shape of every array in a GPT, count its parameters by formula and check the count against the code, estimate the memory to train it, choose an initial scale for the weights, explain why the layers that write into the residual stream are scaled down, and run three quick tests before any long training. You will show that the formula gives 27,648 parameters for our model, the same as the code, and 124,439,808 for a model of the shape of GPT-2 small, of which 31.0% sits in the embedding table; that the initial loss is 3.530 at a weight spread of 0.02 and 11.944 at 1.0, against a uniform guess of 3.5264; that the residual stream's spread grows from 1.32 to 9.76 between 2 and 96 layers with a plain initialisation and stays between 0.78 and 0.93 when the output layers are scaled; and that one batch can be memorised from a loss of 3.5296 to 0.0672 in 300 steps. You need Python and NumPy, helpers.py from Lesson 3.1, gpt.py and train.py from Lesson 4.3.
Lesson 4.3 built a working GPT, and we trained it without much comment about how it started or how big it was. This lesson fills the gaps. It is a collection of habits that every builder of models needs: knowing the shape of everything, being able to say how many numbers the model has and why, and starting from a point from which training can succeed.
Shapes
Most bugs in a transformer are shape bugs, or look like them. Write the shapes down once, and check them with assertions. Let B be the batch size, T the window length, d the width, h the number of heads, dh equal to d divided by h, and V the vocabulary.
Name · Shape · What it isx · (B, T) · integer token ids
E · (V, d) · embedding table
E[x] + Pos[:T] · (B, T, d) · the residual stream at the bottom
Wq, Wk, Wv, Wo · (d, d) each · attention matrices
queries, keys, values · (B, T, d), then (B, h, T, dh) · after splitting into heads
scores, weights · (B, h, T, T) · one T by T matrix per head
attention output · (B, h, T, dh), then (B, T, d) · after gluing the heads together
W1, W2 · (d, 4d) and (4d, d) · feed-forward matrices
hidden activations · (B, T, 4d) · the widest array in a block
g, b of a norm · (d,) · gain and offset
U · (d, V) · output matrix
logits · (B, T, V) · scores for the next token
Three habits help. Annotate every array's shape in a comment where it is created. Assert at the boundaries, for instance that the output of a sublayer has the shape of its input. Remember the residual rule: every sublayer takes (B, T, d) and returns (B, T, d), which is what lets blocks stack. Two shapes cost the most memory in a real model: the T by T score matrices, which Lesson 3.4 covered, and the (B, T, V) logits, which Lesson 2.4 priced.
Counting parameters
A parameter is one number the training adjusts. Counting them exactly is a useful discipline. It catches mistakes in the code, and tells you what the model costs to store and train. Per block, with the standard factor of four in the feed-forward layer:
Part · ParametersAttention: Wq, Wk, Wv, Wo and four bias vectors · 4 d² + 4 d
Feed-forward: W1, W2 and two bias vectors · 8 d² + 5 d
Two layer norms: gain and offset each · 4 d
One block · 12 d² + 13 d
Add the embedding table (V d), the output matrix (V d, unless it shares the embedding table), the final layer norm (2 d), and any learned position table (T d).
python
from helpers import
from gpt import initgpt
def countparams(V, d, L, T=0, tied=False, mlpmult=4):
attention = 4 d d + 4 d # Wq, Wk, Wv, Wo and their biases
mlp = 2 mlpmult d d + (mlpmult + 1) d # two matrices and two bias vectors
norms = 2 2 d # two layer norms per block, each with gain and bias
perlayer = attention + mlp + norms # 12 d^2 + 13 d when mlpmult = 4
total = V d + T d + L perlayer + 2 d # embeddings, learned positions, blocks, final norm
if not tied:
total += V d # a separate output matrix
return total, perlayer
our model
p = initgpt(V, 32, 2)
print("code:", sum(w.size for w in p.values()), " formula:", countparams(V, 32, 2)[0])
print("tied output matrix:", countparams(V, 32, 2, tied=True)[0])
a model of the size of GPT-2 small: 12 layers, width 768, 50,257 tokens, 1,024 positions, tied output matrix
total, perlayer = countparams(50257, 768, 12, T=1024, tied=True)
print("per layer:", perlayer, " total:", total)
print("share of the total in the embedding table:", round(100 50257 768 / total, 1), "%")
print("share in the blocks:", round(100 12 perlayer / total, 1), "%")
memory to train it in 32-bit numbers with Adam: weights, gradients and two running averages
print("weights:", round(total 4 / 1e9, 2), "GB training state:", round(total 16 / 1e9, 2), "GB")
The output:
code: 27648 formula: 27648
tied output matrix: 26560
per layer: 7087872 total: 124439808
share of the total in the embedding table: 31.0 %
share in the blocks: 68.3 %
weights: 0.5 GB training state: 1.99 GB
The formula and the code agree for our model: 27,648. Working it by hand for d = 32, L = 2, V = 34: embeddings 34 × 32 = 1,088; output matrix 1,088; two blocks of 12 × 32² + 13 × 32 = 12,704 each, 25,408; final norm 64; total 27,648. If the numbers disagreed, one of them would hide a bug, such as a missing bias or a matrix of the wrong shape.
The second model in the output has the shape of GPT-2 small: 12 blocks, width 768, a vocabulary of 50,257, 1,024 positions and a tied output matrix. The formula gives 124,439,808, which matches the figure usually quoted for it, about 124 million. Two facts stand out. The embedding table alone holds 38.6 million numbers, 31.0% of the total. A small model with a large vocabulary spends a large part of its budget on words. And the blocks hold 68.3%.
Weight tying shares one matrix between the embedding table and the output matrix, using E transposed as U. A token's input vector and the vector used to score it as an output then coincide, which is a reasonable prior. It saves V d numbers: 1,088 for us (3.9%), and 38.6 million for GPT-2 small (31%). GPT-2 does this.
The memory to train it
Parameters have a memory cost, and in training it is a multiple of their number. In 32-bit numbers (4 bytes), training with Adam keeps four copies: the weights, their gradients, and the two running averages Adam uses (Lesson 5.2). That is 16 bytes per parameter. For 124.4 million parameters, the weights alone take 0.5 GB and the training state 1.99 GB. On top of that come the activations stored for the backward pass, which depend on the batch and the window. Storing the weights in 16 bits for inference halves the weights' cost. Lesson 9.1 covers fewer bits.
Starting well
Training starts from the initial weights, and a bad start wastes steps or ruins the run. Two things matter: the scale of the weights, and the scale of what the layers write into the stream.
The loss at step 0
An untrained model should know nothing, which means it should give every token the same probability. For a vocabulary of V tokens, the loss is then the natural log of V: 3.5264 for 34 tokens. This is the first sanity check on any model. If the starting loss is far above it, the model begins confidently wrong: its scores are large and mostly mistaken, and training must first undo that.
The scale of the initial weights controls it. We initialise from a normal distribution with spread std, and compare four values. For each, the code reports the loss at step 0, the length of the gradient (all parameters together) and the validation loss after 300 steps.
python
from train import
d, L, h = 32, 2, 2
Pos = sinusoidal(T, d)
print("uniform guess:", round(float(np.log(V)), 4))
for std in (0.02, 0.1, 0.5, 1.0):
p = initgpt(V, d, L, seed=0, std=std)
x, y = getbatch(trainids, 32, T, np.random.defaultrng(0))
loss, g = lossandgrads(p, x, y, L, h, Pos)
norm = np.sqrt(sum((v 2).sum() for v in g.values()))
with np.errstate(all="ignore"):
p, = train(std=std, steps=300)
v = validation(p)
print(f"std {std:<5} initial loss {loss:6.3f} gradient norm {norm:7.3f} validation after 300 steps {v:.4f}")
uniform guess: 3.5264
std 0.02 initial loss 3.530 gradient norm 0.864 validation after 300 steps 1.0078
std 0.1 initial loss 3.641 gradient norm 1.410 validation after 300 steps 1.0079
std 0.5 initial loss 6.478 gradient norm 7.633 validation after 300 steps 1.0451
std 1.0 initial loss 11.944 gradient norm 12.104 validation after 300 steps 1.6655
At 0.02 the model starts at 3.530, almost exactly the uniform guess. At 0.1 it is 3.641, still fine. At 0.5 it starts at 6.478, nearly twice the guess, and at 1.0 at 11.944, which is more than three times the guess. The gradient grows with it, and after 300 steps the large-scale starts have not caught up: 1.0451 and 1.6655 against 1.0078. Notice that the model survived all four. Layer norms (Lesson 4.1) rescale the sublayer inputs, which protects it. Without them the largest settings would have been much worse. A common default for transformers is a spread near 0.02, which for wide models matches the rule of scaling by 1 over the square root of the width.
Scaling the layers that write into the stream
Lesson 4.1 showed that the residual stream's spread grows with the number of sublayers that add to it. At initialisation, each sublayer adds a vector with a spread set by its weights. If each of the 2 L sublayers adds an independent vector of variance σ², the stream's variance after all of them is about 2 L σ² (plus the starting variance). To keep the stream's size independent of depth, scale the layers that write into it by 1 over the square root of 2 L. The two writers in each block are Wo (attention's output matrix) and W2 (the feed-forward layer's second matrix). The GPT-2 paper describes exactly this.
The code compares the stream's spread at the top for 2, 8, 32 and 96 blocks of width 64, with a base weight spread of 0.1, with and without the scaling.
python
from train import
d, h = 64, 2
x, = getbatch(trainids, 16, T, np.random.defaultrng(0))
Pos = sinusoidal(T, d)
for L in (2, 8, 32, 96):
row = []
for scaled in (False, True):
p = initgpt(V, d, L, seed=0, std=0.1, residscale=scaled)
, cache = gptfwd(p, x, L, h, Pos)
row.append(round(float(cache["H"].std()), 2))
print(f"{L:3d} layers: spread of the residual stream plain init {row[0]:6.2f} scaled init {row[1]:6.2f}")
2 layers: spread of the residual stream plain init 1.32 scaled init 0.78
8 layers: spread of the residual stream plain init 2.60 scaled init 0.85
32 layers: spread of the residual stream plain init 6.57 scaled init 0.93
96 layers: spread of the residual stream plain init 9.76 scaled init 0.85
With the plain initialisation, the stream grows with depth: 1.32 at 2 blocks, 2.60 at 8, 6.57 at 32 and 9.76 at 96. With scaled Wo and W2, it stays between 0.78 and 0.93 at every depth. A deeper model therefore starts in the same state as a shallow one, which means the same learning rate suits both.
Three tests before any long run
Training a real model takes hours or days. Three checks, each a minute or less, catch most mistakes first.
1. The loss at step 0 equals the log of the vocabulary. We saw it: 3.530 against 3.5264. If it is not close, the initial scales are wrong, or something is not centred.
2. The gradients match numerical ones. Lesson 4.3's check, on a tiny model and a few parameters.
3. The model can memorise one batch. Train on a single batch of data, repeatedly, and the loss should fall nearly to zero. A model that cannot memorise 512 tokens has a bug in the forward pass, the backward pass or the optimiser, and will not learn the full data either.
The third test, in code:
python
from train import
d, L, h = 32, 2, 2
Pos = sinusoidal(T, d)
p = initgpt(V, d, L, seed=0)
opt = Adam(p, 0.003)
x, y = getbatch(trainids, 32, T, np.random.defaultrng(0)) # one batch, used again and again
for step in range(301):
loss, g = lossandgrads(p, x, y, L, h, Pos)
opt.step(g)
if step in (0, 50, 100, 200, 300):
print(step, round(loss, 4))
0 3.5296
50 1.45
100 0.7887
200 0.083
300 0.0672
The loss falls from 3.5296 to 0.0672 in 300 steps. The model memorised its single batch, which it could only do if every part of the forward and backward pass is working. (The loss does not reach exactly zero because of the layer norm's eps, the finite learning rate and sampled positions that repeat inside the batch with different continuations.)
Key takeaways
Write down every array's shape, annotate the code and assert shapes at boundaries. Every sublayer maps (B, T, d) to (B, T, d).
A block has 12 d² + 13 d parameters: attention 4 d² + 4 d, feed-forward 8 d² + 5 d, two norms 4 d. Add V d for the embedding table, V d for the output matrix unless tied, 2 d for the final norm and T d for learned positions.
Our model has 27,648 parameters, by formula and by code. A model of the shape of GPT-2 small has 124,439,808, of which 31.0% is the embedding table and 68.3% the blocks.
Tying the output matrix to the embedding table saves V d numbers: 3.9% for us, 31% for GPT-2 small.
Training in 32 bits with Adam takes 16 bytes per parameter before activations: 1.99 GB for 124.4 million parameters.
The loss at step 0 should be about the log of the vocabulary: 3.530 against 3.5264. A weight spread of 0.02 gives that. A spread of 1.0 starts at 11.944 and lags after 300 steps (1.6655 against 1.0078).
Scale the matrices that write into the stream (Wo and W2) by 1 over the square root of 2 L. The stream's spread then stays between 0.78 and 0.93 from 2 to 96 blocks, against 1.32 to 9.76 without.
Before a long run: check the initial loss, the gradients, and that the model can memorise one batch (3.5296 to 0.0672 in 300 steps).
Common mistakes
Not counting the biases and norms. They are small, but the count will not match the code.
Forgetting the embedding table in a size estimate. For small models with large vocabularies it can be most of the total.
Counting parameters but not memory. Training needs about 16 bytes per parameter, plus the activations.
Starting with large weights. The loss begins far above the log of the vocabulary and training loses steps.
Scaling the whole network equally. The layers that write into the stream need the extra factor.
Tying the embeddings and forgetting the gradient. With a shared matrix, the gradient is the sum from both uses.
Running a long job without testing on one batch first. A hidden bug costs the whole run.
Treating the 0.02 as universal. It suits widths of a few hundred to a few thousand. Other widths want other scales.
Check yourself
1. How many parameters does a block have at d = 64 with a feed-forward factor of 4?
12 × 64² + 13 × 64 = 49,152 + 832 = 49,984.
2. A model has a vocabulary of 32,000, width 1,024, 24 blocks, no learned positions and an untied output matrix. How many parameters?
Embeddings and output matrix: 2 × 32,000 × 1,024 = 65,536,000. One block: 12 × 1,024² + 13 × 1,024 = 12,596,224, so 24 blocks are 302,309,376. Final norm: 2,048. Total 367,847,424.
3. What should the loss be at step 0 for a vocabulary of 50,000?
About ln 50,000 = 10.82.
4. Why scale Wo and W2 by 1 over the square root of 2L?
The stream receives 2L independent additions, so its variance grows in proportion to 2L. Scaling each writer by 1 over the square root of 2L keeps the total variance independent of depth.
5. How much memory does training a 1-billion-parameter model need for the weights, gradients and Adam's two averages in 32-bit numbers?
16 bytes per parameter: 16 GB, before the activations.
6. A model cannot get the loss on a single repeated batch below 2.0. What does that tell you?
There is a bug in the forward pass, the backward pass or the optimiser, since a working model can memorise one batch.
Try this
Set aside two hours. You need Python, NumPy, helpers.py, gpt.py and train.py.
1. Run the parameter count for your own configuration, and check it against sum(w.size for w in p.values()).
2. Tie the output matrix to the embedding table in gpt.py: use E.T as U in the forward pass and add the gradient of U transposed into E's gradient. Check the count and the loss.
3. Run the initial-loss experiment with spreads of 0.005, 0.02 and 0.05 and a model of width 128. Which gives the closest to the log of the vocabulary?
4. Remove the 1 / sqrt(2 L) scaling in initgpt (residscale=False) and train 8 blocks at a learning rate of 0.01. How does the loss at 300 steps compare?
5. Run the memorise-one-batch test with a deliberately broken backward pass (drop a residual term). How does the curve change?
6. Compute the training memory of a 7-billion-parameter model in 32-bit numbers with Adam. How many 80 GB accelerators does the state alone fill?
A good result is a parameter count that matches the code, a starting loss near 3.53, a table of stream spreads for plain and scaled initialisation and a model that memorises one batch. This completes Module 4. We have a GPT that trains and generates. The next module is about training it properly: the loss, the optimiser, learning-rate schedules and reading the curves.
Read more
Alec Radford and colleagues, "Language Models are Unsupervised Multitask Learners" (2019), describes GPT-2, including its scaled initialisation and its tied embeddings. Ofir Press and Lior Wolf, "Using the Output Embedding to Improve Language Models" (2017), analyses weight tying. Andrej Karpathy's "A Recipe for Training Neural Networks" (2019) lists the checks in this lesson: the initial loss, overfitting one batch and verifying shapes.
Tags: Build an LLM Initialisation Parameter count Tensor shapes Transformer