GitHub · minbpe: Minimal, clean code for the Byte Pair Encoding (BPE) algorithm commonly used in LLM tokenization.
Open the sourceKarpathy's minbpe README presents a minimal, readable implementation of byte-level Byte Pair Encoding, the tokenization algorithm used by modern LLMs. He explains the three core tokenizer functions (train, encode, decode), walks through a toy example, shows verification against GPT-4's tiktoken tokenizer, and explains how to train custom tokenizers and safely handle special tokens.
- He explains that BPE is 'byte-level' because it runs on UTF-8 encoded strings, and that modern LLMs like GPT, Llama, and Mistral use it to train tokenizers. - He frames a tokenizer as doing three things: training vocabulary and merges, encoding text to tokens, and decoding tokens to text. - He notes minbpe always allocates the 256 individual bytes as tokens first, then adds merges on top, so merge IDs start at 256. - He describes regex pre-splitting by category (letters, numbers, punctuation) so that no merges happen across category boundaries, as in GPT-2 through GPT-4. - He validates his implementation by reproducing tiktoken's GPT-4 token outputs exactly. - He warns that special tokens must be explicitly allowed during encoding to avoid tokenizing attacker-controlled input as special tokens.
Based on Andrej Karpathy's public content. Not affiliated with or endorsed by Andrej Karpathy.
Supports these rules
Verify each stage before adding complexity
ConfirmedReduce to the minimal readable core
ConfirmedMatch the tool to the task
Quotes from this video
“I tried hard to keep the code itself clean, readable and hackable.”
“You should not have feel scared to read the code and understand how it works.”
“we have to explicitly declare our intent to use and parse special tokens in the call to encode. Otherwise this can become a major footgun, unintentionally tokenizing attacker-controlled data (e.g. user prompts) with special tokens.”
“We can verify that the `RegexTokenizer` has feature parity with the GPT-4 tokenizer from [tiktoken](https://github.com/openai/tiktoken) as follows:”
“you can follow. First, you can decide that you don't want the complexity of splitting and preprocessing text with regex patterns, and you also don't care for special tokens. In that case, reach for the `BasicTokenizer`.”
“you'd want to change around the vocabulary size depending on the size of your dataset.”