1/29
Part 1 of 5 · From words to vectorsLearn

A GPT from scratch

ML coding rounds ask for this model in two ways. Candidates report phone screens that mostly test how well you know the transformer's parts, and ML debugging rounds that hand you a small GPT that runs and still writes the wrong text. Either way, you need to be able to write it yourself. The practice problem asks for all of it:

Write a decoder-only transformer in PyTorch, GPT(vocab_size, block_size, n_embd, n_head, n_layer).

  • self.tok_emb, a token table, plus self.pos_emb, a learned position table with block_size rows.
  • n_layer blocks in self.blocks. Each block does x = x + attn(ln1(x)), then x = x + mlp(ln2(x)), with causal multi-head attention and an MLP of 4 * n_embd with a GELU.
  • A final LayerNorm, self.ln_f, then self.lm_head, which gives a score to every token in the vocabulary. Tie its weight to self.tok_emb.
  • forward(idx, targets=None) returns (logits, loss): logits of shape (B, T, vocab_size), and the mean cross-entropy over every position, or None without targets.
  • Raise ValueError when T > block_size.

It comes in four levels: the two tables, ln_f, the tied head and the length check; then the blocks; then the loss, and a model that learns; then the start, every weight at a spread of 0.02 and every bias at 0, so a fresh model's loss sits near ln V.

Call, with a vocabulary of five words, the cat sat on matReturns
model = GPT(5, 8, 16, 2, 2)a model with 6,800 parameters
model(idx, targets), with idx the ids of the cat sat on the and targets the ids of cat sat on the matlogits of shape (1, 5, 5), and a loss of 1.65 after torch.manual_seed(0), close to ln 5 = 1.61
model(idx)the same logits, and None
model on 9 tokensValueError

The practice problem's own tests use a bigger model, GPT(23, 16, 32, 4, 2). When this lesson says the practice model, it means that one.

This lesson builds the model in the order the data flows through it, each piece with a small task: the token and position tables, the block, the head, the loss and the length check. Then it counts the parameters and covers what interviewers ask next. The whole problem comes back at the end, as the lesson's practice: the full model from a blank file, around your attention module.