8. The bigram model and the training loop

Why this layer exists

A bigram model predicts the next token from the current one alone. It is too weak to be useful as a language model. It is here as the smallest model that is trained exactly as a transformer is trained: token ids in, a (B, T, V) array of logits out, a softmax cross-entropy against the tokens that actually came next, one backward pass, one parameter update, repeated on random minibatches of the training text until the loss stops falling. Everything in that sentence except the model is the same for the next-token models of chapters 9 to 11. Chapter 9 replaces the table with an MLP and SGD with Adam, chapter 11 replaces the MLP with a transformer built on chapter 10’s attention, and both train with this chapter’s train and score with its evaluate. Chapter 13’s chat fine-tune runs the same loop with a mask on the loss. Chapter 50’s QLoRA run on dixie is the same loop, run by a framework on a GPU.

The loop’s output is a loss curve, the thing you watch in any training run: whether the run is learning, whether the learning rate is too high, whether the model still improves on text it has not seen. The bigram model makes the baselines exact, since its best possible table can be computed by counting.

This chapter builds tinygpt.nn: two new Tensor operations, the embedding lookup and the fused cross-entropy chapter 6 promised; an optimizer; the batching, training and evaluation functions; the model; and a sampler. It also adds free_graph, which chapter 6’s engine needs before it can train anything for long.

Mechanism

The objective: predict the next token

A language model assigns a probability to every sequence of tokens x1,…,xnx_1, \ldots, x_n. Chapter 4 (“Joint entropy, conditional entropy and mutual information”) derives the chain rule of probability, peeling the last variable off a joint with the definition of the conditional and repeating on what is left, so any such sequence has probability

p(x1,…,xn)=p(x1)∏t=2np(xt∣x<t), p(x_1, \ldots, x_n) = p(x_1) \prod_{t=2}^{n} p(x_t \mid x_{<t}) ,

where x<tx_{<t} is shorthand for x1,…,xt−1x_1, \ldots, x_{t-1}. Nothing has been assumed: any distribution over sequences factors this way. So a model of sequences can be built from a model of the next token given the ones before, and that is the only thing a GPT-style model computes. At each position it outputs a distribution over the VV vocabulary entries for the token that comes next.

The bigram assumption is that the next token depends on the current one and nothing earlier: p(xt∣x<t)=p(xt∣xt−1)p(x_t \mid x_{<t}) = p(x_t \mid x_{t-1}). This is a first-order Markov chain over tokens. For the grammar that generated py/data/tiny-corpus.txt it is exact in places, since what follows . (the or a, one half each) does not depend on anything before it, and a bad approximation elsewhere: after cat, a verb is allowed only if the sentence does not already have one, and after the, any of six nouns may follow at the start of a sentence but only the verb’s group’s three after a verb. The bigram cannot know either.

Training maximises the log-likelihood of the training text under the model. By the chain rule the log of the product is a sum over positions, and dividing by the number of predictions NN turns the negative of it into a mean,

L=−1N∑tlogpθ(xt∣xt−1), L = -\frac{1}{N} \sum_{t} \log p_\theta(x_t \mid x_{t-1}) ,

which is chapter 4’s cross-entropy with a one-hot target at each position, averaged over positions. A token stream of N+1N + 1 tokens gives NN predictions: every token except the first is a target, and the token before it is the input. The first factor, p(x1)p(x_1), is dropped; in a long stream it is one term among thousands.

A table of logits

With a vocabulary of VV tokens the bigram model is a table W\mathbf{W} of shape (V, V). Row aa, written wa\mathbf{w}_a, shape (V,), holds the logits of the next token when the current token is aa:

pθ(b∣a)=softmax(wa)b=eWab∑j=1VeWaj. p_\theta(b \mid a) = \mathrm{softmax}(\mathbf{w}_a)_b = \frac{e^{W_{ab}}}{\sum_{j=1}^{V} e^{W_{aj}}} .

On the tiny corpus, split on whitespace rather than by chapter 7’s BPE so that each token is a word and every entry of the table can be read as a word pair, V=17V = 17 and the table has 289 parameters. BPE returns in exercise (f) and in chapter 11.

This problem has a closed-form answer, and it is chapter 4’s. Group the NN training predictions by their input token. The NaN_a predictions whose input is aa involve only row aa, and no other prediction does, so the log-likelihood is a sum of VV independent terms, one per row, and each row is a categorical distribution fitted to the tokens that followed aa. Chapter 4 derived the maximum-likelihood estimate of a categorical: the empirical frequencies. With nabn_{ab} the number of times bb follows aa in the training text, the best row is p^(b∣a)=nab/Na\hat{p}(b \mid a) = n_{ab} / N_a. That is the counting bigram. Chapter 4’s add-one smoothing adds 1 to every nabn_{ab} before normalising.

Training by gradient descent heads for the same place. Write the loss by rows. With p^a\hat{\mathbf{p}}_a, shape (V,), the empirical next-token distribution after aa, p^a,b=nab/Na\hat{p}_{a,b} = n_{ab} / N_a, and eb\mathbf{e}_b the one-hot vector of bb,

L=1N∑a=1V∑t:xt−1=a−logsoftmax(wa)xt. L = \frac{1}{N} \sum_{a=1}^{V} \sum_{t:\, x_{t-1} = a} -\log \mathrm{softmax}(\mathbf{w}_a)_{x_t} .

Chapter 6 derived the gradient of one term with respect to its logits, the fused softmax–cross-entropy rule: softmax(wa)−ext\mathrm{softmax}(\mathbf{w}_a) - \mathbf{e}_{x_t}. Row aa appears only in the NaN_a terms whose input is aa, so

∂L∂wa=1N∑t:xt−1=a(softmax(wa)−ext)=NaN(softmax(wa)−p^a), \frac{\partial L}{\partial \mathbf{w}_a} = \frac{1}{N} \sum_{t:\, x_{t-1} = a} \big( \mathrm{softmax}(\mathbf{w}_a) - \mathbf{e}_{x_t} \big) = \frac{N_a}{N} \Big( \mathrm{softmax}(\mathbf{w}_a) - \hat{\mathbf{p}}_a \Big) ,

shape (V,). The second step pulls out NaN_a copies of the softmax, which does not depend on tt, and uses ∑t:xt−1=aext=Nap^a\sum_{t:\,x_{t-1}=a} \mathbf{e}_{x_t} = N_a\, \hat{\mathbf{p}}_a: summing one-hot vectors counts. Stacked over rows, the gradient with respect to W\mathbf{W} is (V, V).

Two things follow. The gradient can vanish only where softmax(wa)=p^a\mathrm{softmax}(\mathbf{w}_a) = \hat{\mathbf{p}}_a for every row that occurs, and any such point is a global minimum, not a saddle, because the loss is convex in each row. Exercise (e) differentiates the row gradient once more and finds row aa’s block of the Hessian, Ha=NaN(diag(pa)−papa⊤)\mathbf{H}_a = \frac{N_a}{N}\big(\mathrm{diag}(\mathbf{p}_a) - \mathbf{p}_a\mathbf{p}_a^\top\big), shape (V, V), with pa=softmax(wa)\mathbf{p}_a = \mathrm{softmax}(\mathbf{w}_a). For any direction v\mathbf{v}, shape (V,),

