Skip to content
AI.info

Natural language processing

Vocabulary Design and Tokenization Diagnostics

Understand subword learning, vocabulary coverage, special tokens, fragmentation, and diagnostics for domain and multilingual tokenizers.

By the end you can

Tokenization spends capacity unevenly

A vocabulary trained mostly on English web text may encode common English words in one token while splitting a low-resource language or a biomedical term into many fragments. Both strings remain representable. But they consume different context and computation.

The gap has been counted rather than supposed. A language written in its own script — Telugu among them — can need up to 5× more tokens to carry the same information. That figure comes from a 2023 study of 22 typologically diverse languages, measured against a live commercial API.

The tokenizer therefore influences latency, truncation, morphology, and the number of steps through which evidence must travel. It is not a neutral formatting layer.

Representability does not imply equal representational efficiency.

Comparison

Common subword construction ideas

These procedures learn useful inventories, not the one true decomposition of language. The dominant one did not come from linguistics at all. It came from data compression. “We adapt byte pair encoding (BPE) (Gage, 1994), a compression algorithm, to the task of word segmentation,” wrote Sennrich, Haddow and Birch at Edinburgh in 2016. The payoff they measured over a back-off dictionary baseline was up to 1.1 and 1.3 BLEU, on the WMT 15 English→German and English→Russian tasks. Jurafsky and Martin now record where that borrowed heuristic ended up: “Two tokenization algorithms are widely used in modern language models: byte-pair encoding (BPE) (Sennrich et al., 2016), and unigram language modeling (ULM) (Kudo, 2018).” So the frequency-driven merge process in the first column and the pruned probabilistic segmentation model in the third are the two survivors. One of them is a 1994 data-compression trick with 1.1 to 1.3 BLEU attached.

Byte-aware subwords are a budget decision with published arithmetic. A BPE built over Unicode code points would need a base vocabulary of over 130,000 entries before a single multi-symbol token is added. Typical BPE vocabularies hold 32,000 to 64,000. The GPT-2 report gives the alternative in one line: “In contrast, a byte-level version of BPE only requires a base vocabulary of size 256.” GPT-2's finished vocabulary is 50,257 tokens, the value Hugging Face still ships as the GPT2Config default. That is what “avoids unknown characters” costs: 256 base symbols instead of 130,000, inside a 50,257-token budget.

What those 256 symbols do not buy is an equal price per character. The same column warns that byte fallback “can lengthen unusual text”. UTF-8 is why. It is a variable-length encoding, and RFC 3629 is explicit about the range: “In UTF-8, characters from the U+0000..U+10FFFF range (the UTF-16 accessible range) are encoded using sequences of 1 to 4 octets”. The 128 ASCII characters cost one byte. Code points at or above 128 cost two, three or four. A byte-level base alphabet therefore spends between one and four positions per character before any merge is applied. Which end of that range a reader pays is decided by the script they write in.

FigureComparison · 4 columns

Byte-pair style merges

Repeatedly combine frequent adjacent symbols.

  • Simple frequency-driven process
  • Produces reusable fragments
  • Merge history defines encoding
  • Splits depend on training corpus

WordPiece-style selection

Choose pieces that improve a vocabulary objective under model assumptions.

  • Common in encoder models
  • Balances frequency and distinctiveness
  • Implementation details vary
  • Not a morphology analyzer

Unigram language model

Start with candidates and prune pieces under a probabilistic segmentation model.

  • Supports alternative segmentations
  • Useful with sampling
  • Corpus-sensitive inventory
  • Requires a decoding procedure

Byte-aware subwords

Anchor the base alphabet in bytes or include byte fallback.

  • Avoids unknown characters
  • Handles arbitrary input
  • Can lengthen unusual text
  • Needs careful display reconstruction

Case

Every earlier subword tool assumed somebody had already split the words

Every subword tool before SentencePiece required that the words had already been split. The 2018 SentencePiece paper says so plainly: “existing subword segmentation tools assume that the input is pre-tokenized into word sequences”. That quietly imports a language-specific word segmenter into every pipeline built on those tools. The tokenizer's behaviour then depends on a component nobody is measuring.

