Skip to main content

Tokenization strategies: granularity, algorithms, and trade-offs

Choosing a discrete representation without conflating compression, linguistics, and quality

A tokenizer is a representation and engineering choice. It must cover expected inputs while managing vocabulary size and sequence cost. No segmentation—word, character, byte, or subword—is optimal for every corpus and task.

Questions and exercises: Open the dedicated practice page.

TipThe one-minute mental model
  • Granularity: word, character, byte, or learned fragment.
  • Algorithm: BPE, WordPiece, unigram, and variants are not interchangeable.
  • Pipeline: normalization, pre-tokenization, vocabulary, and special-token handling affect outputs.
  • Compatibility: IDs have operational meaning only with the associated tokenizer and model weights.
  • Evaluation: fewer tokens may reduce cost, but do not prove better downstream quality.

1. Concept map

The full pipeline—from Unicode text through IDs to embedding lookup—is illustrated on the text-to-token page.

A token is the discrete unit produced by the system, not necessarily a linguistic unit. Initial boundaries, whitespace, normalization, and special-token rules can change outputs as much as the algorithm’s name.

Why whitespace-only splitting is insufficient

A naive split such as str.split() treats runs of characters separated by whitespace as units. It is not a general-purpose tokenizer:

Input text Result of a simplified str.split() Limitation
Hello, world! Hello, · world! Punctuation remains attached to the resulting strings.
New York New · York Repeated spaces are collapsed; their information is not retained in the units.
你好世界 你好世界 With no spaces, no boundaries are produced.

These examples illustrate the limits of one simple rule, not the expected outputs of a real tokenizer. A tokenizer may apply pre-tokenization, handle punctuation and whitespace according to its configuration, and then split segments into subwords or bytes. It does not necessarily aim to recover linguistic words: its objective is to produce a discrete representation compatible with its vocabulary and model.

2. Compare granularity

Approach Strengths Limitations / risks Typical use
Words Readable; short sequences if vocabulary covers the corpus Very large vocabulary; unknown words; inflections and rare names Teaching baselines, closed corpora
Characters Small vocabulary; unseen words can be composed Long sequences; code points, code units, and graphemes differ Specialized models, orthography-sensitive tasks
Bytes General byte-level coverage; no word-level OOV Multiple bytes per character; long sequences; patterns can be harder to learn Byte-level approaches, heterogeneous inputs
Learned subwords Trade-off between vocabulary and length; rare forms remain decomposable if base units cover them Sometimes arbitrary boundaries; language/script-dependent cost; no guaranteed morphology Many modern LLMs

These are idealized categories. Real systems may combine pre-tokenization, subwords, and byte-level representation. “Character” must be defined precisely: Unicode code points, code units, and grapheme clusters are not interchangeable.

3. Components of a tokenizer pipeline

A production tokenizer is not just a segmentation algorithm. Libraries can expose several components whose effects should be distinguished. The Hugging Face Tokenizers component documentation describes these stages; SentencePiece provides another example of tokenizer models and conventions.

Component Role Check
Normalization May transform text before segmentation (for example, casing or Unicode normalization rules) Are visually similar strings normalized in the same way?
Pre-tokenization Splits text into candidate segments before the subword algorithm Do whitespace, punctuation, or numbers create boundaries?
Tokenization model Applies the vocabulary and BPE, WordPiece, or unigram rules Which base units, vocabulary, and rules are used?
Post-processing May add special tokens or prepare sequences for the model Are BOS, EOS, separators, or task tokens added?
Decoder Converts tokens/IDs back to text according to implementation conventions Are whitespace, bytes, and characters reconstructed as expected?

An external illustration of the tokenizer pipeline

Tokenization pipeline: normalization, pre-tokenization, tokenization model, and post-processing.

Tokenization pipeline from the Hugging Face course, showing the stages that transform text into model-ready tokens.

This published illustration comes from the Hugging Face course, “Building a tokenizer, block by block”. It complements the tokenizer-component table immediately above. The image is served from the course’s public documentation assets rather than copied locally; citation does not itself establish reuse permission. Rights review: pending in #156; retained pending asset-level verification.

Special-token spellings are not ordinary vocabulary words

A special token is a reserved vocabulary entry with a dedicated ID and a model-specific role. For example, GPT-2 uses <|endoftext|> as an end-of-text marker. Its visible spelling is not enough, by itself, to establish how an input string will be handled: the token must be registered in that tokenizer, and the API decides whether a matching string is parsed as a special token, rejected, or treated as ordinary text.

