Tokenization Deep Dive
Tokenization is the critical first step in NLP pipelines β converting raw text into model-usable integer tokens. Modern tokenization uses subword algorithms that balance vocabulary size with coverage.
Byte-Pair Encoding (BPE)
BPE iteratively merges the most frequent pair of adjacent symbols.
from collections import Counter, defaultdict
class BPETokenizer:
def __init__(self, vocab_size=300):
self.vocab_size = vocab_size
self.merges = {}
def get_vocab(self, corpus):
vocab = Counter()
for word in corpus:
symbols = list(word) + ['</w>']
for s in symbols:
vocab[s] += 1
return vocab
def get_pair_counts(self, corpus):
pairs = Counter()
for word in corpus:
symbols = list(word) + ['</w>']
for i in range(len(symbols) - 1):
pair = (symbols[i], symbols[i + 1])
pairs[pair] += 1
return pairs
def merge_pair(self, pair, corpus):
merged = ''.join(pair)
new_corpus = []
for word in corpus:
symbols = list(word) + ['</w>']
new_symbols = []
i = 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i+1]) == pair:
new_symbols.append(merged)
i += 2
else:
new_symbols.append(symbols[i])
i += 1
new_corpus.append(''.join(new_symbols[:-1]))
return new_corpus
def train(self, corpus):
vocab = self.get_vocab(corpus)
num_merges = self.vocab_size - len(vocab)
for i in range(num_merges):
pairs = self.get_pair_counts(corpus)
if not pairs:
break
best_pair = max(pairs, key=pairs.get)
corpus = self.merge_pair(best_pair, corpus)
self.merges[best_pair] = ''.join(best_pair)
return corpus
# Example usage
corpus = ["low", "low", "low", "low", "low", "lowest", "newer", "newer", "wider", "wider"]
bpe = BPETokenizer(vocab_size=20)
result = bpe.train(corpus)
print(f"Merges learned: {bpe.merges}")
WordPiece Tokenization
WordPiece is similar to BPE but uses a different selection criterion β it merges the pair that maximizes the language model likelihood.
The pair with the highest score (not highest frequency) is merged.
# Hugging Face WordPiece usage
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
tokens = tokenizer.tokenize("unaffable")
print(tokens) # ['un', '##aff', '##able']
# The ## prefix indicates a subword continuation
tokens = tokenizer.tokenize("tokenization")
print(tokens) # ['token', '##ization']
Unigram Language Model
Unigram starts with a large vocabulary and iteratively removes tokens that contribute least to the language model likelihood.
from transformers import AutoTokenizer
# Unigram tokenizer (T5, ALBERT)
tokenizer = AutoTokenizer.from_pretrained('t5-small')
tokens = tokenizer.tokenize("Hello, how are you?")
print(tokens) # ['βHello', ',', 'βhow', 'βare', 'βyou', '?']
# The β character represents a space before the token
SentencePiece
SentencePiece is a language-independent tokenizer that treats the input as raw Unicode, making it suitable for any language.
| Feature | BPE | WordPiece | Unigram | SentencePiece |
|---|---|---|---|---|
| Algorithm | Frequency-based merging | Likelihood-based merging | Probabilistic removal | Language-independent |
| Pre-tokenization | Required | Required | Required | Optional |
| Vocabulary | Fixed size | Fixed size | Variable | Fixed size |
| Used by | GPT-2, RoBERTa | BERT, DistilBERT | T5, ALBERT | T5, XLNet, ALBERT |
| Word boundary | Space-based | Space-based | Space-based | Learned |
Hugging Face Tokenizers Library
from tokenizers import Tokenizer, models, pre_tokenizers, trainers
# Build a BPE tokenizer from scratch
tokenizer = Tokenizer(models.BPE())
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
trainer = trainers.BpeTrainer(
vocab_size=30000,
min_frequency=2,
special_tokens=["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"]
)
# Train on corpus
files = ["data/corpus.txt"]
tokenizer.train(files, trainer)
# Encode text
encoded = tokenizer.encode("Hello, this is a test!")
print(f"Tokens: {encoded.tokens}")
print(f"IDs: {encoded.ids}")
Tokenization Comparison
| Method | Vocab Size | OOV Handling | Multilingual | Speed |
|---|---|---|---|---|
| Word-level | Large | Poor (UNK) | Poor | Fast |
| Character-level | Small | Excellent | Good | Slow |
| BPE | Medium | Good | Good | Fast |
| WordPiece | Medium | Good | Good | Fast |
| Unigram | Medium | Good | Excellent | Medium |
| SentencePiece | Medium | Good | Excellent | Medium |
Byte-Level BPE
Byte-level BPE (used in GPT-2, RoBERTa) operates on bytes rather than Unicode characters, enabling true open-vocabulary processing.
# Byte-level encoding
text = "Hello, δ½ ε₯½!"
byte_repr = text.encode('utf-8')
print(f"Bytes: {byte_repr}")
# b'Hello, \xe4\xbd\xa0\xe5\xa5\xbd!'
# Each byte maps to a character in the extended ASCII range
# This ensures ANY text can be tokenized
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