Skip to content
ImagineWorld

Tokenization

node_idnode-book_50-ml-projects-to-understand-llms_chapter-02-tokenization
node_typechapter_node
schema_profileworld.chapter_node.v1
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
statusactive
chapter_num2
chapter_titleTokenization
sections2.1 Project 1: Three tokenization schemes, 2.2 Project 2: Book lengths in characters, words, and tokens, 2.3 Project 3: Pandas frequency tables of token lengths, 2.4 Project 4: Token lengths in characters and bytes, 2.5 Project 5: Is tokenization compression?, 2.6 Project 6: Tokenization and compression in different languages, 2.7 Project 7: Translating between tokenizers
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

LLMs don’t process text; they process numbers.

Tokenization is the process of converting written language into integers. You might think that tokenization is as simple as a=1, b=2, c=3, etc. That is one way to tokenize text, but it’s not the only way — and not the most optimal way.

Figure 2.1 shows three ways to tokenize the word “Hello” using integers.

Figure 2.1: Three tokenization schemes for the word “hello”. Same-colored letters are tokens and the numbers are their corresponding token indices.

Figure 2.1 shows three tokenization schemes, but it’s not the case that you choose which scheme to use; tokenization is learned from text data, for example using the byte-pair encoding algorithm. In OpenAI’s GPT models, for example, most English words are represented using one or a small number of tokens.

Tokens are efficient. Using one token to encode “hello” means that the language model has less data to process, which means cheaper and faster runs, and also longer context windows for generating relevant text. For example, encoding “hello” as one integer has a tokenization compression ratio of 5:1 (5 characters → 1 token). Let’s imagine that this is a reasonable average for all words. And imagine we have an LLM with a maximum sequence length of 1000 integers. 1000 tokens is around 5000 characters (1000 words), whereas 1000 characters is around 200 words.

Tokenization happens before the model sees any data. In fact, you won’t even import the LLMs in the projects in this chapter. Instead, the goal of this chapter is to introduce you to using, interpreting, and characterizing tokenization methods of common open-source LLMs.

Note about terminology: A token is a piece of text (more accurately: a sequence of bytes interpreted as text) whereas a token index is an integer associated with the token, because each token has an index in the vocab. Thus, “hello” is a token and 15496 is its token index. However, use the term token is also sometimes colloquially used when referring to the indices.

Three tokenization schemes

The goal of Project 1 is to explore three tokenization schemes: Tokenization based on characters (that is, letters, digits, and punctuation marks), based on words, and based on statistical properties of written language that are implemented in OpenAI’s GPT-2 tokenizer.

You will discover that character- and word-based tokenization schemes have important limitations in applicability, and that professional-grade LLM tokenization uses a mix of characters, words, and “subwords” (a subword is part of word, like forming “hello” from “hel” + “lo”).

Character-based tokenization is easy to understand and to implement, so we will start there.

Tokenization schemes have a vocab (vocabulary) that contains the unique building-blocks from which text is built.

The code below creates a vocab by segmenting text into a list of individual characters, and then finding the set of unique characters. You will use this text for the rest of Project 1.

txt = ’The way you do anything        is the way you do everything.’

characters = [c for c in txt]

char_vocab = list(sorted(set(characters)))

The Python set function does not sort the result, so the variable vocab will always contain the same elements but they could be in a different order. Therefore, its good practice to sort sets using the sorted function.

The variable characters is a list with 53 elements corresponding to the 53 characters in the text (letters, spaces, and the period). The variable vocab, on the other hand, has 18 elements. The discrepancy between the sizes of the two variables is due to repeated characters (e.g., the letter “a” appears three times).

The size of the vocab reflects a trade-off between model complexity and information density. For example, a vocab based on characters is small (a lightweight vocab for English would include 26 letters, 10 digits, and punctuation marks), which reduces model complexity and parameters — but each character carries very little information; for example, the letter “a” appears in many different contexts. On the other hand, a vocab based on words must be larger (English alone has hundreds of thousands of words), which makes LLM training more complicated — but each word carries much more information.

The vocab size is also important because it constrains the context window, which is the number of tokens a model can process at once. The context window is like the LLM’s “working memory capacity.”

Imagine you want an LLM to process a 1000-word essay. Assuming an average of 5 characters per word, that essay would require 5000 character-based tokens. But a word-based tokenization would require only 1000 tokens for the same essay, which would mean that the model could process 5 times as much text with the same resources.

Anyway, back to our investigation of character-based tokenization:

Task

Write code to create a look-up-table that maps each token (a string) onto an integer. Print out the look-up-table as in Figure 2.2.

(Reminder from Chapter 1 that these task-boxes are instructions for you to implement and code. You should now switch to your Python notebook to write code that reproduces Figure 2.2.)

Tip: Use “char” in your variable names here (e.g., char_vocab), because in Part 3 you will compare the total and unique numbers of tokens from the character-, word-, and GPT-2-based tokenizers.

Figure 2.2: A simple tokenizer look-up-table.

Each token has a corresponding integer index, which provides an invertible translation: Going from characters to indices is called encoding and going from indices to characters is called decoding.

Because this is the first project in the book, I want to remind you of three important points:

  1. The solution code is not printed here in the book; instead, it is available at github.com/mikexcohen/ML4LLM_book.

  2. You can choose three levels of difficulty to engage with the project: start from a blank Python notebook; start from the online “helper” code file that contains comments and incomplete code; go through the full solution code file. There’s no wrong way to work on these projects: If you’re satisfied with how much you’re learning, then you’re doing it right.

  3. For tasks that involve visualizations, don’t stress about matching your visualizations exactly to mine, in particular regarding the marker colors and shapes. Focus on the analyses and the core part of the visualization. And feel free to make your graphs look better than mine :

    )

Task

