Vocabulary
Giving every unique token a stable integer identity.
By the end of this chapter, you'll be able to:
- Build a token-to-ID and ID-to-token mapping from a list of tokens
- Encode tokens into IDs and decode IDs back into tokens
- Explain why an ID, by itself, carries no meaning
Tokenization gives you a list of strings. A neural network can't do arithmetic on strings any more than it can on raw text — so the next step is to give every unique token a stable, unique integer: its ID.
Building the mapping
class Vocabulary:
def __init__(self):
self.token_to_id = {}
self.id_to_token = {}
def build(self, tokens):
unique_tokens = sorted(set(tokens))
for index, token in enumerate(unique_tokens):
self.token_to_id[token] = index
self.id_to_token[index] = token
def encode(self, tokens):
return [
self.token_to_id[token]
for token in tokens
]
def decode(self, ids):
return [
self.id_to_token[id]
for id in ids
]build() collects every unique token, sorts them for a deterministic ordering,
and assigns each one the next available integer. encode() and decode() are
exact inverses of each other — one turns tokens into IDs, the other turns IDs back
into tokens.
tokenizer = Tokenizer()
tokens = tokenizer.tokenize("AI, ML, NLP")
print(tokens)
# ['ai', 'ml', 'nlp']
vocabulary = Vocabulary()
vocabulary.build(tokens)
print(vocabulary.token_to_id)
# {'ai': 0, 'ml': 1, 'nlp': 2}
ids = vocabulary.encode(tokens)
print(ids)
# [0, 1, 2]
words = vocabulary.decode(ids)
print(words)
# ['ai', 'ml', 'nlp']| Token | ID |
|---|---|
| ai | 0 |
| ml | 1 |
| nlp | 2 |
An ID is an address, not a meaning
It's tempting to assume token ID 2 is somehow "more" than token ID 0, or that
IDs that are numerically close are semantically related. Neither is true. IDs are
assigned by when a token happened to be encountered while building the
vocabulary — "ai" got 0 here simply because it's alphabetically first. If you
vectorize a corpus in a different order, or Wednesday's tokenizer, you'd get
entirely different numbers for the same words.
This is exactly the problem the next chapter, Embeddings, exists to solve.
What happens at scale
A real vocabulary isn't built from one sentence — it's built once from an entire training corpus, often capped at a fixed size (GPT-family models use vocabularies in the tens of thousands). Every token the model will ever see or produce has to already exist in that fixed table. This is also exactly why subword tokenization (from the previous chapter) matters: it keeps that fixed-size vocabulary from ever being caught completely off guard by a word it's never seen.
Check your understanding
1. In the example above, why does 'ai' get ID 0 instead of, say, 'ml'?
2. What does a token ID represent on its own, before any training happens?