πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Tokenization Deep Dive

TransformersBPE, WordPiece, Unigram, and SentencePiece🟒 Free Lesson

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.

python
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.

python
# 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.

python
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.

FeatureBPEWordPieceUnigramSentencePiece
AlgorithmFrequency-based mergingLikelihood-based mergingProbabilistic removalLanguage-independent
Pre-tokenizationRequiredRequiredRequiredOptional
VocabularyFixed sizeFixed sizeVariableFixed size
Used byGPT-2, RoBERTaBERT, DistilBERTT5, ALBERTT5, XLNet, ALBERT
Word boundarySpace-basedSpace-basedSpace-basedLearned

Hugging Face Tokenizers Library

python
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

MethodVocab SizeOOV HandlingMultilingualSpeed
Word-levelLargePoor (UNK)PoorFast
Character-levelSmallExcellentGoodSlow
BPEMediumGoodGoodFast
WordPieceMediumGoodGoodFast
UnigramMediumGoodExcellentMedium
SentencePieceMediumGoodExcellentMedium

Byte-Level BPE

Byte-level BPE (used in GPT-2, RoBERTa) operates on bytes rather than Unicode characters, enabling true open-vocabulary processing.

python
# 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

  1. Misidentifying the problem type β€” Always start by categorizing the problem
  2. Incorrect formula application β€” Verify the formula applies to your specific case
  3. Unit errors β€” Always check units are consistent throughout
  4. Sign errors β€” Pay careful attention to positive and negative values
  5. Rounding too early β€” Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement