Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

AI tokenization: how do tokens, BPE and SentencePiece work?

A language model does not receive a list of words. A tokenizer first converts text into a sequence of IDs; the model maps those IDs to vector representations. Segmentation affects context length, request cost, language coverage and computation. Why can the same text have different token counts?

AI
Published Written by Reading time 10 min read
On this page Contents: quick navigation between sections

What is a token and a tokenizer?

A token is a unit selected by a tokenizer: a word, part of a word, character, byte sequence or special symbol. The vocabulary assigns numerical IDs. An ID is not a semantic coordinate: the model looks up its embedding and processes that representation in context. A different vocabulary can assign a different ID to the same piece. [4][5]

Word-level tokenization must handle inflection, names and out-of-vocabulary units. Character- or byte-level tokenization can reduce vocabulary requirements but often increases sequence length. Subword methods seek a compromise by retaining frequent pieces and composing rarer ones from smaller units. Token boundaries need not match linguistic morphemes. [1][4]

A typical pipeline includes optional normalization, pre-tokenization, segmentation according to learned vocabulary and rules, ID mapping and optional special-token insertion. The tokenizer decoder reverses the representation only to the extent that information was preserved; it is not the Transformer decoder. Not every tokenizer separates all of these stages. [5]

How does Byte Pair Encoding (BPE) work?

In classical text BPE training, begin with base symbols, count adjacent pairs in the corpus, select the most frequent pair, create a new unit and replace its occurrences. Repeat until a stopping criterion such as the target vocabulary size. Tie-breaking and pre-tokenization boundaries depend on the implementation. [1][4]

Toy corpus: “aba” occurs 3 times, “ab” twice, “ac” once. Start each word as a separate symbol list. Pair (a,b) occurs 5 times, (b,a) 3 times and (a,c) once. Merge a and b into ab; then merge (ab,a), occurring 3 times, into aba. If training stops here, encoding the new piece “abab” yields [ab, ab]. Encoding uses the learned merge order instead of recounting pair frequencies in the user's input. These are synthetic pieces, not real model IDs.

Byte-level BPE starts with byte representations, typically all 256 byte values, rather than only characters seen in training. With appropriate encoding it can represent valid UTF-8 text without an unknown-character token; a single token need not be valid Unicode text. Byte fallback in a character-based tokenizer is a different mechanism: bytes represent otherwise unsupported pieces. [7][8][19]

WordPiece and Unigram: how do they differ?

WordPiece example. With an illustrative vocabulary containing play and ##ing, playing can be split into those two pieces. The continuation marker is not part of the original word. If the remaining characters cannot be covered, typical BERT WordPiece returns an unknown token for the entire word. [11]

WordPiece uses a piece vocabulary and typically encodes a pre-tokenized word by taking the longest matching prefix, then processing the remainder. In BERT's convention, a prefix consisting of two hash signs marks a continuation piece, not literal input characters. If the word cannot be fully covered, typical BERT WordPiece emits [UNK] for the entire word. Its training criterion is not simply BPE pair frequency; exact training implementations may differ. [4][11]

Unigram generally begins with a larger candidate set and prunes the vocabulary by evaluating the effect of removing pieces on data likelihood. Each piece has a probability; a segmentation is scored by the product of piece probabilities, equivalently the sum of log probabilities. Dynamic programming can find the best path. Alternative segmentations can be sampled during model training as a form of regularization. [3][4]

In a fictional vocabulary with p(a)=0.2, p(b)=0.2, p(ab)=0.3 and p(c)=0.3, the one-piece segmentation of “ab” has weight 0.3 versus 0.04 for [a,b]. The best segmentation is [ab]. This illustrates a Unigram tokenizer model, not the probability that a generative LLM emits the string “ab”. The two probabilistic models have different objectives.

What is SentencePiece and how does it handle spaces?

ApproachMechanismKey limitation
BPEFrequent pair mergesDepends on merge rules and base units
WordPieceLongest vocabulary matchWhole-word UNK possible
UnigramProbabilistic segmentationDepends on learned vocabulary
SentencePieceLibrary supporting BPE and UnigramNormalization depends on configuration

SentencePiece is a tokenization library and model format, not a separate segmentation algorithm at the same level as BPE. It supports BPE and Unigram, among other modes, can train on raw sentences without mandatory external word splitting, and exposes configurable segmentation constraints. This is useful for languages where spaces do not delimit all words. [2][7]