v⊤Hav=NaN(∑ipa,ivi2−(∑ipa,ivi)2)=NaNVarpa(v)≥0, \mathbf{v}^\top \mathbf{H}_a \mathbf{v} = \frac{N_a}{N} \Big( \sum_i p_{a,i} v_i^2 - \big( \sum_i p_{a,i} v_i \big)^2 \Big) = \frac{N_a}{N} \, \mathrm{Var}_{\mathbf{p}_a}(v) \ge 0 ,

chapter 4’s E[X2]−E[X]2\mathbb{E}[X^2] - \mathbb{E}[X]^2 for a variable that takes the value viv_i with probability pa,ip_{a,i}. So along any line wa+sv\mathbf{w}_a + s\mathbf{v} the loss has a non-negative second derivative in ss, which is chapter 4’s convexity (“Convexity and Jensen’s inequality”): the first derivative never decreases, and by chapter 4’s tangent-line inequality a point where the first derivative is zero is the lowest point of the line. The same holds for the whole table: the loss is a sum of one term per row, each depending on its own row alone, so along a line in the full (V, V) table the second derivative is the sum of the rows’ second derivatives, each non-negative. A point where the whole gradient is zero is the lowest point of every line through it, a global minimum. (Chapter 12 meets the same variance, of the logits, as the rate at which entropy changes with temperature.) The minimum is unique as a distribution, not as a table: adding a constant to every entry of a row leaves its softmax unchanged, so each row’s logits are determined only up to an additive constant. And each row’s gradient is weighted by Na/NN_a / N, the fraction of training positions whose input is aa: frequent tokens’ rows move fast, rare tokens’ rows slowly, with one learning rate for all.

On this corpus no finite table reaches that point. The counting solution has zeros: of the 289 pairs, 215 never occur in the training text, since the grammar forbids them, and every row has some. A softmax is never exactly 0, so the gradient never vanishes: the loss only approaches its infimum as those logits go to −∞-\infty, and gradient descent follows them down without arriving. After the lab’s 300 steps, no row puts more than 2.9% of its probability on successors it never saw.

Zero initialisation. The model starts with W=0\mathbf{W} = \mathbf{0}. Every row is then a uniform distribution, softmax(0)b=1/V\mathrm{softmax}(\mathbf{0})_b = 1/V, and every prediction costs −log(1/V)=logV-\log(1/V) = \log V nats, so the initial loss is exactly log17=2.833\log 17 = 2.833. test_bigram_starts_uniform and the first loss of test_bigram_training_matches_counting pin it. A first loss far from logV\log V in any language model means the initial logits are not near uniform, which is worth knowing before step 2.

Embedding lookup is a matrix product

The forward pass of the bigram model is a row lookup: for input ids of shape (B, T), the logits are W[ids], shape (B, T, V). Chapter 9 does the same with a table of shape (V, d) and calls it an embedding: each id selects its row of dd numbers. embedding(weight, ids) is one operation for both.

Chapter 6’s engine has no lookup operation, but it has a matrix multiply, and the lookup is one. Flatten the ids to a vector of n=BTn = BT entries and build the one-hot matrix X\mathbf{X}, shape (n, V), with Xir=1X_{ir} = 1 if idsi=r\text{ids}_i = r and 0 otherwise. Then Y=XW\mathbf{Y} = \mathbf{X}\mathbf{W}, shape (n, d), has row ii

Yi⋅=∑r=1VXirWr⋅=Widsi⋅, Y_{i\,\cdot} = \sum_{r=1}^{V} X_{ir}\, W_{r\,\cdot} = W_{\text{ids}_i\,\cdot} ,

since exactly one term of the sum survives. Chapter 6 derived the backward rule of Y=XW\mathbf{Y} = \mathbf{X}\mathbf{W}: W¯=X⊤Y¯\bar{\mathbf{W}} = \mathbf{X}^\top \bar{\mathbf{Y}}, shape (V, n) times (n, d), which is (V, d). Its row rr is

W¯r⋅=∑i=1nXirY¯i⋅=∑i:idsi=rY¯i⋅: \bar{W}_{r\,\cdot} = \sum_{i=1}^{n} X_{ir}\, \bar{Y}_{i\,\cdot} = \sum_{i:\, \text{ids}_i = r} \bar{Y}_{i\,\cdot} :

the sum of the output gradients of every position that selected row rr. A row selected three times receives three gradients, added; a row never selected receives nothing. This is the one-edge-per-use rule of chapter 6’s chain rule, and it is a scatter-add: walk the positions, add each position’s gradient into the row its id names.

Building X\mathbf{X} would cost nVdnVd multiply-adds forward and backward, almost all of them multiplications by 0; the lookup and the scatter-add cost ndnd. The reference computes the forward pass as weight.data[ids] and the backward pass as np.add.at(weight.grad, ids, out.grad). The obvious alternative, weight.grad[ids] += out.grad, is wrong, and silently so. numpy evaluates it as a read of weight.grad[ids], an addition, and a write back to the same indices, and when an index repeats, the writes to it overwrite each other and the last one wins. With a zero array g of three entries, g[[0, 0, 1]] += [1, 2, 3] leaves g as [2, 3, 0]; np.add.at(g, [0, 0, 1], [1, 2, 3]) gives [3, 3, 0]. In real text the common tokens repeat many times per batch, so the bug drops most of the gradient of the rows that matter most. test_embedding_gradcheck_with_repeated_ids uses a row three times so that a gradcheck catches it.

The fused cross-entropy over a batch

The model’s output is (B, T, V) logits and the targets are (B, T) ids. Flatten both: Z\mathbf{Z} of shape (N, V) with N=BTN = BT, and targets tit_i. The loss is the mean over positions of the per-position cross-entropy. Chapter 13 needs to leave some positions out of that mean: a chat transcript trains the model on the assistant’s replies, not on the user turns it is conditioned on. So a target of −1-1 marks a position to ignore. With KK the set of kept positions and n=∣K∣n = \lvert K \rvert,

L=1n∑i∈K−logsoftmax(zi)ti. L = \frac{1}{n} \sum_{i \in K} -\log \mathrm{softmax}(\mathbf{z}_i)_{t_i} .

The forward pass computes each row’s log-softmax directly, as chapter 4 did: with mi=maxjzijm_i = \max_j z_{ij},

logsoftmax(zi)j=(zij−mi)−log∑k=1Vezik−mi, \log \mathrm{softmax}(\mathbf{z}_i)_j = (z_{ij} - m_i) - \log \sum_{k=1}^{V} e^{z_{ik} - m_i} ,

shape (N, V), where every exponent is at most 0 and the sum is at least 1, so nothing overflows and the log never sees 0.

The backward pass is chapter 6’s fused softmax–cross-entropy gradient, applied row by row. Row i∈Ki \in K appears in one term of the sum, with weight 1/n1/n, so

∂L∂zi=1n(softmax(zi)−eti)(i∈K),∂L∂zi=0(otherwise), \frac{\partial L}{\partial \mathbf{z}_i} = \frac{1}{n} \big( \mathrm{softmax}(\mathbf{z}_i) - \mathbf{e}_{t_i} \big) \quad (i \in K), \qquad \frac{\partial L}{\partial \mathbf{z}_i} = \mathbf{0} \quad (\text{otherwise}),

each of shape (V,), stacked to (N, V) and reshaped back to (B, T, V). The divisor is nn, the number of kept positions, not NN: an ignored position is not a prediction the model got right for free, it is not a prediction at all, and dividing by NN would make the loss of a batch depend on how much of it was masked. If every target is −1-1 there is nothing to average, and cross_entropy raises ValueError rather than divide by zero.

Fused, the loss holds one (N, V) intermediate, the log-softmax, where chapter 6 exercise (f)’s composed version held five and turned an underflowed probability into inf and nan. test_cross_entropy_is_stable_for_extreme_logits pins that case: logits (0,−800)(0, -800) with target 1 give a loss of exactly 800 and a gradient of (1,−1)(1, -1).

Minibatches

The full-data gradient on the tiny corpus is a sum over 11,997 predictions, cheap here and not for a transformer on a real corpus. Instead each step computes the gradient on a minibatch: BB random windows of T+1T + 1 consecutive tokens, the first TT as inputs x\mathbf{x}, shape (B, T), and the last TT as targets y\mathbf{y}, the same window shifted by one. get_batch draws the window starts uniformly.

The minibatch gradient is an unbiased estimate of the full-data gradient. Take the simplest sampler: draw one prediction II uniformly from the NN, so P(I=i)=1/NP(I = i) = 1/N, and use its gradient ∇ℓI\nabla \ell_I. By the definition of expectation,

E[∇ℓI]=∑i=1N1N∇ℓi=∇(1N∑i=1Nℓi)=∇L, \mathbb{E}\big[\nabla \ell_I\big] = \sum_{i=1}^{N} \frac{1}{N}\, \nabla \ell_i = \nabla \Big( \frac{1}{N} \sum_{i=1}^{N} \ell_i \Big) = \nabla L ,

where the middle step moves the gradient outside a finite sum. The mean of BB such draws has the same expectation, by linearity. Each step follows the full gradient on average, with noise around it.

The noise shrinks with BB. If the BB draws are independent and one draw’s gradient has variance σ2\sigma^2 per coordinate, chapter 4’s result for averages gives the minibatch mean variance σ2/B\sigma^2 / B per coordinate, so its expected squared distance from ∇L\nabla L, summed over coordinates, falls as 1/B1/B. Measured on the tiny corpus at the zero table, over 2,000 minibatches of windows of 16 for each batch size, E∥gB−∇L∥2\mathbb{E}\lVert \mathbf{g}_B - \nabla L \rVert^2 times BB is 0.0514, 0.0509, 0.0514 and 0.0511 for B=1,4,16,64B = 1, 4, 16, 64: flat, so the squared error is proportional to 1/B1/B. Quadrupling the batch halves the noise’s standard deviation and quadruples the cost of the step. Exercise (b) proves that get_batch’s windows are unbiased too, and for which objective.

Gradient descent on minibatch gradients is stochastic gradient descent, SGD. Its update is chapter 5’s, with the noisy gradient, for the parameters θ\theta (here the (V, V) table) and their minibatch gradient gB\mathbf{g}_B of the same shape:

θ←θ−ηgB. \theta \leftarrow \theta - \eta\, \mathbf{g}_B .

Zeroing gradients

Chapter 6 made leaf gradients accumulate across backward() calls, so that several micro-batches can be summed into one step, and warned that every training loop must therefore zero the parameters’ gradients before each step’s backward pass. train calls opt.zero_grad() before building each step’s graph.

Without it, the gradient in .grad at step tt is the sum of every step’s gradient so far, Gt=∑s≤tgs\mathbf{G}_t = \sum_{s \le t} \mathbf{g}_s, and the update subtracts ηGt\eta \mathbf{G}_t. That is heavy-ball momentum with a momentum coefficient of 1: the velocity never decays. While consecutive gradients point the same way, as they do early on, the steps grow linearly and the loss falls faster than with correct steps. Once the parameters pass the minimum, the new gradients point back, but they have to cancel the whole accumulated sum before the direction of travel reverses, so the parameters overshoot by as much as they gained. test_training_without_zero_grad_does_worse trains two bigram models for 100 steps on the same batches, one with zero_grad a no-op: held out, 1.4116 nats against 1.9128. Exercise (d) takes the numbers apart.

The learning rate

Each row’s gradient is scaled by Na/NN_a / N, at most 0.153 on the tiny corpus (for a; 0.150 for .), and its softmax difference is at most 1 per entry, so the gradients are small and the learning rate is large by chapter 5’s standards. Held-out loss after 300 steps of the lab’s run, varying only the learning rate:

learning rate 1 5 10 20 50 100
held-out loss (nats) 1.5588 1.3870 1.3689 1.3668 1.5508 2.2848

At 1 the rows are still moving toward their targets after 300 steps. From 5 to 20 the runs finish close together. At 50 and above the loss is worse again, and at 200 it ends at 5.81, twice the uniform model’s. Chapter 5 explained the upper side: a step size beyond 2 divided by the curvature makes the steepest direction overshoot by more than it corrects. Exercise (e) computes that curvature for this problem and finds the edge, at a learning rate of 26.6.

Held-out evaluation

evaluate(model, ids, context) returns the mean cross-entropy of predicting every token of a stream after the first, each exactly once, scored in consecutive windows of context inputs. A model that conditions on history sees at most context tokens of it; the bigram needs one.

The split is chapter 4’s: the first 90% of the tiny corpus’s 13,332 tokens for training (11,998) and the last 10% held out (1,334, so 1,333 predictions). On that split:

model held-out cross-entropy perplexity
uniform over 17 words 2.8332 17
unigram, maximum likelihood (chapter 4) 2.6091 13.59
bigram, counting with add-one 1.3640 3.9119
bigram, counting, maximum likelihood 1.3463 3.8431
bigram, trained 300 steps (the lab) 1.3689 3.9310

Chapter 4 quoted 3.91 for the add-one bigram; to four places it is 3.9119. The trained table, after 300 steps, is 0.005 nats behind it; continuing at a learning rate of 20 it reaches 1.3570 after 3,000 steps and 1.3521 after 10,000 (straylight), hovering near the unsmoothed counting solution, which constant-step minibatch SGD approaches but does not settle on. Here the unsmoothed solution scores better held out than the add-one one, because every pair in the held-out text occurs in the training text, so smoothing only moves probability onto pairs the grammar forbids. No bigram model can score below 1.3153 on this held-out text, the entropy of its own next-token frequencies given the previous token: that is Gibbs’ inequality from chapter 4, applied row by row.

Loss curves of the bigram lab run Cross-entropy in nats per token against training step, 0 to 300, for a bigram model trained on the tiny corpus with learning rate 10 and batches of 32 windows of 16 tokens. Two dashed reference lines: the uniform model at log 17 = 2.833 and the counting add-one bigram's held-out loss at 1.364. The training loss of each step starts at 2.833, falls below 1.6 within about 25 steps, and then fluctuates between about 1.34 and 1.48 as it levels off. The held-out loss, marked every 25 steps, falls from 2.833 to 1.596 at step 25, 1.412 at step 100, and 1.369 at step 300, just above the counting model's line. 1.2 1.6 2.0 2.4 2.8 0 50 100 150 200 250 300 training step cross-entropy, nats per token uniform, log 17 = 2.833 counting add-one bigram, held out: 1.364 training loss, every step held-out loss, every 25 steps

The figure is the lab’s run. The thin line is the training loss of each step, each on a different minibatch of 512 predictions, so it is noisy: after step 50 it ranges from 1.34 to 1.48. The dots are evaluate on the held-out text every 25 steps, the same 1,333 predictions every time, so they are smooth. The training line and the held-out dots end close together, with no gap between them: the model has 289 parameters and every row is estimated from at least 275 training occurrences of its token, so there is nothing it could memorise. Chapter 9’s larger model is where the gap opens.

Graph lifetime

Chapter 6’s engine records every operation’s output with a _backward closure, and the closure refers to the output: backward reads out.grad, so out is a variable of the enclosing function that the closure captures. The output refers to the closure through out._backward. That is a reference cycle, in every non-leaf node of every graph: node, closure, the cell holding out, node. CPython frees most objects by reference counting, the moment their count reaches zero, and the count of an object in a cycle never does. Only the separate cycle collector can free it.

The cycle collector runs when the number of container objects allocated minus those freed since the last collection passes a threshold, 2,000 by default (gc.get_threshold() returns (2000, 10, 10) on Python 3.14). It counts objects, not bytes. A training step of the bigram model creates about 18 tracked objects that the cycles keep alive, measured by counting gc.get_objects() over 100 steps with the collector disabled, so the collector runs about once every 110 steps. Everything reachable from those 18 objects lives until then: the logits, their gradient and the log-softmax that the cross-entropy’s closure holds.

For the lab model on the tiny corpus those are 70 KB arrays and nothing is noticed. For exercise (f)’s model, a bigram over chapter 7’s 512-token vocabulary with B=32B = 32 and T=64T = 64, each of the three is 32×64×51232 \times 64 \times 512 float64 values, 8.4 MB, so each step abandons about 25 MB, and 110 steps of it is about 2.8 GB. Measured over 200 training steps of that model, peak resident memory is 2,944 MB without free_graph (the collector ran twice) and 90 MB with it. A transformer’s graph holds far more than three arrays per step.

free_graph(root) breaks the cycles when a step is done with its graph. It walks back from the loss and, on every node that has parents, replaces _backward with a no-op and _parents with an empty tuple. The closure is gone, so each node’s reference count falls to zero as soon as the training loop drops its last name for it, and reference counting frees the whole graph at once. Leaves, the parameters, have no parents and are not touched, so their .grad survives; the root can no longer backpropagate. PyTorch makes the same decision by default: loss.backward() frees the graph’s saved intermediate values as it goes, and a second backward pass through the same graph raises an error unless the first was called with retain_graph=True. Here it is a separate call because chapter 6’s engine promises the opposite (a second backward() accumulates, and its tests require that to keep working), so train, evaluate and generate each call free_graph when their graph is finished. test_free_graph_releases_intermediates_without_the_cycle_collector disables the collector and checks both sides: a node survives del without free_graph and is freed with it.

Sampling

The chain rule of probability that defined the objective also generates text. To draw a sequence from p(x1,…,xn)=p(x1)∏tp(xt∣x<t)p(x_1, \ldots, x_n) = p(x_1) \prod_t p(x_t \mid x_{<t}), draw the first token, then draw each next token from the model’s conditional distribution given everything drawn so far, append it, and repeat. The product of the conditional probabilities of the draws is the probability of the whole sequence, so the sequence is an exact sample from the model’s joint distribution. This is ancestral sampling. generate starts from a prompt instead of a sampled first token, and conditions on it.

For the bigram model each draw is one row of the table passed through a softmax. Chapter 12 adds the controls a real sampler has, temperature, top-k, top-p and min-p, and the KV cache that avoids recomputing the whole context at every step.

Walkthrough

The reference module is py/tinygpt/nn.py.

def embedding(weight, ids):
    """Rows of weight, shape (V, d), selected by integer ids of any shape (...): result (..., d)."""
    ids = np.asarray(ids, dtype=np.int64)
    out = Tensor(weight.data[ids], (weight,), "embedding")

    def backward():
        # Row r was copied once per occurrence of r in ids; its gradient sums those copies.
        np.add.at(weight.grad, ids, out.grad)

    out._backward = backward
    return out

embedding is a Tensor operation in chapter 6’s pattern: forward value, output with its one parent, backward closure adding into the parent’s .grad. ids are data, not a Tensor, and receive no gradient; weight.data[ids] with ids of any shape (...) returns (..., d).

def cross_entropy(logits, targets):
    """Mean of -log softmax(logits)[target] over positions whose target is >= 0.

    logits: Tensor (..., V); targets: ints (...). A target of -1 marks a position to ignore.
    """
    targets = np.asarray(targets, dtype=np.int64)
    V = logits.shape[-1]
    z = logits.data.reshape(-1, V)
    t = targets.reshape(-1)
    keep = t >= 0
    n = int(keep.sum())
    if n == 0:
        raise ValueError("cross_entropy needs at least one target that is not -1")
    shifted = z - z.max(axis=1, keepdims=True)
    logp = shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True))  # (N, V) log-softmax
    rows = np.flatnonzero(keep)
    loss = -logp[rows, t[rows]].sum() / n
    out = Tensor(loss, (logits,), "cross_entropy")

    def backward():
        g = np.exp(logp)                # softmax(z), (N, V)
        g[rows, t[rows]] -= 1.0         # minus the one-hot target
        g[~keep] = 0.0                  # ignored positions contribute nothing
        logits.grad += (out.grad / n) * g.reshape(logits.shape)

    out._backward = backward
    return out

The forward pass flattens the logits to (N, V) and the targets to (N,) and computes the mechanism’s log-softmax row by row. rows is the array of kept positions, and logp[rows, t[rows]] picks one log-probability per kept row: numpy pairs the two index arrays element by element. The backward closure keeps logp, (N, V), and nothing else of size; np.exp(logp) is the softmax, and the next three lines are the mechanism’s gradient, scaled by out.grad (1 when the loss is the root).

def free_graph(root):
    """Unlink the graph that produced root so reference counting frees it at once.

    Every op's backward closure refers to its own output, a reference cycle that only the cycle
    collector can reclaim, and it runs rarely. Clearing each non-leaf node's closure and parents
    breaks the cycles. Leaves (parameters) and their .grad are untouched; root can no longer
    backpropagate.
    """
    stack = [root]
    while stack:
        node = stack.pop()
        if node._parents:
            stack.extend(node._parents)
            node._parents = ()
            node._backward = lambda: None

free_graph is a depth-first walk with an explicit stack, like chapter 6’s backward. It needs no seen set: a node is expanded only while it still has parents, and expanding it empties them, so a node reached a second time, through another consumer, is skipped. Leaves never have parents and are never modified.

A mixture-of-experts model (chapter 11) keeps a second graph that free_graph(loss) cannot reach: its load-balancing loss hangs off the model, not off the cross-entropy, unless train adds it in. When the pass does not use it, the same cycles would wait for the collector, so train, evaluate and generate also call free_aux, which asks a model that has such a loss to free it and does nothing for one that does not.

def free_aux(model):
    """Free the graph of a mixture-of-experts model's balance loss, when the pass did not use it.

    The loss's own graph does not reach the balance loss, which the model keeps for aux_loss(), so
    free_graph(loss) leaves its cycles behind. A model with no such loss has nothing to free.
    """
    release = getattr(model, "free_aux", None)
    if release is not None:
        release()
class SGD:
    """Plain gradient descent: p <- p - lr * grad for every parameter."""

    def __init__(self, params, lr):
        self.params = list(params)
        self.lr = lr

    def zero_grad(self):
        for p in self.params:
            p.grad = np.zeros_like(p.data)

    def step(self):
        for p in self.params:
            p.data -= self.lr * p.grad

step updates p.data in place, so every reference to a parameter stays valid.

def get_batch(ids, context, batch_size, rng):
    """batch_size random windows of the token stream: inputs x and next-token targets y, both (B, T)."""
    ids = np.asarray(ids, dtype=np.int64)
    if len(ids) <= context:
        raise ValueError(f"need more than context={context} tokens, got {len(ids)}")
    starts = rng.integers(0, len(ids) - context, size=batch_size)
    x = np.stack([ids[s:s + context] for s in starts])
    y = np.stack([ids[s + 1:s + context + 1] for s in starts])
    return x, y

A window starting at s needs tokens s to s + context, so the largest valid start is len(ids) - context - 1, and rng.integers(0, len(ids) - context) excludes its upper bound. A stream of context tokens or fewer has no window and raises ValueError.

def train(model, opt, ids, steps, context, batch_size, rng, aux_weight=0.0):
    """Run steps of minibatch training; return the training loss of every step.

    With aux_weight nonzero the loss minimised and returned is the cross-entropy plus aux_weight
    times model.aux_loss(), chapter 11's load-balancing loss; at 0 aux_loss is never called.
    """
    losses = []
    for _ in range(steps):
        x, y = get_batch(ids, context, batch_size, rng)
        opt.zero_grad()                       # leaf gradients accumulate: clear last step's
        loss = cross_entropy(model(x), y)     # forward: (B, T, V) logits against (B, T) targets
        if aux_weight:
            loss = loss + aux_weight * model.aux_loss()
        loss.backward()                       # every parameter's .grad is now dloss/dparam
        opt.step()
        losses.append(float(loss.data))
        free_graph(loss)                      # this step's graph is garbage: release it now
        free_aux(model)                       # and the balance loss's, if the model has one and loss left it out
    return losses

Chapters 9, 11 and 13 train with this loop. The order matters in two places: zero_grad comes before backward, and free_graph after step, once nothing needs the graph. The loss recorded for step kk is computed before step kk’s update, so losses[0] is the loss of the initial model, logV\log V for the bigram. aux_weight is for chapter 11’s mixture-of-experts models, which carry a second, load-balancing loss: when it is nonzero, aux_weight * model.aux_loss() is added to the cross-entropy before backward, and the recorded loss is that sum. At its default of 0, aux_loss is never called and the loss is the cross-entropy alone; test_train_adds_the_weighted_aux_loss checks both.

def evaluate(model, ids, context):
    """Mean cross-entropy (nats per token) of predicting every token of ids after the first.

    The stream is cut into consecutive windows of context tokens; each window predicts its own
    next tokens, so a model sees at most context tokens of history.
    """
    ids = np.asarray(ids, dtype=np.int64)
    total, count = 0.0, 0
    for s in range(0, len(ids) - 1, context):
        x = ids[s:min(s + context, len(ids) - 1)][None, :]  # (1, T); the last window may be short
        y = ids[s + 1:s + 1 + x.shape[1]][None, :]
        loss = cross_entropy(model(x), y)
        total += float(loss.data) * y.size
        count += y.size
        free_graph(loss)
        free_aux(model)
    return total / count

Each window is a (1, T) batch. The last stops at len(ids) - 1 inputs, since the final token is only ever a target, and may be shorter than context. Weighting each window’s mean by y.size makes the result the plain average over all predictions. test_evaluate_scores_every_next_token pins the window arithmetic with 10 tokens and a context of 4: windows of 4, 4 and 1 predictions.

class Bigram:
    """Next-token logits from the current token alone: a (V, V) table, row = current token."""

    def __init__(self, vocab_size):
        self.table = Tensor(np.zeros((vocab_size, vocab_size)))  # all-zero logits: uniform start

    def parameters(self):
        return [self.table]

    def __call__(self, ids):
        return embedding(self.table, ids)  # (B, T) -> (B, T, V)

The model follows the protocol the language models of chapters 9 and 11 follow too: model(ids) maps (B, T) integer ids to (B, T, V) logits, and model.parameters() lists the tensors an optimizer updates. train, evaluate and generate use nothing else, apart from the aux_loss() that train calls when it is given a nonzero aux_weight, and a free_aux method, which free_aux calls if the model has one.

def generate(model, prompt, n_new, context, rng):
    """n_new tokens following prompt, each drawn from the model's distribution given the last context tokens."""
    ids = list(prompt)
    if not ids:
        raise ValueError("generate needs a non-empty prompt")
    for _ in range(n_new):
        logits = model(np.array([ids[-context:]]))
        probs = softmax(logits.data[0, -1])  # distribution for the token after the last one
        free_graph(logits)
        free_aux(model)
        ids.append(int(rng.choice(len(probs), p=probs)))
    return ids[len(prompt):]

generate feeds the model the last context tokens as a (1, T) batch, takes the logits of the last position, logits.data[0, -1], shape (V,), and draws the next id with rng.choice. It frees each graph, since nothing will backpropagate through it, and returns only the new ids. It recomputes the whole window at every step; chapter 12’s KV cache removes that for the transformer.

Exercises

(a) For the corpus a b a b b, compute the counting bigram and the gradient of the mean loss with respect to a zero table by hand, and check the gradient with cross_entropy.

Answer

Four predictions: a→ba \to b, b→ab \to a, a→ba \to b, b→bb \to b. So Na=2N_a = 2 with both successors bb, and Nb=2N_b = 2 with one aa and one bb. The counting bigram is p^(b∣a)=1\hat{p}(b \mid a) = 1, p^(a∣a)=0\hat{p}(a \mid a) = 0, and p^(a∣b)=p^(b∣b)=1/2\hat{p}(a \mid b) = \hat{p}(b \mid b) = 1/2.

At the zero table every row’s softmax is (12,12)(\frac12, \frac12) and the loss is log2=0.6931\log 2 = 0.6931. By the row formula, ∂L/∂wa=24((12,12)−(0,1))=(0.25,−0.25)\partial L / \partial \mathbf{w}_a = \frac{2}{4}\big((\frac12, \frac12) - (0, 1)\big) = (0.25, -0.25) and ∂L/∂wb=24((12,12)−(12,12))=(0,0)\partial L / \partial \mathbf{w}_b = \frac{2}{4}\big((\frac12, \frac12) - (\frac12, \frac12)\big) = (0, 0): row bb is already at its optimum, and row aa is pushed toward bb.

import numpy as np

from tinygpt.autograd import Tensor
from tinygpt.nn import cross_entropy, embedding

ids = np.array([0, 1, 0, 1, 1])             # a b a b b, with a = 0 and b = 1
table = Tensor(np.zeros((2, 2)))
loss = cross_entropy(embedding(table, ids[None, :-1]), ids[None, 1:])
loss.backward()
print(f"loss {float(loss.data):.4f}")
print(table.grad)
loss 0.6931
[[ 0.25 -0.25]
 [ 0.    0.  ]]

(b) Prove that the gradient of a get_batch minibatch loss is an unbiased estimate of a full-data gradient. Which full-data loss, exactly?

Answer

Let the stream have M+TM + T tokens, so there are MM window starts s∈{0,…,M−1}s \in \{0, \ldots, M - 1\}, each drawn with probability 1/M1/M. Write ℓp\ell_p for the loss of predicting token p+1p + 1 from position pp. One window’s loss is 1T∑j=0T−1ℓs+j\frac{1}{T}\sum_{j=0}^{T-1} \ell_{s+j}, and the minibatch loss is the mean over BB windows of that. By linearity of expectation and of the gradient, the expected minibatch gradient is the expected gradient of one window:

E[∇LB]=1M∑s=0M−11T∑j=0T−1∇ℓs+j=∇(∑pcpℓp),cp=∣{(s,j):s+j=p}∣MT. \mathbb{E}\big[\nabla L_B\big] = \frac{1}{M} \sum_{s=0}^{M-1} \frac{1}{T} \sum_{j=0}^{T-1} \nabla \ell_{s+j} = \nabla \Big( \sum_{p} c_p\, \ell_p \Big), \qquad c_p = \frac{\lvert\{(s, j) : s + j = p\}\rvert}{MT} .

So it is unbiased for the weighted loss ∑pcpℓp\sum_p c_p \ell_p. A position pp with T−1≤p≤M−1T - 1 \le p \le M - 1 is covered by TT windows, one for each jj, so cp=1/Mc_p = 1/M. The first and last T−1T - 1 positions are covered by fewer and weigh less: position 0 is in one window only. For the lab, T=16T = 16 and the training stream has 11,997 predictions, so 30 of them are underweighted and the rest weighted equally. Sampling single positions uniformly would remove the edge effect, but chapter 11’s transformer reads a window’s positions together, so contiguous windows are its unit of data.

(c) Zero initialisation is harmless for the bigram table. Why does it break a model with a hidden layer, such as logits =tanh(EidsW1)W2= \tanh(\mathbf{E}_{\text{ids}}\mathbf{W}_1)\mathbf{W}_2 with E\mathbf{E} of shape (V, d), W1\mathbf{W}_1 of shape (d, h) and W2\mathbf{W}_2 of shape (h, V)?

Answer

For the bigram, the gradient of entry WabW_{ab} is NaN(softmax(wa)b−p^a,b)\frac{N_a}{N}(\mathrm{softmax}(\mathbf{w}_a)_b - \hat{p}_{a,b}), which differs from entry to entry because the data differ: the first step already sets each entry on its own course. Nothing in the model is interchangeable.

With a hidden layer, write X=Eids\mathbf{X} = \mathbf{E}_{\text{ids}}, shape (n, d), H=tanh(XW1)\mathbf{H} = \tanh(\mathbf{X}\mathbf{W}_1), shape (n, h), and G\mathbf{G}, shape (n, V), the gradient at the logits. Chapter 6’s rules give W¯2=H⊤G\bar{\mathbf{W}}_2 = \mathbf{H}^\top\mathbf{G} and W¯1=X⊤((GW2⊤)⊙(1−H⊙H))\bar{\mathbf{W}}_1 = \mathbf{X}^\top\big((\mathbf{G}\mathbf{W}_2^\top) \odot (1 - \mathbf{H} \odot \mathbf{H})\big). If everything starts at 0, then H=tanh(0)=0\mathbf{H} = \tanh(\mathbf{0}) = \mathbf{0}, so W¯2=0\bar{\mathbf{W}}_2 = \mathbf{0}; W2=0\mathbf{W}_2 = \mathbf{0}, so W¯1=0\bar{\mathbf{W}}_1 = \mathbf{0}; and E¯\bar{\mathbf{E}} is a product with W1⊤=0\mathbf{W}_1^\top = \mathbf{0}. Every gradient is zero, the step changes nothing, and the next step is the same: the model is stuck at the uniform prediction forever.

Starting every weight at the same nonzero constant fails more quietly. Hidden unit kk is column kk of W1\mathbf{W}_1 feeding row kk of W2\mathbf{W}_2. If all columns are equal and all rows are equal, every hidden unit computes the same value, receives the same gradient (the formulas above are symmetric under swapping two units), and takes the same step, so they stay identical: hh units do the work of one. Random initialisation breaks the symmetry. Chapter 9 draws its weights at random, with a scale derived from chapter 4’s variance rules.

(d) Explain test_training_without_zero_grad_does_worse quantitatively. The run without zero_grad has training losses 2.8332, 1.8133, 1.5757, 1.5603, 1.7464 and 1.8496 at steps 1, 5, 10, 20, 50 and 100; the correct run has 2.8332, 2.2309, 1.9188, 1.6745, 1.4710 and 1.3912.

Answer

Without zeroing, .grad after step tt’s backward pass is Gt=∑s=1tgs\mathbf{G}_t = \sum_{s=1}^{t} \mathbf{g}_s, and the parameters after tt steps are

θt=θ0−η∑s=1tGs=θ0−η∑r=1t(t−r+1)gr: \theta_t = \theta_0 - \eta \sum_{s=1}^{t} \mathbf{G}_s = \theta_0 - \eta \sum_{r=1}^{t} (t - r + 1)\, \mathbf{g}_r :

gradient gr\mathbf{g}_r is applied again at every later step, t−r+1t - r + 1 times in all. While the gradients all point the same way, as they do at the start when every row is far from its target, step tt moves tt times as far as a correct step would. That is why the broken run leads early: 1.81 against 2.23 at step 5, 1.58 against 1.92 at step 10.

Near a row’s target its gradient changes sign, but the step is −ηGt-\eta \mathbf{G}_t, and Gt\mathbf{G}_t changes sign only after the new gradients have cancelled everything accumulated on the way in: the parameters coast past the target for about as many steps as they spent approaching it, then swing back as far. This is momentum with coefficient 1, which has no damping, so the swing does not die out. The loss bottoms out at step 13, at 1.43, and rises: 1.75 at step 50 and 1.85 at step 100, while the correct run passes below it at step 32 and reaches 1.39. The table shows the coasting. After 100 steps the largest logit in the correct table has magnitude 5.7; in the broken one it is 164, far beyond what any probability in the data needs, since a logit difference of 164 is a probability ratio of e164e^{164}. Held out, the two score 1.4116 and 1.9128 nats, a gap of 0.50, where the test requires 0.3.

(e) Find the smallest learning rate at which bigram training on the tiny corpus stops converging, and relate it to chapter 5’s step-size bound.

Answer

Chapter 5’s bound is η<2/λmax\eta < 2/\lambda_{\max}, with λmax\lambda_{\max} the largest eigenvalue of the Hessian at the minimum. Differentiate the row gradient NaN(pa−p^a)\frac{N_a}{N}(\mathbf{p}_a - \hat{\mathbf{p}}_a) once more, with pa=softmax(wa)\mathbf{p}_a = \mathrm{softmax}(\mathbf{w}_a). Write pi=ewi/Sp_i = e^{w_i} / S with S=∑kewkS = \sum_k e^{w_k}. By the quotient rule, ∂pi/∂wj=(δijewiS−ewiewj)/S2=pi(δij−pj)\partial p_i / \partial w_j = (\delta_{ij} e^{w_i} S - e^{w_i} e^{w_j}) / S^2 = p_i(\delta_{ij} - p_j), where δij\delta_{ij} is 1 if i=ji = j and 0 otherwise, so row aa’s block of the Hessian, the derivative of its gradient, is

Ha=NaN(diag(pa)−papa⊤), \mathbf{H}_a = \frac{N_a}{N} \big( \mathrm{diag}(\mathbf{p}_a) - \mathbf{p}_a \mathbf{p}_a^\top \big) ,

shape (V, V), and different rows do not interact, so the Hessian is block diagonal and its eigenvalues are those of the blocks. At the minimum pa=p^a\mathbf{p}_a = \hat{\mathbf{p}}_a. The row of . has Na/N=1801/11997=0.1501N_a / N = 1801 / 11997 = 0.1501 and two successors, the with probability q=0.5014q = 0.5014 and a with 1−q1 - q. Restricted to those two entries, diag(p)−pp⊤=q(1−q)(1−1−11)\mathrm{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top = q(1-q)\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix}, with eigenvalue 2q(1−q)=0.52q(1-q) = 0.5 along (1,−1)(1, -1): raising the logit of the and lowering that of a. So λ=0.1501×0.5=0.0751\lambda = 0.1501 \times 0.5 = 0.0751, the largest of any row, and the bound is 2/0.0751=26.62 / 0.0751 = 26.6.

Full-batch gradient descent, to take minibatch noise out of the picture:

import pathlib

import numpy as np

from tinygpt.nn import SGD, Bigram, cross_entropy, free_graph

tokens = pathlib.Path("data/tiny-corpus.txt").read_text().split()
vocab = sorted(set(tokens))
ids = np.array([vocab.index(t) for t in tokens])
train_ids = ids[:int(0.9 * len(ids))]
x, y = train_ids[None, :-1], train_ids[None, 1:]   # the whole training set as one batch
dot, the, a = vocab.index("."), vocab.index("the"), vocab.index("a")

for lr in [20, 26.6, 26.7, 30, 40]:
    model = Bigram(len(vocab))
    opt = SGD(model.parameters(), lr)
    for step in range(3000):
        opt.zero_grad()
        loss = cross_entropy(model(x), y)
        loss.backward()
        opt.step()
        free_graph(loss)
        if step >= 2998:
            print(f"lr {lr:4}  step {step}  loss {float(loss.data):.4f}  "
                  f"w[., the] - w[., a] = {model.table.data[dot, the] - model.table.data[dot, a]:+.4f}")
lr   20  step 2998  loss 1.3517  w[., the] - w[., a] = +0.0056
lr   20  step 2999  loss 1.3517  w[., the] - w[., a] = +0.0056
lr 26.6  step 2998  loss 1.3515  w[., the] - w[., a] = +0.0056
lr 26.6  step 2999  loss 1.3514  w[., the] - w[., a] = +0.0056
lr 26.7  step 2998  loss 1.3518  w[., the] - w[., a] = -0.1384
lr 26.7  step 2999  loss 1.3518  w[., the] - w[., a] = +0.1496
lr   30  step 2998  loss 1.3788  w[., the] - w[., a] = -1.2360
lr   30  step 2999  loss 1.3786  w[., the] - w[., a] = +1.2520
lr   40  step 2998  loss 1.4509  w[., the] - w[., a] = +2.5997
lr   40  step 2999  loss 1.4525  w[., the] - w[., a] = -2.5574

Up to 26.6 the logit difference settles at log(903/898)=0.0056\log(903/898) = 0.0056, the counting answer. From 26.7 it flips sign every step: the predicted bound, to the first decimal. Unlike chapter 5’s quadratic, the oscillation does not grow without limit. The curvature 2p(1−p)2p(1-p) shrinks as the swing pushes pp away from 12\frac12, so the swing settles at the amplitude where the effective curvature brings the step factor back to −1-1, larger the further η\eta is past the bound. The loss stays finite and just gets worse, which is what the minibatch sweep showed at 50 and 100.

With minibatches the noise blurs the edge, and the held-out loss worsens gradually from 20 upward rather than at 26.6. At the zero initialisation the curvature is lower, at most NaN⋅1V\frac{N_a}{N} \cdot \frac{1}{V}, and the bound there is 222: the binding constraint is at the minimum, where the rows have sharpened.

(f) Train a Bigram on Persuasion tokenized with chapter 7’s 512-token BPE, using chapter 4’s 90/10 split of the token stream. Report its held-out loss and compare it with the unigram cross-entropy of the same tokens.

Answer
import pathlib

import numpy as np

