Character tokenization in nanoGPT
A play starts as text. The preparation script gives each character a number and saves those numbers in the format the trainer reads.
Read the original data/shakespeare_char/prepare.py
Download the text if it is not here yet
The first ingredient is Tiny Shakespeare, a plain-text collection of Shakespeare’s writing. The script looks for input.txt in its own directory. If the file is missing, it downloads a copy and saves it there so later runs can reuse it.
Let the characters themselves be the vocabulary
A token here is one character. The script reads the play, lists every distinct character, and sorts that list so the ids stay stable. stoi turns a letter into its place in that list. itos turns the place back into a letter. Encoding is a walk along the string. Decoding is joining those letters again. About 65 symbols cover this file, including space and punctuation.
Save a 90/10 split as uint16 binaries
Training does not read the play. It reads two binary files. The first 90% of the characters become train.bin, the last 10% become val.bin, and every id is stored as a 16-bit integer, which is plenty for an alphabet of 65. meta.pkl sits beside them and holds vocab_size, stoi, and itos, so a later script can turn ids back into letters. The split is a single cut, not a shuffle, so validation is later text from the same file.
Check your understanding
- What is stored in train.bin versus meta.pkl?
- Why build stoi and itos before writing bytes?