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.