Tokenization is the algorithmic process of segmenting a raw text string into discrete atomic units called tokens. These tokens serve as the fundamental input vocabulary for language models. The process converts unstructured text into a structured sequence of integer IDs, bridging the gap between human-readable language and the numerical tensor operations required by neural networks. Common strategies include word-level, character-level, and subword tokenization, with the latter balancing vocabulary size against the ability to handle rare or unseen words.
Glossary
Tokenization

What is Tokenization?
Tokenization is the foundational preprocessing step that segments raw text into atomic units, such as words or subwords, which can be mapped to integer IDs for model ingestion.
Modern architectures predominantly rely on subword algorithms like Byte-Pair Encoding (BPE) or WordPiece, which iteratively merge frequent character pairs to construct a vocabulary of meaningful fragments. This approach ensures that unknown terms are decomposed into known constituent parts, eliminating out-of-vocabulary errors. The tokenizer's vocabulary is a critical artifact of the model; mismatching the tokenizer during fine-tuning or inference will corrupt the semantic representation, making the model's outputs incoherent.
Core Characteristics of Tokenization
Tokenization is the critical preprocessing step that segments raw text into atomic units, such as words or subwords, that can be mapped to integer IDs for model ingestion. The chosen strategy directly impacts vocabulary size, handling of out-of-vocabulary words, and a model's ability to generalize across languages and domains.
Subword Segmentation
Modern tokenizers like Byte-Pair Encoding (BPE) and WordPiece break text into subword units. This balances vocabulary size with coverage, allowing models to represent rare or unseen words by composing known fragments.
- Mechanism: Iteratively merges the most frequent pair of characters or bytes.
- Benefit: Eliminates the concept of a true out-of-vocabulary token for many models.
- Example: The word 'unhappiness' might be segmented into ['un', 'happiness'] or ['un', 'happi', 'ness'].
Vocabulary Construction
The tokenizer builds a fixed-size vocabulary of unique tokens from the training corpus. Each token is assigned a unique integer ID.
- Size Trade-off: A larger vocabulary captures more whole words but increases model embedding parameters. A smaller vocabulary relies on more subword fragments, increasing sequence length.
- Special Tokens: Includes control tokens like
[CLS],[SEP],[PAD], and[MASK]to structure input for specific model architectures.
Encoding and Decoding
Tokenization is a two-way process essential for text generation.
- Encoding: Converts a raw string into a sequence of integer IDs (
"Hello world" -> [15496, 995]). - Decoding: Converts a sequence of integer IDs back into a human-readable string.
- Lossless Requirement: A robust tokenizer must ensure that
decode(encode(text))returns the original text, preserving whitespace and casing.
Context Window Impact
The tokenizer's efficiency directly affects a model's context window utilization. A tokenizer that produces more tokens for the same text consumes the model's limited attention span faster.
- Multilingual Inefficiency: Languages with non-Latin scripts often require 2-4x more tokens than English for the same semantic content.
- Numerical Fragmentation: Poorly designed tokenizers can split a single number like
3.14159into many separate digit tokens, wasting context.
Normalization and Pre-tokenization
Before segmentation, text undergoes crucial preprocessing steps.
- Normalization: Standardizes text by applying rules like lowercasing, Unicode normalization (NFKC), and stripping accents.
- Pre-tokenization: Splits text into initial word-level chunks using whitespace and punctuation rules. This step prevents subword merges from crossing word boundaries, a key difference between BPE and pure character-level models.
Domain-Specific Tokenization
General-purpose tokenizers often fail on specialized corpora. Domain adaptation of a tokenizer involves training a new vocabulary on target data.
- Code: A tokenizer trained on natural language will fragment common code syntax like
getElementByIdinto many subwords. A code-specific tokenizer preserves these as single tokens. - Biomedical Text: Specialized tokenizers preserve chemical compound names and genetic sequences, preventing fragmentation of critical domain entities.
Tokenization Algorithm Comparison
Comparative analysis of the dominant subword tokenization algorithms used in modern embedding models and large language models, evaluated across vocabulary efficiency, handling of rare words, and language agnosticism.
| Feature | Byte-Pair Encoding (BPE) | WordPiece | Unigram Language Model |
|---|---|---|---|
Core Mechanism | Iteratively merges the most frequent pair of bytes or characters | Merges pairs based on the highest increase in language model likelihood | Starts with a large vocabulary and prunes tokens with the lowest probability contribution |
Training Objective | Frequency maximization | Likelihood maximization | Data likelihood maximization via loss minimization |
Vocabulary Initialization | Base characters or bytes | Base characters | Heavily over-parameterized seed vocabulary |
Handles Rare Words | |||
Language Agnosticism | |||
Reversible to Original Text | |||
Primary Adopters | GPT models, RoBERTa | BERT, DistilBERT | T5, XLNet, SentencePiece |
Segmentation Granularity | Tends toward larger subwords | Tends toward smaller subwords | Probabilistic; offers multiple segmentation candidates |
Frequently Asked Questions
Clear, technical answers to the most common questions about the preprocessing step that converts raw text into the integer IDs a model can ingest.
Tokenization is the foundational preprocessing step that segments a raw text string into a sequence of atomic units called tokens, which are then mapped to unique integer IDs from a predefined vocabulary for model ingestion. The process works by applying a trained tokenizer algorithm—such as Byte-Pair Encoding (BPE) or WordPiece—that scans the input text and splits it into subword units. For example, the word "unbelievably" might be segmented into ["un", "believ", "ably"]. These tokens are then looked up in a vocabulary file to produce a list of integers, which are converted into dense vectors by an embedding layer. This mechanism allows models to handle an open vocabulary, gracefully managing rare or unseen words by decomposing them into known subword fragments rather than resorting to a generic <UNK> token.
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
Tokenization is the critical first step in the NLP pipeline, directly impacting vocabulary size, out-of-vocabulary handling, and downstream model performance. Explore the core algorithms and encoding strategies that define how text is segmented for machine consumption.
Byte-Pair Encoding (BPE)
A data compression algorithm adapted for NLP that iteratively merges the most frequent pairs of bytes or characters to build a subword vocabulary. BPE starts with a base vocabulary of characters and greedily adds new tokens for the most common adjacent pairs.
- Core Mechanism: Iterative frequency-based merging
- Key Benefit: Balances vocabulary size and out-of-vocabulary words
- Example: 'low' + 'er' -> 'lower' becomes a single token if frequent enough
- Usage: GPT models (GPT-2, GPT-3) and Roberta tokenizers
WordPiece Tokenization
A subword segmentation algorithm developed by Google for the BERT model that selects tokens based on maximizing the likelihood of the training data rather than raw frequency. WordPiece uses a greedy longest-match-first strategy during encoding.
- Core Mechanism: Likelihood-based merging using a language model objective
- Key Difference from BPE: Evaluates merge candidates by how much they improve training data probability
- Example: 'un' + '##affordable' uses '##' to mark continuation tokens
- Usage: BERT, DistilBERT, and Electra models
Unigram Language Model Tokenization
A probabilistic subword tokenizer that starts with a large vocabulary and iteratively removes tokens that least impact the overall likelihood of the corpus. Unigram models the joint probability of a token sequence to find the optimal segmentation.
- Core Mechanism: Prunes a large initial vocabulary based on a unigram language model loss
- Key Benefit: Provides multiple segmentation candidates with probabilities, enabling subword regularization
- Example: 'tokenization' could be segmented as ['token', 'ization'] or ['to', 'ken', 'ization'] with different probabilities
- Usage: XLNet, ALBERT, and SentencePiece library
SentencePiece Tokenization
A language-independent tokenization framework that treats the input text as a raw byte stream, eliminating the need for language-specific pre-tokenization. SentencePiece implements both BPE and Unigram algorithms directly on Unicode characters.
- Core Mechanism: Direct byte-level processing without whitespace splitting
- Key Benefit: Fully reversible and lossless encoding; handles any language uniformly
- Example: Whitespace is preserved by replacing spaces with a special meta-character '_' (U+2581)
- Usage: Llama, Mistral, T5, and most modern open-source LLMs
Tiktoken (Byte-Level BPE)
OpenAI's fast BPE tokenizer that operates directly on UTF-8 bytes rather than Unicode characters, ensuring a base vocabulary of exactly 256 byte tokens. Tiktoken is optimized for speed and handles all inputs without unknown tokens.
- Core Mechanism: Byte-level BPE with a fixed 256-byte base vocabulary
- Key Benefit: No out-of-vocabulary tokens ever; extremely fast encoding and decoding
- Example: Every possible input, including emojis and rare scripts, is tokenizable by design
- Usage: GPT-4, GPT-3.5-turbo, and text-embedding-ada-002
Hugging Face Tokenizers Library
A high-performance tokenization library written in Rust with Python bindings, providing implementations of BPE, WordPiece, and Unigram algorithms. Tokenizers is designed for both research flexibility and production throughput.
- Core Mechanism: Rust-backed parallelized tokenization with pre-tokenization and post-processing pipelines
- Key Benefit: Trains new tokenizers on large corpora in seconds; encodes gigabytes of text per minute
- Components: Normalizers, Pre-tokenizers, Models, Post-processors, and Decoders
- Usage: The backbone of all Hugging Face Transformers tokenizers

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