from tinygpt.bpe import BPE
from tinygpt.nn import SGD, Bigram, evaluate, train
from tinygpt.prob import fit_categorical, nll

text = pathlib.Path("data/persuasion.txt").read_text()
ids = np.array(BPE.train(text, 512).encode(text))
cut = int(0.9 * len(ids))
train_ids, test_ids = ids[:cut], ids[cut:]
unigram = fit_categorical(train_ids, 512, alpha=1.0)
print(f"unigram held-out {nll(unigram, test_ids):.4f}")

model = Bigram(512)
opt = SGD(model.parameters(), lr=100.0)
rng = np.random.default_rng(0)
for step in range(250, 1001, 250):
    losses = train(model, opt, train_ids, 250, 64, 32, rng)
    print(f"step {step:4d}  train {np.mean(losses):.4f}  held-out {evaluate(model, test_ids, 64):.4f}")
unigram held-out 5.2352
step  250  train 4.5632  held-out 4.1109
step  500  train 3.8612  held-out 3.8940
step  750  train 3.7128  held-out 3.8148
step 1000  train 3.6436  held-out 3.7726

Run from py/ with OPENBLAS_NUM_THREADS=1; it takes about a minute and a half. The book’s 213,887 tokens split into 192,498 for training and 21,389 held out. The unigram, smoothed with add-one so that no held-out token gets probability 0, scores 5.2352 nats per token, a perplexity of 188. The bigram reaches 3.7726 after 1,000 steps, a perplexity of 43.5, and is still improving. The learning rate is ten times the tiny corpus’s because each row’s gradient is scaled by Na/NN_a/N, and with 512 tokens sharing the positions most rows’ shares are small.

An add-one counting bigram on the same split scores 3.9509, worse than the trained table: of the 262,144 pairs only 17,333 occur in the 192,497 training predictions, and one pseudo-count each moves a large share of every rare row’s probability onto them. The trained table starts uniform and moves each row in proportion to its evidence, so it smooths less where the data say more. An unsmoothed counting bigram scores infinity: 671 of the held-out predictions are pairs the training text never contains.

Lab

Implement every function and class in py/labs/ch08/starter.py. The starter’s docstrings give the contract of each; write embedding and cross_entropy as Tensor operations the way chapter 6 did. Run

make lab CH=08 IMPL=mine

until it passes. Read py/labs/ch08/test_lab.py first. Nine tests pin the two operations and free_graph, with gradchecks, the extreme-logit case and the ignore marker; the rest pin the machinery, ending with 300 steps of training that must reach a held-out perplexity below 4, a no-zero_grad run that must score at least 0.3 nats worse, and 200 sampled tokens that must obey the grammar after . and after a determiner.

Then train and sample. Save this script outside the repository, for example as /tmp/bigram_lab.py:

import math
import pathlib

import numpy as np

from tinygpt.nn import SGD, Bigram, evaluate, generate, 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:]

model = Bigram(len(vocab))
opt = SGD(model.parameters(), lr=10.0)
rng = np.random.default_rng(0)
print(f"step    0  held-out {evaluate(model, test_ids, 64):.4f}  (log V = {math.log(len(vocab)):.4f})")
for step in range(50, 301, 50):
    losses = train(model, opt, train_ids, 50, 16, 32, rng)
    print(f"step {step:4d}  train {np.mean(losses):.4f}  held-out {evaluate(model, test_ids, 64):.4f}")
print(f"held-out perplexity {math.exp(evaluate(model, test_ids, 64)):.4f}")
out = generate(model, [vocab.index(".")], 30, 1, np.random.default_rng(1))
print(" ".join(vocab[i] for i in out))

and run it from py/ with PYTHONPATH=. uv run python /tmp/bigram_lab.py. Change the import to from labs.ch08.starter import SGD, Bigram, evaluate, generate, train to run yours. The reference prints (straylight):

step    0  held-out 2.8332  (log V = 2.8332)
step   50  train 1.7327  held-out 1.4619
step  100  train 1.4420  held-out 1.4116
step  150  train 1.4033  held-out 1.3851
step  200  train 1.3879  held-out 1.3719
step  250  train 1.3783  held-out 1.3795
step  300  train 1.3743  held-out 1.3689
held-out perplexity 3.9310
the queen . the cat . the dog bites a prince commands a prince . a bites a cat . the cat a queen summons the king . a queen

A correct implementation that follows the starter’s docstrings draws the same batches and samples from the same generators, so it should print the same numbers, up to a difference in the last digit where a valid reordering of floating-point operations rounds differently.

  • The train column is a mean over the 50 steps before each line, so it lags the held-out column while the model is improving. By the last 50 steps the two agree to about 0.005 nats, with the held-out loss the lower: the held-out tenth of this corpus is slightly easier, and the counting bigram, fitted on the training text, also scores 1.3508 on it and 1.3463 held out. With 289 parameters and 11,997 training predictions there is no overfitting to see.
  • Held-out loss does not fall monotonically: 1.3719 at step 200, 1.3795 at step 250. Each step follows one minibatch’s gradient, and the heavily weighted rows of ., a and the keep moving around their targets by an amount the held-out loss can see.
  • The sample obeys the grammar one word at a time and not at the level of the sentence. Every sentence starts with a determiner. But the dog bites a prince commands a prince is two sentences with the break missing: prince commands is a correct pair, and the model cannot know that this prince is the object of a verb it has already seen, because it sees one word back. a bites and cat a are pairs that never occur in the training text; after 300 steps the table still gives them 0.08% and 0.25%, and 30 draws happened to take both.

Further reading

  • Claude E. Shannon, “A Mathematical Theory of Communication”, Bell System Technical Journal 27 (1948), part I, section 3, “The Series of Approximations to English”. Text generated from letter and word models of increasing order, including a second-order word approximation, a word bigram sampled by hand from a book.
  • Herbert Robbins and Sutton Monro, “A Stochastic Approximation Method”, Annals of Mathematical Statistics 22(3) (1951). Finding a root of a function observed only through noisy measurements with a decreasing step size: the origin of stochastic gradient methods, with the step-size conditions for convergence.
  • Léon Bottou, Frank E. Curtis and Jorge Nocedal, “Optimization Methods for Large-Scale Machine Learning”, SIAM Review 60(2) (2018). Why SGD beats full-batch methods on large training sets, the role of the minibatch’s variance, and convergence results under the assumptions this chapter uses informally.
  • Ian Goodfellow, Yoshua Bengio and Aaron Courville, Deep Learning (MIT Press, 1st ed., 2016), chapter 6 (cross-entropy costs, softmax output units, back-propagation) and chapter 8 (minibatch SGD, learning rates, momentum, initialisation and symmetry breaking).
  • Daniel Jurafsky and James H. Martin, Speech and Language Processing (3rd ed. draft, August 19, 2026), chapter 3, “N-gram Language Models”. Counting n-gram models, smoothing, perplexity on held-out data, and sampling sentences from a model.

results matching ""

    No results matching ""