Creating a Vocabulary from a Training Set
A real vocabulary is simply a longer sorted list of unique tokens.
Why Text Must Become Numbers
A language model does its arithmetic on numbers, not on words. Before any passage of text can reach the model, each piece of it has to be given a numeric stand-in. This article follows that translation in both directions: first taking text that is new to the system and expressing it as a sequence of numbers, then turning numeric output back into readable words, because a model whose output cannot be read is of little use.
Two ingredients make the conversion possible. The first is a way of cutting text into smaller units called tokens. The second is a lookup structure, the vocabulary, that assigns each distinct token a unique integer label. Once both are in place, converting new text is mostly a matter of looking things up.
What do you think happens?
The tokenized sentence is 'the fox sees the dog'. Before running anything, how many unique tokens does it contain?
Reveal answer
4
There are five tokens in total, but 'the' appears twice. Removing the repeated entry leaves the, fox, sees, and dog: four unique tokens.
Cutting Text into Tokens
Tokenization is the step that cuts text into individual tokens. A token is not a fixed property of language in general. It is whatever unit the tokenizer produces from the text in front of it. This article uses a deliberately simple rule: split on spaces, and keep only plain lowercase words. Real tokenizers can be considerably more sophisticated, but the mapping step that follows works the same way regardless of the cutting rule.
Read the pipeline from left to right. The raw tokens list may contain many repeated entries. The first transformation collapses those repeats so that each distinct token appears once. The second sorts what remains. The third step, assigning IDs, depends on that order, which is why the sort is not optional decoration. Each stage takes the output of the previous one, so a mistake at any point carries forward to every later stage.
From Unique Tokens to Sorted Order
The construction runs in four stages: tokenize, remove duplicates with set, sort alphabetically, and assign IDs by position. The first two stages produce the list of unique tokens. The third stage arranges that list in a fixed order, and the fourth stage numbers its entries. The code below follows those steps for a sentence whose tokens you can count by hand.
4
{'dog': 0, 'fox': 1, 'sees': 2, 'the': 3}split()produces the five tokens exactly as they appear, including the repeated 'the'.set()keeps one copy of each distinct token;sorted()then puts those copies in alphabetical order.len(all_words)counts unique tokens, not total occurrences, so the vocabulary size is 4.enumerate(all_words)pairs each token with its position, and the comprehension stores each pair as token key and integer value.
Building the vocabulary for one sentence
Build a vocabulary from the tokenized sentence 'the fox sees the dog', then state the ID of each unique token.
- 1Tokenize
Split on spaces to get the, fox, sees, the, dog: five tokens, with the repeated once.
- 2Deduplicate
Keep one copy of each distinct token: the, fox, sees, dog.
- 3Sort
Arrange alphabetically: dog, fox, sees, the.
- 4Assign IDs
Number by position starting at 0: dog is 0, fox is 1, sees is 2, the is 3.
The vocabulary has size 4 and maps dog to 0, fox to 1, sees to 2, and the to 3.
Notice what the mapping does and does not depend on. The IDs are not chosen by meaning or by how often a word appears; 'the' appears twice in the sentence but still receives a single ID, 3, because the vocabulary stores each token only once. The IDs simply follow alphabetical position in the sorted list. Because the lookup is the same every time, identical tokens always receive identical IDs.
Scaling from Five Tokens to a Real Text
The source applies the same procedure to a full literary text, Edith Wharton's short story. After tokenizing it and storing the tokens in a variable called preprocessed, the code determines that the vocabulary size for that text is 1,130, and the vocabulary's first 51 entries are printed for inspection. The procedure is identical to the small example; only the scale changes. A real vocabulary is simply a longer sorted list of unique tokens.
Tracing a New Sample Through the Vocabulary
Tokenization is also the first step when a new text sample arrives. The sample is cut into tokens in exactly the same manner as the training set, so its pieces can be compared with the pieces the vocabulary already knows about. Converting the sample means looking up each token in the vocabulary and keeping the original order of the tokens. The output is a list of token IDs in the same sequence as the words.
[3, 0, 2]
['the', 'dog', 'sees']- The new sample is split with the same rule used for the training text.
- Each token is looked up in the existing vocabulary, so the order of the words is kept in the list of IDs.
- The inverse dictionary is built by swapping key and value, which is what makes it reverse the lookup.
This example depends on the vocabulary already containing every word in the new sample. The section this article draws on does not specify how a conversion should behave when a word is missing from the vocabulary, so no answer is assumed here. In plain Python, a dictionary lookup for a key that does not exist raises an error, which is one reason the handling of unseen tokens is a design decision that has to be made deliberately.
Reading Token IDs Back into Text
The conversion so far runs from text toward numbers. But a language model produces numbers as its output, and those numbers have to be turned back into text before a person can read them. The source states this need directly: when the outputs of an LLM are numbers, a way is needed to turn token IDs into text. The inverse vocabulary provides that way.
The inverse vocabulary is the example vocabulary read the other way. Given a token ID such as 3, it returns the word on in the source's example. Applying this lookup to every ID in an output sequence, in order, reconstructs the text. In the source's example, the sequence 0, 1, 2, 3, 0, 4 is run back through the inverse vocabulary to recover the words the, cat, sat, on, the, mat. That example uses a hand-written vocabulary whose IDs follow the table given in the source rather than the alphabetical order produced by the sorting code, so the two should not be confused.
| Structure | Question it answers | Direction | Example lookup |
|---|---|---|---|
| Vocabulary | Which number stands for this token? | Token to ID | fox to 1 |
| Inverse vocabulary | Which token does this number stand for? | ID to token | 1 to fox |
The two structures are mirror images, and a system that converts text in both directions needs both.
Mistakes That Break the Pipeline
Common mistake Counting total tokens instead of unique tokens when sizing the vocabulary
What it looks likeThe sentence 'the fox sees the dog' has five tokens, but its vocabulary size is 4.
Why it failsThe vocabulary stores each distinct token once, so its size is the length of the deduplicated sorted list.
Do this insteadCompute len of the set-based sorted list, and check that it matches the number of distinct words.
Common mistake Assigning IDs before sorting the unique tokens
What it looks likeNumbering the, fox, sees, dog in the order they first appear gives the 0, fox 1, sees 2, dog 3.
Why it failsThe IDs in this construction come from position in the sorted list, so skipping the sort produces a different mapping.
Do this insteadCheck the sorted stage first: the sorted list should read dog, fox, sees, the before any numbers are assigned.
Common mistake Reversing key and value in the dictionary comprehension
What it looks likeWriting the comprehension so that the integer is the key and the token is the value gives the mapping in the wrong direction.
Why it failsIn the vocabulary the key is the token and the value is the integer, so reversing them breaks the lookup from token to ID.
Do this insteadRead the comprehension from the inside out: enumerate pairs each token with its position, and the token becomes the key.
Common mistake Expecting a new sample to use a different cutting rule
What it looks likeSplitting the training text on spaces but tokenizing a new sentence by character.
Why it failsThe new sample must be cut in exactly the same way so its pieces can be compared with the vocabulary.
Do this insteadApply the same tokenizer to every text that goes through the vocabulary.
Checking Your Own Trace
Tokenize the sentence 'a cat sees a cat and a dog' using split on spaces. Write down the tokens, then the unique tokens, then the sorted list, and finally the token-to-ID mapping. Report the vocabulary size and the ID of cat.
Hints
- Count the total tokens first: there are eight entries, with 'a' appearing three times and 'cat' twice.
- Remove repeats, then sort alphabetically: a, and, cat, dog, sees.
- IDs start at 0 and follow the sorted position, so cat should be the third entry in the list.
Key Takeaways
- Tokenization cuts text into individual tokens, and a new sample must be cut the same way before any numbers are assigned.
- A vocabulary is built by removing duplicates, sorting the unique tokens, and assigning each one a unique integer ID by position; its size is the count of unique tokens.
- Converting new text means looking up each token in the existing vocabulary and keeping the original order, producing a list of token IDs.
- An inverse vocabulary maps IDs back to tokens, which is necessary to turn a language model's numeric outputs into readable text.
- When a result is wrong, check the four stages in order (tokens, unique tokens, sorted tokens, IDs) to find where the output first diverged.