Chapter 4: Tokenization¶
Figure 4.1: Tokenization in the big picture.
In the last chapter we learned how to use tensors to store our information. So now that we're moving on to the next part of our map (Figure 4.1), we need to convert our text into numbers. A language model cannot understand patterns in our text if it's not converted to numbers. Neural networks operate on mathematics so we have to represent our text as numbers. This chapter will cover how to make our tokenizer which will take our text and split it into smaller chunks and give each one a number.
In this chapter you will:
- Understand why neural networks need numbers
- Build a character-level vocabulary from the Shakespeare dataset
- Write functions to encode text into integers and decode it back
- Prepare the data for training by splitting it into two sets
Words to Know
- Token: one small piece of text, here a single character.
- Tokenizer: a translator that cuts text into tokens and gives each token a number.
Theory¶
Neural Networks Are Number Machines¶
Figure 4.2: A tokenizer turns each character into a number.
Neural networks aren't able to read. So how would you give them a string of characters such as "Hello"? They deal with arrays of numbers that they can multiply and add together. In order to give the neural network characters we have to turn them into numbers. This process is called tokenization (Figure 4.2).
You want to create some kind of dictionary that if the character a is the number 0 then it will always be 0. This is known as your vocabulary.
The Simplest Tokenizer¶
Text can be tokenized in many ways. You can have a dictionary for each word (tokenizing at the word level) or you can combine frequent characters like th.
We will be using the most basic form of tokenization which is at the character level. Every character that appears in our dataset will have its own corresponding integer.
Say our vocabulary was {a: 0, b: 1, c: 2}, then the word cab would be converted to [2, 0, 1].
The Shakespeare data has 65 unique characters. It has all upper case characters, lower case characters, space, line break and some punctuation and one number. If we assign each of these characters an ID from 0-64 we can convert any sentence in shakespeare to a list of integers.
In Business
If you’re training an assistant to generate text in your organization’s house style, decisions about tokenization can have ramifications. Character-level tokenization leads to longer sequences, while word-level tokenization leads to smaller sequences but requires an enormous vocabulary. Byte-Pair Encoding (BPE) is a compromise widely used in modern enterprise assistants. It merges frequently occurring character sequences into single tokens. We use character-level here because it simplifies the math, while our model learns from its archive (our Shakespeare dataset).
The Training and Validation Split¶
Figure 4.3: Hiding part of the data lets us test whether the model learned.
Once we encode all of Shakespeare into one long list of numbers, we split it into two piles (Figure 4.3):
- Training set (90%): The data the model studies to learn patterns.
- Validation set (10%): The data we hide from the model, used to test it later.
We withhold data so we can test whether our model has learned patterns that generalize to the rest of the text, or if it has simply memorized the passages we showed it during training. If a model does well on the training set but poorly on the validation set, we say it has memorized the training text. This is known as overfitting.
Watch Out
Our tokenizer knows nothing outside of the characters it saw during training. If you give it a number (1 or 2 for example), an emoji, or a Chinese character, Python will throw a KeyError since that character isn't part of our 65-character vocabulary.
Code¶
We write our tokenizer in Python, load the dataset, and encode it.
File:
src/ch03_tokenizer.pyRun it:python src/ch03_tokenizer.py
| src/ch03_tokenizer.py (excerpt) | |
|---|---|
The code does three things:
- Line 3 uses
set(text)to find every unique character in the entire text. - Line 3 uses
sorted()to put them in alphabetical order so the IDs stay consistent. - Lines 6 and 7 build two lookup tables, which Python calls dictionaries: one to go from character to ID (
char_to_id), and one to go back (id_to_char).
Figure 4.4: How the tokenizer processes the dataset.
The script processes the dataset step by step (Figure 4.4). Next, we write the translation functions:
| src/ch03_tokenizer.py (excerpt) | |
|---|---|
Line 3 converts a string (a piece of text) into a list of whole-number IDs, and line 7 converts them back into text.
Now we run the script to see what our 65 characters look like and to test a quick round-trip.
$ python src/ch03_tokenizer.py
!$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
...
--- Testing encode / decode ---
Original : 'Hello, World!'
Encoded : [20, 43, 50, 50, 53, 6, 1, 35, 53, 56, 50, 42, 2]
Decoded : 'Hello, World!'
Round-trip matches: True
--- Encoding the full dataset ---
What just happened:
- The script loaded over a million characters from the dataset.
- It found exactly 65 unique characters. Notice the space and newline characters at the start.
- It translated the string "Hello, World!" into a list of integers.
- It translated those integers back to prove no data was lost.
Finally, we encode the entire dataset into a PyTorch tensor and split it.
Training tokens : 1,003,854
Validation tokens: 111,540
Tokenizer ready! Ready for Chapter 5.
Try It¶
See how different inputs are converted into numbers. We wrote a short script that imports our tokenizer and encodes a few business phrases.
Try It
Open the terminal and run the example script. Notice how every letter, space, and punctuation mark is assigned a specific number from our vocabulary.
Key Takeaways¶
- Neural networks work with numbers. They can't directly work with text. That's why we need to convert text into numbers first.
- This process is called tokenization. We tokenize our texts as numbers based on a static vocabulary.
- We will be using a character-level tokenizer with a vocabulary of 65 characters.
encode()converts strings to lists of IDs.decode()converts IDs back to strings.- We divide our data into training data ("Learn from these") and validation data ("Test on these").
Check Your Understanding¶
- How come we need to turn our text into numbers to use with a language model?
- If we attempt to encode a character that wasn't in the training data using our character-level tokenizer, what will happen?
- Why do we need a validation set?
- How many unique characters are in our vocabulary?
Assignment¶
Assignment 4: Same word, new numbers
About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch04_tokenizer_demo.pyunaltered. Copy the three rows it outputs, which will be phrases with their lists of numbers. - Change one word. Locate the line
"URGENT!",. It's one of the three phrases we'll convert to numbers with this script. Replace the wordURGENTwithurgent, making it all lowercase letters, but leave the rest of the line intact, so it says"urgent!",. Run the script again. - Compare. Which numbers changed in the second row? Which did not, and what letter does it represent? Two numbers in your new row are also in the
invoicerow. What two letters do they represent? - Explain it. In two or three sentences someone who manages you would understand, explain why the model sees
URGENT!andurgent!are two different pieces of text when people reading them understand it's the same word.
Hand in: both sets of three rows, your answers to step 3, and your sentences.
Further Reading¶
Why real models do not use a character vocabulary. Chapter 4 assigns a unique token to every character. This keeps the vocabulary small and the code concise. Models used in production tokenize text into word pieces instead. Common words are not split, rare words are split into subwords, and no word is ever unknown. This paper describes the algorithm, which remains the basis of the tokenizers included with modern models today.
Sennrich, R., Haddow, B., & Birch, A. (2015). Neural machine translation of rare words with subword units (arXiv:1508.07909). arXiv. https://doi.org/10.48550/arXiv.1508.07909
Next up: Chapter 5: Embeddings