9. Embeddings and the MLP language model
Why this layer exists
Chapter 8’s bigram sees one token back. To see more, the obvious extension is a bigger table: one row of next-token logits for every possible context of tokens. That table has rows. On the tiny corpus, with and , that is rows, of which the training text contains 228; the other 4,685 are never observed and their rows are never trained. With a 50,000-token vocabulary, a two-token context needs rows and a three-token context . The emptiness is the real problem, more than the size. On Persuasion with chapter 7’s 512-token vocabulary there are possible three-token contexts, the 192,498 training tokens contain 76,538 of them, and 27.7% of the three-token contexts in the held-out tenth never occur in the training text at all. For those, a counting model knows nothing.
A table treats every context as unrelated to every other: what it learns about the cat quickly says nothing about the dog quickly. Chapter 2 represented words as vectors built by counting co-occurrences and compared them by angle. This chapter learns the vectors instead. Each token gets a row of numbers, its embedding, trained with the rest of the model; a context is the concatenation of its tokens’ embeddings, and a small network maps that to logits. Tokens that behave alike end up with nearby embeddings, because nearby embeddings produce similar predictions and the loss rewards that, so what the model learns from cat carries over to dog. The parameter count grows linearly in instead of as .
This is the architecture of Bengio and colleagues’ 2003 neural language model, and it is the first model in this book with more than one layer. Every transformer you run has the same two ends: a token-embedding matrix of shape (V, d), which the GGUF specification names token_embd.weight, and usually an output projection back to logits, which it names output.weight. Models with tied embeddings have no separate output matrix and reuse token_embd.weight, transposed, for that projection.
The chapter builds tinygpt.mlp: a trainable Linear layer, the context windows, the model, and the Adam optimizer that trains it and the transformers after it. On the way it derives the initialisation that chapters 3 and 4 deferred to here, and it shows the first gap between training and held-out loss.
Mechanism
The model
The model predicts the token after position from the tokens ending at : . For a batch of ids of shape (B, T):
- Context windows.
context_windows(ids, n, pad)gives an integer array of shape(B, T, n)whose entry[b, t, k]isids[b, t - k], newest first. Positions before the start of the window have no token; they get the idpad, which is , one past the last real token. - Embedding. The embedding table has shape
(V + 1, d): one row per token and one extra row, row , for the pad. The pad row is a learned vector like the others; the model learns what “nothing here yet” should look like. Chapter 8’sembedding(E, ctx)looks up every id and returns shape(B, T, n, d). - Concatenation. Reshaping to
(B, T, n·d)lays the embeddings of each position end to end. Call one position’s result , shape(n·d,). The order is fixed, newest first, so the model knows which embedding came from which distance back. - Hidden layer. with of shape
(n·d, h)and of shape(h,), then , elementwise, both of shape(h,). In the batch,(B, T, n·d)becomes(B, T, h). - Output layer. with of shape
(h, V)and of shape(V,): the logits,(B, T, V)in the batch, which chapter 8’scross_entropyscores against the(B, T)targets.
Both layers are chapter 3’s linear layer, on the last axis, now with Tensor parameters so they train. Every position uses the same , so chapter 6’s _unbroadcast sums its gradient over all positions, the one-edge-per-use rule again. The model keeps the bigram’s interface, (B, T) ids in, (B, T, V) logits out, and parameters(), so chapter 8’s train, evaluate and generate run it unchanged.
Its parameter count is
the embedding table, the hidden layer’s weights and bias, and the output layer’s. For the lab’s model, , , and , that is , against 83,521 entries for a count table over three-token contexts ( rows of 17). The -dependence is in one term, , which is linear in .
Why a non-linearity
Chapter 3 showed that two linear maps in a row are one linear map: without the tanh, , a single (n·d, V) matrix of rank at most and a bias. Split into its embeddings , each of shape (d,), and into the matching blocks of shape (d, V), and the logits are a sum:
each context token adding its own vector of logits, with no way for one token’s contribution to depend on another’s. Since the log-probabilities are the logits minus a normaliser, each context token multiplies the next-token probabilities by its own fixed factors.
Some dependencies cannot be written that way. Take a stream of bits where each bit is the XOR of the previous two, flipped with probability 0.1. The best possible prediction costs the entropy of the flip, nats. A sum of per-token logit vectors cannot represent XOR: it needs the log-odds of a 1 to be positive for the contexts and and negative for and , but with and the contributions of bit in the two slots and the constant, the log-odds for the context is , the first two conditions sum to , and the last two to the same quantity . Trained on 10,800 such bits with the lab’s settings and , MLPLM reaches 0.3550 held out; the same model with the tanh removed reaches 0.6913, a coin flip. The non-linearity lets a hidden unit respond to a combination of context tokens, and the output layer then weights those responses.
The tiny corpus is almost additive in this sense: each dependency in its grammar is on one earlier token at a time, and with the tanh model scores 0.9933 held out and the linear one 1.0006. Chapter 11’s transformer puts a feed-forward block of this shape, project up, apply the non-linearity, project down, in every layer.
Initialisation: the variance of a layer’s output
Chapter 3 drew a layer’s weights uniformly from , where is the input width, and promised the reason. Output coordinate of a layer with zero bias is
Treat the inputs and the weights as independent random variables with mean 0: the weights by construction, the inputs as an assumption about the data. Chapter 4 (“Expectation and variance”) derives the variance of a product of independent mean-zero variables, . For one term, and being independent with mean 0,
The terms are independent of each other, since no two share an or a , and chapter 4 showed that variances of independent terms add. With every input of variance and every weight of variance ,
Weights of variance 1 multiply the input’s variance by the width: with inputs and weights, the output variance measures 14.7, 246.9 and 1,020.8 for widths 16, 256 and 1,024, and a stack of such layers multiplies by the width at every layer. makes the factor 1 whatever the width. The weights’ scale is then , because it is the variance, not the standard deviation, that must be divided by .
The uniform distribution on has mean 0 by symmetry and variance , which chapter 5 (“Continuous random variables”) derives by integrating against the density . With ,
so : one third of the input’s variance, whatever the width. That is the “constant factor” chapter 3 mentioned. test_init_keeps_output_variance_independent_of_width measures it: for unit-variance inputs and widths 16, 256 and 1,024 the output variance is 0.3386, 0.3341 and 0.3328. In a deep stack the factor would compound; chapter 11’s transformer keeps its activations in scale with residual connections and layer normalisation instead of relying on the initialisation alone.
Linear starts its bias at zero, where chapter 3’s, like PyTorch’s nn.Linear, drew it from the same uniform range. The random weights already make the units differ, and a zero bias keeps the pre-activations’ mean at zero, as the derivation assumed.
In the lab’s model, is three concatenated embeddings drawn from , so and the pre-activations should have variance , a standard deviation of 0.577. Measured over the held-out positions at initialisation, it is 0.546: one draw is a sample of the distribution, and the 144 entries of this have a sample variance of 0.916, not 1.
tanh saturation
The derivative of tanh is . With , the quotient rule gives
It is 1 at and falls to 0 as grows: at it is . Backpropagation multiplies the gradient reaching by this derivative on the way to , and from there to , and . A unit whose pre-activation is large is saturated: it outputs whatever its input does, and passes back almost no gradient, so it has trouble learning its way out.
The initialisation decides how many units start there. At the lab’s initialisation, no hidden activation at any held-out position has , and the mean of is 0.804. With the hidden weights ten times larger, the pre-activations’ standard deviation is 5.46, 62.8% of unit activations are saturated and the mean derivative is 0.146. With the embeddings ten times larger as well it is 54.6, 96.2% and 0.0148: almost every unit is a sign function of its input, and the gradient through the hidden layer is 54 times smaller than at the lab’s initialisation. Exercise (c) measures it, and finds that the initial loss hardly shows it.
Where the output layer starts
MLPLM multiplies the output layer’s initial weights by 0.1. Without that, the logits have the scale of : by the derivation above, , and without the factor the logits’ variance across the 17 entries at the lab’s initialisation is 0.056 on average. That sounds small, and it costs something. Expand the per-position loss , with the target, around . Write for the mean of the logits and for their variance across . To second order, , so with . With , and to second order (every other term of the square is of third or fourth order in the logits),
since the mean of the squares minus the square of the mean is the variance. Subtracting ,
The middle term is zero on average over the random draw of the weights but not for any one draw; the last is always positive. Both vanish with the logits. Measured at initialisation on the held-out text, the loss is 2.8998 without the factor, 0.067 above , and 2.8373 with it, 0.004 above. test_mlplm_shapes_and_starts_near_uniform pins the start to within 0.05 of . Chapter 8 said that a first loss far from means the initial logits are not near uniform; this is how to arrange that they are.
The output layer could even start at exactly zero. Chapter 8’s exercise (c) derived , with the (N, h) hidden activations (this chapter’s , stacked over positions) and the (N, V) gradient at the logits, and for the gradient reaching the hidden layer. With random , , so a zero still gets a gradient at step 1, and the hidden layer gets one from step 2; the lab’s model trained from reaches 0.9939 held out, against 0.9933. The symmetry that exercise described needs both layers symmetric at once, every column of equal and every row of equal, so randomness in either layer breaks it. From with random, the gradient differs from unit to unit and the columns of separate at step 1; that run reaches 0.9904. With both at zero every weight gradient is zero and only the biases learn, ending at 2.6073, about the unigram’s level. With each layer at its own constant, the 64 hidden units stay identical throughout and the model ends at 1.3281. One of the two layers must start random; MLPLM makes it the hidden layer, which leaves the output layer free to start small.
The factor 0.1 has a second effect: since the gradient reaching the hidden layer is , every gradient below the output layer starts ten times smaller. On one lab minibatch at initialisation, the root-mean-square gradient entry runs from for and for down to for and for , about 180 times smaller at the bottom of the model than at the top.
Adam
Chapter 8’s SGD moves every parameter by the learning rate times its gradient. With gradients that differ by a factor of 180 between the embedding table and the output bias, one learning rate is too large for some parameters or too small for others. SGD does train this model, but the rate has to be found again: the bigram’s rate of 10 sends it to a held-out loss of 9.7352, far worse than uniform, and a sweep over rates gives, after 300 steps of the lab’s run,
| SGD learning rate | 0.1 | 0.3 | 1 | 3 | 10 | 30 |
|---|---|---|---|---|---|---|
| held-out loss (nats) | 1.1931 | 1.0165 | 1.0028 | 1.0154 | 9.7352 | 51.4478 |
Adam gives each parameter entry its own step size, from running statistics of its own gradient. With the gradient at step , it keeps two exponential moving averages, of the gradient and of its elementwise square, both starting at zero, both the shape of the parameter:
estimates the mean of the gradient, the first moment, and the mean of its square, the second moment. The defaults are , an average over roughly the last 10 steps, and , roughly the last 1,000. The update divides one by the square root of the other, entry by entry:
where the hats are the bias corrections derived next and only prevents division by zero.
Bias correction. Unrolling the recursion from ,
If the gradient is stationary, every with the same expectation , linearity and the geometric series give
The weights of the average sum to , not 1: the missing is the weight still on the zero start. Early on the average is biased toward zero, by a factor of 0.1 at . Dividing it out, , makes the estimate unbiased; likewise . Without the corrections, a constant gradient gives a step of instead of : at step 1, at its peak at step 12, still at step 300, because , with its long memory, stays biased much longer than . The learning rate would mean something different at step 10 and at step 1,000. On the lab’s model, dropping the corrections happens to speed the first steps at and ends at 0.9974 held out against 0.9933; at it is worse from step 10 on and ends at 1.0364 against 1.0007.
The first step is in every coordinate. At , and , so each entry moves by , which is unless is near . test_adam_first_step_moves_each_coordinate_by_lr pins it with gradients of 2, and : all three coordinates move by 0.1. The step’s size no longer depends on the gradient’s scale, only on its direction and consistency. For an entry whose gradient has mean and standard deviation over the recent steps, and , so the step is about
near where the gradient is consistent and small where it is mostly noise. The learning rate is a distance in parameter space per step, a unit that does not depend on how the loss happens to scale each parameter’s gradient.
Badly scaled curvature. Chapter 5 showed that gradient descent on a quadratic is stable only for and that the flattest direction then sets the pace. Take , whose gradient is . A gradient step multiplies by , which has magnitude below 1 only for , and by , which in that range is at least 0.998. After 300 steps at , is and is still 0.5518; at , has grown to 380.
Adam is invariant to the scale of each coordinate’s gradient: multiply one coordinate’s gradients by and scales by , by , and the step does not change. Starting from the two coordinates’ gradients are and , the same sign and a fixed ratio, so Adam moves them identically: both are 0.95 after step 1, 0.1112 after step 20, overshoot to at step 50 as the momentum carries them past 0, and are below after 300 steps. test_adam_minimizes_a_badly_scaled_quadratic requires both below 0.05 after 300 steps at , fifty times the largest rate plain gradient descent survives.
On the MLP the difference is less dramatic than on the quadratic, and it is in speed and tolerance of the learning rate rather than in the final loss. Held-out loss after 300 steps, varying the rate:
| Adam learning rate | 0.001 | 0.003 | 0.01 | 0.03 | 0.1 |
|---|---|---|---|---|---|
| held-out loss (nats) | 1.0831 | 0.9920 | 0.9933 | 1.0007 | 1.0391 |
Too large a rate costs 0.05 nats, where for SGD it cost everything. Against SGD at its best rate, 1, on the same batches, Adam at 0.01 is at 1.0208 after 50 steps and 0.9837 after 100, where SGD is at 1.1545 and 1.0411; SGD catches up by step 600 (0.9891) and after 1,000 steps is at 0.9860 to Adam’s 0.9940. The course uses Adam from here on for those reasons: fewer steps to a good loss, graceful degradation when the rate is too large, and a rate that survives changes to the model that rescale the gradients, as the factor of 0.1 on the output layer did.
Decoupled weight decay. Weight decay shrinks every parameter toward zero a little at each step, a pressure toward small weights that counts against the fit. The classic form adds to the loss, which adds to the gradient; with SGD, the step then includes . With Adam that enters and with the rest of the gradient and is divided by , so parameters with large gradients are decayed less than parameters with small ones, which is not what the penalty meant. Loshchilov and Hutter’s fix is to apply the decay outside the adaptive step:
every entry shrinking by the same fraction per step. This is AdamW, and Adam(..., weight_decay=λ) implements it. Its effect on overfitting is measured below.
Results on the tiny corpus
Held-out loss after the lab’s 300 steps, , , Adam at 0.01, beside the bigram of chapter 8 and counting models whose context is the last tokens (maximum-likelihood tables fitted to the training text and scored on all 1,333 held-out predictions, the first few taking their context from the last training tokens):
| context | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| MLP, held-out loss | 1.3744 | 1.1885 | 0.9933 | 1.0156 |
| counting table, held-out loss | 1.3463 | 1.1699 | 0.9768 | 0.9882 |
| parameters of the MLP | 1,825 | 2,337 | 2,849 | 3,361 |
With the MLP sees what the bigram sees and scores about the same as the trained table’s 1.3689. The gains come from the grammar in make_tiny_corpus.py: determiner, subject, optional adverb, verb, determiner, object, ., with nouns and verbs in two groups, animal and royal, that never mix within a sentence.
- sees one token further back. After an adverb, that token is the subject, which fixes the verb’s group; after a determiner, it says whether a subject (after
., any of six nouns) or an object (after a verb, one of its group’s three) comes next. - resolves the last ambiguity: after a noun, only the token before the determiner says whether the noun was the subject, followed by an adverb or a verb, or the object, followed by
.. Three tokens determine every prediction the grammar makes up to its own randomness. Exercise (e) measures where the gains land. - adds 512 weights and no information, and scores slightly worse. So does the counting table. Every held-out four-token context occurs in the training text, but for 8 held-out predictions the actual next token never followed that context there (
prince . the kingwas never followed byrules), so the maximum-likelihood table gives it probability 0 and an infinite loss; its average leaves those 8 out. A table this specific has seen each context too few times to have seen every successor.
The floor is computable. The grammar’s own probabilities, given the whole history, assign the held-out text 0.9616 nats per prediction; over a long text a sentence carries nats in tokens on average, 0.971 per token. The MLP at is 0.032 above the held-out floor, and a third of that is the scoring: evaluate cuts the text into 21 windows of 64, and the first two positions of each see the pad instead of the real history. Scored as one window, it gets 0.9829.
Overfitting and validation
Take a model with and , 17,201 parameters. Trained on all 11,998 training tokens for 600 steps it ends at 1.0015 on them and 1.0104 held out (exercise (f)). Trained on the first 300 tokens, 299 predictions, as the lab script does, its training loss falls to 0.63 by step 100 and ends at 0.5948, while the held-out loss rises from 2.0197 to 2.3604. The difference between them, the generalisation gap, is 1.77 nats: the model has learned the 300 tokens, not the grammar.
A training loss of 0.59 is below the grammar’s 0.96, which is what memorising looks like. The 300 tokens contain 134 distinct three-token contexts, most seen once or twice, and a counting table fitted to them scores 0.5122 on them: a context seen once is followed by its one successor with probability 1. The model reproduces those frequencies, and on held-out text each confident miss is expensive.
Three things control the gap.
- Validation and early stopping. Held-out loss is the measurement; training loss says only how well the model fits what it has seen. Checked every 10 steps, the 300-token run’s held-out loss is lowest at step 20, 1.3752 with a training loss of 0.8064, and rises from there. Stopping when the held-out loss stops falling, and keeping the parameters from the best point, is early stopping. In practice this needs a third split: if the held-out set chooses when to stop, its loss is no longer an unbiased estimate, and a test set touched only once reports the final number.
- Regularisation. Weight decay trades fit for small weights. On the same 600-step, 300-token run, decoupled weight decay of 0.1, 1 and 3 gives held-out losses of 2.0417, 1.4958 and 1.1936, against 2.3604 without, with training losses of 0.5999, 0.6639 and 0.8858: the pressure toward small weights keeps the model from making the extreme logits that memorising needs.
- Capacity against data. Neither recovers what data gives. The same model trained on 1,000, 3,000 and all 11,998 tokens has gaps of 0.48, 0.07 and 0.009 (exercise (f)). A model with far more parameters than predictions can memorise; the amount of data, not the parameter count alone, decides whether it does.
Walkthrough
The reference module is py/tinygpt/mlp.py.
class Linear:
"""Trainable y = x W + b on the last axis, (..., in) -> (..., out).
Weights are drawn uniformly from [-1/sqrt(in), 1/sqrt(in)] (chapter 3's rule, derived in
this chapter); the bias starts at zero.
"""
def __init__(self, in_features, out_features, rng, bias=True):
bound = 1.0 / np.sqrt(in_features)
self.weight = Tensor(rng.uniform(-bound, bound, size=(in_features, out_features)))
self.bias = Tensor(np.zeros(out_features)) if bias else None
def parameters(self):
return [self.weight] + ([self.bias] if self.bias is not None else [])
def __call__(self, x):
y = x @ self.weight
return y + self.bias if self.bias is not None else y
Chapter 3’s layer with Tensor parameters, a zero bias, and an option to have none. x @ self.weight works on any number of leading axes, (..., in) @ (in, out), and chapter 6’s broadcasting rules sum the weight’s gradient over them. parameters() lists the tensors in a fixed order, weight then bias, which MLPLM.parameters() relies on.
def context_windows(ids, n, pad):
"""For ids (B, T), the n most recent tokens at each position, newest first: (B, T, n).
out[b, t, k] = ids[b, t - k], or pad where t - k < 0.
"""
ids = np.asarray(ids, dtype=np.int64)
B, T = ids.shape
out = np.full((B, T, n), pad, dtype=np.int64)
for k in range(n):
out[:, k:, k] = ids[:, :T - k]
return out
context_windows fills the output with pad and copies the ids in one slot at a time: slot at position holds ids[:, t - k], which exists only for , so out[:, k:, k] = ids[:, :T - k] and the first positions keep the pad. Each row of ids is its own stretch of text, and its start is treated as the start of the history. test_context_windows pins the layout.
class MLPLM:
"""Embed the last n tokens, concatenate, one tanh hidden layer, project to V logits."""
def __init__(self, vocab_size, n, d_embed, d_hidden, rng):
self.n = n
self.pad = vocab_size # an extra embedding row stands for "before the start"
self.embed = Tensor(rng.normal(0.0, 1.0, size=(vocab_size + 1, d_embed)))
self.hidden = Linear(n * d_embed, d_hidden, rng)
self.out = Linear(d_hidden, vocab_size, rng)
self.out.weight.data *= 0.1 # small initial logits: predictions start near uniform
def parameters(self):
return [self.embed] + self.hidden.parameters() + self.out.parameters()
def __call__(self, ids):
ctx = context_windows(ids, self.n, self.pad) # (B, T, n)
e = embedding(self.embed, ctx) # (B, T, n, d_embed)
B, T = ctx.shape[:2]
h = self.hidden(e.reshape(B, T, -1)).tanh() # (B, T, d_hidden)
return self.out(h) # (B, T, V)
The forward pass is the five steps of the mechanism, with the shape of each intermediate in the comments. e.reshape(B, T, -1) is chapter 6’s Tensor.reshape, whose backward pass reshapes the gradient back to (B, T, n, d). embedding then scatter-adds that into , pad row included: the pad gets gradient from the first positions of every training window. The pad is an id like any other, , the index of the extra row, so neither the lookup nor chapter 8’s scatter-add needs a special case for it.
class Adam:
"""Adam: per-coordinate steps from running averages of the gradient and its square."""
def __init__(self, params, lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0):
self.params = list(params)
self.lr, (self.b1, self.b2), self.eps, self.wd = lr, betas, eps, weight_decay
self.m = [np.zeros_like(p.data) for p in self.params]
self.v = [np.zeros_like(p.data) for p in self.params]
self.t = 0
def zero_grad(self):
for p in self.params:
p.grad = np.zeros_like(p.data)
def step(self):
self.t += 1
for p, m, v in zip(self.params, self.m, self.v):
m *= self.b1
m += (1 - self.b1) * p.grad # running mean of g
v *= self.b2
v += (1 - self.b2) * p.grad ** 2 # running mean of g^2
m_hat = m / (1 - self.b1 ** self.t) # undo the bias toward the zero start
v_hat = v / (1 - self.b2 ** self.t)
p.data -= self.lr * (m_hat / (np.sqrt(v_hat) + self.eps) + self.wd * p.data)
Adam keeps and as plain numpy arrays, one pair per parameter, updated in place. The step counter t is shared, since every parameter is updated at every step. m_hat / (np.sqrt(v_hat) + self.eps) is the elementwise quotient of the mechanism; the weight decay term is added inside the same self.lr * (...), which is the decoupled form: it is never seen by m or v. zero_grad is SGD’s, and the optimizer follows the same protocol, so chapter 8’s train takes either.
Exercises
(a) Count the parameters of MLPLM(512, n=4, d_embed=16, d_hidden=128), a model for a 512-token BPE vocabulary, by hand, and check with sum(p.data.size for p in model.parameters()). Which term would a count table over the same contexts need, and which term dominates the MLP?
Answer
The embedding table has rows of : 8,208. The hidden layer maps inputs to units: weights and 128 biases. The output layer maps 128 to 512: weights and 512 biases. The total is .
import numpy as np
from tinygpt.mlp import MLPLM
model = MLPLM(512, n=4, d_embed=16, d_hidden=128, rng=np.random.default_rng(0))
print([p.data.shape for p in model.parameters()])
print(sum(p.data.size for p in model.parameters()))
[(513, 16), (64, 128), (128,), (128, 512), (512,)]
82576
A count table over four-token contexts has rows of 512 entries, numbers. In the MLP the context is one term, ; the output layer’s is 79% of the model. With a real vocabulary the ends of the model, and , both proportional to , dominate a small model’s parameter count, and chapter 11’s count of a transformer keeps them apart from the blocks.
(b) The derivation in the text kept the forward pass’s variance in scale. Derive what a layer does to the variance of the gradient flowing backward through it, and from the two conditions derive Glorot and Bengio’s compromise for a uniform initialisation. Evaluate both factors for the lab’s hidden layer, 24 inputs and 64 outputs, under Glorot’s bound and under Linear’s.
Answer
With and , the gradient reaching input is (chapter 6’s rule for a matrix product, ). It has the same form as the forward sum, over terms instead of , so with independent mean-zero weights and gradients the same argument gives
Keeping both passes in scale needs and , which agree only for a square layer. Glorot and Bengio take the harmonic mean of the two targets, , and with the uniform distribution’s from the text, . For 24 inputs and 64 outputs, , , a forward factor of and a backward factor of : neither is 1, and they straddle it. Linear’s bound, , has , a forward factor of and a backward factor of .
import numpy as np
n_in, n_out = 24, 64 # the lab's hidden layer
rng = np.random.default_rng(0)
x = rng.normal(size=(20000, n_in)) # unit-variance inputs
g = rng.normal(size=(20000, n_out)) # unit-variance gradients at the outputs
for name, a in [("Glorot", np.sqrt(6 / (n_in + n_out))), ("Linear", 1 / np.sqrt(n_in))]:
W = rng.uniform(-a, a, size=(n_in, n_out))
print(f"{name}: a = {a:.4f} forward {(x @ W).var():.3f} backward {(g @ W.T).var():.3f}")
Glorot: a = 0.2611 forward 0.527 backward 1.402
Linear: a = 0.2041 forward 0.334 backward 0.885
Each line is one draw of , so it scatters around the prediction; the mean over 20 draws is 0.546 and 1.452 for Glorot’s bound and 0.334 and 0.887 for Linear’s. In a deep stack of wide-to-narrow and narrow-to-wide layers the two factors compound in opposite passes, which is what the compromise balances. In chapter 11’s transformer the residual connections and layer norms hold the scale instead.
(c) Scale the initial embeddings and hidden weights of the lab’s model by 10. Report the fraction of saturated hidden activations () over the held-out positions, and the initial held-out loss.
Answer
import pathlib
import numpy as np
from tinygpt.mlp import MLPLM, context_windows
from tinygpt.nn import evaluate
tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
test_ids = ids[int(0.9 * len(ids)):]
for scale in [1, 10]:
model = MLPLM(len(vocab), n=3, d_embed=8, d_hidden=64, rng=np.random.default_rng(0))
model.embed.data *= scale
model.hidden.weight.data *= scale
ctx = context_windows(test_ids[None, :], model.n, model.pad) # (1, T, 3)
x = model.embed.data[ctx].reshape(1, len(test_ids), -1) # (1, T, 24)
h = np.tanh(x @ model.hidden.weight.data + model.hidden.bias.data) # (1, T, 64)
print(f"scale {scale:2d} saturated {np.mean(np.abs(h) > 0.99):.4f} "
f"mean tanh' {np.mean(1 - h ** 2):.4f} initial loss {evaluate(model, test_ids, 64):.4f}")
scale 1 saturated 0.0000 mean tanh' 0.8040 initial loss 2.8373
scale 10 saturated 0.9623 mean tanh' 0.0148 initial loss 2.8439
Scaling both the embeddings and the weights multiplies the pre-activations by 100, and 96% of the activations are pinned at . The initial loss barely moves, 2.8439 against 2.8373: tanh bounds the activations at whatever their input, and the output layer’s small weights keep the logits near zero. The loss at step 0 cannot tell you the hidden layer is saturated; the activations can.
The damage shows in training. After the lab’s 300 steps, SGD at a learning rate of 1 reaches 1.1038 held out from the scaled start and 1.0028 from the normal one. Adam reaches 1.0293 and 0.9933: it divides the shrunken gradients by their own shrunken root-mean-square, which recovers much of the step size. It does not unsaturate the units: after training, 99.2% of the scaled model’s activations are saturated, against 10.6% of the normal one’s.
(d) Compute Adam’s and for the first two steps under a constant gradient , and show that the step is both times.
Answer
Step 1: and , so and .
Step 2: , so . In the same way and .
Both steps are , which is up to the , whatever the size of . The pattern holds at every step: , exactly the factor the correction divides out, so under a constant gradient Adam moves by per step forever. With the defaults, 0.9 and 0.999, the uncorrected would be and would be , and the uncorrected step times .
The matters only when is comparable to it. For the test’s gradient of the step is , which differs from 0.1 by .
(e) On the held-out split, find which predictions the MLP () makes better than the bigram, by grouping the per-position losses by the previous word. Connect the result to the grammar in make_tiny_corpus.py.
Answer
import pathlib
import numpy as np
from tinygpt.mlp import MLPLM, Adam
from tinygpt.nn import SGD, Bigram, free_graph, train
tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
cut = int(0.9 * len(ids))
train_ids, test_ids = ids[:cut], ids[cut:]
bigram = Bigram(len(vocab))
train(bigram, SGD(bigram.parameters(), 10.0), train_ids, 300, 16, 32, np.random.default_rng(0))
rng = np.random.default_rng(0)
mlp = MLPLM(len(vocab), n=3, d_embed=8, d_hidden=64, rng=rng)
train(mlp, Adam(mlp.parameters(), 0.01), train_ids, 300, 16, 32, rng)
def losses(model):
"""Per-position held-out loss, the whole split as one window: (1333,)."""
logits = model(test_ids[None, :-1])
z = logits.data[0] # (1333, V)
free_graph(logits)
z = z - z.max(axis=1, keepdims=True)
logp = z - np.log(np.exp(z).sum(axis=1, keepdims=True)) # log-softmax, (1333, V)
return -logp[np.arange(len(z)), test_ids[1:]]
lb, lm = losses(bigram), losses(mlp)
prev = test_ids[:-1]
rows = []
for w in range(len(vocab)):
at = prev == w
rows.append((lb[at].mean() - lm[at].mean(), vocab[w], at.sum(), lb[at].mean(), lm[at].mean()))
print(f"{'previous':9s} {'count':>5s} {'bigram':>7s} {'MLP':>7s} {'saved':>7s}")
for saved, w, count, b, m in sorted(rows, reverse=True):
print(f"{w:9s} {count:5d} {b:7.4f} {m:7.4f} {saved:+7.4f}")
previous count bigram MLP saved
bird 67 1.3703 0.6396 +0.7307
queen 57 1.4685 0.7708 +0.6977
quietly 78 1.8157 1.1192 +0.6965
king 86 1.4368 0.7495 +0.6874
quickly 66 1.8244 1.1441 +0.6803
prince 88 1.4382 0.7657 +0.6726
dog 52 1.3655 0.7064 +0.6591
cat 47 1.4167 0.7600 +0.6567
a 203 1.8262 1.4084 +0.4178
the 193 1.8078 1.4733 +0.3345
sniffs 28 0.6436 0.5667 +0.0769
chases 27 0.7454 0.6876 +0.0578
summons 36 0.7132 0.6959 +0.0173
commands 35 0.7025 0.6949 +0.0075
rules 44 0.7658 0.7984 -0.0326
. 198 0.6966 0.7298 -0.0332
bites 28 0.7079 0.8068 -0.0990
The whole gain is in three places, and each is a dependency more than one token long.
- After a noun. After a subject the next token is
quietlyorquickly(1/3 each) or one of the group’s three verbs (1/9 each), an entropy of nats; after an object it is., entropy 0. Half the nouns are subjects, so a model that tells them apart, from the token before the determiner, pays about ; the MLP pays 0.64 to 0.77. The bigram pays the entropy of the mixture, . - After an adverb. The verb’s group is the subject’s, two tokens back. The MLP pays about (1.12 and 1.14); the bigram, not knowing the group, about (1.82).
- After a determiner. A subject is any of six nouns (), an object one of the verb’s group’s three (), and the token before the determiner says which. The average is 1.445; the MLP pays 1.41 and 1.47, the bigram about .
After . and after a verb the next token is the or a, 1/2 each, whatever came before: is the floor for any model, and the differences there, up to 0.1 nats either way, are noise on groups of 27 to 198 predictions.
(f) Repeat the overfitting experiment with 300, 1,000, 3,000 and all 11,998 training tokens, and tabulate the final generalisation gap.
Answer
import pathlib
import numpy as np
from tinygpt.mlp import MLPLM, Adam
from tinygpt.nn import evaluate, train
tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
cut = int(0.9 * len(ids))
train_ids, test_ids = ids[:cut], ids[cut:]
print(f"{'tokens':>6s} {'train':>7s} {'held-out':>8s} {'gap':>7s}")
for size in [300, 1000, 3000, len(train_ids)]:
rng = np.random.default_rng(0)
model = MLPLM(len(vocab), n=3, d_embed=16, d_hidden=256, rng=rng)
subset = train_ids[:size]
train(model, Adam(model.parameters(), 0.01), subset, 600, 16, 32, rng)
tr, ho = evaluate(model, subset, 64), evaluate(model, test_ids, 64)
print(f"{size:6d} {tr:7.4f} {ho:8.4f} {ho - tr:7.4f}")
tokens train held-out gap
300 0.5948 2.3604 1.7656
1000 0.8398 1.3170 0.4772
3000 0.9452 1.0159 0.0707
11998 1.0015 1.0104 0.0089
It takes about 20 seconds on talos. Only the data changes between rows. More data raises the training loss, since less of it can be memorised, and lowers the held-out loss, until at 3,000 tokens both are near the grammar’s 0.96 and the gap is 0.07; with all the data it is 0.009. The full run’s held-out 1.0104 is worse than the smaller lab model’s 0.9933: the extra capacity costs training steps and buys nothing on this grammar.
Lab
Implement every function and class in py/labs/ch09/starter.py, following its docstrings; the tests use the attribute names and the order of MLPLM.parameters() given there. Run
make lab CH=09 IMPL=mine
until it passes. Read py/labs/ch09/test_lab.py first. It gradchecks Linear and the whole model; pins the initialisation, the window layout, the near-uniform start and the two Adam properties derived above; requires the 300-token run to overfit by more than a nat; and has the acceptance test, test_mlp_beats_bigram_on_held_out_loss: after 300 steps each, the MLP must beat the bigram held out by at least 0.3 nats.
Then compare the models and watch one overfit. Save this script outside the repository, for example as /tmp/mlp_lab.py:
import pathlib
import numpy as np
from tinygpt.mlp import MLPLM, Adam
from tinygpt.nn import SGD, Bigram, evaluate, train
tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
cut = int(0.9 * len(ids))
train_ids, test_ids = ids[:cut], ids[cut:]
bigram = Bigram(len(vocab))
train(bigram, SGD(bigram.parameters(), 10.0), train_ids, 300, 16, 32, np.random.default_rng(0))
print(f"bigram held-out {evaluate(bigram, test_ids, 64):.4f}")
for n in [1, 2, 3, 4]:
rng = np.random.default_rng(0)
mlp = MLPLM(len(vocab), n=n, d_embed=8, d_hidden=64, rng=rng)
train(mlp, Adam(mlp.parameters(), 0.01), train_ids, 300, 16, 32, rng)
print(f"MLP n={n} held-out {evaluate(mlp, test_ids, 64):.4f}")
print("overfitting: 300 training tokens, 16-dim embeddings, 256 hidden units")
rng = np.random.default_rng(0)
mlp = MLPLM(len(vocab), n=3, d_embed=16, d_hidden=256, rng=rng)
opt = Adam(mlp.parameters(), 0.01)
small = train_ids[:300]
for step in range(100, 601, 100):
train(mlp, opt, small, 100, 16, 32, rng)
print(f"step {step} train {evaluate(mlp, small, 64):.4f} held-out {evaluate(mlp, test_ids, 64):.4f}")
and run it from py/ with OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/mlp_lab.py; it takes about 20 seconds on talos (an Intel i3-1315U laptop). Change the import to from labs.ch09.starter import MLPLM, Adam to run yours. The reference prints:
bigram held-out 1.3689
MLP n=1 held-out 1.3744
MLP n=2 held-out 1.1885
MLP n=3 held-out 0.9933
MLP n=4 held-out 1.0156
overfitting: 300 training tokens, 16-dim embeddings, 256 hidden units
step 100 train 0.6262 held-out 2.0197
step 200 train 0.6142 held-out 2.1585
step 300 train 0.6170 held-out 2.2134
step 400 train 0.5878 held-out 2.2471
step 500 train 0.5962 held-out 2.2809
step 600 train 0.5948 held-out 2.3604
An implementation that draws its initial weights with the calls the starter’s docstrings name, in the same order (embedding, hidden weight, output weight), draws the same weights and the same batches, so it should print the same numbers, up to the last digit where a valid reordering of floating-point operations rounds differently.
- The bigram line is chapter 8’s lab.
MLP n=1has the same information, one token, factored through an 8-dimensional embedding and 64 hidden units instead of a free table, and ends 0.006 nats worse. - The drop from to , 0.38 nats, is the grammar’s longer dependencies, which exercise (e) takes apart.
- The overfitting run is past its best before its first line. Its held-out loss was lowest at step 20, 1.3752. From step 100 on the training loss barely moves while the held-out loss climbs at every checkpoint: the model grows more confident about the 300 tokens it has, and pays for that on every held-out prediction it gets wrong.
Further reading
- Yoshua Bengio, Réjean Ducharme, Pascal Vincent and Christian Jauvin, “A Neural Probabilistic Language Model”, Journal of Machine Learning Research 3 (2003). The model of this chapter: learned word vectors, concatenated over a fixed context, a tanh hidden layer and a softmax output, with the curse-of-dimensionality argument against count tables. It also adds direct connections from the embeddings to the output, which
MLPLMomits. - Xavier Glorot and Yoshua Bengio, “Understanding the difficulty of training deep feedforward neural networks”, AISTATS (2010). The variance argument of this chapter applied to both the forward and the backward pass, measurements of saturation in deep tanh and sigmoid networks, and the initialisation that bears Glorot’s name.
- Diederik P. Kingma and Jimmy Ba, “Adam: A Method for Stochastic Optimization”, ICLR (2015). The algorithm, the bias-correction derivation, and the invariance to rescaled gradients.
- Ilya Loshchilov and Frank Hutter, “Decoupled Weight Decay Regularization”, ICLR (2019). Why an L2 penalty and weight decay differ under Adam, and AdamW.
- Ian Goodfellow, Yoshua Bengio and Aaron Courville, Deep Learning (MIT Press, 1st ed., 2016), chapter 7 (regularisation: parameter norm penalties, early stopping, the role of validation data) and chapter 8 (optimisation: parameter initialisation strategies, and algorithms with adaptive learning rates, Adam among them).