ReaderTube

AI summary

Yellow marks are automatic key passages. They aren’t personal saved highlights. Select a timestamp to follow along with the video.

Tokenization, the process of turning text into integer tokens for large language models, is an unpleasant but essential stage that underlies many of their oddities, from poor spelling, arithmetic and non-English performance to GPT-2's weakness at Python. The byte-pair encoding algorithm builds a vocabulary by encoding text as UTF-8 bytes and repeatedly merging the most frequent pair into a new token, and a tokenizer trained this way can encode and decode text. GPT-2 and GPT-4 add regex-based chunking rules, special tokens and other changes on top of this, while SentencePiece, used by Llama, runs the merges on code points with a byte fallback, and vocabulary size remains a tuned trade-off between sequence length and model cost. Weirdness such as trailing-space warnings, partial and unstable tokens, and the untrained SolidGoldMagikarp token traces back to tokenization, so in the presenter's view the practical advice is to reuse the GPT-4 tokenizer through tiktoken where possible, with a hope for a trainable tiktoken equivalent.

Why tokenization matters

Tokenization is a process that has to be understood in some detail when working with large language models, even though it is an unpleasant part of the work. It is hairy and gnarly, it hides many foot guns, and a lot of the oddness in large language models traces back to it.

Character-level tokenization revisited

The earlier video "Let's Build GPT from Scratch" already used tokenization, but only a naive, simple version. The training set there was the Shakespeare data set, which begins as one large string of text in Python. To plug that text into a language model, a vocabulary was created from the 65 possible characters that occur in the string. A lookup table converts each character, a little string piece, into a token, which is an integer. For example, the string "High there" was converted into a sequence of tokens, and the first 1,000 characters of the data set were encoded into 1,000 tokens (18, 47, and so on), because the tokenization was at the character level. These tokens enter the language model through an embedding table. With 65 possible tokens, the table has 65 rows. The integer for each token serves as a lookup into the table, and the corresponding row is plucked out. That row consists of trainable parameters, learned through backpropagation, and the resulting vector feeds into the Transformer. This is how the Transformer perceives every token.

Chunk-level tokens and byte-pair encoding

State-of-the-art language models use much more complicated schemes for constructing token vocabularies. They work at the level of character chunks rather than individual characters, and the chunks are built with algorithms such as the byte-pair encoding algorithm, which this video covers in detail. The paper that introduced byte-level encoding as a tokenization mechanism for large language models is probably the GPT-2 paper. Its "input representation" section covers tokenization and the properties a tokenizer should have. It concludes with a vocabulary of 50,257 possible tokens and a context size of 1,024 tokens. In the attention layer of the Transformer, every token attends to the previous tokens in the sequence, up to 1,024 of them. Tokens are the fundamental unit, the atom, of large language models. Everything is in units of tokens, and tokenization is the process of translating text into sequences of tokens and back. Tokens are pervasive: searching the Llama 2 paper for "token" returns 63 hits, and the paper states that the model was trained on two trillion tokens of data.

Why build a tokenizer, and what goes wrong

The byte-pair encoding algorithm is not super complicated, so a tokenizer can be built from scratch. Before diving into code, a brief taste of the complexities is worth having, to motivate why the work is necessary and why it is so gross. Tokenization is at the heart of a lot of weirdness in large language models, and it should not be brushed off. Many issues that look like problems with the neural network architecture or the model itself fundamentally trace back to tokenization: - Difficulty with spelling tasks. - Difficulty with simple string processing. - Much worse performance in non-English languages. - Weakness at simple arithmetic. - GPT-2 having considerably more trouble with Python than later versions. - Weird warnings about a trailing whitespace. - The earlier behavior in which asking GPT about "SolidGoldMagikarp" made the model go totally crazy and veer off on a completely unrelated tangent. - The advice to use YAML over JSON for structured data. These issues are revisited at the end of the video.

The Tiktokenizer web app

The Tiktokenizer web app runs tokenization live in the browser in JavaScript, so any text typed in is tokenized immediately. The left side holds the input string, and the right side shows the tokens, here from the GPT-2 tokenizer, in a different color for each token. The pasted string tokenizes into 300 tokens. The word "tokenization" becomes two tokens, 3,642 and 1,634. The token " is" (with its leading space) is token 318. White space can be shown or hidden at the bottom for clarity. The token " at" is 379 and " the" is 262. The space is part of the token chunk, which is how an English sentence breaks up, and that seems all well and good.

Arbitrary splitting of numbers

In an arithmetic example, 127 feeds into the model as a single token, while 677 feeds in as two separate tokens, a space followed by 6 and then 77. The model has to account for that and process it correctly in its network. The number 804 is also broken into two tokens. Another example with four-digit numbers shows the same pattern: sometimes multiple digits form a single token, sometimes individual digits are separate tokens, and it is all pretty arbitrary, coming out of the tokenizer.

Case and position sensitivity: the "egg" example

The string "egg" at the beginning of a sentence becomes two tokens, but " egg" with a leading space, as in "I have an egg", is a single token for the exact same string. Lowercase "egg" is also a single token, with a different color and so a different token, since tokenization is case sensitive. A capital "Egg" would again be different tokens, arbitrarily two of them. For the same concept, whether at the beginning of a sentence, at the end, lowercase, uppercase or mixed, the tokens and IDs are very different. The language model has to learn from raw internet training data that these are all the same concept, grouping them in the parameters of the neural network based on data patterns, as very, very similar though perhaps not exactly identical.

Non-English languages and token bloat

A Korean introduction from OpenAI's ChatGPT shows that non-English languages work slightly worse in ChatGPT. Part of the reason is that ChatGPT's training data set is much larger for English than for everything else. The same is true of the tokenizer: it has its own training set, which contains a lot more English than non-English text. As a result, English gets many longer tokens. A sentence that is about 10 tokens in English typically takes far more tokens when translated into Korean, Japanese or another language, because the chunks are much more broken up. This bloats the sequence length of all documents. When the tokens attend to each other in the Transformer, the maximum context length runs out sooner. Non-English text is stretched out from the Transformer's perspective, because the tokenizer's training produces bigger tokens and larger groups for English and many little boundaries for everything else. Translated into English, the same text would take significantly fewer tokens.

Python indentation and GPT-2

A small Python snippet for FizzBuzz shows each indentation space as a separate token, token 220, repeated again and again, followed by a single token for " if". The Transformer has to handle all these spaces individually, feeding them one by one through the entire network in the sequence. Tokenizing this way is extremely wasteful. It is the reason GPT-2 is not very good with Python, and it has nothing to do with coding or the language model itself. Heavy space indentation, as is usual in Python, bloats the text and spreads it across far too much of the sequence, so the context length runs out. Far too much token space is taken up.

Comparing tokenizers

The tokenizer can be changed in the web app. The GPT-2 tokenizer creates a token count

GPT-4 Tokenizer vs. GPT-2: Token Counts

Switching the tokenizer from GPT-2 to cl100k_base, the GPT-4 tokenizer, drops the token count for the same string from 300 to 185. The text is represented with roughly half as many tokens, because the GPT-4 vocabulary holds roughly double the number of tokens: about 100K, up from about 50K. This is a good thing, since the same text is squished into half as many tokens, which makes for a much denser input to the Transformer. In a Transformer, every token can pay attention only to a finite number of tokens before it. With the denser encoding, the model can see roughly twice as much text as context when predicting the next token. Increasing the number of tokens is not strictly better without limit. As the vocabulary grows, the embedding table gets larger, and at the output, the softmax over the next-token prediction grows as well. This is covered in more detail later. Somewhere there is a sweet spot, a just-right vocabulary size where everything is appropriately dense and still fairly efficient.

Better Whitespace Handling for Python

One thing worth noting specifically about the GPT-4 tokenizer is that its handling of whitespace for Python has improved a lot. Four spaces are represented as a single token, three spaces are covered by one token followed by another token for the remaining characters, and seven spaces are grouped into a single token. Python is therefore represented far more efficiently. This was a deliberate choice by OpenAI when designing the GPT-4 tokenizer: a lot more spaces are grouped into a single token. This densifies Python, so more code can be attended to before the position where the next token is predicted. The improvement in Python coding ability from GPT-2 to GPT-4 is therefore not only a matter of the language model, the architecture and the details of the optimization. A good part of it comes from the design of the tokenizer and how it groups characters into tokens.

The Goal: Turning Strings into Integers

Now it is time to start writing code. The goal is to take strings and feed them into language models. For that, strings must somehow be tokenized into integers in a fixed vocabulary. Those integers are then used to look up vectors in a lookup table, and the vectors are fed into the Transformer as input. This gets tricky because the aim is not just to support the simple English alphabet. Different kinds of languages need support, such as "안녕하세요" in Korean, which means hello, as well as the many special characters found on the internet, such as emoji. So how can such text be fed into Transformers, and what exactly is this text in Python?

Unicode Code Points

According to the Python documentation, strings are immutable sequences of Unicode code points. Unicode code points are defined by the Unicode Consortium as part of the Unicode standard. The standard is a definition of roughly 150,000 characters, covering what they look like and which integers represent them. As of now it covers 150,000 characters across 161 scripts. The standard is very much alive: the latest version, 15.1, appeared in September 2023. The code point of a single character can be accessed with Python's ord function. For the single character "H", the code point is 104. This can get arbitrarily complicated: the code point of the emoji shown here is around 128,000, and that of the Korean character is around 50,000. The function accepts only a single character and returns its integer, so passing in a whole string fails. To look up all characters of a string, ord can be applied to each character in a list comprehension, which yields the code points of the whole string.

Why Raw Code Points Are Not Enough

Since the raw characters have now been turned into integers, one might ask why these integers cannot simply be used as they are, with no tokenization at all. One reason is that the vocabulary would be quite long: for Unicode, it would be 150,000 different code points. More worrying still, the Unicode standard keeps changing, so it is not necessarily a stable representation to use directly. Something better is needed, and that leads to encodings.

UTF-8, UTF-16 and UTF-32

The Unicode Consortium defines three types of encodings: UTF-8, UTF-16 and UTF-32. These encodings translate Unicode text into binary data, or byte streams. UTF-8 is by far the most common. It takes every code point and translates it into a byte stream of between one and four bytes, so it is a variable-length encoding. UTF-32 is nice because it is fixed length, but it has many other downsides. The full spectrum of pros and cons of the three encodings is beyond the scope of this discussion. A blog post on the subject is worth reading, and its references include the "UTF-8 Everywhere Manifesto". The manifesto lays out why UTF-8 is significantly preferred over the other encodings and why it is used far more prominently on the internet. One major advantage is that UTF-8 is the only one of the three that is backward compatible with the much simpler ASCII encoding of text. UTF-8 is the encoding to stick with.

Encoding Strings in Python

Python's string class has an encode method that takes the encoding, for example UTF-8. The result is a bytes object, which does not print nicely. Passing it through list gives the raw bytes of the encoding, that is, the raw bytes that represent the string according to UTF-8. Encoding with UTF-16 yields a slightly different byte stream and reveals one of its disadvantages: the output shows a pattern of zero, something, zero, something, zero, something. For simple ASCII or English characters, the structure is just zero followed by something, which makes it a rather wasteful encoding. The same holds for UTF-32: expanded, it shows a lot of zeros followed by something. This is undesirable, so UTF-8 is the choice.

The Problem with Raw Bytes

Using UTF-8 naively means working with byte streams, which implies a vocabulary of only 256 possible tokens. That vocabulary is very small. All text would be stretched out over very long sequences of bytes. The embedding table would be tiny and the prediction at the final layer would be tiny, but the sequences would be very long. The context length is finite, as is the attention a Transformer can support for computational reasons. With very long sequences, the model cannot attend to sufficiently long stretches of text before the current position for the next-token prediction task. Raw UTF-8 bytes are therefore not a good fit. What is needed is a larger vocabulary size that can be tuned as a hyperparameter, while still sticking with the UTF-8 encoding of the strings. The answer is the byte pair encoding algorithm, which compresses these byte sequences to a variable degree.

Tokenization-Free Modeling

Feeding raw byte sequences directly into language models would be ideal, and there is a paper from the summer of last year on how this could potentially be done. The Transformer architecture has to be modified, because attention becomes extremely expensive when the sequences are so long. The paper proposes a hierarchical structuring of the Transformer that would allow raw bytes to be fed in. At the end, the authors state that together these results establish the viability of tokenization-free autoregressive sequence modeling at scale. Tokenization-free modeling, with byte streams fed directly into models, would indeed be amazing. Unfortunately, it has probably not yet been proven out by sufficiently many groups at sufficient scale. It would be wonderful if someone came up with it, but for now the bytes cannot be fed directly into language models and must be compressed with the byte pair encoding algorithm.

How Byte Pair Encoding Works

The byte pair encoding algorithm is not all that complicated, and its Wikipedia page is quite instructive for the basic idea. Start with an input sequence. In the example, the vocabulary has only four elements, a, b, c and d, instead of bytes, and the sequence over them is too long and needs compressing. The algorithm iteratively finds the pair of tokens that occurs most frequently. Once that pair is identified, it is replaced with a single new token that is appended to the vocabulary. In the example, the byte pair "aa" occurs most often, so a new token, call it capital Z, is minted, and every occurrence of "aa" is replaced by Z. The sequence of 11 characters with a vocabulary size of four becomes a sequence of only nine tokens, but with a vocabulary of five, because a fifth vocabulary element has just been created, Z, standing for

Completing the first merges

The first merge replaces the pair AA with a new token, Z, which stands for the concatenation of AA. The sequence is then scanned again to find the most frequent pair, which is now AB. AB is replaced with a new token, Y, and every occurrence of AB is swapped out. The sequence now has seven tokens, and the vocabulary has grown to six elements.

The third merge and the shorter sequence

In the final round, the most frequent pair is ZY, which is replaced with a new token, X, so X stands for ZY. Every occurrence of ZY is replaced, leaving a sequence of five tokens. The vocabulary now has seven elements.

Why iterative merging works

Overall, the process turns a sequence of 11 tokens with a vocabulary of four into a sequence of five tokens with a vocabulary of seven. Repeating this process compresses the sequence by minting new tokens. The same idea applies at the byte level. The algorithm starts with a vocabulary of 256 byte values, repeatedly finds the most frequent pairs, and mints new tokens for them. The result is a compressed training dataset and an algorithm that can encode any sequence using the learned vocabulary and decode it back into strings.

Implementing the algorithm

To put this into practice, the first paragraph of a blog post is copied into a text variable, which becomes one long line. The first step is to turn the text into tokens. The text is encoded as UTF-8, which produces a raw stream of bytes. To make the data easier to work with, those bytes are converted into a list of integers in Python. This list is what the merging algorithm operates on.

Encoding the paragraph as bytes

The code prints the original paragraph along with its encoded form. The paragraph contains 533 code points. Once encoded in UTF-8, it becomes a sequence of 616 bytes, which means 616 tokens at this stage.

Why the byte count grows

The byte count is higher than the code point count because many simple ASCII characters take up only one byte, while more complex Unicode characters take between two and four bytes. This expands the sequence. The next step is to find the pair of bytes that occurs most frequently, since that pair will be merged. Readers working through the notebook alongside this material are encouraged to try writing this function themselves before continuing.

Counting consecutive pairs

The get_stats function takes a list of integers and uses a dictionary to track counts. It iterates over consecutive pairs of elements using a Pythonic approach covered in the previous lesson, and it increments the count for each pair. When called on all the tokens, it returns a dictionary whose keys are tuples of consecutive elements and whose values are their counts.

Sorting the pair counts

To print the counts more readably, each item is converted into a (value, key) pair and placed in a list. Sorting that list in reverse puts the most frequent pairs first, because Python sorts by the first element by default, which here is the count. The most common pair is (101, 32), which occurs 20 times.

Checking the most common pair

Searching the token list for 101, 32 confirms that the pair appears 20 times. Using chr, the inverse of ord, which converts a Unicode code point into a character, the pair decodes to 'e' followed by a space. This means many words in the text end in 'e', so this pair is very common.

Minting token 256

The current tokens range from 0 to 255, so the new token will receive the ID 256. The list is scanned from start to finish, and every occurrence of the pair 101, 32 is replaced with 256.

Selecting the highest-ranked pair

The highest-ranked pair is found by calling max on the stats dictionary. Passing stats.get as the key function ranks the keys by their values, so max returns the key with the highest count, which is (101, 32).

Designing the merge function

The merge function takes a list of IDs, the pair to replace, and the new index that replaces it. It builds a new list by moving through the original from left to right. At each position, it checks whether the current element and the next one match the pair.

Handling the boundary check

When a match is found, the function appends the new index to the new list and advances the position by two, which skips the entire pair. If no match is found, it copies the current element and advances by one. A boundary check is essential here: the function must not access an index past the end of the list at the final position, or it will raise an out-of-bounds error. A small example illustrates the behavior. Given the list 5, 6, 6, 7, 9, 1, replacing the pair 6, 7 with 99 produces 5, 6, 99, 9, 1.

Applying the merge to the paragraph

When the merge is applied to the actual token list, the length drops from 616 to 596. This decrease of 20 matches the 20 occurrences of the pair. The token 256 now appears many times in the new list, and the pair 101, 32 no longer appears.

Repeating merges and choosing the vocabulary size

The process is repeated: find the most common pair and replace it. The number of merges is a hyperparameter. More merges produce a larger vocabulary and a shorter sequence, and there is a sweet spot that usually works best in practice. For example, GPT-4 uses roughly 100,000 tokens, which is a reasonable scale for current large language models.

Using longer text for training statistics

Large language models rely on vocabularies of this size. The next step is to assemble the pieces into a loop. Before doing so, the entire blog post is used rather than just the first paragraph or two. It is stretched into a single line. Longer text provides more representative statistics for byte pairs, which leads to more sensible merges.

Encoding the longer text

The raw text is encoded into bytes using UTF-8, then converted into a list of integers, as before. The two helper functions from earlier are included again for reference, and they are identical to the previous versions. The new code adds the merge loop, which begins by choosing the final vocabulary size.

Setting the vocabulary size to 276

The final vocabulary size is set to 276. Since the byte-level vocabulary already contains 256 tokens, reaching 276 requires exactly 20 merges, each adding one new token.

Copying the tokens and recording merges

A copy of the tokens list is created by wrapping it in a new list, which constructs a separate list containing the same elements. A merges dictionary is then created to map each pair of child tokens to the new token that replaces them.

The merge structure as a forest

The merges form a binary tree-like structure, but it is not exactly a tree. A true tree would have a single root node with leaves beneath it. Here, the leaves at the bottom are the 256 individual byte tokens, and each merge combines two tokens at a time. Because many separate structures grow as merges happen, the result is more like a forest.

Running the merge loop

For each of the 20 merges, the most common pair is found and assigned a new token integer. The first new token is 256, and the loop prints each merge as it occurs. Every occurrence of the pair is replaced with the new token, and the merge is recorded in the merges dictionary.

Reviewing the output of the first merges

Running the loop completes 20 merges. The first merge matches the earlier example: the tokens 101 and 32 merge into the new token 256. The individual tokens 101 and 32 can still appear elsewhere in the sequence, and they become 256 only when they occur consecutively. In particular, the token 256, which is the

Newly minted tokens and the compression ratio

The newly minted token 256 is itself eligible for merging. In the output, the 20th merge combined 256 and 259 into 275. Every time a pair is replaced, the new token becomes a candidate for merging in the next round of iteration, which is why the process builds up a small binary forest rather than a single tree. The compression ratio achieved is also worth checking. The token list started at about 24,000 bytes, and after 20 merges only about 19,000 tokens remain. Dividing the two gives a compression ratio of roughly 1.27, achieved with only 20 merges. The more vocabulary elements are added, the greater the compression ratio becomes. This completes the training of the tokenizer.

The tokenizer as a separate stage from the language model

The tokenizer is a completely separate object from the large language model itself. Nothing in this process touches the language model; only the tokenizer is trained. It is a separate pre-processing stage, run once at the beginning. The tokenizer has its own training set of documents, just as a large language model has its own, potentially different, training set. The byte pair encoding algorithm is run on that training set to produce the tokenizer's vocabulary and merges. Once the tokenizer is trained, it supports both encoding and decoding. It acts as a translation layer between raw text, a sequence of Unicode code points, and token sequences: raw text can be turned into tokens, and tokens can be translated back into raw text. With this translation in place, the language model is trained as a second step. In a state-of-the-art setup, all of the language model's training data may be run through the tokenizer and translated into one massive token sequence. The raw text can then be thrown away, leaving only the tokens stored on disk, and those tokens are what the language model actually reads during training. This can be done as a single massive pre-processing step.

Choosing the tokenizer's training data

Because the tokenizer is a separate stage with its own training set, that set may differ from the language model's. A tokenizer should perform well not just on English text but on many different languages, and on code as well. It is therefore worth experimenting with different mixtures of languages and different amounts of code. The amount of each language in the tokenizer's training set determines how many merges that language receives, and therefore how densely its data is represented in token space. Intuitively, a tokenizer trained on a large amount of Japanese data will merge more Japanese tokens, so Japanese text becomes shorter token sequences. That benefits the language model, which has a finite context length in token space.

Decoding tokens back into text

Decoding goes from a token sequence back to a Python string, the raw text. The function takes a list of integers and returns a string. It makes a good exercise to implement it independently. One approach starts by building a preprocessing variable called vocab, a dictionary mapping each token ID to its bytes object. It begins with the raw bytes for tokens 0 to 255. Then, going through the merges in order, it adds an entry for each merged token: the bytes of the first child concatenated with the bytes of the second. Since these are bytes objects, the addition is simple concatenation. One subtlety is that iterating the merges dictionary with .items() must follow the order in which items were inserted. Starting with Python 3.7 this order is guaranteed; before that, the iteration might have been out of order and the approach might not have worked. A modern Python is fine. Given the IDs, the function looks up each token's bytes in vocab and concatenates them all into raw bytes. Those bytes are then decoded with UTF-8 into a Python string. Previously, encode was called on a string to get bytes; now decode is called on the bytes object to get a string. The text is then returned.

Invalid UTF-8 and the errors parameter

This implementation has an issue that can raise an error when an unlucky sequence of IDs is passed in. Decoding 97 simply returns the letter "a". But decoding the single token 128 fails with: the utf-8 codec can't decode byte 0x80 in position 0: invalid start byte. Understanding this requires the UTF-8 schema from Wikipedia. Multi-byte UTF-8 characters must follow a specific envelope. The binary representation of 128 is a one followed by all zeros, which fits none of the allowed formats. A valid leading byte of a multi-byte character must begin with a one followed by another one and then a zero, with the character's content bits after that. So 128 is an invalid start byte, and the sequence cannot be decoded. The fix is the errors argument of Python's bytes.decode function. By default, errors is strict, which raises an error when the bytes are not valid UTF-8. Many other error-handling options exist. Changing it to replace substitutes the special replacement character for invalid bytes, and the decode then returns that character instead of failing. Not every byte sequence is valid UTF-8. If a large language model predicts tokens in a bad manner, the result may not be valid UTF-8 and cannot be decoded cleanly. The standard practice is to use errors="replace", which is also what OpenAI's released code does. Whenever this replacement character appears in an output, something went wrong: the language model produced an invalid sequence of tokens.

Encoding text into tokens

Next comes the opposite direction: given a string, encode it into tokens. The function takes a string and returns a list of integers. Again, implementing it independently is a worthwhile exercise. There are many ways to do it. One approach first encodes the text into UTF-8 to get raw bytes, then calls list on the bytes object to get a list of integers. These are the starting tokens, the raw bytes of the sequence. According to the merges dictionary, some of these bytes may then be merged. The merges dictionary was built from top to bottom, in the order items were inserted, and the merges must be applied in that same order, early merges before later ones. For example, one merge relies on token 256, which was created by an earlier merge, so the order matters whenever anything is merged. Since a number of merges are expected, the process runs in a while True loop. Each iteration must find a pair of consecutive bytes that is allowed to be merged. To reuse existing functionality, the get_stats function is used. It counts how many times each pair occurs in the token sequence and returns a dictionary mapping pairs to counts. Here the counts do not matter, only which pairs occur, so only the keys of the dictionary are used as the set of possible merge candidates. The next step is to identify which pair to merge at this stage of the loop: what do we want, we want to find the pair

Choosing the Pair to Merge

The pair to merge at each step is the key inside stats that has the lowest index in the merges dictionary, because all the early merges must be done before working toward the later ones. There are many ways to implement this, but a slightly fancy one uses Python's min over an iterator. Calling min on the dictionary stats iterates over its keys, which are all the consecutive pairs found in the tokens. Min takes a key function that returns the value to minimize over. Here that function looks each pair up in merges and returns its index, so the pair with the smallest merge index wins. For example, if the pair (101, 32) occurs, it is identified and returned, and the new token index replaces it. The fallback value float("inf") is used in the get call for a reason: a pair that does not occur in merges is not eligible for merging. Such a pair has no index and cannot be merged, which is denoted by infinity. Infinity is convenient because it guarantees that an unmergeable pair never wins the min. In short, this returns the most eligible merging candidate that occurs in the tokens.

Handling the Case Where Nothing Can Be Merged

One thing needs care: the function can fail when nothing is left to merge. If no pair in the tokens appears in merges, every pair evaluates to infinity, and min simply returns the first element of stats arbitrarily. That pair is not actually mergeable. So if the returned pair is not in merges, no pair can be merged anymore, and the loop breaks out. Other implementations are possible, and this one is somewhat contorted Python, but the goal is only to find the mergeable pair with the lowest index. If a pair inside merges with the lowest index is found, it is merged. The merges dictionary gives that pair's index, and tokens is replaced by a new list in which every occurrence of the pair is replaced with idx. This repeats until nothing can be merged, at which point the loop breaks and the tokens are returned. Running it works as expected; for example, 32 is a space in ASCII, and it appears in the output as it should.

Edge Case and Round-Trip Tests

The implementation is not quite right yet, because it leaves out a special case. With a single character or an empty string, stats is empty, and that causes an error inside min. The fix is to proceed only if the length of tokens is at least two. With fewer than two tokens there is nothing to merge, so the function just returns. Some test cases follow. Encoding a string and decoding it back should return the same string, and that holds here and in general. The reverse direction has no such identity: not all token sequences are valid UTF-8 byte streams, so some cannot even be decoded. The check therefore runs in one direction only. Encoding and then decoding the training text, which the tokenizer was trained on, returns the same text. Validation text taken from a web page, which the tokenizer has not seen, also round-trips correctly. This gives confidence that the implementation is correct.

Summary of Byte Pair Encoding and the Move to GPT-2

These are the basics of the byte pair encoding algorithm. A tokenizer is trained on a training set, and its parameters are just the dictionary of merges, which creates a small binary forest on top of the raw bytes. With the merges table, text can be encoded to token sequences and decoded back. That is the simplest setting of a tokenizer. State-of-the-art language models use tokenizers that complicate this picture very quickly, and the complications can be taken one at a time. The GPT series is the starting point, specifically the GPT-2 paper from 2019, about five years earlier. Its input representation section describes the tokenizer. It is fairly readable and worth pausing to read. It motivates applying the byte pair encoding algorithm to the byte-level representation of UTF-8 and discusses vocabulary sizes.

Why GPT-2 Restricts Merges

Everything matches what has been covered so far until the paper says that the naive algorithm is not applied as is. Take a common word like "dog". It occurs very frequently in text, right next to all kinds of punctuation: "dog.", "dog!", "dog?" and so on. Naively, the BPE algorithm could merge these into single tokens, leaving many tokens that are just "dog" with slightly different punctuation. That clusters things that should not be clustered, combining semantics with punctuation, which is suboptimal. According to the paper's experiments, it is indeed suboptimal. The remedy is to enforce, top down and manually, that some types of characters are never merged together. These merging rules are imposed on top of the byte pair encoding algorithm.

The Regex Pattern in GPT-2's Code

The GPT-2 repository on OpenAI's GitHub shows how these rules are enforced. Under the source folder there is a file called encoder.py. The name is somewhat awkward, since this is the tokenizer and a tokenizer does both encoding and decoding, but it is the tokenizer. Much goes on in it, and it will be stepped through in detail later. For now the focus is on the regex pattern created there. It looks very complicated, and it is the core part that enforces which parts of the text are never merged. The re.compile call is slightly misleading, because the code does not use Python's built-in re module. It does import regex as re. The regex package can be installed with pip install regex and is an extension of re that is somewhat more powerful.

Trying the Pattern with findall

Copying the pattern into the Jupyter notebook allows it to be tried out, exactly as their code does: calling re.findall with the pattern on an arbitrary string, namely the string to be encoded into tokens for an LLM like GPT-2. The function matches the pattern against the string from left to right and collects all occurrences into a list. The pattern is a raw string, and the three double quotes only start the string. It is made up of many alternatives separated by vertical bars, which are "or" in regex. Matching proceeds from left to right, trying each alternative wherever the position is. For "hello", the alternatives for apostrophe-s, apostrophe-t and the others do not match. What does match is an optional space followed by \p{L} one or more times. According to the documentation, \p{L} is a letter from any language, and "hello" is made of letters. So an optional space followed by one or more letters matches "hello". The match ends there, because a space is not a letter. A new attempt begins from that point, skipping over the alternatives that fail until reaching the same optional-space-plus-letters alternative again, which matches " world". The result is a list of two elements, "hello" and " world". Adding more letters or words produces more elements in the same way.

Splitting Text Before Tokenization

The string is not encoded directly for tokenization. It is first split up. At a high level, the code splits the text into a list of text chunks like this one, and all the elements of this list are processed independently by the tokenizer, and all of the

Chunks Are Tokenized Independently

Splitting the text with the regex pattern turns a string such as "hello world how are you" into a list of five elements. Each element goes independently from text to a token sequence, and the resulting sequences are concatenated. Merges can therefore only be found within each element. After all possible merging is done for every element individually, the results are joined by concatenation. The "e" at the end of one word is never merged with the space that starts the next, because they belong to separate elements of the list. Using the regex pattern to chunk up the text is thus a way of enforcing that some merges never happen. At a high level, the pattern prevents merging across letters, numbers, punctuation and so on.

Separating Letters from Numbers

The next part of the pattern uses \p{N}, which in the regex documentation is any kind of numeric character in any script. An optional space followed by numbers is matched as its own group, so letters and numbers are separated. In "Hello World 123 how are you", "world" stops matching at the "1", because "1" is a number and not a letter, and the digits come out as a separate entity.

Hardcoded Apostrophe Handling

With an apostrophe contraction such as "'ve", the apostrophe is neither a letter nor a number, so the letter match for "hello" stops there and the contraction is matched exactly by the apostrophe rules and comes out as a separate piece. The apostrophe rules probably exist because these are very common apostrophe patterns, but the design is not a good one. For "house's" with a standard apostrophe, the contraction is separated out. With a Unicode apostrophe, the rule no longer applies and the apostrophe becomes its own token. The pattern is hardcoded for one specific kind of apostrophe, and otherwise apostrophes become completely separate tokens.

Case Sensitivity and Language Specificity

The GPT-2 documentation, where the pattern is defined, notes that re.IGNORECASE should have been added so that BPE merges can happen for capitalized versions of contractions. The rules match an apostrophe followed by lowercase letters, and without case-insensitive matching they do not separate the apostrophe when the letters are uppercase. "house's" splits one way, while "HOUSE'S" leaves the apostrophe standing by itself. Tokenization therefore works differently for uppercase and lowercase, separating apostrophes inconsistently. It feels extremely gnarly and slightly gross, but that is how it works. The rules are also quite language specific. Languages that use or do not use apostrophes would be tokenized inconsistently as a result.

Matching Punctuation

After the apostrophe expressions come letters, then numbers. If neither matches, the pattern falls back to an optional space followed by one or more characters that are not letters, numbers or spaces. This roughly matches punctuation: anything that is not a letter and not a number. Punctuation characters therefore get caught in their own group and are separated out.

The Whitespace Lookahead

Another part of the pattern is also a little confusing. It matches whitespace, but with a negative lookahead assertion, so that it matches whitespace up to but not including the last whitespace character. This is subtle. Whitespace is always included at the beginning of a word, as in " r" or " u". When there are many spaces in a row, all of them except the last are caught by this rule and separated out, so that the last space can join the following word to form something like " u". That is useful because " u" is a common token. With extra spaces in front, the tokenizer still gets " u", plus the leftover whitespace as separate pieces. The GPT-2 tokenizer likes to have a space followed by letters or numbers, and it prunes the extra spaces to keep that consistent. The last fallback is a general whitespace match, which catches any trailing spaces and the like.

A Python Example and Spaces That Never Merge

Splitting a piece of Python code with the pattern gives a list with many elements, because the text is split every time the character category changes. No merges ever happen within these elements. It might seem that OpenAI trained the tokenizer by splitting text into chunks with this pattern and then running a plain BPE algorithm within each chunk, but that is not exactly what happened. In the Python example, runs of spaces end up as entire elements, yet OpenAI never merges them. Pasting the same chunk into the tiktokenizer web app shows every space kept independent, each one token 220. At some point OpenAI probably enforced a rule that these spaces are never merged, so there are additional rules on top of chunking and BPE that OpenAI has not made clear.

Only Inference Code Was Released

The training code for the GPT-2 tokenizer was never released. The released code is inference code only: it takes the merges described above and applies them to a new piece of text. It cannot be given text to train a tokenizer on. How OpenAI trained the tokenizer is therefore unknown, but it was not as simple as chunking the text up and running BPE.

The tiktoken Library

Tiktoken is OpenAI's official library for tokenization, installed with pip install tiktoken. It is again inference code only, not training code, and its use is quite simple. Running it gives the GPT-2 tokens or the GPT-4 tokens, GPT-4 being the more recent tokenizer. In GPT-2, whitespace stays unmerged, while in GPT-4 the whitespace is merged, as the same example shows when run with each tokenizer.

How the GPT-4 Pattern Differs

GPT-4 changed the regular expression used to chunk up text. The definitions of all the tokenizers OpenAI maintains are in the tiktoken library, in the file tiktoken_ext/openai_public.py. Publishing some details of the pattern strings was necessary to make inference possible. The GPT-2 string there is slightly different from the one discussed above but equivalent to it, and executes a little faster. Special tokens are covered later. Further down, for cl100k_base, the GPT-4 tokenizer, the pattern has changed. This is the major change, along with a number of other special tokens. The full detail of the pattern change is numbing, and the practical advice is to pull out ChatGPT and the regex documentation and step through it. The major changes are these. First, the "i" flag makes the match case insensitive, so the earlier concern about re.IGNORECASE is fixed, and apostrophe contractions like 's, 'd and 'm are matched in both lowercase and uppercase. Second, whitespace is handled differently in several ways that are not covered in full detail here. Third, numbers are matched only one to three digits at a time, so numbers with more than three digits are never merged beyond three digits. This probably prevents tokens that are very long number sequences, but the reasons for any of these changes are unknown because none of it is documented and only the pattern is available. The vocabulary size also went from roughly 50k to roughly 100k.

Reading OpenAI's GPT-2 encoder.py

The gpt2 encoder.py file that OpenAI released is fairly short and should be relatively understandable by now. At the bottom, it loads two files, encoder.json and vocab.bpe, does some light processing on them, and calls the resulting object the encoder, which is the tokenizer. These two files together constitute the saved tokenizer, and they can be downloaded and inspected with a short piece of code. The encoder, as it is called in their code, is exactly equivalent to the vocab object built earlier, which allowed efficient decoding by mapping an integer to its bytes. The vocab is exactly their encoder. Their vocab.bpe, confusingly named, holds the merges: their BPE merges, based on the data inside vocab.bpe, end up being equivalent to the merges built earlier.

Saving a tokenizer: merges and vocab

OpenAI's saved tokenizer consists of two variables that are also the two critical variables in the tokenizer built here: the merges and the vocab. These two variables alone are enough to represent a tokenizer, and once it has been trained they allow both encoding and decoding.

The byte encoder and decoder layer

One slightly confusing part of OpenAI's code is that, in addition to the encoder and decoder, there is also a byte encoder and a byte decoder. This is an unfortunate, spurious implementation detail that is neither deep nor interesting, so it is skipped here. For reasons that are not fully understood, OpenAI keeps a whole separate layer that is used serially with the tokenizer: first byte encode, then encode, and on the way back decode, then byte decode. The two layers are simply stacked on top of each other, and the code can be stepped through for anyone who is curious.

The bpe function is algorithmically familiar

Ignoring the byte encoder and decoder, the rest of the file is algorithmically very familiar. The core is a function called bpe, whose loop closely resembles the one built earlier: it identifies the pair that should be merged next, and then a for loop merges that pair wherever it appears in the sequence. This repeats until no more merges are possible in the text. An encode and a decode function sit around it, just as in the version built here. The code is a little messy, but algorithmically it is identical to what has been built so far, and that is all that is needed to train a BPE tokenizer and then encode and decode with it.

Special tokens and the end of text token

The next topic is special tokens. In addition to the tokens that come from raw bytes and BPE merges, all kinds of other tokens can be inserted to delimit different parts of the data or to create special structure in the token stream. The encoder object of OpenAI's GPT-2 is very similar to the vocab built here, except that it maps in the opposite direction, from string to integer, for no amazing reason. Its length is 50257. That number comes from 256 raw byte tokens plus 50,000 merges, which would give 50256 tokens. The 50257th token is a single special token called end of text. It is the very last token and is used to delimit documents in the training set. When training data is created, each document is tokenized into a stream of tokens in the range 0 to 50256, and the end of text token is inserted between documents. It signals to the language model that a document has ended and that what follows is unrelated to the previous document. The model still has to learn this from data: it must learn that this token usually means it should wipe its memory of what came before, because that material is not informative for what comes next. The model is simply given a special delimiter and expected to learn its meaning.

Special tokens bypass the BPE merges

This can be seen in the Tiktokenizer web page with the GPT-2 tokenizer. Typing a string such as hello world, how are you produces ordinary tokens. Typing the characters of end of text one at a time still produces ordinary, different tokens, but the moment the string is completed it collapses into the single token 50256. This works because the string never goes through the BPE merges. The code that produces tokens has special-case instructions for handling special tokens. These instructions are absent from the encoder.py file, but the tiktoken library, which is implemented in Rust, contains all kinds of special-case handling for them. Special tokens can be registered and added to the vocabulary, and whenever the library sees one in the text, it swaps in that special token. These tokens therefore sit outside the typical BPE encoding algorithm.

Special tokens in chat models

Special tokens are used pervasively, not just in base language modeling, which predicts the next token in a sequence, but especially in the fine-tuning stage and in all the chat aspects of ChatGPT. There the goal is to delimit not just documents but entire conversations between an assistant and a user. Refreshing the Tiktokenizer page shows a default example that uses a fine-tuned model's tokenizer rather than a base model's. With the GPT-3.5 Turbo scheme, tokens such as im_start and im_end appear as special tokens, where the name is short for imaginary monologue start, marking in effect the start and end of every single message. Many other tokens are used to delimit conversations and keep track of the flow of messages.

Extending tiktoken and GPT-4's special tokens

At the bottom of the tiktoken documentation there is a section on extending the library. The cl100k_base tokenizer used in GPT-4 can be forked and extended with more special tokens. These are entirely up to the user: any arbitrary tokens can be added with new IDs afterwards, and the library will correctly swap them out when it sees them in strings. In the tiktoken openai_public file, the GPT-2 definition contains the vocabulary, the splitting pattern, and a registration of the single special token, end of text, with its ID. In GPT-4, the pattern has changed, as discussed earlier, and the special tokens have changed too. End of text is still present, as in GPT-2, but there are four additional tokens: FIM prefix, FIM middle, FIM suffix, and one more serve token. FIM is short for fill in the middle. The idea comes from a paper, but its details are beyond the scope of this video.

Model surgery when adding special tokens

It is very common to train a language model and then add special tokens afterwards. Doing so requires some model surgery on the Transformer and its parameters, because adding a token means adding an integer. The embedding matrix for the vocabulary tokens must be extended by adding a row, which is typically initialized with small random numbers or something similar, so that a vector stands for the new token. The final layer of the Transformer must also be extended by one, so that the projection at the very end into the classifier covers the new token. Tokenization changes therefore have to be coupled with changes to the model. This is a very common operation, especially when fine-tuning a model, for example taking a base model to a chat model like ChatGPT.

Building your own GPT-4 tokenizer: minbpe and the exercise

At this point everything needed to build a GPT-4 tokenizer is in place. In the course of developing this lecture, that was done and the code was published in a repository called minbpe. Its contents will probably change quite a bit because work on it is going to continue. Alongside the repository there is an exercise progression. The exercise.md file breaks the task into four steps that build up to a GPT-4 tokenizer. The steps and the guidance can be followed exactly, and whenever the work gets stuck, the minbpe repository can serve as a reference, either through its tests or through the code itself, which is kept fairly clean and understandable. Once the tokenizer is written, it should reproduce the behavior of tiktoken: encoding a string with the GPT-4 tokenizer should give the same tokens, and encoding and then decoding the same string should recover it. In addition, it should be possible to implement a train function of one's own, which the tiktoken library does not provide, since it is inference code only. minbpe includes one, which makes it possible to train custom token vocabularies.

Comparing GPT-4 merges with a trained vocabulary

The minbpe repository includes visualizations of the token vocabularies that training can produce. On the left are the GPT-4 merges: the first 256 entries are raw individual bytes, and the rest show the merges GPT-4 performed during its training. The very first merge combined two spaces into a single token, token 256. This is the order in which merges happened during GPT-4 training. On the right is the merge order obtained in minbpe by training a tokenizer, in this case on the Wikipedia page of Taylor Swift. The choice has nothing to do with being a fan; it is apparently one of the longest Wikipedia pages available, though the singer is pretty cool as well. The two vocabularies can be compared. GPT-4 merged i and n into in, and the same thing happened for the trained tokenizer at token 259. Space and t became space-t in GPT-4, and that happened a little later in the trained tokenizer. As far as can be understood, the difference comes down to the training set. Because the GPT-4 list shows a lot of whitespace merges, GPT-4 probably had a lot of Python code in the tokenizer's training set, though this is not certain. The Wikipedia page contains much less of that. Roughly speaking, the two look the same, and they look the same because they are running the same algorithm, and when you train your

Training your own tokenizer gives similar results

Training a tokenizer from scratch typically produces something similar to the existing vocabularies, depending on what data it is trained on.

Introducing SentencePiece

Beyond tiktoken and the way OpenAI tokenizes strings, another very commonly used library for tokenization in language models is SentencePiece. It is popular because, unlike tiktoken, it can do both training and inference, and it is quite efficient at both. It supports a number of algorithms for training vocabularies, one of which is the byte-pair encoding algorithm examined so far. SentencePiece is used by the Llama and Mistral series and many other models. It lives on GitHub under google/sentencepiece.

Code points first, bytes as a fallback

The big difference with SentencePiece is the order of operations, which is subtle and easier to understand through an example. Tiktoken first takes the code points in the string, encodes them to bytes using UTF-8, and then merges bytes. That is fairly straightforward. SentencePiece works directly on the level of the code points themselves. It looks at whatever code points are available in the training set and starts merging those, so BPE runs at the code-point level. Some rare code points do not come up often, and how rare is determined by the character coverage hyperparameter. These rare code points are either mapped to a special unknown token such as UNK, or, if the byte fallback option is turned on, encoded using UTF-8, with the individual bytes of that encoding translated into tokens. Special byte tokens are added to the vocabulary for this purpose. In short, SentencePiece runs BPE on code points and falls back to bytes for rare code points. The speaker personally finds the tiktoken approach significantly cleaner, though this is a subtle but pretty major difference between the two.

Setting up a toy example

A concrete example makes this easier to grasp. SentencePiece is imported, and a small toy dataset is created from the description of SentencePiece itself. The library likes to work from a file, so the content is saved as toy.txt. SentencePiece has a remarkable number of options and configurations. It has been around for a while and tries to handle a large diversity of use cases, so it has accumulated quite a bit of historical baggage. The configuration arguments shown here are not even all of them; the full list of training options is available online, and the raw protobuf used to represent the trainer spec is also quite useful documentation. Many options are irrelevant here. For example, the shrinking factor is not used by the byte-pair encoding algorithm and applies to a different training algorithm.

Configuring SentencePiece to mimic Llama 2

The setup here is meant to be very similar, hopefully identical, to the way Llama 2 was trained. This was done by opening the tokenizer model file that Meta released using the protobuf definition, inspecting all the options, and copying over those that looked relevant. The input is the raw text file, and the output is a model and vocab pair named tok400. The BPE algorithm is selected, with a vocabulary size of 400.

Normalization rules and the concept of sentences

There are many configurations for preprocessing and normalization rules. Normalization was very prevalent in natural language processing before LLMs, in machine translation and text classification, where text is normalized and simplified by lowercasing it and removing double whitespace. In language models, it is preferable to do none of this. As a deep learning person, the speaker prefers not to touch the data and to keep it as raw as possible, so most of these options are turned off where possible. SentencePiece also has a concept of sentences. It was developed early, when the idea was to train a tokenizer on a bunch of independent sentences, so it has options for how many sentences to train on, the maximum sentence length, and shuffling sentences. Sentences are treated as the individual training examples. In the context of LLMs, this is a spurious and weird distinction: raw data should not be touched. Sentences happen to exist, but in raw datasets it is hard to say exactly what is or is not a sentence, and the concept can differ across languages. It is hard to define an actual sentence when digging into it, so the concept makes little sense; the preference would be to treat a file as a giant stream of bytes.

Rare-character handling, splitting rules and special tokens

SentencePiece has a lot of treatment around rare word characters, where "word" here means code points; this comes up again shortly. It also has rules for splitting digits, splitting whitespace and numbers, and how to deal with them. These work as merge rules and are roughly equivalent, if one squints, to tiktoken using a regular expression to split text into categories. Digits can be split up, for example. Special tokens can also be indicated. SentencePiece hardcodes the UNK token, the beginning-of-sentence and end-of-sentence tokens, and a pad token. The UNK token must exist, to the speaker's understanding.

Training and inspecting the vocabulary

Pressing train creates the files tok400.model and tok400.vocab. The model file can then be loaded and its vocabulary inspected. The vocabulary of size 400 was trained on the toy text, and these are the individual tokens SentencePiece creates. At the beginning is the UNK token with ID 0, then the beginning-of-sequence and end-of-sequence tokens with IDs 1 and 2. The pad ID was set to negative 1, meaning it is not used, so there is no pad ID here. Next come the individual byte tokens. Byte fallback was turned on, as in Llama, so the 256 byte tokens follow, with their IDs. After the byte tokens come the merges. Only the parent nodes of the merges are shown, not the children, along with their IDs. Finally come the individual code-point tokens. So the ordering in which SentencePiece represents its vocabulary is special tokens, then byte tokens, then merge tokens, then individual code-point tokens. The raw code-point tokens are all those encountered in the training set, meaning the entire set of code points that occurred. Those that are extremely rare, as determined by character coverage, are ignored and not added to the vocabulary. For instance, a code point that occurred only once in a million sentences would be dropped.

Encoding with byte fallback

With a vocabulary in place, text can be encoded into IDs, and the individual tokens can be decoded back into little pieces, as SentencePiece calls them. Looking at the output for a test string beginning with "hello", the token IDs come back, and a few things stand out. First, the Korean characters were not part of the training set. SentencePiece encounters code points it has not seen during training, and those have no token associated with them, so they would suddenly become unknown tokens. Because byte fallback is true, SentencePiece instead falls back to bytes: it encodes the characters with UTF-8 and uses the byte tokens to represent them. What appears is the UTF-8 encoding, shifted by three because of the special tokens that have earlier IDs.

What happens without byte fallback

Retraining with byte fallback set to false changes things. All the byte tokens disappear, leaving only merges, and there are now many more merges, because the vocabulary size no longer has to hold all the bytes. Encoding the same string now yields 0: the entire string is unknown, and since the UNK token is token zero, the result is zero. This output would feed into a language model, and it is not what is wanted if all kinds of different rare, unrecognized things end up mapping to UNK. That is why Llama correctly used byte fallback set to true: rare or unknown code points should be fed into the model in some manner.

The dummy prefix option

Another thing to notice appears when decoding the individual tokens. Spaces are shown as a bold underline character. It is not clear why SentencePiece swaps whitespace for these characters; perhaps it is for visualization. Another oddity is the extra space in front of "hello". It comes from the add dummy prefix option, which is true. The documentation describes it as adding whitespace at the beginning of text in order to treat "world" in "world" and "world" in "hello world" in exactly the same way. This matters because, in the tiktoken tokenizer, "world" as a token by itself has a different ID than " world" with a leading space: one is 1917 while the other is 14 and so on. These are two different tokens for the language model, and the language model has to learn from

The Dummy Prefix Option

A language model has to learn from data that "world" and " world" are closely related concepts. In the Tiktoken tokenizer, words at the beginning of a sentence and words in the middle of a sentence look completely different, and the model has to learn that they are roughly the same. The add-dummy-prefix option fights this problem a little. As part of pre-processing, it takes the string and adds a space at the front, so that "world" in the first position and " world" in the middle both become " world". That is another pre-processing option that is turned on, and Llama 2 uses it as well.

Wrapping Up SentencePiece

That covers the preview of SentencePiece and how it differs from other tokenizers. The raw protocol buffer representation of the trained tokenizer is included here, so it is possible to step through it. Anyone who wants a tokenization identical to Meta's Llama 2 can copy and paste these settings, as was done above. In summary, SentencePiece carries a lot of historical baggage. Many of its concepts are slightly confusing and potentially contain footguns, such as the concept of a sentence and its maximum length. It is nonetheless fairly common in the industry, because it is efficient and can do both training and inference. It also has quirks: the unk token must exist, and the way byte fallbacks are done is not particularly elegant. Unfortunately, it is not well documented either. Understanding what is happening took a lot of time working with it directly and visualizing things, because in this view the documentation is not super amazing. Still, it is a very nice repository for anyone who wants to train their own tokenizer.

Considerations for Setting Vocabulary Size

Revisiting how the vocabulary size should be set means returning to the GPT model architecture built from scratch in the previous video. In that file, the vocab size was defined as 65 or so, an extremely small number that will grow much larger with real tokenizers. Vocab size does not come up in most of the layers. It appears in exactly two places. The first is the token embedding table, a two-dimensional array whose number of rows equals the vocab size. Each vocabulary element, each token, has a vector of size n_embd (the number of channels in the Transformer) that is trained with backpropagation. As the vocab size increases, rows are added to this table. The second is the LM head layer at the end of the Transformer, a linear layer used to produce the logits, which become the probabilities for the next token in the sequence. Intuitively, a probability must be produced for every token that might come next at every point in time, so more tokens mean more probabilities. Every additional token introduces another dot product in this final linear layer. If so, why can't the vocab size grow to infinity? There are several reasons. First, the token embedding table and the linear layer both grow, which means a lot more computation, since the LM head layer becomes more expensive. Second, more parameters raise the worry of undertraining some of them. With a very large vocabulary, say a million tokens, each token comes up more and more rarely in the training data because so many other tokens are around. Each individual token is seen in fewer examples, so the vectors associated with it may be undertrained, since they rarely participate in the forward and backward pass. Third, as the vocab size grows, sequences shrink a lot. That is nice, because the model attends to more text. But it also means that overly large chunks of text are squished into single tokens, so the model has less time to think per number of characters. Too much information gets packed into a single token, and the forward pass of the Transformer may not be enough to process it appropriately. These are the considerations in designing the vocab size. It is mostly an empirical hyperparameter, and in state-of-the-art architectures today it is usually in the high tens of thousands, or somewhere around 100,000.

Extending the Vocabulary of a Pre-trained Model

Another consideration is taking a pre-trained model and extending its vocabulary, which is done fairly commonly. When fine-tuning for ChatGPT, for example, many new special tokens are introduced on top of the base model to maintain the metadata and structure of conversation objects between a user and an assistant. More special tokens might be added for using a browser or any other tool, and it is very tempting to add many tokens for all kinds of special functionality. Adding a token is totally possible. The embedding table is resized by adding rows, and these new parameters are initialized from scratch to small random numbers. The weights inside the final linear layer are extended as well, so that dot products are computed with the associated parameters and the probabilities for the new tokens can be calculated. Both are just resizing operations, a very mild form of model surgery that can be done fairly easily. It is quite common to freeze the base model, introduce the new parameters, and train only those to bring new tokens into the architecture. Arbitrary parts of the model can be frozen or trained, which is entirely up to the practitioner. Only minor surgery is required to introduce new tokens.

Gist Tokens and Prompt Compression

There is also an entire design space of introducing new tokens into a vocabulary that goes far beyond adding special tokens and new functionality. It could fill an entire video by itself, but one example gives a sense of it: a paper on learning to compress prompts with what are called gist tokens. The rough idea concerns language models used in settings that require very long prompts. Long prompts slow everything down, because they have to be encoded, used, and attended over, and it is heavy to carry very large prompts. The paper instead introduces a few new tokens, placed in a sequence, and trains the model by distillation. The entire model stays frozen, and only the representations (embeddings) of the new tokens are trained. They are optimized so that the behavior of the language model is identical to that of the model given the very long prompt. This compresses the long prompt into a few new gist tokens. At test time, the old prompt can be discarded and the gist tokens swapped in to stand in for it, with almost identical performance. This is one technique in the class of parameter-efficient fine-tuning methods, where most of the model is fixed. There is no training of the model weights, and no training of LoRA or any other new parameters; the only parameters trained are the token embeddings. It is just one example, but it shows there is a whole design space here that is potentially worth exploring in the future.

Tokenizing Other Modalities

Recently there has been a lot of momentum around constructing Transformers that process not just text as the input modality but many others, such as images, videos, and audio. The question is how to feed in all these modalities, and potentially predict them, and whether the architecture has to change in some fundamental way. Many people are converging on the view that the architecture does not change. The Transformer stays, the input domains are tokenized, and the result is treated as if it were text tokens, with everything else done in an identical manner. An early paper has a nice graphic of how an image can be chunked into integers, which become the tokens of images. These tokens can be hard tokens, forced to be integers. They can also be soft tokens, which are not required to be discrete but whose representations are forced through bottlenecks, as in autoencoders. OpenAI's Sora, which blew the minds of many people and inspired a lot of thinking about what is possible, follows the same pattern. Its graphic shows that where LLMs have text tokens, Sora has visual patches. Videos are chunked into tokens with their own vocabularies, and these can be processed either as discrete tokens, say with autoregressive models, or as soft tokens with diffusion models. All of this is being actively worked on and is beyond the scope of this video, but it is worth mentioning briefly.

Revisiting the Opening Questions: Spelling

Having gone deep into the tokenization algorithm and understood much more about how it works, it is time to loop back to the beginning of the video and go through the opening bullet points to see why those problems happen. The first is why an LLM cannot spell words very well or do other spelling-related tasks. Fundamentally, this is because

Why LLMs struggle with spelling and character-level tasks

Text is chunked into tokens, and some of those tokens are fairly long. In the GPT-4 vocabulary, for example, the string "default style" turns out to be a single token, which packs a lot of characters into one unit. The suspicion is that a model would not be good at spelling-related tasks involving such a token. To test this, GPT-4 was asked how many letters L appear in "default style". The prompt was deliberately built so that the phrase becomes a single token, which is exactly what the model sees. The model fails: it answers three, when the correct answer is four. A second character-level task points the same way. Asked to reverse the string "default style", GPT-4 tried to use a code interpreter. After that was stopped and the model was told to just try it, it produced a jumble, so it does not really know how to reverse the string from right to left. If tokenization is the cause, a different approach should help. The same string was reversed in two steps: first print every character separated by spaces, then reverse that list. Again the model reached for a tool, but once stopped it first listed all the characters, correctly, and then reversed them, also correctly. The model cannot reverse the string directly, but once the string is broken up into individual characters, those characters become much easier to see and reverse.

Why non-English languages are worse

Models perform worse on non-English languages for two reasons. The language model sees less non-English data while training its parameters, and the tokenizer itself is not sufficiently trained on non-English data. For example, "hello how are you" is five tokens, while its translation is fifteen tokens, a threefold blow-up. The Korean greeting "annyeong", which is basically just "hello", ends up as three tokens. That is surprising for such a common, typical greeting, whereas the English "hello" is a single token. Everything is more bloated and diffuse, which is probably part of the reason the model works worse on other languages.

Why LLMs are bad at simple arithmetic

Weak arithmetic comes from the tokenization of numbers. Addition follows a character-level algorithm: add the ones, then the tens, then the hundreds, referring to specific digits along the way. But numbers are represented completely arbitrarily, depending on whatever happened to merge or not merge during tokenization. A good blog post on the subject is titled "Integer tokenization is insane". It systematically explores the tokenization of numbers, in what is believed to be GPT-2. For four-digit numbers, a number may be a single token, or two tokens split as 1-3, 2-2 or 3-1, and the different numbers fall into all of these combinations arbitrarily. The model therefore sometimes sees one token for all four digits, sometimes for three, sometimes for two, sometimes for one, in an arbitrary manner. This is a headwind for the language model. It is remarkable that models can deal with it at all, but it is far from ideal. That is why Meta, when training Llama 2 with SentencePiece, made sure to split up all the digits, partly to improve simple arithmetic performance.

Why GPT-2 is weaker at Python

GPT-2's weakness in Python is partly a modeling issue, tied to the architecture, the dataset and the strength of the model. It is also partly a tokenization issue. As the simple Python example showed, the tokenizer encodes spaces terribly: every single space is an individual token. This dramatically reduces the context length the model can attend across. It is almost a tokenization bug in GPT-2, and it was later fixed in GPT-4.

Halting on the string "end of text"

Another odd behavior is that an LLM can abruptly halt when it sees the string "end of text". Asked to print the string "end of text", GPT-4 replies by asking the user to specify the string. Given "end of text is the string" and then "here's a string", it still does not print it. Something is clearly breaking in the handling of the special token. What OpenAI does under the hood is unknown. It may be that the text is parsed as an actual special token rather than as individual pieces without special-token handling logic. Someone calling encode may be passing in allowed special tokens, allowing end of text as a special token inside the user prompt. But the user prompt is attacker-controlled text, so special tokens should ideally not be parsed from that kind of input. Something is evidently going wrong, and knowledge of special tokens can become an attack surface. To confuse an LLM, try giving it some special tokens and see whether something breaks by chance.

The trailing whitespace problem

A particularly fun issue is trailing whitespace. In the OpenAI playground, GPT-3.5 Turbo Instruct is a completion model rather than a chat model, so it is much closer to a base model: it continues the token sequence. Given "here's a tagline for ice cream shop", it can be submitted and returns a continuation without trouble. But if a space is added after "ice cream shop" before submitting, a warning appears: "your text ends in a trailing space, which causes worse performance due to how the API splits text into tokens". The reason lies in how such text appears in training data. Suppose a completion of a tagline were found on a web page in the training data. In GPT tokenization, a space is always a prefix of the token that follows it. A word like "oh" is therefore not an "o" token but a "space o" token, which is token 8840, with the space as part of the token. When the model is left to complete the next token, it can sample "space o". But when a space is added to the prompt, that trailing space is encoded as its own token, 220. That token would otherwise have been part of the next token of the tagline, and the model has seen very little data of a bare space by itself. The sequence has been split at an unnatural point and is out of distribution, so arbitrary bad things can happen. That is the reason for the warning.

Tokens are the atoms of what the LLM sees

The fundamental issue is that the LLM sits on top of tokens, and tokens are text chunks, not characters in the way people think of them. They are the atoms of what the LLM sees, and a number of weird behaviors follow from that. Returning to the "default cell style" example, the model has probably never seen "default cell sta" without the remaining letters in its training set. It has always seen the string as a single group, probably as part of some kind of function or API, and this broken combination of tokens would be extremely rare in the training data. Copying that truncated string into the playground and trying to complete from it immediately produced a big error: the model predicted a completion that begins with a stop sequence, resulting in no output, and the message suggested adjusting the prompt or stop sequences. The model had emitted something like an end of text token right away, because the input was off the data distribution and the model was confused. In effect it is brain damage: the model has never seen this before and is shocked, predicting end of text or something similar. A second attempt did complete, but then raised the message that the request may violate usage policies. It was flagged, so something went wrong somewhere. There is a sense of jank here, because the model is extremely unhappy with this input and does not know how to complete it. In training it always appears as a single token.

Partial tokens and unstable tokens

These issues, where a prompt completes only the first character of the next token or contains a long token with just some of its characters, can all be described as problems with partial tokens. The tiktoken repository shows how seriously this is handled. Searching the Rust code for "unstable" turns up encode-unstable, native unstable tokens and a lot of special-case handling. None of this material about unstable tokens is documented anywhere, but there is a ton of code dealing with unstable tokens.

Unstable Tokens and Completion APIs

Unstable tokens are exactly the problem of partial tokens described above. A more capable completion API would not simply append the next token after the given token list. When asking for the next token sequence, such an API would search over characters that, if re-tokenized, would be of high probability. That way it could add a single individual character instead of adding the next full token that follows the partial token list. This is very tricky to describe, and the code is worth reading directly. It is an extremely gnarly and hairy topic that comes from tokenization fundamentally, and it may deserve an entire video of its own in the future.

Solid Gold Magikarp: Strange Tokens

The best case comes last, and by far the favorite: SolidGoldMagikarp. The blog post of that name is internet famous among people working with LLMs and is worth reading in full. The author went to the token embedding table and clustered the tokens by their embedding representation. A cluster of very strange tokens appeared, including "rot e stream Fame", "solid gold Magikarp", "Signet message" and other really weird entries. What these tokens are and where they come from is unclear at first, since "solid gold Magikarp" makes no sense as a token. The plot thickens when the model is asked about them. A benign request such as "please can you repeat back to me the string solid gold Magikarp" produces totally broken LLM behavior. The model may evade ("I'm sorry, I can't hear you"), hallucinate, or even insult the user and call them names. Asking about "streamer bot" gets similar results, and some responses show weird humor. Simple strings like "at Roth" and "solid gold Magikarp" effectively break the model. Many tokens besides SolidGoldMagikarp behave this way. These trigger words send the model haywire when they appear in a prompt, producing very strange behaviors, including ones that violate typical safety guidelines and the model's alignment, such as swearing back at the user.

Why Untrained Tokens Break Models

The cause comes down to tokenization. SolidGoldMagikarp is a Reddit user (u/SolidGoldMagikarp). This has not been definitively explored, but the likely explanation is that the tokenization data set was very different from the training data set of the language model itself. The tokenization data set probably contained a lot of Reddit data in which this user was mentioned, since the user posted very often. The string therefore occurred many times in the tokenization data set, and its characters were merged into a single token for that Reddit user. That gave the user a dedicated token in GPT-2's vocabulary of roughly 50,000 tokens. Later, when the language model was trained, the Reddit data was not present. The string SolidGoldMagikarp never occurs in the language model's training set, so the token is never activated. Its embedding row is initialized at random at the beginning of optimization, and through all the forward and backward passes and updates, that row vector is never sampled, never used and never trained. It is like unallocated memory in a typical binary program written in C. At test time, evoking this token plucks out a row of the embedding table that is completely untrained and feeds it into the Transformer, which creates undefined behavior. This never-before-seen behavior is what appears in the examples above. Any of these weird tokens evokes it, because the model is fundamentally out of sample and out of distribution.

Token Efficiency Across Formats

A last point, one many people are already aware of: different formats, representations and languages can be more or less efficient with GPT tokenizers, or any other tokenizer. JSON is really dense in tokens, while YAML is a lot more efficient. The same data comes to 116 tokens in JSON and 99 in YAML, quite an improvement. In the token economy, costs are paid per token in several ways: in context length and in the dollar cost of processing structured data. YAML is therefore preferable to JSON. In general, tokenization density deserves constant attention. It pays to look for efficient encoding schemes and to spend time in the Tiktokenizer web app measuring the token efficiency of different formats and settings.

Closing Thoughts on Tokenization

That concludes this fairly long video on tokenization. It is tricky, annoying and irritating, and the presenter personally dislikes this stage. Even so, it should not be brushed off. There are many footguns and sharp edges here, along with security issues and AI safety issues, as the example of plugging unallocated memory into language models showed. The stage is worth understanding. Eternal glory still goes to anyone who can get rid of it, and the one paper shown that attempts this is hopefully the first of many to follow.

Practical Recommendations

The final recommendations for applications are as follows. If the GPT-4 tokens and vocabulary can be reused, that option deserves consideration, using Tiktoken, which is a very efficient and nice library for BPE inference. The byte-level BPE used by Tiktoken and OpenAI is also a favorite. To train a vocabulary from scratch, BPE with SentencePiece is the option, with reservations. The presenter is not a huge fan of SentencePiece: its byte fallback is disliked, as is its running BPE on Unicode code points. It also has a million settings and many footguns, and the settings are easy to miscalibrate. A parameter that is not fully understood can end up cropping sentences, for example. The settings need great care: copy exactly what Meta did, or spend a lot of time examining all the hyperparameters and going through the SentencePiece code to confirm they are correct. Even with every setting correct, the algorithm remains somewhat inferior to what Tiktoken does. For anyone who needs to train a vocabulary, the best approach may be to wait for minbpe to become as efficient as possible, which is something the presenter hopes to work on. What is really wanted is Tiktoken with training code. That ideal thing does not currently exist. minbpe is an implementation of it, but it is currently in Python.

Sign-off and Start of GPT-2 Code Walkthrough

That is all for tokenization for now. A more advanced video, even drier and more detailed, might follow in the future, but this is where things stop, and hopefully the video was helpful. The transcript then continues with a separate segment: the context size was increased from GPT-1's 512 to 1024 in GPT-2. Next comes a brief walkthrough of OpenAI's GPT-2 encoder code, including a spurious layer that will be explained shortly.

Turn your watchlist into a reading routine

Bring your YouTube videos together, read summaries with key passages marked, and explore the full transcript. Save your own highlights with Pro.

Start with 5 free batteries. Each covers up to 30 minutes of a new summary.

New summaries depend on video availability and demand; processing may take time or require retry.