Tokenization: how text becomes numbers
LLMs never see letters or words — they see token ids. Learn how subword tokenizers like BPE are built, why vocabulary size matters, and why tokens drive cost, context limits and some famously odd model behaviour.
A neural network can only multiply numbers, so before a large language model can read your prompt, the text must be cut into pieces called tokens and each piece mapped to an integer id. This step — Tokenization — looks like boring plumbing, but it decides how much text fits in the Context window, how much an API call costs, how well a model handles Indonesian versus English, and even why models struggle to count the letters in a word.
Three ways to cut text
| Granularity | Vocabulary size | Sequence length | Main problem |
|---|---|---|---|
| Word-level | Huge (hundreds of thousands+) | Short | Unknown words (OOV) become <unk>; “makan”, “makanan”, “dimakan” are unrelated ids |
| Character/byte-level | Tiny (~100–256) | Very long | Sequences 4–5× longer → attention cost explodes; model must learn spelling from scratch |
| Subword (BPE, WordPiece, Unigram) | Medium (30k–200k) | Medium | Best trade-off; used by virtually all modern LLMs |
Byte-Pair Encoding (BPE), step by step
BPE was originally a data-compression trick; Sennrich et al. adapted it in 2016 to build subword vocabularies for neural machine translation[1]. The idea is greedy and simple: start from single symbols and repeatedly glue together the pair that appears most often in the training corpus.
- Split every word in the corpus into characters (or bytes) and count word frequencies.
- Count every pair of adjacent symbols, weighted by word frequency.
- Merge the most frequent pair into a new symbol and record the merge rule.
- Repeat until the vocabulary reaches the target size (base symbols + number of merges).
- To tokenize new text, apply the learned merges in the same order they were learned.
- (a, b)*
- the winning pair of adjacent symbols for this merge step
- argmax₍ₐ,ᵦ₎
- “the pair (a, b) that makes the following expression largest”
- Σ_w
- sum over all distinct words w in the training corpus
- freq(w)
- how many times word w occurs in the corpus
- count_w(a b)
- how many times a is directly followed by b inside word w (as currently split)
- →
- then: apply the merge, adding “ab” to the Vocabulary
▸Worked example
Worked example. Corpus: low×5, lower×2, newest×6, widest×3. The pair e s appears 6 + 3 = 9 times → merge to es. Now es t appears 9 times → est. Next l o (7) → lo, then lo w (7) → low. After only four merges, the unseen word lowest is tokenized as low + est — two meaningful pieces, no unknown token. That generalization is the whole point of subwords.
Byte-level BPE and other tokenizer families
- Byte-level BPE (GPT-2 and later): the base alphabet is the 256 possible bytes of UTF-8, so *any* string — emoji, Javanese script, code — can be encoded with zero unknown tokens. GPT-2 used 50,257 tokens; text is first pre-split with a regex so merges never cross word/number/punctuation boundaries[2].
- WordPiece (BERT): similar to BPE but picks merges that most increase the likelihood of the training data; continuation pieces are marked with
##(e.g.token,##ization). BERT-base uses ~30k tokens. - Unigram LM / SentencePiece (T5, many multilingual models): starts from a large candidate vocabulary and prunes it; SentencePiece treats the input as a raw stream and encodes spaces as
▁, so it needs no language-specific pre-tokenizer[3].
Try this
- Set the number of merges to 0: every character is its own token, so the token count equals the character count.
- Slowly raise the merges and watch the merge table: the first merges are very common pairs (often a letter + space or frequent suffixes like
an). The token count of your input drops quickly, then flattens. - Type a word that appears in the corpus and one that does not (e.g. a made-up word like
memperlatihkan). The known word becomes 1–2 tokens; the unknown one splits into several familiar pieces. - Edit the training corpus to be mostly English, then tokenize an Indonesian sentence: it needs more tokens. This is exactly why non-English text is often more expensive with English-heavy tokenizers.
Why tokens matter in practice
- Cost and limits are counted in tokens, not words. For English with modern tokenizers, a rough rule of thumb is ~4 characters or ~¾ of a word per token; other languages usually need more tokens for the same meaning.
- Spelling and counting are hard: the model sees
strawberryas one or a few chunks, not ten letters, so “how many r’s?” requires knowledge the model never directly observed. - Numbers split unevenly (e.g.
12345may become123+45), which makes digit-level arithmetic harder. - Whitespace is part of the token:
hello(with a leading space) andhelloare different ids. A stray trailing space in a prompt can subtly change the output. - Special tokens such as
<|endoftext|>,[CLS],[SEP]or chat-template markers carry structure. They must match what the model saw in training.
- What it is
- How many distinct tokens the tokenizer can output. Each token gets a row in the embedding matrix and a column in the output layer (V × d parameters each).
- ↑ If you increase it
- Text compresses into fewer tokens (cheaper, more fits in context), but the embedding/output matrices grow and rare tokens get too few training examples to learn good embeddings.
- ↓ If you decrease it
- Smaller model head and well-trained tokens, but sequences get longer, so each text costs more compute and the effective context shrinks.
- Typical values
- ~30k (BERT WordPiece), 32k (Llama 2), 50,257 (GPT-2), ~100k–200k (GPT-4-era tiktoken encodings, Llama 3 at 128k), ~250k for strongly multilingual models.
- What it is
- The number of merge rules learned during BPE training. Final vocabulary = base alphabet (e.g. 256 bytes) + merges + special tokens.
- ↑ If you increase it
- Longer, more word-like tokens; common words become a single token; diminishing returns once most frequent words are covered.
- ↓ If you decrease it
- Tokens approach single characters/bytes; sequences get longer and the model must learn more composition itself.
- Typical values
- Tens of thousands for production tokenizers; 50–500 in the toy widget.
- What it is
- When you call a tokenizer for a model,
max_lengthwithtruncation=Truecuts sequences that are too long (andpaddingfills short ones) so batches fit the model’s context window. - ↑ If you increase it
- Less information is cut off, but memory and compute per batch grow (attention cost grows roughly quadratically with length).
- ↓ If you decrease it
- Faster and lighter training, but you may silently drop the part of the document that contains the answer or the label-relevant text.
- Typical values
- 512 for BERT-style encoders; 2k–8k for fine-tuning LLMs; never above the model’s maximum.
import tiktoken
from transformers import AutoTokenizer
text = "Tokenisasi itu penting untuk LLM."
# OpenAI-style byte-level BPE (tiktoken)
enc = tiktoken.get_encoding("cl100k_base")
ids = enc.encode(text)
print(len(ids), ids)
print([enc.decode([i]) for i in ids]) # see each piece
# Hugging Face tokenizer that matches a specific model
tok = AutoTokenizer.from_pretrained("gpt2")
print(tok.tokenize(text)) # 'Ġ' marks a leading space
tok.pad_token = tok.eos_token # GPT-2 has no pad token by default
batch = tok([text, "short"], padding=True, truncation=True, max_length=16,
return_tensors="pt")
print(batch["input_ids"].shape, batch["attention_mask"])from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders
tokenizer = Tokenizer(models.BPE())
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tokenizer.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer(
vocab_size=16_000, # base bytes + merges + specials
special_tokens=["<|endoftext|>"],
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
)
tokenizer.train(["corpus_id.txt", "corpus_en.txt"], trainer)
enc = tokenizer.encode("Saya sedang belajar tokenisasi.")
print(enc.tokens, enc.ids)
tokenizer.save("my-bpe.json")model.resize_token_embeddings(len(tok)) — and remembering the new rows start untrained. (5) Assuming a token count measured with one model’s tokenizer holds for another model.▸Go deeper: compression, glitch tokens and tokenizer-free models
- compression ratio
- average number of characters per Token
- fertility
- average number of tokens per word
- characters
- number of characters in the text (including spaces)
- tokens
- number of tokens the tokenizer produces for that text
- words
- number of whitespace-separated words
- ÷
- divided by
▸Worked example
A tokenizer is trained separately from — and before — the model. If some string was frequent in the tokenizer’s corpus but almost absent from the model’s training data, its token gets an embedding that was barely updated. Such “glitch tokens” were famously found in GPT-2/GPT-3 vocabularies and could make models behave erratically.
Researchers also explore byte-level models without a learned vocabulary. They avoid tokenizer artifacts but pay with much longer sequences. For a hands-on build of BPE in ~100 lines of Python, see Karpathy’s minbpe[6]; the Hugging Face course walks through BPE, WordPiece and Unigram in detail[4], and tiktoken shows the production encodings used by OpenAI models[5].
Quiz
References
- [1]Neural Machine Translation of Rare Words with Subword UnitsPaperSennrich et al.2016arxiv.orgIntroduced BPE for subword vocabularies.
- [2]Language Models are Unsupervised Multitask Learners (GPT-2)PaperRadford et al.2019cdn.openai.comByte-level BPE with a 50,257-token vocabulary.
- [3]SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text ProcessingPaperKudo & Richardson2018arxiv.org
- [4]Hugging Face LLM Course — Byte-Pair Encoding tokenizationCourseHugging Facehuggingface.co
- [5]tiktoken — fast BPE tokenizer for OpenAI modelsDocsOpenAIgithub.com
- [6]minbpe — minimal, clean code for byte-level BPECourseAndrej Karpathy2024github.com