Some APIs make this choice explicit through an allow-list. For example, tiktoken and Karpathy’s minbpe expose controls for which special-token spellings may be interpreted. This is implementation-specific behaviour, not a universal tokenizer rule. In an application, do not indiscriminately allow every special token in untrusted user text; reserved tokens should normally be inserted intentionally by a trusted formatting layer.

See the tiktoken encoding API and the minbpe special-token handling notes.

Implementation comparison. These projects expose different layers of the same broad byte-level BPE family: tiktoken delegates production encoding to a native core and uses encoding-specific merge ranks and special-token policies; its _educational.py module makes the merge loop inspectable. Karpathy’s minbpe separates a minimal byte-only implementation (BasicTokenizer) from regex-pretokenized and special-token-aware variants (RegexTokenizer), with a GPT-4 wrapper that reconstructs a specific pretrained vocabulary. Neither the library name nor the BPE label alone establishes compatibility. See the implementation audit and comparison.

Not every tokenizer exposes or uses these stages in the same way. An algorithm name alone is therefore insufficient to reproduce a segmentation: the configuration and versions also matter.

Same text, different tokenizer pipelines

A tokenizer’s visible output is shaped by more than its segmentation algorithm. The following examples are taken from the Hugging Face course and refer to specific checkpoints; they are pre-tokenizer outputs, not the final model token IDs.

For normalization, the course shows that the bert-base-uncased normalizer transforms:

Héllò hôw are ü?  →  hello how are u?

For pre-tokenization, consider the exact input Hello, how are you?:

Checkpoint Pre-tokenizer output (visible pieces) What to notice
bert-base-uncased Hello, ,, how, are, you, ? Whitespace and punctuation create boundaries; repeated spaces do not become separate pieces.
gpt2 Hello, ,, Ġhow, Ġare, Ġ, Ġyou, ? The visible Ġ convention marks whitespace; the repeated space is retained in the pre-tokenizer output.
t5-small ▁Hello,, ▁how, ▁are, ▁you? The SentencePiece-based convention uses ▁; this pre-tokenizer splits on whitespace rather than punctuation and does not preserve the repeated space as a separate piece.

Important: the table calls the pre-tokenizer component directly; it does not apply the normalizer shown above. That is why the BERT pre-tokenizer row still displays Hello with a capital letter. A complete tokenizer call applies the configured stages together.

These outputs are specific to the named configurations and the Hugging Face Tokenizers pipeline. The markers Ġ and ▁ are visible representations, not literal characters that should be inserted into arbitrary text.

This comparison illustrates why an algorithm label such as BPE is insufficient to reproduce tokenization. Normalizer, pre-tokenizer, model, post-processor, decoder, and their configuration jointly determine the behaviour. See the Hugging Face course’s normalization and pre-tokenization lesson for the source examples.

A related coverage distinction is important: a character-based tokenizer whose initial alphabet omits a character may need an unknown-token fallback. A byte-level BPE with all 256 byte values in its base vocabulary can instead represent arbitrary input bytes. This is a property of that byte-level design, not a guarantee about every tokenizer called BPE.

4. BPE, WordPiece, and unigram

Family Core idea Limitation to remember
BPE Iteratively merge adjacent pairs according to a frequency/priority rule Variants differ in base units, pre-tokenization, markers, and conventions
WordPiece Select units using a likelihood-related criterion, then encode with implementation-specific rules Not simply BPE under another name; some systems mark continuations with ##
Unigram Probabilistic model over candidate subwords, often reduced by pruning Output depends on model, candidates, and conventions

Detailed WordPiece and Unigram mechanisms

How WordPiece differs from BPE

In the common WordPiece training explanation, candidate adjacent units are ranked with a score related to how strongly they co-occur relative to the frequencies of their individual parts. A simplified form is:

\(\operatorname{score}(a,b)=\frac{f(ab)}{f(a)\,f(b)}\)

where frequencies are estimated from the training corpus. This favours a pair whose joint frequency is high relative to the frequencies of its parts; it is not simply the most frequent pair, as in basic BPE. Caveat: Google’s original WordPiece training procedure is not fully specified in a public reference implementation. Hugging Face presents its account as a reconstruction, so this formula is explanatory rather than a guarantee that every WordPiece trainer uses exactly this procedure.

At encoding time, common WordPiece implementations use greedy longest-match-first search over the vocabulary. In BERT-style tokenizers, continuation pieces are conventionally prefixed with ##. If the complete input word cannot be segmented under the configured rules, a tokenizer such as BERT may emit one [UNK] for the whole word rather than retain a partial segmentation. These are implementation conventions, not universal properties of every WordPiece tokenizer.

