Let's build the GPT Tokenizer

Andrej Karpathy

Karpathy builds a GPT tokenizer from scratch and traces LLM quirks to it

In a 133-minute lecture, Andrej Karpathy codes the Byte Pair Encoding algorithm behind OpenAI's GPT tokenizers, compares it with Google's SentencePiece, and shows how spelling, arithmetic and odd glitches trace back to tokenization.

Andrej Karpathy, in a two-hour-plus lecture on his channel, builds a tokenizer of the kind used in the GPT series from the ground up. He calls tokenization his least favourite part of working with large language models, but argues it must be understood because much of their odd behaviour traces back to it. The code is published as the minbpe repository, with exercises to follow along.

How Byte Pair Encoding works

A tokenizer translates between text and integer tokens, and it is a separate stage from the model, with its own training set. Karpathy starts from the UTF-8 bytes of a string, which gives a vocabulary of only 256 tokens and very long sequences. Byte Pair Encoding fixes that by repeatedly finding the most common adjacent pair of tokens and replacing it with a newly minted token.

He implements functions to count pairs and merge them, then loops. With 20 merges on a long blog post, 24,000 bytes shrink to about 19,000 tokens, a compression ratio of roughly 1.27. He then writes encode and decode, and notes that decoding must handle byte sequences that are not valid UTF-8 by replacing them rather than raising an error.

A coding notebook showing a loop that repeatedly merges the most common byte pair and prints the results.
The Byte Pair Encoding training loop runs 20 merges and reports the compression ratio.

GPT-2 and GPT-4 regex splitting and special tokens

OpenAI does not apply the plain algorithm. A regular expression first splits text into chunks, so merges never cross boundaries between letters, numbers and punctuation. Karpathy walks through the GPT-2 pattern, including its hard-coded handling of apostrophes. The GPT-4 pattern is case-insensitive and merges numbers only up to three digits. The GPT-4 vocabulary is roughly 100,000 tokens, against roughly 50,000 for GPT-2, and it groups runs of Python indentation into single tokens.

He also covers special tokens such as end of text, which separates documents in training data and bypasses the merge process. Adding one means extending the model's embedding table and final layer by a row each.

SentencePiece and vocabulary size

Karpathy contrasts OpenAI's tiktoken, which is inference only, with Google's SentencePiece, which can train and run tokenizers and was used for Llama 2. SentencePiece merges Unicode code points rather than bytes, with an optional byte fallback for rare characters. He finds it cluttered with historical settings and poorly documented.

On vocabulary size, a larger vocabulary shortens sequences but enlarges the embedding table and output layer, and leaves rare tokens undertrained. Figures in the high tens of thousands up to around 100,000 are typical today.

Transformer model code on screen showing the token embedding table and the final linear layer.
Discussion of how vocabulary size affects the embedding table and the final output layer.

Why LLMs stumble: spelling, numbers, Solid Gold Magikarp

The final stretch ties known quirks to tokens. Models struggle to count letters in a long single token. Non-English text costs more tokens, so Korean greetings can take several times as many as English. Numbers split arbitrarily, which hampers arithmetic. A trailing space in a prompt pushes the model off its training distribution.

The best-known case is Solid Gold Magikarp. Karpathy explains that it was a Reddit username frequent enough in the tokenizer's data to earn its own token, yet absent from the model's training data. That left the token's embedding untrained, which he likens to unallocated memory, and prompts containing it produced erratic output. He also notes YAML takes fewer tokens than JSON for the same data (99 against 116 in his example).

A browser window with a blog post about glitch tokens found by clustering token embeddings.
Explaining why the Solid Gold Magikarp token was never trained and caused erratic model behaviour.

Recommendations

If you can, reuse the GPT-4 vocabulary through tiktoken. To train your own, he prefers a byte-level approach and says SentencePiece needs great care with its settings. What he wants is tiktoken's design with training code, which he says does not yet exist, and minbpe is his Python attempt. He closes by hoping someone eliminates tokenization entirely, citing research on byte-level models that is not yet proven at scale.

Questions and answers

What did Andrej Karpathy release in his GPT tokenizer lecture in 2024?

Andrej Karpathy released a 133-minute lecture in which he builds a GPT-style tokenizer from scratch. He codes the Byte Pair Encoding algorithm behind OpenAI's GPT tokenizers and publishes the code as the minbpe repository, with exercises so viewers can follow along.

How does Byte Pair Encoding work in Andrej Karpathy's GPT tokenizer lecture?

Byte Pair Encoding starts from the UTF-8 bytes of a string, a vocabulary of only 256 tokens, then repeatedly finds the most common adjacent pair of tokens and replaces it with a newly minted token. With 20 merges on a long blog post, 24,000 bytes shrank to about 19,000 tokens, a ratio of roughly 1.27.

How do the GPT-2 and GPT-4 tokenizers differ?

Both OpenAI tokenizers first split text with a regular expression so merges never cross boundaries between letters, numbers and punctuation. The GPT-4 pattern is case-insensitive and merges numbers only up to three digits. Its vocabulary is roughly 100,000 tokens against roughly 50,000 for GPT-2, and it groups Python indentation runs into single tokens.

Why do large language models struggle with spelling, arithmetic and non-English text?

Andrej Karpathy traces these problems to tokenization. Models struggle to count letters inside a long single token. Numbers split arbitrarily, which hampers arithmetic. Non-English text costs more tokens, so Korean greetings can take several times as many tokens as English, and a trailing space in a prompt pushes the model off its training distribution.

What was the Solid Gold Magikarp glitch in large language models?

Solid Gold Magikarp was a Reddit username frequent enough in the tokenizer's data to earn its own token, yet absent from the model's training data. Andrej Karpathy explains that this left the token's embedding untrained, likening it to unallocated memory, so prompts containing it produced erratic output.

What does Andrej Karpathy recommend for choosing a tokenizer?

Andrej Karpathy recommends reusing the GPT-4 vocabulary through OpenAI's tiktoken if possible. To train your own, he prefers a byte-level approach and says Google's SentencePiece needs great care with its settings. He wants tiktoken's design with training code, which he says does not yet exist, and minbpe is his Python attempt.

From the YouTube description

The Tokenizer is a necessary and pervasive component of Large Language Models (LLMs), where it translates between strings and tokens (text chunks). Tokenizers are a completely separate stage of the LLM pipeline: they have their own training sets, training algorithms (Byte Pair Encoding), and after training implement two fundamental functions: encode() from strings to tokens, and decode() back from tokens to strings. In this lecture we build from scratch the Tokenizer used in the GPT series from OpenAI. In the process, we will see that a lot of weird behaviors and problems of LLMs actually trace back to tokenization. We'll go through a number of these issues, discuss why tokenization is at fault, and why someone out there ideally finds a way to delete this stage entirely.

Chapters:
00:00:00 intro: Tokenization, GPT-2 paper, tokenization-related issues
00:05:50 tokenization by example in a Web UI (tiktokenizer)
00:14:56 strings in Python, Unicode code points
00:18:15 Unicode byte encodings, ASCII, UTF-8, UTF-16, UTF-32
00:22:47 daydreaming: deleting tokenization
00:23:50 Byte Pair Encoding (BPE) algorithm walkthrough
00:27:02 starting the implementation
00:28:35 counting consecutive pairs, finding most common pair
00:30:36 merging the most common pair
00:34:58 training the tokenizer: adding the while loop, compression ratio
00:39:20 tokenizer/LLM diagram: it is a completely separate stage
00:42:47 decoding tokens to strings
00:48:21 encoding strings to tokens
00:57:36 regex patterns to force splits across categories
01:11:38 tiktoken library intro, differences between GPT-2/GPT-4 regex
01:14:59 GPT-2 encoder.py released by OpenAI walkthrough
01:18:26 special tokens, tiktoken handling of, GPT-2/GPT-4 differences
01:25:28 minbpe exercise time! write your own GPT-4 tokenizer
01:28:42 sentencepiece library intro, used to train Llama 2 vocabulary
01:43:27 how to set vocabulary set? revisiting gpt.py transformer
01:48:11 training new tokens, example of prompt compression
01:49:58 multimodal [image, video, audio] tokenization with vector quantization
01:51:41 revisiting and explaining the quirks of LLM tokenization
02:10:20 final recommendations
02:12:50 ??? 🙂

Exercises:
- Advised flow: reference this document and try to implement the steps before I give away the partial solutions in the video. The full solutions if you're getting stuck are in the minbpe code https://github.com/karpathy/minbpe/blob/master/exercise.md

Links:
- Google colab for the video: https://colab.research.google.com/drive/1y0KnCFZvGVf_odSfcNAws6kcDD7HsI0L?usp=sharing
- GitHub repo for the video: minBPE https://github.com/karpathy/minbpe
- Playlist of the whole Zero to Hero series so far: https://www.youtube.com/watch?v=VMj-3S1tku0&list=PLAqhIrjkxbuWI23v9cThsA9GvCAUhRvKZ
- our Discord channel: https://discord.gg/3zy8kqD9Cp
- my Twitter: https://twitter.com/karpathy

Supplementary links:
- tiktokenizer https://tiktokenizer.vercel.app
- tiktoken from OpenAI: https://github.com/openai/tiktoken
- sentencepiece from Google https://github.com/google/sentencepiece

Watch on YouTube

Working out what this means for your business?

Aileron Shift builds the systems behind this site: AI newsrooms that research, write and publish on their own, marketing automation and WordPress hosting for companies that need to move faster than their competitors.