From logits to one token
A trained model doesn't write text. At each position it outputs a score for every token in its vocabulary, called the logits. Decoding is the loop that turns those scores into text, one token per step.
1@torch.no_grad()2def generate(3 model: nn.Module, idx: torch.Tensor, max_new_tokens: int, **decoding4) -> torch.Tensor:5 """idx: (B, T) token ids. Returns (B, T + max_new_tokens)."""6 for _ in range(max_new_tokens):7 logits, _ = model(idx[:, -model.block_size:]) # (B, T, V)8 next_id = sample(logits[:, -1, :], **decoding) # (B,)9 idx = torch.cat([idx, next_id[:, None]], dim=1) # (B, T + 1)10 return idxThis is the whole loop that writes text with a GPT. Each step runs the model, keeps the scores at the last position, picks one token and adds it to the end. Step through it above.
B is the number of sequences, T the tokens in each, and V the number of tokens in the vocabulary. A token is a word or a piece of a word.
The logits are the model's raw scores, before any softmax.
Decoding is the rule inside sample that turns a (B, V) row of scores into one token id per sequence. The weights never change. Still, the same model can write something sharp, something bland or pure nonsense, and that one function decides which.
Greedy decoding takes the top score every time
The model has read The cat sat on the and scores six candidates. Pretend they are the whole vocabulary.
import torch
words = ["mat", "floor", "sofa", "bed", "roof", "moon"]
row = torch.tensor([[3.0, 2.0, 1.0, 0.5, 0.0, -1.0]])
print(row.softmax(dim=-1).round(decimals=3))
print(words[row.argmax(dim=-1).item()])
Six scores, [3.0, 2.0, 1.0, 0.5, 0.0, -1.0], for mat to moon. About how much probability does the softmax give mat, and which word does the argmax pick?