A common configuration represents whitespace with ▁ (U+2581) and may insert a dummy leading space marker. This retains boundary information in normalized text. Default SentencePiece rules may nevertheless normalize characters and remove extra whitespace. Do not promise byte-identical round trips when configuration transforms the input. Byte fallback is configurable, not guaranteed for all SentencePiece models. [6][7]

Practical verification: SentencePiece 0.2.1 trained two small tokenizers (BPE and Unigram) on ten repetitions of six sentences: “aba”, “ab”, “ac”, “aba ab ac”, “é é” and “A B”. Settings: vocab_size=24, hard_vocab_limit=False, shuffle_input_sentence=False, num_threads=1, default normalization. In both cases an input with two spaces before aba, between aba and ab, and after ab produced [▁aba, ▁ab] and decoded to “aba ab”. Both composed and decomposed é produced [▁é]. This result applies to the tested configuration, not every SentencePiece model. [6][7]

For a pretrained model, use its compatible vocabulary, rules and special symbols rather than selecting an arbitrary tokenizer algorithm. When training from scratch, compare data coverage, sequence lengths, vocabulary cost and downstream task performance. The algorithm name alone does not determine model quality. [4][15]

Unicode, bytes, whitespace and reversibility

RepresentationGraphemesCode pointsUTF-16 code unitsUTF-8 (B)
é (U+00E9)1112
e + U+03011223
😀 (U+1F600)1124

Unicode code points, UTF-16 code units, UTF-8 bytes and grapheme clusters are different concepts. The emoji 😀 has one code point, two UTF-16 code units and four UTF-8 bytes. The letter é can be written as U+00E9 or e followed by combining accent U+0301; both are one grapheme cluster, but have different code-point and byte counts. The table shows these counts, not token counts. [9][10]

NFC can compose canonically equivalent sequences; NFKC additionally considers compatibility equivalence, for example converting a fullwidth character to its ordinary counterpart. Lowercasing, accent removal and whitespace removal are separate operations. Do not arbitrarily normalize code, passwords or identifiers when character changes could alter meaning. [5][6][9]

A byte-level token may contain only part of a multibyte character. To visualize individual pieces, inspect their bytes or verified text offsets: independently decoding each token as UTF-8 can produce the replacement character U+FFFD. Streaming decoders need to retain incomplete byte sequences until they can be decoded correctly. Offset units may be bytes, code points or code units depending on the API. [17][19]

Special tokens, chat templates and generation

BOS and EOS may mark sequence boundaries, PAD supports length alignment, UNK indicates unknown units and MASK is used by certain models. Not all models have all these symbols. Some use additional role and message markers. Padding requires a correct attention mask; attention masking and loss masking are distinct. [12][18]

For batches, padding aligns lengths to a chosen size; dynamic padding to the longest batch item can reduce unnecessary computation. Truncation removes tokens according to configuration. When an input exceeds its limit, select relevant information and preserve the current question and required instructions. Do not silently drop a document ending or the oldest message. For generation batches, use padding side and masks compatible with the model and runtime. [18]

A chat model receives serialized messages rather than arbitrary application JSON. A chat template defines roles and separators. In Hugging Face, when apply_chat_template(tokenize=False) produces text containing the required special tokens, subsequent encoding should normally set add_special_tokens=False to avoid duplication. Alternatively, tokenize directly with the template. Do not let untrusted user text insert control symbols on its own; role boundaries do not replace authorization checks. [12][18][19]

An autoregressive LLM produces vocabulary logits and the generation strategy selects the next ID. The tokenizer decodes IDs into text. Output usage may include control or other non-visible tokens counted by a service; the number of visible pieces need not equal billed usage. [13]

Context, cost and performance

To convert token counts into a workload cost estimate, enter input and output volumes separately in the AI Model Cost Calculator. Check cache and reasoning-token billing rules; the illustrative rates above are not provider prices. [21]

Selecting information within a token budget is a separate engineering problem. The relationship between instructions, evidence and tools is explained in Prompt Engineering vs Context Engineering. [20]

There is no universal words-to-tokens conversion. A matching local tokenizer can count a particular string exactly but may not know provider request serialization. System instructions, history, tools, schemas, additional modalities and formatting can increase input usage. Tokenization is not generally additive: if a+b merges into ab, separately encoding “a” and “b” yields two tokens while “ab” yields one. Count the complete serialized input and use documented provider counting and usage reporting. [13][17]

