A GPT from scratch
- Follow a GPT from token ids to scores to loss, with the shape at every step
- Say why a GPT needs a position table, and the one input that proves it
- Draw the block as two steps that each add back to the stream, and write it
- Say why the norm goes before each step, and what the final LayerNorm is for
- Tie the head to the token table in one line, and say what it saves
- Shift the targets by one, check the starting loss against the log of V, and count the parameters
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.
The whole model in one picture
A GPT reads token ids and, at every position, gives a score to every token in its vocabulary. A token is a word or a piece of a word, and the vocabulary is the list of all of them. The scores at position t are its guess for the token at position t + 1.
This lesson follows one sentence through the whole model: the cat sat on the mat. To keep the numbers small, the vocabulary has only five words, and each word's id is its place in the list.
import torch
import torch.nn.functional as F
from torch import nn
# the vocabulary: V = 5
words = ["the", "cat", "sat", "on", "mat"]
# "mat" is word 4
print(len(words), words.index("mat"))
5 4
The sentence goes in as a (B, T) tensor of ids: 1 sentence, 6 tokens. Here is everything the model does to it, top to bottom. Tap a step to see its shape and the lines of code that do it.
1def forward(2 self, idx: torch.Tensor, targets: torch.Tensor | None = None3) -> tuple[torch.Tensor, torch.Tensor | None]:4 """idx: (B, T) token ids. Returns (B, T, V) logits, and the loss."""5 B, T = idx.shape6 if T > self.block_size:7 raise ValueError(f"got {T} tokens, block_size is {self.block_size}")8 pos = torch.arange(T, device=idx.device)9 x = self.tok_emb(idx) + self.pos_emb(pos)10 for block in self.blocks:11 x = block(x)12 logits = self.lm_head(self.ln_f(x))13 if targets is None:14 return logits, None15 V = logits.size(-1)16 loss = F.cross_entropy(logits.reshape(-1, V), targets.reshape(-1))17 return logits, lossThe letters are the ones from the PyTorch lesson: B sequences, T tokens each, C numbers per token. V is the number of words in the vocabulary: 5 here, and 50,257 in GPT-2.
Your multi-head attention sits inside every block.
In the editor, words is the five-word vocabulary and text is the sentence. Set ids, each word's place in words, then idx, the same ids as a (1, 6) tensor, then back, the sentence read from idx.
Every token becomes a vector
A token id is just a number, like 1 for cat. The model needs a vector of C numbers to work with. nn.Embedding(V, C) is a table with one row per word, and looking a token up means reading its row:
# the cat sat on the mat
idx = torch.tensor([[0, 1, 2, 3, 0, 4]])
torch.manual_seed(0)
# V = 5 words, C = 3 numbers each
tok_emb = nn.Embedding(5, 3)
# one row per token
x = tok_emb(idx)
# (B, T, C)
print(x.shape)
# "the" at positions 0 and 4
print(torch.equal(x[0, 0], x[0, 4]))
torch.Size([1, 6, 3])
True
Six tokens in, six vectors out. the appears twice, at positions 0 and 4, so it gets the same row twice. The table is learned, like any other weight.
In the editor, idx holds the ids of the cat sat on the mat. Build tok_emb, a table with a row of 4 numbers for each of the 5 words. Then set x, the vectors for idx, and same, whether both copies of the got the same vector.
Positions get a table too
A second table, pos_emb, has one row per position: row 0 for the first position, row 1 for the second, and so on, up to block_size rows. Each token's vector is its word's row plus its position's row:
# one row per position
pos_emb = nn.Embedding(6, 3)
x = tok_emb(idx) + pos_emb(torch.arange(6))
# "the" at 0 and 4, now
print(torch.equal(x[0, 0], x[0, 4]))
False
Tap a word to see the row it reads, then switch the positions on:
tok_emb one row per wordx one vector per tokentorch.arange(T) is the positions 0 to T - 1. The position vectors are (T, C), and broadcasting adds the same positions to every sentence in the batch. In the model, build them on the same device as idx: torch.arange(T, device=idx.device). A plain torch.arange(T) sits on the CPU, and the model fails the first time it runs on a GPU.
Write embed(idx, tok_emb, pos_emb): each token's row of tok_emb plus its position's row of pos_emb. It's the first line of the model's forward, so build the positions on idx's device.
Write embed(idx, tok_emb, pos_emb). idx is (B, T) token ids, and each output vector is its token's row of tok_emb plus its position's row of pos_emb, (B, T, C) in all. Build the positions on idx's device.
Raschka adds a second embedding table, one row per position, adds it to the token embeddings, and names the newer option many models use instead, rotary position embeddings.
Why the positions matter
Attention mixes tokens, but it has no idea where any token is. Without positions and without the mask, it sees each sentence as a bag of words: dog bites man and man bites dog hold the same three vectors, just in a different order.
No positions and no mask. Attention reads dog bites man, then man bites dog. What comes back?
You drop pos_emb and train on real text. What do you see?
The block: two steps, each added back
This is the heart of the model. Every block does two steps, and each step adds its result back to the tokens' vectors. Tap each piece of the picture:
Read the picture top to bottom:
- The line down the left is the stream: the tokens' vectors,
(B, T, C). It goes through every block, and it never gets replaced. Each step only adds to it. - Step 1, attention. Each token gathers information from the tokens before it. This is your multi-head attention, and it's the only place where tokens see each other.
- Step 2, the MLP. Each token works on its own vector, alone. It's two linear layers with a GELU between them: up to
4 * Cnumbers, then back down to C. GELU is a smooth version of ReLU. - LayerNorm, before each step. It rescales each token's C numbers so they have mean 0 and spread 1. Each step then gets inputs of a steady size, whatever happened in the blocks before.
In the editor, x is 2 sentences of 5 tokens with C = 8 numbers each. Build mlp with nn.Sequential, run it on x to get out, and count its weights and biases in n.
LayerNorm keeps each token steady
LayerNorm works on one token at a time: it moves the token's C numbers to mean 0 and spread 1. Here it is on one token's four numbers:
ln = nn.LayerNorm(4)
with torch.no_grad():
print(ln(torch.tensor([[1., 2., 3., 10.]])).round(decimals=2))
tensor([[-0.8500, -0.5700, -0.2800, 1.7000]])
The order stays the same, the big number stays big, and the scale is now steady. LayerNorm also learns a scale and a shift of its own, which start at 1 and 0.
In the editor, x holds two tokens, four numbers each. Compute LayerNorm by hand: set mean, then var, then by_hand. The last line prints nn.LayerNorm(4) on the same x, so you can compare.
The block in code
Here is the block from the picture, in code:
class Block(nn.Module):
def __init__(self, n_embd: int, n_head: int, block_size: int) -> None:
super().__init__()
self.ln1 = nn.LayerNorm(n_embd)
self.attn = CausalSelfAttention(n_embd, n_head, block_size)
self.ln2 = nn.LayerNorm(n_embd)
self.mlp = nn.Sequential(
# up to 4C numbers
nn.Linear(n_embd, 4 * n_embd),
nn.GELU(),
# back down to C
nn.Linear(4 * n_embd, n_embd),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: (B, T, C), the stream. Returns (B, T, C)."""
...
forward runs the two steps, and you write it a few steps from now. Each step reads a normalized copy of the stream, changes it, and adds the change back. The block's output has the same shape as its input, (B, T, C), so blocks stack like bricks.
The model keeps its blocks in nn.ModuleList, not in a plain Python list.
You keep the blocks in a plain Python list instead. What happens when you train on the CPU?
Catch a model that reads ahead
The causal mask lives inside your attention module, and a model without it still trains. Train the whole model on random tokens, where nothing can be predicted: with its mask, the loss stays near ln 23 = 3.14, the lowest possible when each next token is a random pick from 23. Without it, the loss falls to 0.21 in 300 steps, because each position copies the answer from the next position. A loss lower than the data allows means the model is reading the answer.
Which test catches a model that reads ahead?
Why the norm goes before each step
The original transformer put LayerNorm after each add. GPT-2 moved it to the start of each step, and that's the version you write. Switch the picture between the two:
- Norm after (original):
x = LayerNorm(x + step(x)) - Norm before (GPT-2):
x = x + step(LayerNorm(x))
The difference is in what happens to the stream.
- Norm before: the stream is a plain sum. Each block adds its changes, and nothing else touches the stream. During training, the gradient from the loss flows straight back along that sum to every block, however deep the model is.
- Norm after: a LayerNorm sits on the stream itself after every step, so the gradient must pass through all of them on the way back. Research on this (Xiong et al., 2020) showed that this makes the gradients near the output large at the start of training. That's why those models needed a slow warm-up of the learning rate. With the norm before each step, they trained without it.
Norm before each step: x = x + step(LayerNorm(x)). If both steps output 0, what does the block do to the stream?
The head scores every word
After the last block, ln_f normalizes the stream one more time. Then the head turns each token's C numbers into V scores, one for each word in the vocabulary.
The head reuses the token table. This is called weight tying:
# C = 3 in, V = 5 scores out
lm_head = nn.Linear(3, 5, bias=False)
print(tok_emb.weight.shape, lm_head.weight.shape)
# one shared table
lm_head.weight = tok_emb.weight
print(lm_head.weight is tok_emb.weight)
torch.Size([5, 3]) torch.Size([5, 3])
True
On the way in, a word picks its row of the table. On the way out, the final vector is dotted with every row of the same table, and each dot product is one word's score:
vector0.5-1.00.8score = row · vectorthe→-0.68cat→0.25sat→-1.22on→0.54mat→-2.39
So the score for a word is the final vector dotted with that word's own row. The direction that means a word on the way in is the direction that predicts it on the way out.
In the editor, table is a hand-made token table for the five words, 3 numbers a row, and h is the final vector at one position. Set scores, h dotted with every row of table, and best, the word with the top score.
Tie the head to the table
Tying changes how often each row of the table learns:
A rare token shows up in one batch out of a thousand. How often does its row of the head get a gradient?
Start every weight small, so the model starts unsure
A model's first loss depends on how its weights start.
GPT-2 starts every weight as small random numbers, with a spread of 0.02, and every bias at 0. A model method, _init_weights, does it in one loop over self.modules(), the model's layers, with nn.init.normal_ for the weights and nn.init.zeros_ for the biases.
The point is a model that starts out unsure. Small weights give small scores, small scores give a softmax close to equal over all words, and an unsure model has a known starting loss: about ln V, the natural log of the vocabulary size. The next part shows why.
All V scores start near 0. What does the softmax give each word?
Guess the next token, everywhere at once
The model predicts each next token from the tokens before it. So the targets are the inputs shifted by one. With the sentence:
# the cat sat on the mat, as a plain list
ids = [0, 1, 2, 3, 0, 4]
# inputs: all but the last
print(ids[:-1])
# targets: all but the first
print(ids[1:])
[0, 1, 2, 3, 0]
[1, 2, 3, 0, 4]
idxtargetsOne sentence of six tokens gives five guesses, one per position, all graded at once. The shift happens where the batch is built, not inside the model.
You shift the targets where the batch is built, and again inside the model. What happens?
Flatten before the loss
The loss is the average, over every guess, of how unlikely the model found the right answer: minus the log of the probability it gave to the right next word. F.cross_entropy computes it. It wants one row of V scores per guess, so flatten the batch and the positions together first: (B, T, V) becomes (B * T, V), and (B, T) becomes (B * T,).
Here are five rows of random scores, the logits in the code further down, one row per guess. Each row is labeled with the word its position has just read. The marked cell is the right next word, and it's the only score in its row the loss looks at:
logits.reshape(-1, V) (5, 5)Pass (B, T, V) straight in, and PyTorch reads the second axis, T, as the vocabulary. This sentence has 5 guesses and 5 words, so T and V are both 5:
# cat sat on the mat
targets = torch.tensor([[1, 2, 3, 0, 4]])
torch.manual_seed(0)
# (B, T, V): 5 guesses, 5 words
logits = torch.randn(1, 5, 5)
right = F.cross_entropy(logits.reshape(-1, 5), targets.reshape(-1))
# reads T as the vocabulary
wrong = F.cross_entropy(logits, targets)
print(round(right.item(), 4), round(wrong.item(), 4))
One loss flattens the logits to (5, 5). The other passes (1, 5, 5) as it is. What happens?
The loss at the start
A fresh model is equally unsure about every word, so it gives each about 1/V. The loss of one guess is minus the log of the chance it gave the right word, and -ln(1/V) is ln V:
import math
print(round(math.log(5), 3), round(math.log(23), 3), round(math.log(50257), 2))
1.609 3.135 10.82
The practice model starts within 0.1 of ln 23, and GPT-2 near 10.96.
GPT-2 starts near 10.96, a little above ln 50,257 = 10.82. Why above?
The length limit
The position table has block_size rows, and the mask is block_size by block_size. So the model can't read more than block_size tokens. Check the length first:
if T > self.block_size:
raise ValueError(f"got {T} tokens, block_size is {self.block_size}")
Without the check, 17 tokens in a 16-position model still fail, but badly: the lookup asks for row 16 of a 16-row table and raises IndexError: index out of range in self from deep inside PyTorch. On a GPU the error can even be reported at a later line. Your check gives one clear message, at the line that caused it.
This matters most when the model generates text. Each step adds a token, so the text soon grows past block_size.
The text has grown past block_size. Which tokens go into the model for the next one?
Counting the parameters
Count one block, then multiply.
One block holds 12C² weights. Where are most of them?
Memory and compute for training
The parameter count also tells you what training will cost.
How much memory does training GPT-2 small take, with 32-bit numbers and the AdamW optimizer, before any activations?
What interviewers ask next
Write generate. Cut to the last block_size tokens, run the model, keep only the last position's scores, pick one token, add it, repeat. Each step reruns the whole sequence. The KV cache lesson removes that waste, and the decoding lesson covers how to pick the token: temperature, top-k and top-p.
Learned positions stop at block_size. Rotary embeddings, RoPE, rotate each query and key by an angle set by its position. What does the score between two tokens then depend on?
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.Your GPT has no position embeddings, and you feed it six copies of token 3. How do the logits at positions 1 and 4 compare?
2.You forget the causal mask and train on uniformly random tokens. What does the training loss do?
3.You leave out
self.lm_head.weight = self.tok_emb.weightin GPT-2 small. What changes?4.Your loss uses
reduction="sum"and the batch is (2, 12). What does it report at initialization?5.block_size is 16, there's no length check, and a batch arrives with 17 tokens. What happens on a CPU?
Where this shows up
The reports behind this lesson, each with its source.
MLE candidate (interviewed Oct 2025, rejected): phone screen ML coding mainly tested Transformer architecture knowledge.
Same MLE report, onsite ML coding: NumPy fluency was essential.
Same April 2026 MLE report, ML debug round: fix a broken miniGPT in PyTorch until it generates correct text, then implement a KV cache.
Same Blind commenter (Oct 2025): the recruiter's e-mail said to study the transformer model ahead of the ML debugging round.
Practice
Sources (6)
- Attention Is All You Need · arXiv 1706.03762 · Jun 12, 2017
“Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence.”
- Using the Output Embedding to Improve Language Models · arXiv 1608.05859 · Aug 20, 2016
“This means that vectors representing rare words are updated only a small number of times. The output embedding updates every row at each timestep.”
- Language Models are Unsupervised Multitask Learners · OpenAI (the GPT-2 paper) · Feb 14, 2019
“Layer normalization (Ba et al., 2016) was moved to the input of each sub-block ... an additional layer normalization was added after the final self-attention block. A modified initialization which accounts for the accumulation on the residual path with model depth is used.”
- On Layer Normalization in the Transformer Architecture · arXiv 2002.04745 · Feb 12, 2020
“if the layer normalization is put inside the residual blocks (recently proposed as Pre-LN Transformer), the gradients are well-behaved at initialization”
- Scaling Laws for Neural Language Models · arXiv 2001.08361 · Jan 23, 2020
“the number of model parameters, excluding all vocabulary and positional embeddings”
- Transformer Language Models without Positional Encodings Still Learn Positional Information · arXiv 2203.16634 · Mar 30, 2022
“We conjecture that causal attention enables the model to infer the number of predecessors that each token can attend to, thereby approximating its absolute position.”