Write code to tokenize (encode) the text by transforming it from a list of characters into a sequence of integers, which you can print out.

If your look-up-table was the same as mine, you’ll get the following token sequence.

[2, 7, 5, 0, 16, 3, 17, 0, 17, 10, 14, 0, 4, 10,
0, 3, 9, 17, 13, 7, 8, 9, 6, 0, 8, 12, 0, 13, 7,
5, 0, 16, 3, 17, 0, 17, 10, 14, 0, 4, 10, 0, 5,
15, 5, 11, 17, 13, 7, 8, 9, 6, 1]

Professional-grade tokenizers are more complicated, but the essence is the same: you provide text to the LLM (e.g., a prompt asking ChatGPT a question) and that text is encoded into a sequence of integers. Those integers in turn are used to pick out embeddings vectors from a matrix, which you’ll learn about in the next chapter.

Task

Visualize the token sequence in a plot like in Figure 2.3. The x-axis corresponds to positional indices, and the y-axis corresponds to the token indices on the left and the token strings on the right. Draw a box at the y-axis location of each token index.

Notice that at this stage, the strings and integers have a lossless mapping: Using characters is more human-readable, but the one-to-one mapping between characters and integers means that the tokenization is exact and invertible. A fully invertible mapping between text and number is not guaranteed for all tokenization schemes, as you’ll see in Project 7. Furthermore, perfect invertibility is present only before the numbers get inside the LLM: The LLMs transform the numeric representations of text to incorporate context and world knowledge, and to associate with predictions for new text.

Figure 2.3: Visualization of token sequence for a short text.

You might have noticed that our vocab is severely limited. For example, it lacks the letter “x”, not to mention digits, punctuations, emojis, non-Latin letters, and lots of other characters that have a Unicode representation but were not in the short text. But that’s OK; the goal here was not to create a universal tokenizer. You now understand the concept of creating a vocab and a look-up-table to encode a piece of text as a sequence of token indices.

The procedure for word-based tokenization is the same as for character-based tokenization: segment the text, build a vocab of unique elements, and transform the text into a sequence of integers.

The difference is that the vocab will now comprise whole words instead of individual characters. A simple way to segment text into words is to use the .split() method on a string.

Task

Write code to create a vocab of unique words in the same text that you worked with in Part 1. Print the vocab and report the number of tokens in the text and in the vocab.

Visualize the tokenization as in Figure 2.4.

You should find 11 words in the text and 8 elements in the vocab. Here they are:

The list of words is:

[’The’, ’way’, ’you’, ’do’, ’anything’, ’is’, ’the’,
’way’, ’you’, ’do’, ’everything.’]

The vocab is:

[’The’, ’anything’, ’do’, ’everything.’, ’is’,
’the’, ’way’, ’you’]

Figure 2.4: Visualizing a word-based tokenization.

With word-based tokenization, each individual token is much more meaningful than an individual character. For example, the word “you” contains a lot more information than the letter “y”. But a word-based vocab would need a lot more elements: it would need to include all the words in all the languages that the LLM should be trained on. It would also need additional tokens for common misspellings, as well as code “words” like <html> and range(10).

Note: Segmenting a text into words using the .split() method on a string is fast and simple, but is prone to errors because, for example, punctuation marks are included in the segmentation. That’s not a problem here because we won’t continue using word-based tokenization, but is something to be aware of.

The vocabs in LLM tokenizers comprise characters, whole words, and subwords. Real tokenizers are created by combining characters that often appear together in text. For example, “th” is encoded as one token whereas “tq” is encoded as two separate tokens.

The most common algorithm for creating a vocab is called the byte-pair encoding algorithm. Briefly, the algorithm begins with a small character-level vocab, then increases the vocab by adding pairs of characters that often appear together in a large sample of text. The vocab keeps increasing until a set limit is reached. That limit is a meta-parameter specified by the developers. For example, BERT has a vocab size of 30,222, GPT-2 has a vocab size of 50,257, and GPT-4 has a vocab size of around 100,000. (In fact, the tokenization is based on bytes not characters; more about that distinction in Project 4.)

Let’s explore the GPT-2 tokenizer. You can download it using the transformers library provided by the AI organization Hugging Face.

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained(’gpt2’)

Note: You may see a warning message about secret ’HF_TOKEN’. You can safely ignore this warning. There are some models that require providing personal information before downloading from Hugging Face — in which case you would need to authenticate with a unique token — but I have selected models for this book that can be downloaded freely and anonymously.

The tokenizer variable is an object, and includes many useful methods and attributes. For example, tokenizer.vocab_size returns 50257.

You’ll learn more about using tokenizers throughout this book. For now, you need to know only two methods: .encode() segments text and returns a sequence of token indices; and .decode() reconstructs text from a sequence of token indices.

The code and output below encodes text to create token indices, and then decodes each integer back into its string token.

gpt2_tokens = tokenizer.encode(txt)

for token in gpt2_tokens:
toktext = tokenizer.decode([token])
print(f’{token:4} is "{toktext}"’)

Token  464 is “The” Token  835 is ” way” Token  345 is ” you” Token  466 is ” do” Token 1997 is ” anything” Token  318 is ” is” Token  262 is ” the” Token  835 is ” way” Token  345 is ” you” Token  466 is ” do” Token 2279 is ” everything” Token   13 is ”.”

A few remarks about this tokenization:

  1. Each token corresponds to a whole word or punctuation. That happened here because all the words in this sentence are common English words. There is, in general, no guarantee or constraint that tokens correspond to whole words.

  2. Except for the first and final tokens, each token has a preceding space. Leading spaces in tokens is quite common in tokenizers created from the byte-pair encoding algorithm.

  3. Tokens with vs. without leading spaces are distinct. You might consider “ Mike” and “Mike” to be the same word, but GPT-2 assigns those two tokens to indices 4995 and 16073, respectively.

  4. Because tokenization is based on statistical characteristics (byte-pair frequency), you should think about tokens as a way of segmenting text into statistically efficient chunks, not as a way of isolating individual linguistic units.

Side-note on preceding spaces To us humans, the words “stable” and “ stable” are the same: The space is not meaningful as a separate character; it is merely a practical way to separate words. But to a language model, “stable” and “ stable” are distinct. For example, the token “stable” (no space) is also used in “ unstable”. As an example, the output below shows some words and their tokenizations.

” stable” -> [15528] “stable” -> [29092] “unstable” -> [359, 29092]

” able” -> [3025] “able” -> [481] ” unbelieveable” -> [653, 9978, 19704, 481]

Task

Write code to confirm that there are 12 tokens in the text, 9 of which are unique.

Create bar plots showing a comparison of the number of total and unique tokens based on our character and word tokenizers, and from GPT-2’s tokenizer, as in Figure 2.5.

Figure 2.5: Counting the number of tokens using character-based, word-based, and GPT-2-based tokenization.

Don’t over-interpret the comparisons across the tokenization schemes; this is based on one very short piece of text. However, I want you to see the visualization and have the code to run this analysis, because that leads directly into the next project.

day-mode Bookmark

Book lengths in characters, words, and tokens

The goal of Project 2 is to count the number of total and unique characters, words, and GPT-2 tokens in 10 different books that are freely available from gutenberg.org, a website that hosts books that are out of copyright (and therefore free and legal to use for educational and commercial purposes).

Books on gutenberg.org are accessible via a numerical code, and can be imported into Python using the requests library. For example, the following code will retrieve the full text of the book Frankenstein’s monster.

url1 = ’https://www.’ url2 = ’gutenberg.org/cache/epub/84/pg84.txt’ text = requests.get(url1+url2).text print(text)

Once you have the full text of the book, you can count the characters, words, and tokens as you learned in Project 1.

The books on gutenberg.org include headers and footers that aren’t part of the original texts. That’s not a problem for these projects, but is something to be aware of if you want to tokenize only the book text without the added information.

Part 1: Total characters, words, and tokens

Section titled “Part 1: Total characters, words, and tokens”

The goal of Part 1 is to create a table of total characters, words, and tokens, for each of 10 books.

Task

The online code file has a list of 10 books and their gutenberg.org codes. In a for-loop, import each book using the requests library, count the number of characters, words, and GPT-2 tokens, and report the results in a table.

As I discussed in Project 1, using the .split method on a string is not the most accurate method of identifying words, but it’s a good enough approximation for our purposes here.

  Book title     |  Chars  |  Words  |  Tokens -----------------+---------+---------+--------- Frankenstein     | 446,544 |  78,101 | 114,216 GreatGatsby      | 296,858 |  51,257 |  89,268 AliceWonderland  | 167,674 |  29,564 |  52,954 RomeoJuliet      | 167,429 |  29,000 |  56,185 HuckFinn         | 602,714 | 114,125 | 193,378 HeartDarkness    | 232,885 |  40,952 |  63,994 GrimmsTales      | 549,736 | 104,151 | 158,438 EdgarAllenPoe    | 632,131 |  98,100 | 197,306 WarOfTheWorlds   | 363,420 |  63,114 |  96,438 GulliversTravels | 611,742 | 108,135 | 158,345

The first time you tokenize a large text, you might get a warning message about the tokenized sequence length being longer than the maximum sequence length. The maximum context window of GPT-2 is 1024, and if you try to input a longer sequence, that sequence will be clipped. In this case, we’re just counting tokens, not prompting GPT-2, so we can safely ignore that warning.

The goal of Part 2 is to visually compare total and unique token counts for the three different tokenization schemes.

Task

Write code to create Figure 2.6. The figure shows the total (left) and unique (right) number of characters, words, and tokens. Each marker represents a book, and the horizontal bar is the average over all the books.

These findings highlight the trade-off in tokenization that I discussed at the outset of this chapter: Simple tokenizations (e.g., character-based) have small vocabs but also less efficient encoding that does not leverage statistical redundancies in written language (e.g., “th” can be grouped). On the other hand, a word-based tokenization is more efficient (fewer tokens for a given text) but requires a larger number of unique tokens. Professional-grade tokenizers are in between these two extremes.

Figure 2.6: Total and unique counts of characters, words, and tokens, in 10 books (each marker corresponds to a book). Small random x-axis jitters were added to increase visibility.

A challenge in data visualization is comparing results in different scales. For example, the number of unique characters in panel B appears to be zero, but that is an illusion created by the y-axis being scaled by the much larger number of unique words and tokens.

It seems intuitive that the more unique characters, words, and tokens a book contains, the more total characters, words, and tokens it contains. On the other hand, intuition is good for inspiration, but not a successful strategy for rigorous science.

Therefore, the goal of Part 3 is to visualize and quantify the relationship between unique and total counts that you calculated in Part 2.

Task

Write code to produce Figure 2.7. You can calculate the correlation coefficient using np.corrcoef.

Figure 2.7: Relationships between unique and total counts for the three tokenization schemes. Each marker indicates one of 10 books.

The results partially confirm our intuition: Books with more unique tokens are longer in general. However, there is an outlier that skews the relationship for the characters. This outlier is also present in Figure 2.6, but it is invisible because the y-axis is dominated by the words and tokens count. This is a good example of the importance of careful data visualization.

Task

Find which book is the outlier and print out the set of unique characters for inspection.

The “outlier” book is the collection of Edgar Allen Poe’s writings.

However, the numerical value is actually not that extreme; it has only around 20 additional characters, most of which are stylized non-Latin characters like ë. 112 seems like an extreme value only because the other books are so homogeneous with 90-95 unique tokens. Many of the special characters appear only a few times (e.g., ë appears only once in the entire text).

Final comment for Projects 1 and 2: Tokenizing text based on characters or words (via spaces) is fast and easy, and suitable for a conceptual introduction, but those tokenization methods are too limited to be practical. From now on, you’ll use the professional-grade tokenizers.

day-mode Bookmark

Pandas frequency tables of token lengths

In the GPT-2 tokenizer, some tokens correspond to individual characters, but many tokens comprise multiple characters that form subwords and words. How many characters are in different tokens? The goal of Project 3 is to explore that question. You will tokenize various English texts and count the number of characters in the tokens.

(In fact, token lengths are more accurately expressed in bytes not characters. You’ll learn about that distinction in the next project; here we will focus on character counts.)

Use the pandas library when solving this project. You could actually solve this project using NumPy, but pandas is a popular library for tabular (spreadsheet) data, and this project is a good opportunity to practice and improve your pandas skills.

Igor Stravinsky was one of the most influential music composers and philosophers of the 20^th century. The 1913 premier of his ballet The Rite of Spring was so avant-garde at the time that it caused an uproar in the audience (sometimes described as a “riot” although it probably wasn’t that extreme).

But my favorite of Stravinsky’s ballets is called Pulcinella. The online code file contains a description of the ballet from Wikipedia.

Task

Tokenize the text that is printed in the online code file. Confirm that there are 104 words and 174 tokens, 129 of which are unique.

Use the .decode method on the tokenizer to reconstruct the text from the token indices. Confirm that the reconstruction is perfect both qualitatively (by printing out the decoded tokens) and quantitatively (by testing whether the decoded tokens are equal to the original text).

You can test for a match by evaluating whether the following expression is true: tokenizer.decode(tokens) == txt

It is not trivially always the case that decoding an encoded token sequence (that is, inverting the tokenization) is a perfect match to the original text. Whether the reconstruction is perfect depends on the text and on the tokenizer, and you’ll see examples of the non-invertibility with the BERT tokenizer in Project 7. Anyway, the purpose of tokenization is to get text into a numerical format that LLMs can process; there is no need for them to be perfectly invertible functions.

Task

Create a pandas dataframe that contains 174 rows (one per token) and two columns. The first column is the token index and the second column is the number of characters in that token. Print out the first five rows.

Use the dataframe method .value_counts() to create a bar plot of token length distributions, as in Figure 2.8. Use the Seaborn library. I used the color palette plasma.

Here’re the first five rows of the dataframe; your results should match these exactly.

 token length 0    47      1 1   377      2 2    66      1 3   500      3 4  8466      3

Applying the .value_counts() method to the “length” column of the dataframe will create a new Series (“Series” is a pandas data type) with counts of unique token lengths. For example, 38 tokens contain four characters, 36 tokens contain 3 characters, and so on.

The first four rows of that Series should look like this:

length count

4 38
3 36
1 25
2 2

Figure 2.8: Distribution of token lengths (in characters) in the Stravinsky text.

The distribution is obviously strictly positive (counts cannot be negative, and there are no zero-length tokens). Most tokens in the text are three or four characters long, but there are longer tokens — up to 13 characters. Also note that Seaborn sorted the bars according to token lengths (the x-axis values), but did not space the tick marks accordingly. For example, there is no tick mark for 11 characters. It is debatable whether this is incorrect, but it can cause confusion and therefore is something to be aware of.

Keep in mind that this graph is based on one small piece of text. The goal of Part 2 is to explore whether the shape of that token-length distribution is observed in other, and longer, English texts.

Part 2: Distributions of book token lengths

Section titled “Part 2: Distributions of book token lengths”

The primary goal here is to reproduce the analysis and visualization of token lengths from Part 1, using data from the 10 English books from gutenberg.org that you used in the previous project.

Task

In a for-loop over the list of book titles and website codes from Project 1, import and tokenize each book, create the dataframe and Series as in Part 1 of this project, and visualize the results in a scatter plot, using Seaborn’s scatterplot function, as in Figure 2.9.

Books have different lengths, so you will need to normalize the counts.

The value_counts method has an optional input for normalize=True that returns proportions instead of raw counts.

Figure 2.9: Distributions of token lengths in 10 different English books. x-axis is log-scaled.

The distributions look remarkably similar across books: Lots of single-character tokens (these are largely punctuation marks, single digits, formatting characters like new-line, and the pronoun “a”), a peak in the distribution of tokens with 3-5 characters, and a decreasing number of longer tokens.

Keep in mind that although this dataset is considerably bigger than that used in Part 1, it is not representative of the GPT-2 training set: Much of the training set comes from modern web text like Wikipedia, reddit, scientific and medical research articles, and so on. Using small and non-representative samples is fine for educational purposes, but is an important consideration in real research. The risk is that the results observed in a small sample may not generalize to LLM behavior in other situations.

day-mode Bookmark

Token lengths in characters and bytes

Tokens are actually based on bytes, not characters. On the one hand, many characters are represented by exactly one byte — indeed, a byte was originally defined as encoding one character — but other single-character strings comprise multiple bytes, including emojis, letters with diacritical marks like umlauts, characters in languages like Chinese or Tamil, special formatting characters, and so on.

What is a byte? In digital computers, all information is fundamentally coded as binary (zero or one; off or on; False or True). Binary information coding is powerful because it is simple, but one “atom” of information (zero or one — a “bit”) does not convey a lot of rich meaning. Instead, richer information comes from combining bits. A byte is 8 bits grouped together. That provides more information, because one bit has only two possible states whereas a group of 8 bits has 2^8 = 256 possible states. That means there are 256 distinct pieces of information that one byte can represent — more than enough for all the letters and punctuation marks in English, but not enough for all the letters in other languages, not to mention emojis and formatting indicators. That’s why some characters require more than one byte.

Why is a byte 8 bits? Actually, that’s just common convention; bytes could be defined using any other number of bits. Eight bits is convenient because it’s a power of 2 (2^3 = 8), and computer scientists tend to feel comfortable with powers of 2.

Counting bytes in Python You can count the number of bytes in a character in Python by re-encoding it in utf-8. For example, Figure 2.10 shows code and output that counts the number of bytes in different characters.

Figure 2.10: Counting bytes in different characters.

The overall goal of Project 4 is to explore the relationship between token length in characters vs. bytes. As you will discover, the main conclusion is that byte count equals character count for tokens that represent common English words, and byte count is larger than character count for tokens representing non-Latin characters, including emojis and non-English languages. Along the way, you’ll learn more about working with tokenizers and visualizing data.

Part 1: Character vs. byte lengths in all tokens

Section titled “Part 1: Character vs. byte lengths in all tokens”

The goal of part 1 is create two NumPy arrays that store the character and byte lengths of all GPT-2 tokens.

Task

Import the GPT-2 tokenizer. Loop through all tokens in the tokenizer’s vocab, and count the number of characters and the number of bytes in each token. Then depict the results in a scatter plot as in Figure 2.11. The x-y coordinate pairs correspond to the unique pairs of character lengths and byte lengths, and the color of each marker corresponds to the log-frequency of that pair occurring in the vocab.

Getting the color mapping is tricky, and requires using a normalization and Matplotlib ScalarMappable object. However, it is a useful way to visualize a third dimension in a 2D axis, and you’ll use this approach of coloring markers and lines throughout the book.

Figure 2.11: Scatter plot of token lengths in characters and bytes.

The markers on the dashed diagonal line of equality are tokens that have the same number of characters as bytes, while the markers above the diagonal have more bytes than characters.

The plot shows that many tokens have the same number of characters as bytes, while other tokens have more bytes than characters. No tokens have fewer bytes than characters.

In terms of coding implementation, Figure 2.11 can be created by incrementing counts in a matrix of character length by byte length. However, the rest of this project will require having a vector of length 50,257 (the vocab size of GPT-2’s tokenizer) where each element contains the length of that token.

Task

Find the tokens that have a mismatch between character and byte count. You should find 873 tokens with mismatching lengths. Print out 30 randomly selected tokens separated by a pipe symbol (the vertical line). Figure 2.12 shows a random subset.

Figure 2.12: A random subset of tokens that have more bytes than characters, separated by vertical lines.

If you need a hint about printing on the same line instead of in new lines, use the input argument end= in the print() function.

Because the code randomly selects mismatching characters, you can run the code multiple times to see more multi-byte tokens. When the Python notebook cannot display a character, it prints a diamond with a question mark in the middle.

Do longer tokens appear later in the vocab? In other words, is the vocab sorted (exactly or approximately) by token length? That’s what you will explore in this part of the project.

Task

Write code to produce Figure 2.13. This figure shows the token length on the y-axis, as a function of the token index on the x-axis, for characters and for bytes.

Figure 2.13: The x-axis shows token index in the vocab, and the y-axis shows token lengths.

The scatter plot shows that there is no systematic relationship between token length and token index, although it is the case that the earliest tokens tend to be shorter. Try, for example, zooming into the first 600 tokens.

The ordinal positions of tokens in the vocab are not random: They are sorted by the byte-pair encoding algorithm, with more frequent byte pairs appearing earlier in the vocab. On the other hand, differences in tokenizer training sets, meta-parameters, and implementations mean that different tokenizers have different mappings between text segments and token indices. You’ll explore this more in Project 7.

Part 3: Finding the “mismatch-length” tokens

Section titled “Part 3: Finding the “mismatch-length” tokens”

“Mismatch-length” is not a formal technical term; I’m using it here colloquially to refer to tokens that have more bytes than characters.

Are mismatch-length tokens clustered in neighboring token indices, e.g., at the end of the vocab? Or are they distributed throughout the tokenizer? That’s the question you will answer here.

Task

Write code to create Figure 2.14. Each token index has a small circle plotted at y = 0 (same number of characters as bytes) or y = 1 (more bytes than characters). Add small random jitters to help visualize the density of dots.

Figure 2.14: “Mismatched” tokens (where the number of bytes is greater than the number of characters) appear throughout the vocab.

There certainly is no trivial ordering of the tokens according to byte-character mismatch. In other words, the uncommon non-English tokens are not preferentially clustered in the GPT-2 tokenizer.

In Project 3, you calculated and visualized the lengths of tokens in 10 English novels. That plot was informative, but it didn’t show all the tokens; it showed only the tokens in those books.

Here in Part 4, you will follow-up on that analysis by examining distributions of the lengths of the tokens in the GPT-2 tokenizer.

Task

Use np.unique to calculate the unique number of characters and bytes in the tokenizer, using the variables you created in Part 1. Convert the counts to percent and plot the results as in Figure 2.15.

Do not be confused about the differences between Figures 2.9 (from Project 3, Part 2) and Figure 2.15 (from this project and part): Project 3 was about lengths of tokens that appear in texts, whereas this project is about lengths of unique tokens in the tokenizer’s vocab.

Figure 2.15: Distributions of token lengths in characters and bytes, log-scaled. The peak in the distribution is around 5-7 bytes.

Interesting to see that there are relatively few tokens with one or two characters, although those tokens appear very often in texts. Also interesting that there is one token with 128 bytes. You can find and print that token to see what it is.

day-mode Bookmark

Is tokenization compression?

Each token an LLM processes has costs. A computational cost, an energy cost, a financial cost, a training cost. Extraneous tokens are wasted tokens. That’s why tokens don’t correspond to bits: Imagine burning 8 times as many tokens to get the same answer compared with a byte-based tokenizer. And of course, many tokens are subwords and words, which further reduces the number of tokens it takes to encode a text prompt.

Therefore, models benefit by having fewer tokens to process, where each token encodes more information. For example, the word “hello” requires 40 tokens for a bit-based tokenizer, five tokens for a byte-based tokenizer, and one token for a word-based tokenizer.

On the other hand, packing too much information into one token is not advantageous: If there were one token per sentence, the model would need a near-infinite number of tokens for the near-infinite number of sentences that are used — not to mention the fragility to minor spelling or grammar mistakes.

As you now know, tokenizers encode individual bytes, subwords, and words. Subwords and words are made of multiple bytes. That seems to imply that tokenization is compression. The goal of this project is to explore this idea using books and websites. We’ll stick to English books and websites here, and then explore other languages in the next project.

Before starting, a word of preemptive caution: I’m using compression here to refer to using fewer tokens compared to characters or bytes. For example, from a data-storage perspective, an investigation into compression would need to consider whether the tokens are encoded as ints or floats. But tokens are used to pick out dense vectors that the LLM transforms. Therefore, the relevant interpretation of “compression” for this project is the number of elements that encodes a text. For example, using one token to encode “hello” vs. five tokens to encode [“h”,“e”,“l”,“l”,“o”] would correspond to a compression ratio of 1∕5 = 20%.

We will continue working with the same 10 books from gutenberg.org that you’ve now used several times.

Task

In a for-loop over books, count the number of characters, the number of words (using the .split() method), and the number of tokens in each book. Calculate two compression ratios: the number of tokens divided by the number of characters, and the number of tokens divided by the number of words. Print the information in a table as below.

The final column in the table below is the compression ratio in percent for tokens relative to characters (before the slash) and words (after the slash). For example, the book Frankenstein’s Monster contains 446k characters and 114k tokens, thus we can say that tokenization compressed the book by 26% relative to the character count. On the other hand, there are more tokens than words in the text, leading to an expansion (“compression” of 146%).

  Book title     |  Chars  |  Words  |  Tokens | Compress -----------------+---------+---------+---------+--------- Frankenstein     | 446,544 |  78,101 | 114,216 | 26 / 146 GreatGatsby      | 296,858 |  51,257 |  89,268 | 30 / 174 AliceWonderland  | 167,674 |  29,564 |  52,954 | 32 / 179 RomeoJuliet      | 167,429 |  29,000 |  56,185 | 34 / 194 HuckFinn         | 602,714 | 114,125 | 193,378 | 32 / 169 HeartDarkness    | 232,885 |  40,952 |  63,994 | 27 / 156 GrimmsTales      | 549,736 | 104,151 | 158,438 | 29 / 152 EdgarAllenPoe    | 632,131 |  98,100 | 197,306 | 31 / 201 WarOfTheWorlds   | 363,420 |  63,114 |  96,438 | 27 / 153 GulliversTravels | 611,742 | 108,135 | 158,345 | 26 / 146

Interestingly, all books have roughly the same compression relative to characters: The GPT-2 tokenizer has around a quarter to a third of the number of tokens compared to the number of characters. On the other hand, there are many more tokens than words. Part of that difference is due to the inaccuracies of the .split() method (e.g., punctuation marks are attached to their preceding word), and part is due to tokenizers encoding characters and subwords for low-frequency or longer words.

By the way, you learned in Project 4 that the number of bytes can exceed the number of characters. If you are curious, you can recreate the table, or add an additional column, using byte counts instead of character counts. However, because these books contain relatively few non-Latin-standard characters, the results are largely the same.

This part of the project is similar to the previous but using websites instead of English books. But not just the text from websites — the html code behind the websites.

You can import a website using the same requests library that you used for book texts from gutenberg.org. For example, Figure 2.16 shows how to retrieve the html code of python.org.

Figure 2.16: Demo of importing a website html file into Python.

Task

Write code to produce the table shown in Figure 2.17. There aren’t “words” in html code, so you can focus on characters and bytes. The online code file has a list of website urls that you can use.

Figure 2.17: Table of compression ratios in html code.

Because html code mostly comprises standard English characters (letters, punctuation marks, and code characters like < and >), the number of bytes is nearly identical to the number of characters.

The conclusion of Project 5 seems to be that tokenization compresses text relative to the number of characters, by a factor of 3-4. That certainly is a valid conclusion based on the data used in this project, but the conclusion does not necessarily generalize to other languages. Segue to Project 6…

day-mode Bookmark

Tokenization and compression in different languages

Over the past several projects, you have seen that (1) the number of bytes roughly matches the number of characters in common English texts, and (2) there are fewer tokens than characters in English books and html code. Are those observations generally true in other languages? Let’s explore that here.

You’ll inspect only a small piece of text instead of multiple books, but we only need a small sample size to demonstrate the key results.

Part 1: Compression in different languages

Section titled “Part 1: Compression in different languages”

Let’s use some lyrics from the Beatles song Penny Lane. I used Google’s translator to translate the lyric into seven other languages: Spanish, Arabic, Persian, Lithuanian, Chinese, Tamil, and Hebrew. The translations are printed in the online code file.

Task

In a for-loop over the translations, count the number of characters, bytes, and GPT-2 tokens, and store the results in lists (you’ll need the data to visualize later).

Print out the decoded tokens to ensure accuracy of the encoding.

Generate the table below and compare the results across languages.

 Language  |  Chars  |  Bytes  |  Tokens -----------+---------+---------+---------

English | 159 | 159 | 36
Spanish | 174 | 175 | 61
Arabic | 119 | 215 | 130
Persian | 179 | 330 | 215