Kudo and Richardson state their alternative in the same breath: “SentencePiece can train subword models directly from raw sentences, which allows us to make a purely end-to-end and language independent system”. The implementation “is available under the Apache 2 license”.

Note what kind of claim that is. It is not a benchmark result. It is the discovery that a dependency existed at all, in tools already in production, unnamed in their interfaces and unmeasured in their evaluations.

Visual

How a tokenizer becomes a production dependency

Changes at any stage can make old data or models incompatible.

Stages three and four are visible in any released checkpoint, and they rarely match the paper. The BERT paper specifies a round number: “We use WordPiece embeddings (Wu et al., 2016) with a 30,000 token vocabulary.” The artifact that shipped is not that number. google-bert/bert-base-uncased declares vocab_size 30522, and its vocab.txt runs to 30,522 lines. Of those, 994 are [unused0] through [unused993] — empty slots deliberately left for later additions. Five more are control symbols nailed to fixed integers: [PAD]=0, [UNK]=100, [CLS]=101, [SEP]=102, [MASK]=103, with [PAD] first in the file and the other four at lines 101–104.

That is stage four in one file. A design figure of 30,000 became an address space of 30,522 entries. 994 of them are reserved emptiness. Five are pinned to integers that every downstream serving path, every cached dataset and every trained embedding row now agrees on.

Stage five is not ceremonial either. Land and Bartolo found 2,450 confirmed under-trained tokens among 2,966 tested in Qwen1.5 32B's 151,646-token vocabulary. A shipped model carried that defect until somebody audited for it.

FigureProcess · 5 steps
  1. 1. Define normalization and pretokenization

    Decide how raw strings reach the learning algorithm.

  2. 2. Sample the training corpus

    Choose languages, domains, frequencies, and protected text.

  3. 3. Learn vocabulary and reserved symbols

    Allocate ordinary pieces, control markers, and fallback behavior.

  4. 4. Freeze IDs and model interfaces

    Persist token-to-ID mapping, model maximums, and padding conventions.

  5. 5. Audit and version

    Measure fragmentation, offsets, round trips, truncation, and drift.

Example

Diagnostics that expose unequal tokenization

Average tokens per sentence is too coarse to explain who pays the cost.

The size of the gap has been measured rather than estimated. A NeurIPS 2023 paper found that “the same text translated into different languages can have drastically different tokenization lengths, with differences up to 15 times in some cases”, and that “these disparities persist even for tokenizers that are intentionally trained for multilingual support”. Character-level and byte-level models narrow the gap without closing it: such models “also exhibit over 4 times the difference in the encoding length for some language pairs”. A fifteen-fold ratio is a fifteen-fold difference in the cost of a commercial language service. It is also a difference in processing time, and in how much of a document fits inside the context window. It is paid by the speakers of one language and not the other.

The second thing an audit finds is entries that should not be in the vocabulary at all. Land and Bartolo, at Cohere, defined the class in 2024 as “tokens present in the tokenizer vocabulary but that are nearly or entirely absent during model training”. Then they counted them. 67 of 999 candidate tokens in GPT-2 XL, whose vocabulary holds 50,257 entries. 200 of 999 in GPT-J 6B. And 2,450 of 2,966 in Qwen1.5 32B, whose vocabulary holds 151,646. The Gemma team released a fix in response to their report.