Planning example: a hypothetical shared context limit of 32,768 tokens, 20,000 input tokens and 4,096 reserved output tokens leaves 8,672. Also check independent input and output limits and reasoning-token accounting. A reservation is not a prediction of output length. At illustrative rates of USD 2 per million input tokens and USD 8 per million output tokens, actual usage of 20,000 and 2,000 tokens costs USD 0.056, excluding caching, taxes and other charges. These are fictional prices. [13]

Sequence length affects attention work and KV-cache memory, but fewer tokens do not guarantee proportional speedup. A larger vocabulary can increase embedding and output-head parameters: increasing V from 32,000 to 64,000 with d=4,096 adds 131,072,000 weights to a V×d matrix, or 250 MiB at 2 bytes per weight. An untied output matrix of the same dimensions adds the same amount again, excluding biases and overhead. [14]

Choosing, evaluating and deploying a tokenizer

Multilingual tokenizers may produce different sequence lengths for semantically equivalent texts. Measure token-count distributions for Polish, other target languages, code and domain data. Compare bytes per token, tokens per word (fertility, with an explicit word segmentation rule), and relative lengths on parallel texts. Recent research on multilingual efficiency and equity motivates evaluating both objectives; better compression does not guarantee better downstream results. [15][16]

Pin model and tokenizer revisions, vocabulary, merges or model file, normalization, special symbols and chat template. A changed vocabulary may change ID semantics; matching vocabulary size is insufficient. Adding units requires adjusting embeddings and the output head as applicable, and training the model to use new parameters. Resizing alone does not establish quality. [14][18]

Before deployment, verify reference cases with exact IDs, whitespace, line breaks, accents, emoji, composed and decomposed text, long inputs, control symbols, truncation and decoding. In RAG, chunk documents according to the embedding model tokenizer and budget generation context separately. Preserve original text and metadata; token logs can expose content just like text logs. [5][18][19]

Tokenization is part of the text-to-model contract, not cosmetic word splitting. Use the exact compatible tokenizer, measure serialized inputs and inspect usage reports. When building models, evaluate representation efficiency together with real task quality in target languages.

Tools for this topic

AI Tokenization BPE WordPiece Unigram SentencePiece Unicode LLM Context Window NLP

Frequently asked questions

Is a token always a word?

No. It can be a word fragment, byte sequence, character, word or special symbol.

Are SentencePiece and BPE competing algorithms?

Not strictly. SentencePiece implements BPE and Unigram among other modes.

Does the same text always have the same token count?

Only for the same deterministic configuration and input. Different tokenizers, message formatting or segmentation sampling can change it.

Does a local count establish the exact API cost?

Not always. Text counts may omit serialization, tools, caching, reasoning and billing rules.

Does decoding always restore the original input?

No. Normalization, unknown units, truncation and special-token removal may lose information.

Is a larger vocabulary always better?

No. It may shorten sequences but increases matrix sizes and requires downstream evaluation.

Can I replace a pretrained model's tokenizer?

Not without checking ID and architecture compatibility; a new vocabulary usually requires model adaptation and training.

Sources and references

  1. Sennrich et al., Neural Machine Translation of Rare Words with Subword Units↩1↩2
  2. Kudo & Richardson, SentencePiece↩
  3. Kudo, Subword Regularization↩
  4. Hugging Face, Tokenization algorithms↩1↩2↩3↩4↩5↩6
  5. Hugging Face, Tokenizers components↩1↩2↩3↩4
  6. SentencePiece, normalization↩1↩2↩3
  7. SentencePiece, options↩1↩2↩3↩4
  8. OpenAI, tiktoken↩
  9. Unicode Standard Annex #15, Unicode Normalization Forms↩1↩2
  10. Unicode Standard Annex #29, Unicode Text Segmentation↩
  11. Hugging Face, WordPiece tokenization↩1↩2
  12. Hugging Face, Chat Templates↩1↩2
  13. OpenAI, Counting tokens↩1↩2↩3
  14. Hugging Face, Customizing tokenizers↩1↩2
  15. Wei et al., Equity with Efficiency: An Empirical Study of Tokenizers for Multilingual Large Language Models↩1↩2
  16. Foroutan et al., Parity-Aware Byte-Pair Encoding: Improving Cross-lingual Fairness in Tokenization↩
  17. OpenAI, How to count tokens with Tiktoken↩1↩2
  18. Hugging Face, Tokenizer API↩1↩2↩3↩4↩5
  19. OpenAI, tiktoken core implementation↩1↩2↩3↩4
  20. POLPROG, Prompt Engineering vs Context Engineering↩
  21. POLPROG, AI Model Cost Calculator↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning