Text Tokenizer
A skill for tokenizing text into numerical IDs for machine learning models.
What is Tokenizing?
Tokenizing is the process of breaking down text into smaller pieces called tokens, each assigned a unique numerical ID. This is fundamental for preparing text for ML models, especially in NLP.
Goal: Divide input into tokens (IDs) in a way that makes sense for the model.
Basic Tokenization
1. Splitting Text
- Simple tokenizer splits text into words and punctuation
- Example:
"Hello, world!" → ["Hello", ",", "world", "!"]
2. Creating a Vocabulary
- Maps each token to a numerical ID
- Special tokens:
[BOS] (Beginning of Sequence): Marks text start
[EOS] (End of Sequence): Marks text end
[PAD] (Padding): Makes sequences same length in batches
[UNK] (Unknown): Represents tokens not in vocabulary
- Example:
"Hello, world!" → [64, 455, 78, 467]
3. Handling Unknown Words
- Words not in vocabulary get replaced with
[UNK]
- Example:
"Bye, world!" → [987, 455, 78, 467] (assuming [UNK] = 987)
Advanced Tokenization Methods
Byte Pair Encoding (BPE)
- Purpose: Reduces vocabulary size, handles rare/unknown words
- How it works:
- Starts with individual characters as tokens
- Iteratively merges most frequent token pairs
- Continues until no more frequent pairs exist
- Benefits:
- Eliminates need for
[UNK] token
- More efficient and flexible vocabulary
- Example:
"playing" → ["play", "ing"]
WordPiece
- Used by: BERT and similar models
- Purpose: Similar to BPE, breaks words into subword units
- How it works:
- Begins with base vocabulary of individual characters
- Iteratively adds most frequent subword that maximizes training data likelihood
- Uses probabilistic model for merging decisions
- Benefits:
- Balances vocabulary size with word representation
- Efficiently handles rare and compound words
- Example:
"unhappiness" → ["un", "happy", "ness"]
Unigram Language Model
- Used by: SentencePiece
- Purpose: Uses probabilistic model for optimal subword selection
- How it works:
- Starts with large set of potential tokens
- Iteratively removes tokens that least improve model probability
- Finalizes vocabulary with most probable subword units
- Benefits:
- Flexible and natural language modeling
- Often results in more efficient tokenizations
- Example:
"internationalization" → ["international", "ization"]
Implementation with tiktoken
Basic Usage
import tiktoken
# Load GPT-2 tokenizer
encoding = tiktoken.get_encoding("gpt2")
# Encode text to token IDs
token_ids = encoding.encode("Hello, world!")
print(token_ids) # [15496, 11, 995, 0]
# Decode token IDs back to text
text = encoding.decode(token_ids)
print(text) # "Hello, world!"
With Special Tokens
# Encode with special tokens allowed
token_ids = encoding.encode("Hello, world!", allowed_special={"[EOS]"})
# Check token count
print(len(token_ids))
Processing Files
import urllib.request
# Download text file
url = "https://raw.githubusercontent.com/rasbt/LLMs-from-scratch/main/ch02/01_main-chapter-code/the-verdict.txt"
file_path = "the-verdict.txt"
urllib.request.urlretrieve(url, file_path)
# Read and tokenize
with open(file_path, "r", encoding="utf-8") as f:
raw_text = f.read()
token_ids = tiktoken.get_encoding("gpt2").encode(raw_text, allowed_special={"[EOS]"})
# Print first 50 tokens
print(token_ids[:50])
Common Use Cases
- Preprocessing text for training - Convert training data to token IDs
- Understanding model input requirements - Know what format your model expects
- Debugging tokenization issues - Inspect how text is being tokenized
- Comparing different tokenization methods - Evaluate BPE vs WordPiece vs Unigram
Best Practices
- Choose tokenizer based on your model - GPT-2 uses BPE, BERT uses WordPiece
- Handle special tokens appropriately - Include
[BOS], [EOS] as needed for your use case
- Consider vocabulary size vs. tokenization quality tradeoff - Larger vocabularies may tokenize more efficiently but use more memory
- Test with edge cases - Rare words, special characters, different languages
- Use the right encoding - Match the tokenizer to your model architecture
Troubleshooting
Unknown tokens appearing
- Check if your vocabulary is large enough
- Consider using BPE or WordPiece instead of basic tokenization
- Verify special tokens are properly configured
Token count seems too high
- Try a different tokenization method (BPE often produces fewer tokens)
- Check if you're including unnecessary whitespace or special characters
Decoding produces unexpected output
- Ensure you're using the same encoding for encode/decode
- Check if special tokens are being handled correctly
- Verify the token IDs are valid for your vocabulary
References
1---2name: text-tokenizer3description: How to tokenize text for LLMs and NLP models. Use this skill whenever the user needs to convert text into token IDs, understand tokenization methods (BPE, WordPiece, Unigram), work with vocabularies, or implement tokenization for machine learning. Make sure to use this skill when users mention tokenizing, token IDs, vocabulary creation, BPE, WordPiece, or any text preprocessing for ML models.4---56# Text Tokenizer78A skill for tokenizing text into numerical IDs for machine learning models.910## What is Tokenizing?1112Tokenizing is the process of breaking down text into smaller pieces called tokens, each assigned a unique numerical ID. This is fundamental for preparing text for ML models, especially in NLP.1314**Goal:** Divide input into tokens (IDs) in a way that makes sense for the model.1516## Basic Tokenization1718### 1. Splitting Text19- Simple tokenizer splits text into words and punctuation20- Example: `"Hello, world!"` → `["Hello", ",", "world", "!"]`2122### 2. Creating a Vocabulary23- Maps each token to a numerical ID24- **Special tokens:**25 - `[BOS]` (Beginning of Sequence): Marks text start26 - `[EOS]` (End of Sequence): Marks text end27 - `[PAD]` (Padding): Makes sequences same length in batches28 - `[UNK]` (Unknown): Represents tokens not in vocabulary29- Example: `"Hello, world!"` → `[64, 455, 78, 467]`3031### 3. Handling Unknown Words32- Words not in vocabulary get replaced with `[UNK]`33- Example: `"Bye, world!"` → `[987, 455, 78, 467]` (assuming `[UNK]` = 987)3435## Advanced Tokenization Methods3637### Byte Pair Encoding (BPE)38- **Purpose:** Reduces vocabulary size, handles rare/unknown words39- **How it works:**40 - Starts with individual characters as tokens41 - Iteratively merges most frequent token pairs42 - Continues until no more frequent pairs exist43- **Benefits:**44 - Eliminates need for `[UNK]` token45 - More efficient and flexible vocabulary46- **Example:** `"playing"` → `["play", "ing"]`4748### WordPiece49- **Used by:** BERT and similar models50- **Purpose:** Similar to BPE, breaks words into subword units51- **How it works:**52 - Begins with base vocabulary of individual characters53 - Iteratively adds most frequent subword that maximizes training data likelihood54 - Uses probabilistic model for merging decisions55- **Benefits:**56 - Balances vocabulary size with word representation57 - Efficiently handles rare and compound words58- **Example:** `"unhappiness"` → `["un", "happy", "ness"]`5960### Unigram Language Model61- **Used by:** SentencePiece62- **Purpose:** Uses probabilistic model for optimal subword selection63- **How it works:**64 - Starts with large set of potential tokens65 - Iteratively removes tokens that least improve model probability66 - Finalizes vocabulary with most probable subword units67- **Benefits:**68 - Flexible and natural language modeling69 - Often results in more efficient tokenizations70- **Example:** `"internationalization"` → `["international", "ization"]`7172## Implementation with tiktoken7374### Basic Usage7576```python77import tiktoken7879# Load GPT-2 tokenizer80encoding = tiktoken.get_encoding("gpt2")8182# Encode text to token IDs83token_ids = encoding.encode("Hello, world!")84print(token_ids) # [15496, 11, 995, 0]8586# Decode token IDs back to text87text = encoding.decode(token_ids)88print(text) # "Hello, world!"89```9091### With Special Tokens9293```python94# Encode with special tokens allowed95token_ids = encoding.encode("Hello, world!", allowed_special={"[EOS]"})9697# Check token count98print(len(token_ids))99```100101### Processing Files102103```python104import urllib.request105106# Download text file107url = "https://raw.githubusercontent.com/rasbt/LLMs-from-scratch/main/ch02/01_main-chapter-code/the-verdict.txt"108file_path = "the-verdict.txt"109urllib.request.urlretrieve(url, file_path)110111# Read and tokenize112with open(file_path, "r", encoding="utf-8") as f:113 raw_text = f.read()114115token_ids = tiktoken.get_encoding("gpt2").encode(raw_text, allowed_special={"[EOS]"})116117# Print first 50 tokens118print(token_ids[:50])119```120121## Common Use Cases1221231. **Preprocessing text for training** - Convert training data to token IDs1242. **Understanding model input requirements** - Know what format your model expects1253. **Debugging tokenization issues** - Inspect how text is being tokenized1264. **Comparing different tokenization methods** - Evaluate BPE vs WordPiece vs Unigram127128## Best Practices129130- **Choose tokenizer based on your model** - GPT-2 uses BPE, BERT uses WordPiece131- **Handle special tokens appropriately** - Include `[BOS]`, `[EOS]` as needed for your use case132- **Consider vocabulary size vs. tokenization quality tradeoff** - Larger vocabularies may tokenize more efficiently but use more memory133- **Test with edge cases** - Rare words, special characters, different languages134- **Use the right encoding** - Match the tokenizer to your model architecture135136## Troubleshooting137138### Unknown tokens appearing139- Check if your vocabulary is large enough140- Consider using BPE or WordPiece instead of basic tokenization141- Verify special tokens are properly configured142143### Token count seems too high144- Try a different tokenization method (BPE often produces fewer tokens)145- Check if you're including unnecessary whitespace or special characters146147### Decoding produces unexpected output148- Ensure you're using the same encoding for encode/decode149- Check if special tokens are being handled correctly150- Verify the token IDs are valid for your vocabulary151152## References153154- [Build a Large Language Model from Scratch](https://www.manning.com/books/build-a-large-language-model-from-scratch)155- [LLMs from Scratch - Tokenization](https://github.com/rasbt/LLMs-from-scratch/blob/main/ch02/01_main-chapter-code/ch02.ipynb)