The failure mode had been public since 5 February 2023, when Rumbelow and mwatkins described anomalous tokens such as SolidGoldMagikarp and RandomRedditorWithNo that made GPT-2 and GPT-3 evade, hallucinate or emit garbled output: “Many of these tokens reliably break determinism in the OpenAI GPT-3 playground at temperature 0 (which theoretically shouldn't happen).” Two years elapsed between that post and the systematic count. A vocabulary is not audited by being read.

  • Fertility: tokens per word, character, or grapheme, reported by language and domain — and never reported alone, since Ali et al. found fertility and parity not reliably predictive of downstream performance.
  • Continuation burden: how often meaningful units are split into many pieces or single characters, against a byte floor of one to four octets per character under RFC 3629.
  • Context cost: the share of documents truncated because fragmentation consumes the model window — the mechanism behind the up-to-15-times length ratio measured at NeurIPS 2023.
  • Unknown and fallback behavior: frequency, location, script, and round-trip correctness for unsupported input, plus under-trained entries of the kind Land and Bartolo confirmed at 2,450 of 2,966 tested tokens in one shipped vocabulary.
  • Identifier integrity: treatment of product codes, URLs, equations, names, file paths, and domain abbreviations.
  • Special-token tests: padding, separators, masks, conversation roles, and control symbols under every serving path, checked against the shipped file rather than the paper — [PAD]=0, [UNK]=100, [CLS]=101, [SEP]=102, [MASK]=103 in bert-base-uncased.

Analogy

A printing press with a fixed case of type

A printer chooses which reusable letter clusters to keep in a limited type case. Common pieces make frequent text fast to compose, while rare words require more assembly.

Token pieces have no stable linguistic meaning. Their boundaries are learned for compression or modeling utility and can cut across morphemes or scripts. The analogy holds precisely because the first such procedure was a compression algorithm: Gage's 1994 method, adapted to word segmentation in 2016 and judged by whether it moved a translation score.

A vocabulary is a budget for efficient reuse, not a dictionary of true language units.

Key idea

Tokenizer changes invalidate simple model comparisons

A candidate model with a different tokenizer may see more or fewer effective words inside the same context limit; throughput, training tokens, truncation, and cost can shift even when parameter counts look similar.

This has been isolated rather than argued. Ali and co-authors trained 24 mono- and multilingual tokenizers and, for each one, a separate 2.6B-parameter decoder-only model on up to 52B tokens. The data and the hyperparameters were held fixed, so the tokenizer was the only thing that moved. On the habit of applying an English-centric tokenizer to a multilingual model, their 2024 abstract reports: “we find that this approach results in a severe downstream performance degradation and additional training costs of up to 68%, due to an inefficient tokenization vocabulary”. Multilingual tokenizers over five European languages needed roughly three times English's vocabulary size. And the cheap proxy rescued nobody: fertility and parity were not reliably predictive of downstream performance.

An earlier and independent group reached the neighbouring conclusion from controlled retraining: “We find that while the pretraining data size is an important factor, a designated monolingual tokenizer plays an equally important role in the downstream performance.”

Compare models on original documents and user outcomes, not only token counts reported in each model's private unit. Record both raw-character and tokenizer-specific statistics.

Tokens are model-specific accounting units, not a universal measure of language volume.

Steps

Audit a tokenizer before adopting it

Use real text and deliberately difficult examples rather than a few attractive demonstrations.

Step five is what makes the first four interpretable. The 68% figure could be pinned on the tokenizer only because the tokenizer varied across 24 trained models while everything else stood still. An audit that changes the vocabulary and the corpus at the same time produces a number nobody can assign to either. And because that same work found fertility and parity unreliable as predictors of downstream performance, step two cannot stand in for step five. A favourable fertility table is a hypothesis about quality. It is not a measurement of it.

Step four has a concrete acceptance test. Decode what you encoded, then confirm that the reserved symbols still sit where the shipped vocabulary file says they sit — in bert-base-uncased, [PAD] at 0 and [UNK], [CLS], [SEP] and [MASK] at 100 to 103.

FigureProcess · 5 steps
  1. 1. Stratify the corpus

    Select languages, domains, scripts, channels, lengths, and high-value identifiers.

  2. 2. Measure sequence expansion

    Report fertility, truncation, fallback, and latency by slice.

  3. 3. Inspect segmentation examples

    Review names, morphology, compounds, numbers, code, and mixed-script text.

  4. 4. Verify reversible interfaces

    Test offsets, decoding, special symbols, padding, and serialization.

  5. 5. Run downstream comparisons

    Measure task quality and cost with the tokenizer fixed as an explicit variable.

Replacing a tokenizer is usually a model migration

Token IDs index learned embedding rows, so a new vocabulary cannot normally be substituted beneath an existing model without adaptation. Added tokens have to be initialized and trained. Removed or reordered IDs can corrupt every embedding lookup.

The 994 [unused0] through [unused993] entries in bert-base-uncased are what foresight about this looks like. 994 addresses set aside in a 30,522-entry vocabulary, so that a later addition can be given an ID without renumbering the entries that were already trained. A vocabulary shipped without that provision has no such room. Every insertion is a renumbering.

Plan tokenizer upgrades with model retraining or controlled adaptation, compatibility tests, data versioning, and serving rollout; treat the old tokenizer as an artifact needed for historical reproducibility.

A token-to-ID mapping is part of the learned model interface.

Position

Tokenization sets a price, and it is not the same price in every language

Two things are true of a tokenizer at once, and only the first is usually taught. It decides how a string is cut up. It also decides what that string costs, how long it takes to process and how much of a document survives inside the context window. Those are the three consequences the NeurIPS 2023 paper lists: “the cost of accessing commercial language services, the processing time and latency, as well as the amount of content that can be provided as context to the models”. All three move with the number of tokens the string becomes. This lesson has already measured how far that number stretches: up to fifteen times, for the same text translated into different languages.

The two replies available to that are both closed inside the same measurement. The first is to adopt a multilingual tokenizer, and those same authors report that the disparities persist even for tokenizers intentionally trained for multilingual support. The second is to abandon the learned vocabulary altogether and work in characters or bytes. Those models still show over 4 times the difference in encoding length for some language pairs. RFC 3629 makes that floor unsurprising: UTF-8 already spends one octet on an ASCII character and two, three or four on a code point at or above 128. A 4× floor is better than a 15× ratio. It is still one language spending four times the sequence on the same sentence.

And the length ratio has since been converted into a bill. Twenty-two typologically diverse languages were taken to a live commercial API in 2023. On the XLSUM task, prompting and generation in Telugu and Amharic cost up to 4× more than in English. The authors call the result “double unfairness”: the speakers charged more per token are also the ones who get less back, and they come from lower-HDI regions. Their abstract states it without hedging — “We show evidence that speakers of a large number of the supported languages are overcharged while obtaining poorer results.” Writing in AI & SOCIETY in 2026, Paolo Caffoni restates the finding at the scale of one person: “While LMs like ChatGPT might perform tasks in Telugu, for example, a user in Andhra Pradesh might pay 5× more than an English user in the US for an equivalent use of the model”.

Now look at how a setting of that consequence normally arrives. The SentencePiece observation earlier in this lesson is worth rereading as a fact about authorship rather than about software: “existing subword segmentation tools assume that the input is pre-tokenized into word sequences”. That assumption put a language-specific word segmenter inside every pipeline built on those tools — a component nobody in the pipeline was measuring. That is what an inherited setting looks like. Not argued where it is paid for. Not measured there either.

Which is why this course declines to call tokenization preprocessing. A choice inherited rather than argued, and then billed per token, is a price list distributed as a configuration file. It allocates cost and access across languages before a model has been trained. A callout earlier in this lesson already says tokens are model-specific accounting units rather than a universal measure of language volume. The position is the consequence. An accounting unit that varies fifteen to one in length, four to one in money on a real vendor's API, and that speakers of Telugu and Amharic pay the wrong end of, is not an implementation detail. It is a commercial term, and it should be reported per language like one.

The same sentence at fifteen times the token count is the same sentence at fifteen times the price.

Compare two tokenizers on one multilingual workload

Use original documents rather than already tokenized examples; report characters and words per token, truncation, sequence percentiles, fallback, latency, and task quality by language. Include at least one language written in its own script. That is where the up-to-5× token requirement was found, across 22 languages measured on a live commercial API. Price the workload in currency as well as in tokens.

Inspect twenty high-cost examples and explain whether fragmentation reflects domain mismatch, script coverage, normalization, or an acceptable trade-off. Then check the vocabulary itself rather than only its output: reserved symbols at their declared IDs, round-trip decoding, and any entries the model may never have trained on — the class Land and Bartolo confirmed at 67 of 999 candidate tokens even in GPT-2 XL.

Tokenizer evaluation should connect segmentation behavior to model quality, cost, and access across users.

Key takeaways