Byte-Pair Encoding (BPE) is a subword tokenization algorithm that constructs a vocabulary by iteratively merging the most frequent adjacent pairs of bytes or characters in a corpus. Originating as a lossless data compression technique, BPE was adapted for NLP to segment text into variable-length subword units, balancing the semantic richness of words with the flexibility of characters. The algorithm begins with a base vocabulary of all unique characters and repeatedly counts co-occurring pairs, merging the most frequent pair into a new token until a target vocabulary size is reached. This bottom-up, frequency-driven process ensures that common words remain intact as single tokens, while rare and morphologically complex words are decomposed into meaningful, reusable fragments like roots and affixes.
Glossary
Byte-Pair Encoding (BPE)

What is Byte-Pair Encoding (BPE)?
Byte-Pair Encoding (BPE) is a data compression algorithm adapted for subword tokenization that iteratively merges the most frequent pair of bytes or characters to build a vocabulary, effectively handling out-of-vocabulary words.
The primary advantage of BPE is its ability to handle out-of-vocabulary (OOV) terms by decomposing any unseen word into a sequence of known subword units, eliminating the <UNK> token problem inherent in fixed word-level vocabularies. During inference, an input word is tokenized by applying the learned merge operations in order, greedily segmenting the sequence into the longest possible subwords from the vocabulary. This deterministic, reversible process is foundational to modern large language models, including the GPT series, and is often implemented alongside a </w> end-of-word symbol to distinguish subwords that terminate a word from those that do not, enabling precise reconstruction of the original text.
Key Characteristics of BPE
Byte-Pair Encoding (BPE) is a data compression algorithm repurposed for NLP to segment text into subword units. It iteratively merges the most frequent pair of bytes or characters, building a vocabulary that balances word-level semantics with character-level flexibility to handle out-of-vocabulary terms.
Iterative Merge Operations
BPE constructs its vocabulary from the bottom up through a deterministic, iterative process. Starting with a base vocabulary of individual characters, the algorithm scans the training corpus to find the most frequently adjacent pair of symbols. It then creates a new symbol by merging that pair and replaces all its occurrences in the corpus. This process repeats for a predefined number of merge operations, with each iteration adding one new subword unit to the vocabulary. The final vocabulary size is a hyperparameter that directly controls the granularity of tokenization.
Out-of-Vocabulary Resolution
A core strength of BPE is its ability to encode any unseen word by decomposing it into known subword units. Since the base vocabulary contains all individual characters, even a completely novel word can be represented as a sequence of characters or known subword fragments. This eliminates the need for a fallback <UNK> token that discards information. For example, a model trained on 'low' and 'lower' can tokenize the unseen word 'lowest' as ['low', 'est'] if those subword merges were learned, preserving morphological relationships.
Frequency-Driven Vocabulary
BPE's merge priority is strictly governed by frequency counts in the training data. This statistical grounding ensures that the most common character sequences—which often correspond to morphemes, root words, and common affixes—are merged early and receive dedicated tokens. Rare or idiosyncratic spellings remain segmented into smaller pieces. This dynamic adaptation to corpus statistics makes BPE inherently language-agnostic. It requires no linguistic knowledge, morphological rules, or pre-built dictionaries, allowing it to work effectively across hundreds of languages and even code.
Reversible and Lossless Encoding
The BPE tokenization process is fully reversible. A tokenized sequence of subword units can be deterministically reconstructed back into the original surface text string without any loss of information. This is because the merge rules are applied as direct string concatenations, and the decoder simply joins the tokens. This lossless property is critical for generative tasks like machine translation and text summarization, where the model's subword output must be detokenized into clean, readable text for the end user.
Hyperparameter: Number of Merges
The primary hyperparameter governing BPE is the total number of merge operations, which directly determines the final vocabulary size. A smaller number of merges results in a more granular, character-heavy segmentation, increasing sequence length but reducing vocabulary size. A larger number of merges creates a coarser vocabulary with more whole-word tokens, reducing sequence length but increasing the model's embedding matrix size. Typical vocabulary sizes range from 8k to 50k subword units, balancing the trade-off between sequence length and model parameter count.
Byte-Level BPE Variant
A modern adaptation, Byte-Level BPE (BBPE), applies the merge algorithm directly to UTF-8 encoded bytes rather than Unicode characters. This forces the base vocabulary to be exactly 256 tokens, one for each possible byte value. BBPE completely eliminates the concept of an unknown character and provides a universal representation for any language, emoji, or symbol. This variant is used in models like GPT-2 and RoBERTa, enabling robust handling of noisy, multilingual, and code-mixed text without any character-level preprocessing.
BPE vs. Other Tokenization Methods
A feature-level comparison of Byte-Pair Encoding against word-level, character-level, and Unigram tokenization approaches for handling vocabulary size, OOV rates, and sequence length.
| Feature | Byte-Pair Encoding | Word-Level | Character-Level | Unigram LM |
|---|---|---|---|---|
Token Unit | Subwords | Full words | Single characters | Probabilistic subwords |
Handles OOV Words | ||||
Vocabulary Size | Moderate (8k-50k) | Large (100k-500k+) | Tiny (50-256) | Moderate (8k-50k) |
Sequence Length | Moderate | Short | Very Long | Moderate |
Preserves Morphology | ||||
Training Data Required | Moderate | Massive | Minimal | Moderate |
Rare Word Representation | Compositional | UNK token | Compositional | Compositional |
Deterministic Encoding |
Frequently Asked Questions
Clear, technical answers to the most common questions about the subword tokenization algorithm that powers modern large language models.
Byte-Pair Encoding (BPE) is a data compression algorithm adapted for subword tokenization that iteratively merges the most frequent pair of adjacent symbols in a corpus to build a vocabulary. The process begins by splitting every word into a sequence of individual characters, with a special end-of-word symbol appended. The algorithm then counts all adjacent symbol pairs, identifies the most frequent pair, and merges it into a new single symbol. This merge operation is applied everywhere that pair occurs, and the process repeats for a predetermined number of merge operations. The final vocabulary consists of the base characters plus all merged subword units, enabling the model to represent any word as a sequence of known subwords—effectively eliminating out-of-vocabulary issues.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Byte-Pair Encoding is part of a broader ecosystem of subword tokenization and text normalization techniques. These related concepts define how models handle vocabulary, out-of-vocabulary words, and text preprocessing.
Out-of-Vocabulary (OOV)
The central problem that Byte-Pair Encoding solves. An OOV token is any word or character sequence encountered during inference that was not present in a model's fixed vocabulary. Without subword tokenization, OOV terms are typically mapped to a generic <UNK> token, causing complete information loss. BPE eliminates OOV issues by decomposing any unknown word into known subword units. For example, the unseen word 'hyperparameterization' can be tokenized as ['hyper', 'parameter', 'ization'] if those subwords exist in the vocabulary.
Tokenization
The fundamental NLP task of segmenting a continuous string of text into discrete units called tokens. Tokenization strategies exist on a spectrum:
- Word-level: Splits on whitespace and punctuation, creating large vocabularies with severe OOV problems.
- Character-level: Splits into individual characters, creating tiny vocabularies but losing semantic meaning and requiring very long sequences.
- Subword-level (BPE, WordPiece, Unigram): Strikes a balance by splitting rare words into frequent subword units while keeping common words intact.
BPE is the most widely adopted subword tokenization algorithm, used in GPT, RoBERTa, and many other models.
WordPiece Tokenization
A subword tokenization algorithm closely related to BPE, developed by Google for the BERT model. While BPE merges the most frequent pair of tokens, WordPiece selects the pair that maximizes the likelihood of the training data when merged. This difference means WordPiece prioritizes merges that improve the language model's probability rather than raw frequency. WordPiece also uses a special ## prefix to mark subword tokens that are continuations of a word, e.g., ['playing'] becomes ['play', '##ing']. This explicit continuation marking is absent in standard BPE.
Unigram Language Model Tokenization
A probabilistic subword tokenization algorithm used in models like XLNet and ALBERT. Unlike BPE's bottom-up merge approach, Unigram starts with a large vocabulary and iteratively removes tokens that least impact the overall likelihood of the training corpus. For any given word, multiple tokenization candidates exist, and the algorithm selects the one with the highest probability under the unigram model. This provides a probabilistic foundation that BPE lacks, allowing for multiple valid tokenizations of the same word and better handling of ambiguous segmentations.
SentencePiece
A language-independent tokenization library developed by Google that treats the input text as a raw sequence of Unicode characters, eliminating the need for language-specific preprocessing. SentencePiece implements both BPE and Unigram algorithms but operates directly on the character stream rather than requiring pre-tokenized words. This is critical for languages like Chinese, Japanese, and Korean that do not use whitespace to separate words. SentencePiece also normalizes text using NFKC Unicode normalization and can be configured to include a byte fallback mechanism, ensuring zero OOV tokens by falling back to raw byte representations.
Text Canonicalization
The comprehensive preprocessing pipeline applied to raw text before tokenization. BPE operates on the output of canonicalization, making the quality of this step critical. A typical canonicalization pipeline includes:
- Unicode Normalization (NFKC): Converts visually identical characters to a single binary representation.
- Case Folding: Converts all text to lowercase to reduce vocabulary size.
- Whitespace Normalization: Collapses multiple spaces and strips leading/trailing whitespace.
- Punctuation Handling: Optionally separates or normalizes punctuation marks.
Inconsistent canonicalization between training and inference can cause BPE to produce entirely different token sequences for semantically identical text.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us