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, plusself.pos_emb, a learned position table withblock_sizerows.n_layerblocks inself.blocks. Each block doesx = x + attn(ln1(x)), thenx = x + mlp(ln2(x)), with causal multi-head attention and an MLP of4 * n_embdwith a GELU.- A final LayerNorm,
self.ln_f, thenself.lm_head, which gives a score to every token in the vocabulary. Tie its weight toself.tok_emb.forward(idx, targets=None)returns(logits, loss): logits of shape(B, T, vocab_size), and the mean cross-entropy over every position, orNonewithout targets.- Raise
ValueErrorwhenT > 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 mat Returns model = GPT(5, 8, 16, 2, 2)a model with 6,800 parameters model(idx, targets), withidxthe ids of the cat sat on the andtargetsthe ids of cat sat on the matlogits of shape (1, 5, 5), and a loss of 1.65 aftertorch.manual_seed(0), close to ln 5 = 1.61model(idx)the same logits, and Nonemodelon 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.