This lesson is where the pieces of the course meet: a model, text, a loss and an optimizer, ending with a network that writes. It pairs with Let's build GPT: from scratch, in code, spelled out. by Andrej Karpathy, linked under Watch & read. You write the pipeline around a small GPT that is supplied: encode a text, split it, draw batches, evaluate, train while keeping the best weights, and sample at a chosen temperature. The longer Deep Dive into LLMs like ChatGPT, also linked, covers the same loop at the scale of real models.
Every step has one job that the next step depends on.
Start with the data. A character-level model reads text as a list of integers, one per distinct character, numbered in sorted order. The first 80 percent of the ids train the model and the rest is held back. A window is context consecutive ids, and its target is the same window moved one place to the right: position t of the target is the token that follows position t of the input. One window therefore contains context separate prediction problems, and the causal attention mask lets the model solve all of them in one pass.
text = "the cat sat on the mat. " * 40
chars = sorted(set(text))
print(len(text), len(chars), "".join(chars).replace(" ", "_"))
ids = [chars.index(c) for c in text]
cut = int(0.8 * len(ids))
print(cut, len(ids) - cut)
s = 4
print(ids[s:s + 6], ids[s + 1:s + 7])The text is 960 characters with 11 distinct ones, so 768 ids train and 192 validate. The window starting at 4 begins with the ids 3, 2, 10, and its target begins with 2, 10, 0: the same list, one place later. A batch is batch such windows with random starts. The largest legal start leaves room for the one extra token the last target needs.
Before training, know what counts as good. A model that guesses uniformly over 11 characters has loss ln 11 = 2.398. A bigram model, which sees only the previous character, does better, because the text is far from random.
import math
text = "the cat sat on the mat. " * 40
chars = sorted(set(text))
ids = [chars.index(c) for c in text]
cut = int(0.8 * len(ids))
train_ids, val_ids = ids[:cut], ids[cut:]
n = len(chars)
counts = [[1] * n for _ in range(n)]
for a, b in zip(train_ids, train_ids[1:]):
counts[a][b] += 1
nll = [-math.log(counts[a][b] / sum(counts[a])) for a, b in zip(val_ids, val_ids[1:])]
print(round(math.log(n), 3), round(sum(nll) / len(nll), 3))The bigram loss on the validation ids is 0.728. A real context should beat it clearly, since after "the " the next letter is not decided by the space alone. The GPT in this lesson has context 16 and 26,699 parameters. Trained for 150 steps with batches of 16 at a learning rate of 0.003, its validation loss is below the bigram line by step 30 and keeps falling.
The last step is not the best one, which is why train copies the weights whenever the validation loss improves. Copy them for real: state_dict() returns references to the live tensors, so a saved dictionary changes as training continues. A deep copy stays fixed.
evaluate must not disturb anything. It cuts the validation ids into non-overlapping windows of the context length, uses only windows whose targets all exist, and averages the loss. With 192 ids and context 16 that is 11 windows and 176 targets; the last 16 ids are left over. It runs with gradients off and in eval mode, then puts the model back in whatever mode it was in, so calling it in the middle of training does not change the training.
Sampling is a loop. Take the last context ids, run the model, keep the logits of the final position, divide them by the temperature, apply softmax and draw one id. Append it and repeat. The temperature decides how sharp the draw is.
import math
logits = [2.0, 1.0, 0.0]
for t in (0.5, 1.0, 2.0):
e = [math.exp(v / t) for v in logits]
print(t, [round(v / sum(e), 3) for v in e])Below 1 the likely tokens gain probability, and as the temperature approaches 0 the draw becomes the argmax. Above 1 the choice flattens. Zero itself would divide by zero, so it is rejected.
Two mistakes recur. If the targets are not shifted, the model is asked to copy its input. In the run above the validation loss reaches 0.066 by step 40 and 0.006 by step 150, better than any honest run, and the model has learned nothing about what comes next. If sample feeds the whole sequence instead of the last context ids, it works until the sequence is longer than the position table, and then fails. Smaller slips are also common: leaving the model in eval mode after evaluate, or saving the best weights without copying them.
The tests check evaluate against a loop over windows, check greedy decoding at a tiny temperature against an argmax loop, and require the trained model to beat a bigram model computed inside the test. That evidence has limits. The text is one sentence repeated, so the validation windows are near copies of the training windows, and a good score does not show that the model handles new text. Choosing the best step by validation loss also makes that number slightly optimistic. An honest final figure needs a third part of the data that nothing chose by.