Lithuanian |   168   |   177   |   84

Chinese | 47 | 141 | 94
Tamil | 202 | 558 | 557
Hebrew | 106 | 191 | 122

You can print the table one line at a time inside the for-loop. But if you’d like to challenge yourself a bit more, define the table as an expanding string inside the for-loop, and then print the table in a separate code block.

Inspecting the table reveals an interesting pattern: Some languages have identical or very similar numbers of characters and bytes (e.g., English and Spanish), while other languages have many more bytes than characters (e.g., Chinese and Tamil).

Having data in a small table is great, but staring at a grid of numbers is not always conducive to comprehension. If only there were a better way to visualize these results (segue to the next part)…

Task

Write code to create Figure 2.18. Each letter in the plot is the first letter of a language. To use a letter as a marker in a plot, you can use either plt.text() or plt.plot() with the marker specified using latex formatting (a letter surrounded by dollar signs).

Panel A shows that the non-Latin alphabet languages (Chinese, Arabic, Hebrew, Persian, Tamil) have more bytes than characters, and more diversity in translation length, whereas the Latin alphabet languages (English, Spanish, Lithuanian) have comparable character and byte counts, and similar lengths. These results are not surprising considering that English dominated the tokenizer training data.

Figure 2.18: Scatter plot of characters by bytes count in various languages. Each letter is the first letter of the language.

Panel B shows tokenization compression relative to characters. The languages below the diagonal indicate compression (fewer tokens compared to characters) whereas the languages above the diagonal indicate expansion (more tokens than characters). The non-Latin alphabet languages have individual letters that require multiple bytes to encode (that’s also the case for, e.g., emojis).

Panel C shows tokenization vs. byte count. Here, all languages fall on or below the diagonal line of unity, with languages further below the line indicating fewer tokens compared to bytes.

Back to the question of this project Is tokenization compression? The answer is it can be, depending on several factors including the language of the text. To be clear: These results do not demonstrate that some languages are intrinsically more or less compressible than other languages; the differences observed here are due to differences in training distribution used in the GPT-2 tokenizer. The training datasets are dominated by English and other common Latin-based languages like Spanish and German, and thus those languages have privileged representations in the tokenizer — and in the LLMs. This has implications for evaluating, deploying, and ensuring accuracy and safety of LLMs used in different languages and in different geographical regions.

Also keep in mind that this project is based on GPT-2; modern commercial LLMs have improved multi-lingual capabilities, and there are LLMs that are custom-tailored for particular languages, or for multi-language translations.

day-mode Bookmark

Translating between tokenizers

All tokenizers are the same in that they translate text into a sequence of integers. But tokenizers can differ across AI-development companies. Even within a company, different versions of an LLM can have different tokenizers that segment text in different ways.

The two goals of this project are (1) to explore differences between tokenizers and (2) to create Python functions that can translate text between tokenizers.

We will focus on two tokenizers from OpenAI: one from their GPT-2 model family and one from their GPT-4 family. The code below shows how to import the two tokenizers using libraries provided by Hugging Face.

# GPT-4’s tokenizer
import tiktoken

tokenizer_4 = tiktoken.get_encoding(’cl100k_base’)

# GPT-2’s tokenizer
from transformers import GPT2Tokenizer

tokenizer_2 = AutoTokenizer.from_pretrained(’gpt2’)

Note 1: tiktoken is formed from tik and token, not tiktok and en.

Note 2: The cl100k_base is used by several OpenAI models, including GPT-3.5. However, I will refer to it as the GPT-4 tokenizer for simplicity.

Part 1 involves exploring the tokenizer variables (class instances). You will discover that although the tokenizers are from the same company (OpenAI) and correspond to nearly the same model (GPT-2 vs. GPT-3.5/4), the tokenizers have distinct properties.

Task

Find the number of tokens in each tokenizer, using the relevant attribute in the tokenizer instances. You already know from previous projects that the GPT-2 tokenizer has an attribute vocab_size; the question is whether the GPT-4 tokenizer has that same attribute with the same name. You can use dir(obj) to see a list of all attributes of variable obj.

The relevant attributes are:

tokenizer_2.vocab_size tokenizer_4.n_vocab

You can print out the vocab sizes to confirm that the GPT-4 tokenizer has 100,277 tokens, and that the GPT-2 tokenizer has 50,257 tokens.

One practical implication of the difference in attribute naming is that you cannot assume that code written for GPT-2 will work for other OpenAI models, let alone models developed by other orgs. (That said, all GPT-2 variants use the same tokenizer.)

GPT-4 has around twice as many tokens as GPT-2. What are those additional tokens? We can gain some insight into the differences by plotting distributions of token lengths.

Task

Count the number of bytes in all tokens, and generate the histograms shown in Figure 2.19. Use the NumPy function bincounts instead of a histogram.

Note 1: The GPT-4 tokenizer requires a different input data type for its decoding method, compared to GPT-2. If you encounter errors, consider changing the input argument data type from int to something else. Note 2: The lengths of the GPT-2 tokens can be calculated using a for-loop or using list comprehension; I show both approaches in my solutions file. Note 3: The GPT-4 tokenizer gives an error for a some token indices that cannot be decoded in isolation; you will need to figure out how to deal with errors arising from those tokens.

A few additional notes about generating Figure 2.19:

  • These data are integers (no floating-point numbers). Therefore, using exact counts (from np.bincount) is better than defining bin boundaries with histograms.
  • Because the tokenizers have different lengths, you need to convert the data into proportions. That would also be true if you used histograms.
  • Use logarithmic scaling for both the x- and y-axes, because the ranges are quite wide. Logarithmic scaling also helps to interpret the subtle differences between the two tokenizers. You can re-plot using linear axis scaling for comparison.