See the Hugging Face WordPiece explanation and WordPiece model documentation.

How Unigram differs from merge-based tokenizers

A Unigram tokenizer starts from a relatively large candidate vocabulary with associated probabilities. Training iteratively removes candidates whose removal causes the smallest increase in the model’s loss, reducing the vocabulary toward the target size. This is pruning over a probabilistic segmentation model—not a sequence of pair merges.

At encoding time, several segmentations may be possible. The Viterbi algorithm finds the highest-probability segmentation under the learned model. This contrasts with BPE’s application of a learned merge order and WordPiece’s common greedy longest-match procedure. See the Hugging Face Unigram explanation and SentencePiece.

SentencePiece is a library that can train BPE or unigram models from raw text; it is not one algorithm. Hugging Face Tokenizers is a library of models and pipeline components. tiktoken is a BPE implementation with specific encodings. These names therefore do not all belong at the same comparison level.

Worked example: BPE merges on a tiny corpus

This schematic example preserves an explicit trace of the merges. Teaching convention: each word starts as characters followed by an end-of-word marker </w>. The tiny corpus contains one occurrence each of low, lower, and lowest.

Word Initial units
low l · o · w · </w>
lower l · o · w · e · r · </w>
lowest l · o · w · e · s · t · </w>

Count every adjacent pair across the corpus. Each word occurs once here, so the pair counts are:

Pair Count Pair Count
l + o 3 w + e 2
o + w 3 w + </w> 1
e + r 1 r + </w> 1
e + s 1 s + t 1
t + </w> 1

The most frequent pair is tied: l + o and o + w both occur three times. Assume the deterministic tie-breaker chooses l + o → lo. Replace non-overlapping occurrences, then recount. The pair lo + w now occurs three times and can be merged next.

Step low lower lowest
0 l · o · w · </w> l · o · w · e · r · </w> l · o · w · e · s · t · </w>
1: merge l + o lo · w · </w> lo · w · e · r · </w> lo · w · e · s · t · </w>
2: merge lo + w low · </w> low · e · r · </w> low · e · s · t · </w>

The frequency table makes the greedy choice visible; it does not mean BPE discovers linguistic morphemes or an optimal vocabulary. This is a word-level teaching convention with an end-of-word marker, not a complete byte-level production tokenizer. Real outputs also depend on pre-tokenization, base units, corpus frequencies, special-token handling, and implementation-specific tie-breaking. An interactive visualizer is listed in the complementary resources.

Historical distinction. Gage’s 1994 byte-pair encoding algorithm (ACM bibliographic record) is a general-purpose compression method: it repeatedly replaces frequent adjacent byte pairs with unused byte values and records substitutions for decompression. NLP subword BPE adapts the pair-merging idea to build a token vocabulary and merge order over text units. Its base units, pre-tokenization, vocabulary construction, and encoding procedure are different; GPT-style byte-level BPE is one specific design. A key NLP adaptation is Sennrich, Haddow and Birch (2016), who use the merge idea for word-level subword segmentation in open-vocabulary neural machine translation (ACL paper). This is a distinct historical step, not a specification of GPT-style byte-level tokenization. Gage is therefore the historical reference for the pair-replacement idea, not a specification of a modern LLM tokenizer.

Tokenizer training versus encoding at inference

Two processes must be distinguished:

  1. Tokenizer training: builds a vocabulary and, depending on the algorithm, rules or a merge order from a corpus.
  2. Encoding new text: applies the already learned rules to produce tokens and IDs; it does not recount frequencies or relearn the vocabulary for every request.

flowchart LR
    A["Training corpus"] --> B["Pre-tokenization and base units"]
    B --> C["Learn merges / vocabulary"]
    C --> D["Saved tokenizer"]
    E["New text"] --> F["Previously learned rules"]
    D -. "reused" .-> F
    F --> G["Tokens then IDs"]
    G --> H["Compatible model"]

This diagram does not describe neural-network training, which is distinct and learns model parameters from sequences of token IDs. A byte-level tokenizer can cover arbitrary text input at the byte level, but not every BPE tokenizer is byte-level.

Mapping tokens back to source text: offsets and alignment

Tokens are model-internal units; an application often needs to recover the source text span they correspond to. A fast tokenizer’s offsets associate each token with an interval in the original input string. They can help reconstruct a named entity from several subtokens, highlight a prediction, or attach a model output to its context.

With a compatible fast tokenizer, the Transformers API exposes this information through the BatchEncoding object:

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
text = "My name is Sylvain."
encoding = tokenizer(text, return_offsets_mapping=True)

for token, (start, end) in zip(
    encoding.tokens(), encoding["offset_mapping"]
):
    print(token, repr(text[start:end]))

Offsets are positions in the original string and can be used to extract a slice. Special tokens may have a zero-length interval such as (0, 0). The word_ids(), token_to_chars(), and char_to_token() methods expose other directions of this alignment; they are not available in the same way for every slow tokenizer.

Why this matters: in token classification, a label supplied for a word must be aligned with one or more subtokens. In extractive question answering, predicted positions must be mapped back to character spans in the context. When a context exceeds the model’s maximum length, splitting it into overlapping windows (overflow / stride) requires tracking offsets and window identity: a position local to one window is not automatically a global document position.

Do not confuse an offset with a token ID: the ID indexes the vocabulary; the offset points to a slice of the input text. Normalization transformations and implementation conventions matter, especially for Unicode text and paired inputs.

See the Hugging Face lessons on fast-tokenizer capabilities and their use in the question-answering pipeline. API names and availability should be checked against the Transformers version in use.

5. Examples that expose trade-offs

The overview page illustrates Unicode normalization with precomposed é and decomposed e\u0301: they may look identical while having different code-point sequences. A tokenizer may normalize them before segmentation; inspect its configuration rather than assuming the outputs match.

Input Question to ask Naive-approach risk
Hello world and Hello world Does a leading space change segmentation? Space handling may be part of pre-tokenization or token spelling
ChatGPT, chatgpt, CHATGPT Is casing normalized or preserved? Case handling depends on tokenizer configuration
unbelievable, unbelievably Do fragments reuse frequent substrings? Boundaries do not guarantee morphological analysis
café and cafe\u0301 Which Unicode normalization is applied? Same appearance, different code-point sequences
2026-10-29, 123456789 How are digits and separators split? One token need not be a whole number
你好 Does the system depend on spaces between words? Whitespace splitting may yield no useful boundaries
def predict_next(x): return x + 1 How are whitespace, identifiers, and operators handled? Segmentation can look arbitrary
Emoji and rare symbols What coverage and sequence length result? Coverage does not mean uniform efficiency

This table poses questions to test, not exact outputs. To report a result, record tokenizer/version, input string, visible tokens, and token count.

NoteGo deeper

Vocabulary size, training budgets, and comparative tokenizer evaluation raise questions about cost, quality, and multilingual equity. These design choices go beyond understanding the segmentation mechanism; see the advanced guide to tokenizer design and evaluation.

NoteCanonical comparison

The controlled comparison on the fixed text 2 + 2 = 4, including fragments, IDs, and decoding, is presented in From text to tokens. This page deepens the mechanisms that explain why boundaries and lengths can differ.

6. Counterexamples

  • Fewer tokens = a better model. No: it first demonstrates a length difference, not quality.
  • BPE discovers morphemes. No: linguistic analysis is not guaranteed.
  • The vocabulary is the tokenizer. No: pre-tokenization, merge rules, normalization, and special tokens also matter.
  • SentencePiece = unigram. No: it can train multiple families, including BPE.
  • IDs transfer between models. Generally not: the same ID can denote different fragments.
  • Byte-level = language-independent. No: coverage guarantees neither uniform cost nor uniform quality.

Where does this page sit in the route?

This page is an optional deepening of From text to tokens: it compares the strategies that turn text into tokens and IDs. You do not need to know BPE, WordPiece, or unigram tokenization to understand embedding lookup. The core route continues directly with From token IDs to vectors, which shows how IDs select initial vectors. For empirical evaluation criteria, see tokenizer design and evaluation; for character representation, see Unicode and text.

Resources for visualizing mechanisms and inspecting implementations

Suggested reading order

  1. Watch Karpathy’s video to build intuition about bytes, merges, and special tokens.
  2. Follow merges with the visualizer listed above.
  3. Read minbpe or the educational tiktoken module to inspect the code.
  4. Compare with tiktoken, SentencePiece, and Hugging Face documentation to distinguish implementation conventions.
  5. Return to Raschka’s Chapter 2 to connect IDs to embeddings and input-target examples.
  6. Test multilingual text, code, numbers, leading spaces, and unusual Unicode forms.

Educational code and implementations

The Hugging Face Tokenizers, SentencePiece, and tiktoken documentation links are grouped in the mechanism and implementation resources.

Language: Français · English

Supplementary resources Experiment, explore further, and practise the ideas from this lesson.