← All lessons
How tokenizers work
Learn merges from a tiny corpus
train.js
// every word starts as single characterslet words = corpus.map(([w, n]) => ({ parts: [...w], n }));const merges = [];for (let m = 0; m < numMerges; m++) { // count neighbor pairs, weighted by word count const pairs = countPairs(words); const [a, b] = mostFrequent(pairs); // join the most frequent pair everywhere words = words.map((w) => mergePair(w, a, b)); merges.push([a, b]); vocab.push(a + b);}encode.js
function encodeWord(word, merges) { let parts = [...word]; // replay the merges in the order they were learned for (const [a, b] of merges) { parts = mergePair(parts, a, b); } return parts;}Tokenize your own text with a tokenizer trained on one page of English
Or try
Tokens
Token IDs, what the model reads
0characters
0UTF-8 bytes
0tokens
-chars / token
Hex chips are pieces of one character. The tokenizer never learned the whole emoji, so it falls back to bytes
tokenize.js
function encode(text) { // split into words first, each keeps its leading space const words = text.match(/ ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+/gu); const ids = []; for (const word of words) { // start from bytes, so any text has an encoding let parts = [...new TextEncoder().encode(word)]; // merge the pair learned earliest, until none apply while (true) { const pair = lowestRankPair(parts, ranks); if (!pair) break; parts = mergePair(parts, pair, ranks[pair]); } ids.push(...parts); } return ids;}decode.js
// decoding joins the bytes backconst bytes = ids.flatMap((id) => [...vocab[id]]);new TextDecoder().decode(new Uint8Array(bytes));Grow the vocabulary and watch the count drop
Tokens
vocab.js
// fewer merges: a smaller vocabulary, more tokens per textconst merges = learned.slice(0, n);const vocabSize = 256 + merges.length; // 0 merges: every byte is its own tokenif (n === 0) ids = [...utf8(text)];else ids = encode(text, merges);Topics
Next: How LLM sampling works
Open lesson