In my code solution, I initialized the lengths variables as NumPy arrays of integers, then set any non-functional tokens to a value of -1. That allowed me to extract the counts of only the non-negative lengths.

Figure 2.19: Distributions of token lengths for two OpenAI tokenizers.

The distributions show that both tokenizers have comparable proportions of tokens that have roughly 10 bytes (10^1) or fewer, whereas the difference between the tokenizers is that GPT-4 has many more tokens encoding longer (more bytes) subwords. Those longer tokens can be used for non-Latin languages and for code segments.

Do the differences you observed in part 2 have implications for tokenizing texts? Let’s explore.

The goal here is to count both the total number of tokens, and the average token length (in bytes) in the 10 gutenberg.org books that you’ve been using so far in this chapter, and then visualize the comparisons of the two tokenizers in scatter plots.

Task

In a for-loop over the books, import each book, tokenize twice to obtain a list of GPT-2 tokens and a list of GPT-4 tokens, count and store the total number of tokens in the book, and count and store the average number of bytes in all the tokens in the book.

Visualize the results in two scatter plots as in Figure 2.20.

A few additional comments about creating the figure:

  • Use scientific notation for the axis tick marks in the left plot.
  • Within each plot, use the same x-axis and y-axis limits to facilitate interpretation.
  • The diagonal line of unity has a slope of 1, and can be calculated by finding the minimum and maximum values of both tokenizer results.

Figure 2.20: Comparison of tokenization in GPT-2 vs. GPT-4. Panel A shows token counts in various books, and panel B shows average token lengths in bytes. Each marker represents data from each book.

The token lengths plot in panel A shows all books below the diagonal, indicating that there are more GPT-2 tokens than GPT-4 tokens for the same texts. On the other hand, the scatter plot in panel B shows that the GPT-4 tokens are, on average, longer (more bytes). Thus, GPT-4 tokenization uses fewer, longer tokens compared to GPT-2 tokenization.

There is no one-to-one mapping between tokens in different tokenizers. Therefore, to translate between, e.g., GPT-2 and GPT-4 tokens, you need to decode the tokens back to text, and then re-encode.

For this reason, it is generous to label the functions you’ll create here “translators”; a more accurate description would be “decode → re-encode” functions. That is, we’re not directly translating from one tokenizer to another; instead, we are decoding back to the original language and then encoding into another tokenization scheme.

Task

Write two Python functions that take in a token integer sequence in one tokenizer (e.g., GPT-4) and return a token integer sequence in another tokenizer (GPT-2). Test your functions using the following text (preserve the capitalization): Canadian winters are kept WArM bY the friendliness of THE PEOPLE.

The text below shows the results of my translator functions. The idea is to start from the original text, encode using GPT-2, then translate into GPT-4 tokens, and checking that the original text is perfectly reconstruction. Then repeat but starting with GPT-4 tokens.

Original text:

Canadian winters are kept WArM bY the
friendliness of THE PEOPLE.

GPT-2 tokens:

[28203, 45764, 389, 4030, 370, 3163, 44, 275,
56, 262, 1545, 26061, 286, 3336, 36388, 13]

GPT-4 tokens:

[60674, 86082, 527, 8774, 468, 7098, 44, 293,
56, 279, 4333, 49958, 315, 3247, 67825, 13]

GPT-2 reconstruction:

Canadian winters are kept WArM bY the
friendliness of THE PEOPLE.

GPT-4 reconstruction:

Canadian winters are kept WArM bY the
friendliness of THE PEOPLE.

GPT-2 to GPT-4 translation:

Canadian winters are kept WArM bY the
friendliness of THE PEOPLE.

GPT-4 to GPT-2 translation:

Canadian winters are kept WArM bY the
friendliness of THE PEOPLE.

The awkward capitalization in the original text allows you to confirm that OpenAI’s GPT tokenizers preserve non-standard capitalization. In other words, the two tokenizers are distinct, but their translation (at least for this short text) is lossless. Lossless tokenization is not trivial nor is it guaranteed in all tokenizers, as you will soon discover.

The goal of Part 5 is to repeat the previous four parts of this project but comparing the BERT tokenizer with GPT-2 (instead of GPT-4 vs. GPT-2).

Task

Make a copy of the GPT-2 vs. GPT-4 notebook file (Parts 1-4) to modify for Part 5 (in the online code solutions, the filename is ml4llm_ch2_proj7b.ipynb).

BERT is an acronym for bidirectional encoder representations from transformers. It was an early LLM developed by Google and was customized for classifying text, e.g., product reviews as positive or negative. Its vocab contains 30,522 elements.

You can import the BERT tokenizer using the following code.

from transformers import BertTokenizer

name = ’bert-base-uncased’ tokenizer_B = BertTokenizer.from_pretrained(name)

Note: The BERT tokenizer automatically includes two additional tokens before and each each text. For example:

Original text:  Peanut and strawberry

Token sequence:  [101, 21443, 1998, 16876, 102]

Token index    101 is “[CLS]” Token index  21443 is “peanut” Token index   1998 is “and” Token index  16876 is “strawberry” Token index    102 is “[SEP]”

[CLS] is for classification and is used in classification tasks like sentiment analysis. [SEP] is for separator and is used to demarcate different text segments.

Task

Find at least two ways to obtain BERT tokens without the preceding and postceding special tokens. Slicing and toggling them off during encoding are two options.

These “special tokens” are relevant for training and for certain classification tasks, but are not necessary here. In fact, they are confounds for this project because they inflate the number of tokens. You’ll see an application of using the [CLS] token for sentiment classification in Project 30.

Task

Modify the notebook file to replace the GPT-4 tokenizer with the BERT tokenizer, and rerun the code file.

I won’t show all of the resulting figures here, but of course you can check my results using the online code solution. There are several take-home points: