AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
✎Large Language Models
  1. Tokenization: how text becomes numbers
  2. How LLMs work: next-token prediction at scale
  3. Decoding: greedy, beam search, temperature, top-k, top-p
  4. Scaling laws: parameters, data and compute
  5. Fine-tuning & alignment: SFT, RLHF, DPO, LoRA/QLoRA
  6. Prompting: zero-shot, few-shot, chain-of-thought, structured output
  7. Retrieval-Augmented Generation (RAG)
  8. Agents & tool use: ReAct, function calling, MCP
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Large Language Models

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.

Intermediate~18 min·6 references
Key terms
TokenTokenizationByte-Pair Encoding (BPE)VocabularyContext windowEmbedding

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.

≈
Analogy: LEGO bricks
Imagine a LEGO set where very common shapes come pre-assembled (a whole car door), while rare shapes must be built from small 1×1 bricks. A subword tokenizer works the same way: frequent words like “the” or “yang” are a single token, while a rare word like “mempertanggungjawabkan” is assembled from several smaller pieces. Nothing is ever impossible to build, because the tiniest bricks (single bytes) are always available.

Three ways to cut text

GranularityVocabulary sizeSequence lengthMain problem
Word-levelHuge (hundreds of thousands+)ShortUnknown words (OOV) become <unk>; “makan”, “makanan”, “dimakan” are unrelated ids
Character/byte-levelTiny (~100–256)Very longSequences 4–5× longer → attention cost explodes; model must learn spelling from scratch
Subword (BPE, WordPiece, Unigram)Medium (30k–200k)MediumBest trade-off; used by virtually all modern LLMs
Subword tokenization sits in the sweet spot between words and characters.

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.

  1. Split every word in the corpus into characters (or bytes) and count word frequencies.
  2. Count every pair of adjacent symbols, weighted by word frequency.
  3. Merge the most frequent pair into a new symbol and record the merge rule.
  4. Repeat until the vocabulary reaches the target size (base symbols + number of merges).
  5. To tokenize new text, apply the learned merges in the same order they were learned.
(a, b)* = argmax₍ₐ,ᵦ₎ Σ_w freq(w) · count_w(a b) → replace every “a b” with “ab”
One BPE training step: find the most frequent adjacent pair and merge it.
In words: Count every pair of neighbouring symbols across the whole corpus, weighting each word by how often it occurs. The most frequent pair wins and becomes a new token everywhere. Repeat until the vocabulary reaches the target size.
Symbols(hover a symbol in the formula)
(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
Corpus (split into characters): low ×5, lower ×2, newest ×6, widest ×3 Pair counts: e s = 6 + 3 = 9, s t = 9, w e = 2 + 6 = 8, l o = 5 + 2 = 7, o w = 7, n e = 6, … Winner: “e s” (9) → newest = n e w es t, widest = w i d es t Next step: “es t” = 9 → merge to “est”, and so on.

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].
Loading interactive…
A real BPE trainer running in your browser on a small bilingual corpus.

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 strawberry as 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. 12345 may become 123+45), which makes digit-level arithmetic harder.
  • Whitespace is part of the token: hello (with a leading space) and hello are 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.
knobvocab_size
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.
knobnum_merges (BPE)
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.
knobmax_length / truncation
What it is
When you call a tokenizer for a model, max_length with truncation=True cuts sequences that are too long (and padding fills 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.
python
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"])
Inspecting real tokenizers with tiktoken and Hugging Face transformers.
python
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")
Training your own byte-level BPE tokenizer with the 🤗 tokenizers library.
!
Common pitfalls
(1) Using a tokenizer that does not match the model — ids then point to the wrong embeddings and output is garbage. Always load both from the same checkpoint. (2) Estimating budgets in characters or words instead of tokens. (3) Forgetting the model’s chat template or special tokens when building prompts by hand. (4) Adding new tokens without calling 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 = characters ÷ tokens fertility = tokens ÷ words
Two common ways to compare tokenizers across languages.
In words: Compression ratio says how much text one token covers (higher = more efficient). Fertility says how many pieces an average word is cut into (lower = better; 1.0 means one token per word). Both depend on the language and on the tokenizer's training data.
Symbols(hover a symbol in the formula)
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 text of 1,000 characters and 220 words becomes 300 tokens compression ratio = 1,000 ÷ 300 = 3.33 characters per token fertility = 300 ÷ 220 = 1.36 tokens per word If another tokenizer needs 450 tokens for the same text, it costs 1.5× more context and compute.

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

1.
Why do modern LLMs use subword tokens instead of whole words?
2.
In BPE training, which pair is merged at each step?
3.
What happens if you greatly increase the vocabulary size of a tokenizer?
4.
Why can byte-level BPE (as in GPT-2) encode any string without an unknown token?
5.
A prompt in Indonesian uses 40% more tokens than its English translation with the same model. What is the most likely reason?
Score: 0/5

References

  1. [1]
    Neural Machine Translation of Rare Words with Subword Units
    PaperSennrich et al.2016arxiv.org
    Introduced BPE for subword vocabularies.
  2. [2]
    Language Models are Unsupervised Multitask Learners (GPT-2)
    PaperRadford et al.2019cdn.openai.com
    Byte-level BPE with a 50,257-token vocabulary.
  3. [3]
    SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing
    PaperKudo & Richardson2018arxiv.org
  4. [4]
    Hugging Face LLM Course — Byte-Pair Encoding tokenization
    CourseHugging Facehuggingface.co
  5. [5]
    tiktoken — fast BPE tokenizer for OpenAI models
    DocsOpenAIgithub.com
  6. [6]
    minbpe — minimal, clean code for byte-level BPE
    CourseAndrej Karpathy2024github.com
← Previous
Attention and Transformers
Next →
How LLMs work: next-token prediction at scale