How nanoGPT generates text
A trained model continues a prompt one token at a time. Sampling picks from the model’s scores and feeds each new token back in.
Choose how to sample, then apply overrides
Sampling starts as another list of globals. Resume from a checkpoint unless a GPT-2 name is given. Draw ten continuations of 500 new ids, at temperature 0.8, keeping the 200 most likely ids. The seed is 1337. Then configurator.py runs, so a flag or a config path can retarget the output directory before any weights load. Temperature below 1 makes the distribution a bit sharper. 0.8 is only mildly sharp.
Load a checkpoint, or a published GPT-2
Resume reads ckpt.pt, rebuilds the GPT from the saved model args, and loads the tensors, stripping a compile prefix off the names if torch.compile() had wrapped the module. A gpt2 name calls from_pretrained with dropout set to 0. Then the module is put in evaluation mode with eval() and moved to the device. Eval matters: dropout left on would change the distribution every call. Compile stays off unless you ask.
Turn text into ids the same way training did
A character checkpoint is only meaningful with the alphabet that built it. If the checkpoint names a dataset and that folder has meta.pkl, encode and decode use stoi and itos. Otherwise the script loads the GPT-2 tokenizer. Mixing them, character ids decoded as word-pieces or the reverse, prints nonsense. The pickle from the first lesson is what keeps letters matched.
Encode the prompt and print samples
The prompt is a string, or the contents of a file if it starts with FILE:. It is encoded with whichever codec the previous block chose and shaped as a single batch. generate, which you read at the bottom of model.py, appends new ids inside the model. This script does not sample itself. It turns gradients off, calls generate with the temperature and top-k from the top of the file, decodes the finished row, and prints a divider between samples.
Check your understanding
- Why divide by temperature before softmax?
- What happens after each sampled id?