LLM Foundations
Tokenization β How LLMs Break Text Into Manageable Pieces
Tokenization is the critical first step in processing text for LLMsβconverting raw text into a sequence of integer tokens that the model can process. This guide covers BPE, WordPiece, SentencePiece, and Unigram algorithms with practical implementation details.
- BPE β The most widely used tokenization algorithm in modern LLMs
- Vocabulary Design β Balancing sequence length against embedding parameters
- Multilingual Support β How tokenization choices affect cross-language performance
Good tokenization is the invisible foundation of every great language model.
Tokenization for LLMs
Tokenization is the critical first step in processing text for LLMs---converting raw text into a sequence of integer tokens that the model can process. This tutorial covers the main tokenization algorithms, their mathematical foundations, and practical considerations.
Why Tokenization Matters
The choice of tokenization algorithm affects:
- Vocabulary size: Larger vocabularies reduce sequence length but increase embedding parameters
- Out-of-vocabulary (OOV) handling: How the model handles unseen words
- Multilingual support: How well the tokenizer works across languages
- Model performance: Better tokenization can improve downstream task performance
Byte Pair Encoding (BPE)
BPE is the most widely used tokenization algorithm in modern LLMs (GPT-2, GPT-3, LLaMA, Mistral).
BPE Training Algorithm
- Initialize vocabulary with all unique characters (bytes)
- Count frequency of all adjacent token pairs
- Merge the most frequent pair into a new token
- Add the new token to the vocabulary
- Repeat until desired vocabulary size is reached
The merge score (also called pointwise mutual information) measures how often two tokens appear together relative to their individual frequencies.
BPE Example
Starting with text: {"low": 5, "lower": 2, "newest": 6, "widest": 3}
Initial vocabulary: {l, o, w, e, r, s, t, n, i, d}
Iteration 1: Most frequent pair is e, s (appears 9 times). Merge to create es token. Iteration 2: Most frequent pair is es, t (appears 9 times). Merge to create est token. Iteration 3: Most frequent pair is l, o (appears 7 times). Merge to create lo token.
WordPiece
WordPiece was originally developed for Google Translate and is used in BERT and other encoder models.
The key difference from BPE: WordPiece optimizes for likelihood rather than raw frequency. This can lead to different tokenizations, especially for rare words.
SentencePiece
SentencePiece is a language-agnostic tokenization library that treats text as a raw stream of Unicode characters, without requiring pre-tokenization.
Key advantages:
- Language-agnostic: Works without language-specific tokenizers
- Reversible: Perfectly reversible tokenization (no information loss)
- Pre-tokenization free: Handles whitespace natively
Unigram Language Model
Unigram is an alternative to BPE that starts with a large vocabulary and prunes it down.
The optimal tokenization is found by:
Tiktoken Implementation
Tiktoken is OpenAI's fast BPE tokenizer used for GPT-3.5 and GPT-4. It is implemented in Rust for speed.
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4")
text = "Hello, world! This is a tokenization example."
tokens = enc.encode(text)
print(f"Tokens: {tokens}")
print(f"Token strings: {[enc.decode([t]) for t in tokens]}")
decoded = enc.decode(tokens)
assert decoded == text
HuggingFace Tokenizers
The HuggingFace okenizers library provides fast, customizable tokenization:
from tokenizers import Tokenizer
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from tokenizers.pre_tokenizers import ByteLevel
from tokenizers.processors import TemplateProcessing
tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
tokenizer.pre_tokenizer = ByteLevel(add_prefix_space=False)
trainer = BpeTrainer(
vocab_size=32000,
special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"],
min_frequency=2
)
files = ["corpus.txt"]
tokenizer.train(files, trainer)
output = tokenizer.encode("Hello, how are you?")
print(f"Tokens: {output.tokens}")
print(f"IDs: {output.ids}")
`
Impact on Model Performance
Key considerations:
- Multilingual tokenization: Languages like Chinese/Japanese may require 2-3x more tokens than English for the same content
- Code tokenization: Indentation and syntax must be preserved
- Numerical tokenization: Numbers should be tokenized consistently
Practice Exercises
-
Implementation: Implement BPE from scratch. Train a tokenizer on a small corpus and compare its vocabulary with SentencePiece.
-
Analysis: For a given text in English vs Chinese, compare the number of tokens produced by GPT-4's tokenizer. What is the tokenization overhead for Chinese?
-
Mathematical: Given a vocabulary of 50K tokens and a text of 10,000 characters, estimate the expected number of tokens if the average token covers 3.5 characters.
-
Research: Investigate how tokenization affects multilingual LLM performance. Why do some languages require more tokens per word?
What to Learn Next
-> LLM Architecture Deep Dive How transformers power language models with self-attention and KV cache.
-> Pretraining Language Models Learning language from the internet with CLM, scaling laws, and data curation.
-> Fine-Tuning LLMs Customizing language models for your specific tasks and domains.
-> Prompt Engineering Getting the most out of language models through effective input design.
-> In-Context Learning Teaching LLMs new tasks without trainingβpurely through prompts.
-> Chain-of-Thought Reasoning Making LLMs think step by step for complex reasoning problems.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type β Always start by categorizing the problem
- Incorrect formula application β Verify the formula applies to your specific case
- Unit errors β Always check units are consistent throughout
- Sign errors β Pay careful attention to positive and negative values
- Rounding too early β Keep full precision until the final answer
- Forgetting constraints β Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic β Build on the foundation laid here
- Next Topic β See how this concept extends to more advanced material
- Practice Problems β Additional exercises with solutions
- Video Explanation β Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions