2 Foundations 5 / 6
  1. In this chapter
  2. Python and tensor shapes
  3. From Language Modeling to Next-Token Prediction
  4. Neural Network Basics
  5. Information Theory Refresher
  6. Tokenizers and Embeddings
  7. Optimizers and Training Stability
All chapters →

Chapter 2 · Foundations 2.5

Tokenizers and Embeddings: BPE, Vocabulary Size and the Embedding Table

An LLM only processes integers: a tokenizer splits text into tokens with a subword algorithm such as BPE and maps them to ids, then each id is looked up in a vocabulary-size by hidden-size embedding table. Vocabulary size trades off sequence length, parameters and long-tail coverage.

Beginner 33 min read Updated Companion code ↓

After this page you will be able to

  • Explain why a model cannot read a raw string and has to turn text into token ids first.
  • Explain how BPE grows a vocabulary out of a corpus, and implement it yourself in a few dozen lines.
  • Tell what byte-level BPE, WordPiece, Unigram and SentencePiece each solve, and which one the major models use.
  • Relate token ids, vocabulary size and the parameter count of the embedding table, and say what share of a model the embeddings take.
  • Describe how the tokenizer shapes sequence length and cost, and avoid the pitfalls around spaces, digits and special tokens.
On this page
  1. Why the tokenizer is the first interface of an LLM
  2. From a string to token ids: the full input pipeline
  3. BPE: growing a vocabulary from data
  4. The algorithm
  5. Hands on: train a BPE in the browser
  6. BPE in code
  7. Byte-level BPE: why modern LLMs almost never see unk
  8. Pre-tokenization: BPE only merges inside chunks
  9. Bytes to visible characters
  10. Beyond BPE: WordPiece, Unigram and SentencePiece
  11. From token id to vector: the embedding lookup
  12. An embedding is not “the real meaning”
  13. Vocabulary size: parameters, sequence length and the trade-off
  14. How many parameters the embedding takes
  15. The three-way trade-off
  16. How the tokenizer affects sequence length and cost
  17. Common pitfalls
  18. Summary and exercises
  19. Quick self-check
  20. Further reading
  21. FAQ

This page reads best right after From Language Modeling to Next-Token Prediction: that page is about what the model predicts, this one is about what a token actually is. Afterwards, continue with Attention Basics: How a Transformer Reads Context and Positional Encoding Explained: Absolute, Relative and RoPE.

Why the tokenizer is the first interface of an LLM

A neural network can only process numeric tensors, while people write text. A tokenizer converts in both directions: encoding cuts a string into a sequence of tokens and maps each to an integer id, and decoding turns ids back into a string. The model only ever sees id sequences: in language modeling, every xtx_t in p(xt∣x<t)p(x_t \mid x_{<t}) is an id from the vocabulary.

That raises a design question: how big should the unit of text be?

GranularityVocabulary sizeSequence lengthMain problem
Characters or bytesTiny (bytes: only 256)Very longAttention cost grows with the square of the sequence length, and the model has to assemble words from characters itself
Whole wordsHuge, and never completeShortNew words, spelling variants and proper nouns all become <unk> (out-of-vocabulary, OOV) and the information is lost
SubwordsTens of thousands to over a hundred thousandIn betweenThe splitting rules have to be learned from data, and details such as spaces and digits affect model behavior

The tokenizer’s job is to find a trainable compromise between vocabulary size and sequence length. It is not just preprocessing: it is the first abstraction through which the model perceives the world.

From a string to token ids: the full input pipeline

Before a piece of text enters the model it goes through roughly these steps:

  1. Normalization: Unicode normalization, whether to lowercase and so on. Tokenizers differ (the uncased BERT lowercases everything, Qwen2.5 applies NFC normalization).
  2. Pre-tokenization and splitting: cut the text into a token sequence according to the rules.
  3. Map each token to an integer id in the vocabulary.
  4. Look the ids up in the embedding table to get vectors.
  5. Add positional information (see Positional Encoding Explained) and feed the result to the Transformer.

The model does not “see words”, it sees “the vectors that tokens map to”, so changing how text is split changes the whole training trajectory. Besides ordinary tokens, the vocabulary contains special tokens: BOS (start of sequence), EOS (end of sequence), role markers in chat templates and so on. They do not correspond to any piece of text; they are control signals for the model.

Drawing the pipeline makes it clearer why the tokenizer is not an optional preprocessing step but the model’s real input interface:

From text to embeddings: the input pipeline Raw text is normalized and split into subwords, mapped to token ids, looked up in the embedding table to get vectors, combined with positional information and fed to the Transformer. The tokenizer decides the granularity at which text enters the model Raw text String / Unicode Tokenize normalize + split BPE / SentencePiece tokens ["Trans", "former", ...] token id [1523, 91, ...] Embedding table lookup [vocab_size, d_model] + positions to the Transformer Split the same text differently and the sequence length, embedding size, context cost and training trajectory all change.
A tokenizer does more than number the text: it defines the smallest unit the model sees, and directly affects vocabulary size, sequence length and embedding cost.

BPE: growing a vocabulary from data

BPE (Byte Pair Encoding) started out as a data compression algorithm (Gage, 1994). In 2016 Sennrich et al. applied it to neural machine translation so that a model could handle an open vocabulary with a fixed-size subword vocabulary. The idea is simple: start from the smallest units and repeatedly merge the pair of symbols that occurs together most often into a new symbol.

The algorithm

Training a BPE vocabulary:

  1. Count how often each word occurs in the corpus and split every word into a sequence of characters. The initial vocabulary is all characters that occur.
  2. Count how often each pair of adjacent symbols occurs (weighted by word frequency).
  3. Take the most frequent pair (a,b)(a, b), merge it into a new symbol abab that is added to the vocabulary, and replace every adjacent a ba\,b in the corpus with abab.
  4. Repeat steps 2 and 3 until the vocabulary reaches the target size. The vocabulary size equals the number of initial symbols plus the number of merges.

Step 3 can be written as

(a∗,b∗)=arg⁡max⁡(a,b)∑wnw cw(a,b)(a^*, b^*) = \arg\max_{(a,b)} \sum_{w} n_w \, c_w(a,b)

where nwn_w is how often word ww occurs in the corpus and cw(a,b)c_w(a,b) is how often the pair (a,b)(a,b) is adjacent in the current segmentation of ww.

To encode new text, split each word into the smallest symbols and then apply the merge rules in the order they were learned. So the order of the merge rules is itself part of the tokenizer.

After enough merges the vocabulary naturally contains frequent whole words, frequent affixes (est, er) and frequent subword fragments. No one writes these rules by hand; they grow out of the data.

Hands on: train a BPE in the browser

The component below implements the same algorithm in the browser. Pick a corpus at the top left (the default is the classic low / lower / newest / widest example), drag the number of merges, and the table on the right lists which pair of symbols each step merged and how often that pair occurred. Then type any text into the segmentation box to see how it gets split.

Three things are worth watching:

  1. The first merges are all frequent combinations. In the classic example, e + s and es + t merge first, because newest and widest together contribute 9 occurrences.
  2. More merges mean fewer tokens for the corpus and a bigger vocabulary. That is exactly the trade-off between sequence length and vocabulary size.
  3. Unseen words are split into pieces that already exist. Choose the English paragraph, drag the merges to the maximum and split tokenization of unusual words: words occurs in the corpus and is a single token, while unusual never occurs and can only be split into single characters.

BPE in code

Below is a BPE trainer and encoder in under 40 lines. The corpus matches the default of the component above: ▁low 5 times, ▁lower 2 times, ▁newest 6 times and ▁widest 3 times, where ▁ stands for “the space in front of the word” (explained again when SentencePiece comes up), so that the space can be part of a token.

from collections import Counter

# word -> count; ▁ marks the space before a word
corpus = {"▁low": 5, "▁lower": 2, "▁newest": 6, "▁widest": 3}
words = {tuple(w): n for w, n in corpus.items()}  # word -> symbols (characters)


def merge_pair(symbols, pair):
    out, i = [], 0
    while i < len(symbols):
        if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
            out.append(symbols[i] + symbols[i + 1])
            i += 2
        else:
            out.append(symbols[i])
            i += 1
    return tuple(out)


merges = []
for step in range(1, 11):
    pairs = Counter()
    for symbols, n in words.items():
        for a, b in zip(symbols, symbols[1:]):
            pairs[(a, b)] += n
    # most frequent adjacent pair; ties go to the one seen first
    pair, count = pairs.most_common(1)[0]
    merges.append(pair)
    words = {merge_pair(s, pair): n for s, n in words.items()}
    new = pair[0] + pair[1]
    print(f"{step:2d}  {pair[0]} + {pair[1]} -> {new}  ({count} times)")


def encode(word):
    symbols = tuple(word)
    for pair in merges:  # apply the learned merges in order
        symbols = merge_pair(symbols, pair)
    return list(symbols)


print(encode("▁lowest"), encode("▁newer"), encode("▁wider"))

Output:

 1  e + s -> es  (9 times)
 2  es + t -> est  (9 times)
 3  ▁ + l -> ▁l  (7 times)
 4  ▁l + o -> ▁lo  (7 times)
 5  ▁lo + w -> ▁low  (7 times)
 6  ▁ + n -> ▁n  (6 times)
 7  ▁n + e -> ▁ne  (6 times)
 8  ▁ne + w -> ▁new  (6 times)
 9  ▁new + est -> ▁newest  (6 times)
10  ▁ + w -> ▁w  (3 times)
['▁low', 'est'] ['▁new', 'e', 'r'] ['▁w', 'i', 'd', 'e', 'r']

Reading it step by step:

  • In step 1, e+s and s+t both occur 9 times (newest 6, widest 3); ties go to the pair seen first, e+s. In step 2, es+t forms the suffix est, again 9 times.
  • Steps 3 to 5 follow ▁low, and each of those pairs occurs 7 times (▁low 5 plus ▁lower 2).
  • Step 9 joins ▁new and est into the whole word ▁newest.

The last line shows how three words that never occurred in the training corpus get segmented:

New wordSegmentationComment
▁lowest▁low + estBoth pieces were learned, so an unseen word can still be represented
▁newer▁new + e + rThe prefix was learned; er occurs only twice, in ▁lower, and its turn has not come within these 10 steps
▁wider▁w + i + d + e + rFew merges apply, so it is almost back to single characters

That is the benefit of subword methods: the vocabulary has no lowest, yet the model can see it as low plus est and “partly understand” it from known pieces.

Byte-level BPE: why modern LLMs almost never see unk

The BPE above uses characters as base symbols, and that has a catch: Unicode has too many characters. The GPT-2 paper points out that reference BPE implementations working on Unicode code points would need a base vocabulary of over 130,000 before a single merge, far more than the 32,000 to 64,000 typically used with BPE; if not every character is included, rare characters can only become <unk>.

GPT-2 instead uses UTF-8 bytes as base symbols: the base vocabulary has just 256 entries, every string can be split losslessly into bytes, and <unk> is no longer needed (Radford et al., 2019). The Llama 3 and Qwen2.5 tokenizers are byte-level BPE as well. Two details deserve their own sections.

Pre-tokenization: BPE only merges inside chunks

Running BPE directly on the whole byte sequence would give dog, dog., dog! and dog? a vocabulary slot each, wasting vocabulary and model capacity. GPT-2 prevents BPE from merging across character categories (letters, digits and punctuation stay apart) and makes an exception only for the space, which improves compression noticeably without fragmenting words too much (Radford et al., 2019).

Modern tokenizers usually do this with a regular expression that first cuts the text into chunks, and BPE merges only inside each chunk. The regex below comes from Llama 3’s tokenizer.json:

import regex  # already a dependency of transformers

# The pre-tokenization regex from Llama 3's tokenizer.json.
# BPE merges only inside a chunk, never across chunks
PAT = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}|"
       r" ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+")
print(regex.findall(PAT, "Hello, world! It's 12345678."))

Output:

['Hello', ',', ' world', '!', ' It', "'s", ' ', '123', '456', '78', '.']

Three things to notice:

  • The leading space of world and It is glued to the word, which is why Hello and Hello are two different tokens in the vocabulary.
  • Contractions such as 's and each run of punctuation form their own chunks.
  • \p{N}{1,3} groups digits into runs of at most three, so 12345678 becomes 123, 456, 78.

Bytes to visible characters

Among the 256 bytes there are unprintable control bytes. GPT-2 maps every byte to a displayable Unicode character so that the vocabulary can be stored as a text file, and the space (0x20) becomes Ġ. That is why you see tokens such as Ġworld in the vocabulary, where Ġ means “one space before the word”. Cyrillic letters take two bytes each in UTF-8, and when the vocabulary has no token for a whole letter they show up in this byte form, which looks like garbage.

The code below reads GPT-2’s tokenizer.json directly, counts where the 50,257 tokens come from, and then splits a few strings:

import json
from transformers import AutoTokenizer

gpt2 = AutoTokenizer.from_pretrained("gpt2")
spec = json.loads(gpt2.backend_tokenizer.to_str())
vocab, merges = spec["model"]["vocab"], spec["model"]["merges"]
n_bytes = sum(len(token) == 1 for token in vocab)  # single chars = the 256 bytes
n_special = len(spec["added_tokens"])
sizes = (len(vocab), n_bytes, len(merges), n_special)
print("vocab size %d = bytes %d + merges %d + special %d" % sizes)
print("first three merge rules:", merges[:3])

texts = ["Hello, world!", " Hello", "tokenization", "Привет"]
for text in texts:
    ids = gpt2.encode(text)
    print(repr(text), "->", len(ids), gpt2.convert_ids_to_tokens(ids))
ok = all(gpt2.decode(gpt2.encode(t)) == t for t in texts)
print("lossless round trip:", ok)

Output:

vocab size 50257 = bytes 256 + merges 50000 + special 1
first three merge rules: [['Ġ', 't'], ['Ġ', 'a'], ['h', 'e']]
'Hello, world!' -> 4 ['Hello', ',', 'Ġworld', '!']
' Hello' -> 1 ['ĠHello']
'tokenization' -> 2 ['token', 'ization']
'Привет' -> 7 ['Ð', 'Ł', 'ÑĢ', 'и', 'в', 'е', 'ÑĤ']
lossless round trip: True
  • Vocabulary 50,257 = 256 bytes + 50,000 merges + 1 special token (<|endoftext|>).
  • The first merge rules learned are Ġ+t, Ġ+a and h+e, all extremely frequent English letter combinations.
  • All four strings round-trip without loss: byte-level BPE encoding and decoding are exact inverses.
  • Привет (“hello” in Russian) takes 7 tokens for its 6 letters, more than one per letter, while Hello is a single token. GPT-2’s training corpus WebText was built by deliberately filtering out non-English web pages (Section 3.7 of the paper), so a letter such as the capital П here survives only as two separate byte tokens.

Beyond BPE: WordPiece, Unigram and SentencePiece

BPE is not the only subword algorithm, and the names are easy to mix up. First separate algorithms from tools:

MethodHow the vocabulary is builtNotes
BPEBottom-up: repeatedly merge the most frequent pair of adjacent symbolsGPT-2, the Llama family and Qwen2.5 are all based on BPE
WordPieceAlso grows the vocabulary step by step, but picks merges by language-model likelihood rather than frequencyUsed by BERT, whose paper states a 30,000-token vocabulary
Unigram LMTop-down: start from a very large candidate vocabulary and prune it by “which removal lowers the likelihood least”, always keeping single charactersA sentence has several segmentations, each with a probability; the main alternative to BPE
  • Kudo (2018) treats WordPiece in a footnote as a variant of BPE: the vocabulary also grows incrementally, only the objective is likelihood instead of frequency. In WordPiece output, word-internal pieces carry a ## prefix: BERT’s tokenizer splits embeddings into em, ##bed, ##ding, ##s, and lowercases all input.
  • Because Unigram can output several segmentations of a sentence, Kudo (2018) proposed subword regularization: sample a different segmentation by probability during training, which makes a translation model more robust to segmentation noise.

SentencePiece is not a new algorithm but a library for training and running tokenizers that implements both BPE and Unigram (Kudo and Richardson, 2018). It has two defining traits:

  • It trains directly on raw text with no prior word splitting, so languages written without spaces, such as Chinese and Japanese, go through the same pipeline.
  • The space is treated as an ordinary symbol, written as the meta symbol ▁ (U+2581). To decode, concatenate all tokens and turn ▁ back into a space, so encoding and decoding are exact inverses; the paper calls this lossless tokenization.

The early Llama models used SentencePiece to train a BPE vocabulary (32,000 entries). The Llama 1 paper also states that all numbers are split into individual digits and that unknown UTF-8 characters fall back to bytes (Touvron et al., 2023).

Putting the major tokenizers side by side (numbers taken from each model’s public tokenizer.json and checked against the papers, November 2026):

ModelAlgorithmVocabulary sizeNotable details
BERT (uncased)WordPiece30,522Lowercases; word-internal pieces carry ##
GPT-2Byte-level BPE50,257256 bytes + 50,000 merges + 1 special token
Llama / Llama 2SentencePiece BPE32,000Space written as ▁; digits split one by one; unknown characters fall back to bytes
Llama 3Byte-level BPE128,000 (128,256 with special tokens)100K from tiktoken plus 28K added for better non-English support; digits in groups of at most three
Qwen2.5Byte-level BPE151,643 (151,665 with special tokens)Digits split one by one; NFC normalization first

From token id to vector: the embedding lookup

Once the text is cut into tokens and mapped to ids, the model’s first computation is the embedding lookup. The embedding table is a matrix EE of shape [V,d][V, d], where VV is the vocabulary size and dd is the hidden size (the length of the vector the model keeps at each position). The initial vector of the tt-th token is simply the matching row of EE:

xt=E[idt]∈Rd\mathbf{x}_t = E[\mathrm{id}_t] \in \mathbb{R}^{d}

This is equivalent to writing the id as a one-hot vector ot∈{0,1}V\mathbf{o}_t \in \{0,1\}^V and multiplying by the matrix, xt=ot⊤E\mathbf{x}_t = \mathbf{o}_t^{\top} E. In practice the row is simply indexed; nobody multiplies by a VV-dimensional vector. The code below checks that the two agree, using real GPT-2 ids:

import torch
from transformers import AutoTokenizer

gpt2 = AutoTokenizer.from_pretrained("gpt2")
ids = gpt2.encode("Hello world")
print(ids, gpt2.convert_ids_to_tokens(ids))

V, d = 50257, 768
emb = torch.nn.Embedding(V, d)  # V rows of d numbers each, random at first
x = emb(torch.tensor(ids))  # lookup: take rows 15496 and 995
one_hot = torch.nn.functional.one_hot(torch.tensor(ids), V).float()
same = torch.allclose(x, one_hot @ emb.weight)
print(x.shape, "lookup == one-hot @ matrix:", same)

Output:

[15496, 995] ['Hello', 'Ġworld']
torch.Size([2, 768]) lookup == one-hot @ matrix: True

The numbers in the table start out random and are updated by backpropagation during pretraining. The less often a token occurs in the corpus, the less training signal its row receives.

An embedding is not “the real meaning”

Many introductions say “an embedding is a word vector that encodes meaning”. That is true but oversimplified:

  • An embedding is only the initial mapping from discrete symbols to vectors: the same token gets the same vector no matter what the context is.
  • Once inside the deeper layers, the hidden state at every layer is rewritten again and again by the context.

For example, “bank” means different things in different contexts. The static vector from the lookup cannot resolve that; the contextual modeling after it does. That is why, in the LLM era, people talk about contextual representations rather than only static word vectors.

Vocabulary size: parameters, sequence length and the trade-off

How many parameters the embedding takes

The embedding table has V⋅dV \cdot d parameters. At the end the model also has an output layer (the unembedding) that maps the hidden state back to VV logits, which is again a V×dV \times d matrix. The two can share one set of weights, called weight tying, which Press and Wolf (2016) recommend; or each can have its own.

Build the models from their real configurations on the meta device and count how much the embeddings take:

import torch
from transformers import GPT2Config, GPT2LMHeadModel
from transformers import LlamaConfig, LlamaForCausalLM
from transformers import Qwen2Config, Qwen2ForCausalLM

qwen = Qwen2Config(vocab_size=151936, hidden_size=896,
                   intermediate_size=4864, num_hidden_layers=24,
                   num_attention_heads=14, num_key_value_heads=2,
                   tie_word_embeddings=True)
llama = LlamaConfig(vocab_size=128256, hidden_size=4096,
                    intermediate_size=14336, num_hidden_layers=32,
                    num_attention_heads=32, num_key_value_heads=8,
                    tie_word_embeddings=False)

with torch.device("meta"):  # shapes only, no memory: counting takes seconds
    models = [  # (name, model, number of embedding tables)
        ("GPT-2 small", GPT2LMHeadModel(GPT2Config()), 1),  # input/output tied
        ("Qwen2.5-0.5B", Qwen2ForCausalLM(qwen), 1),
        ("Llama 3 8B", LlamaForCausalLM(llama), 2),  # separate in/out tables
    ]
for name, model, copies in models:
    total = sum(p.numel() for p in model.parameters())
    table = model.get_input_embeddings().weight.numel()  # V x d
    share = copies * table / total
    print(f"{name:12} total {total:>13,}  "
          f"table {table:>11,} x{copies}  share {share:.1%}")

Output:

GPT-2 small  total   124,439,808  table  38,597,376 x1  share 31.0%
Qwen2.5-0.5B total   494,032,768  table 136,134,656 x1  share 27.6%
Llama 3 8B   total 8,030,261,248  table 525,336,576 x2  share 13.1%

Two things follow from these three lines:

  • The smaller the model, the more expensive the vocabulary. Nearly a third of GPT-2 small and more than a quarter of Qwen2.5-0.5B sit in the embeddings. The model body grows faster with depth and hidden size, so even with separate input and output tables (two copies) Llama 3 8B spends only 13.1%.
  • The number of rows is not necessarily the number of tokenizer entries. The embedding table of Qwen2.5-0.5B has 151,936 rows while its tokenizer has only 151,665 entries; the extra rows do not correspond to any token.
Where the numbers come from

GPT-2 small has 124,439,808 parameters when counted from the default Hugging Face GPT2Config (Table 2 of the paper lists the smallest model as 117M). Qwen2.5-0.5B and Llama 3 8B use the values in their public config.json: Table 3 of the Llama 3 paper gives a vocabulary of 128,000, and the released model has 256 more special tokens, 128,256 rows in total.

The three-way trade-off

Vocabulary size is the most important hyperparameter in tokenizer design, and it pulls on three things at once:

AspectLarge vocabularySmall vocabulary
Embedding and output-layer parametersMany: V⋅dV \cdot d grows linearly with VVFew
Sequence lengthShort: more whole words and long fragments, so the same text needs fewer tokensLong: relies more on assembling subwords
Long-tail coverageMany rare tokens, each with very little training signalRare words are split into common pieces, each trained more thoroughly

Llama 3 is a concrete example: the vocabulary grew to 128K (100K from tiktoken plus 28K added for better non-English support), and the English compression rate rose from 3.17 characters per token with the Llama 2 tokenizer to 3.94. For the same million English characters, the number of tokens falls from about 315 thousand to about 254 thousand, roughly 19.5% fewer, which means reading more text for the same training compute; the 28K added non-English tokens also improved both compression and downstream performance without affecting English tokenization (Llama Team, 2024).

A bigger vocabulary is still not simply better: the embedding table and output layer cost more to store and compute (the output layer computes VV logits at every position), and any vocabulary contains tokens that almost never appeared in the training corpus. Their embeddings are barely trained, and when such a token shows up in the input the model can misbehave (see glitch tokens below).

Drawing the trade-off:

The vocabulary-size trade-off A small vocabulary shrinks the embedding table but lengthens sequences, a medium one is the usual engineering compromise, and a large one keeps more whole words but enlarges the table and makes rare tokens hard to train well. Vocabulary size trades off table size, sequence length and granularity Small vocabulary finer pieces, more assembly Small embedding table Longer sequences Rare words split up Medium vocabulary where most production tokenizers sit Table size in check Moderate length Words and subwords Large vocabulary more whole words, longer pieces Bigger embedding table Shorter sequences Long tail needs data A good tokenizer keeps table size, sequence cost and tail coverage all acceptable.
Vocabulary size is a three-way balance: what you save in embedding parameters you often pay back in sequence length and inference cost.

How the tokenizer affects sequence length and cost

Suppose the context window is fixed at 8K tokens. The more finely a tokenizer cuts, the more tokens a document uses, and the higher the training and inference cost; when an API bills by token, that becomes price directly. The code below cuts the same four texts with three tokenizers:

from transformers import AutoTokenizer

texts = {
    "English": ("Large language models split text into tokens "
                "before they process it."),
    "Spanish": ("Los modelos de lenguaje dividen el texto en tokens "
                "antes de procesarlo."),
    "Russian": ("Большие языковые модели разбивают текст на токены "
                "перед обработкой."),
    "Python": "def add(a, b):\n    return a + b\n",
}
tokenizers = {
    "GPT-2": "gpt2",
    "Llama": "hf-internal-testing/llama-tokenizer",
    "Qwen2.5": "Qwen/Qwen2.5-0.5B",
}
print("characters", {k: len(v) for k, v in texts.items()})
for label, name in tokenizers.items():
    tok = AutoTokenizer.from_pretrained(name)
    counts = {k: len(tok.encode(v, add_special_tokens=False))
              for k, v in texts.items()}
    print(f"{label:7} vocab {len(tok):>7,} {counts}")

Output:

characters {'English': 68, 'Spanish': 71, 'Russian': 67, 'Python': 32}
GPT-2   vocab  50,257 {'English': 12, 'Spanish': 23, 'Russian': 75, 'Python': 16}
Llama   vocab  32,000 {'English': 13, 'Spanish': 19, 'Russian': 24, 'Python': 14}
Qwen2.5 vocab 151,665 {'English': 12, 'Spanish': 17, 'Russian': 21, 'Python': 12}
  • The English sentence barely differs: 12 to 13 tokens in all three.
  • The 71-character Spanish sentence takes 23, 19 and 17 tokens.
  • The 67-character Russian sentence: GPT-2 needs 75 tokens, Llama (SentencePiece, 32,000 entries) 24 and Qwen2.5 only 21. GPT-2’s tokenizer spends about 3.6 times as many tokens (75 ÷ 21), so the same context window holds only about 28% as much Russian as with Qwen2.5.
  • Python code differs little, 12 to 16 tokens.

The widget below makes this table draggable: pick a sentence and drag the context window to see how many tokens each tokenizer spends and how many repetitions of the sentence fit into the window.

This is a demonstration on a few sentences, not a benchmark, and the exact ratios change with the text. Systematic studies point the same way: Petrov et al. (2023) found that when the same text is translated into different languages, the tokenized length can differ by up to 15 times, which means that using one model in different languages costs different amounts.

That is why RAG, long context and API billing are all tied to the tokenizer: the same retrieved passage may fit in one model’s window and not in another’s. Evaluation needs care as well, because perplexity is averaged per token and cannot be compared directly between models with different tokenizers (see From Language Modeling to Next-Token Prediction).

Common pitfalls

All of the following can be reproduced with the code on this page:

from transformers import AutoTokenizer

gpt2 = AutoTokenizer.from_pretrained("gpt2")
llama = AutoTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")

# 1) a leading space gives a different token
print(gpt2.tokenize("Hello"), gpt2.tokenize(" Hello"))
# 2) the same word splits differently with and without the leading space
print(gpt2.tokenize("strawberry"), gpt2.tokenize(" strawberry"))
# 3) how digits are split differs between tokenizers
print(gpt2.tokenize("12345678"), llama.tokenize("12345678"))
# 4) BOS is added automatically; writing <s> in the text makes it two
bos = llama.bos_token_id
print(llama("Hi").input_ids.count(bos), llama("<s>Hi").input_ids.count(bos))
# 5) special-token strings inside the text become real special tokens
print(gpt2.encode("<|endoftext|>"))

Output:

['Hello'] ['ĠHello']
['st', 'raw', 'berry'] ['Ġstrawberry']
['123', '45', '678'] ['▁', '1', '2', '3', '4', '5', '6', '7', '8']
1 2
[50256]
SymptomCauseWhat to do
Hello and Hello are different tokensPre-tokenization glues the leading space to the wordMind the spaces when you assemble prompts; do not end a completion-style prompt with a stray space, since most words are stored in the vocabulary with a leading space
The model cannot count the letters in a word strawberry with a leading space is a single token in the GPT-2, Qwen2.5 and Llama 3 vocabularies, so the model receives one id and the letters are not in the inputFor character-level work, have the model spell the word out letter by letter first, or hand it to code
Digits are split irregularlyGPT-2 splits 12345678 into 123, 45, 678; Llama and Qwen2.5 split digit by digit, Llama 3 in groups of threeKnow the splitting rule of your tokenizer; for tasks that need digit-level handling, split explicitly in preprocessing
Two BOS tokens at the startadd_special_tokens adds BOS automatically by default, and writing another <s> in the text makes a second oneWhen the text already contains special tokens, turn add_special_tokens off when encoding
A special-token string in user input is treated as a real special tokenHugging Face tokenizers by default recognize special-token strings inside the textFor untrusted input, escape or filter those strings before encoding
A few tokens make the model behave strangelyThe vocabulary has tokens that almost never occurred in the training corpus (glitch tokens), and their embeddings are barely trainedLand and Bartolo (2024) propose a way to detect under-trained tokens automatically, worth checking when evaluating or red-teaming a model
Quality collapses after swapping the tokenizerEach row of the embedding table is tied to a token id, so a new tokenizer means a new set of input symbolsUse the tokenizer and the weights as a pair; when adding tokens, extend the embedding table and keep training
A tokenizer that does well on English is wasteful on other languages or codeThe vocabulary is determined by the corpus the tokenizer was trained on, and a different language mix or code share gives a different compression rateChoose the tokenizer for the target languages and code share, or train one on the target corpus

Summary and exercises

Key points:

  1. The tokenizer turns text into an id sequence and the model only sees ids; subword splitting trades vocabulary size against sequence length.
  2. BPE starts from the smallest symbols and repeatedly merges the most frequent adjacent pair; the order of the merges is the encoding rule, and a word never seen in training is split into pieces that were learned.
  3. Byte-level BPE uses the 256 bytes as base symbols so every string can be represented; pre-tokenization sets the boundaries BPE merges within, and the handling of leading spaces and digits comes from that step.
  4. The embedding table and the output layer are each a V×dV \times d matrix: about 31% of GPT-2 small, about 27.6% of Qwen2.5-0.5B and about 13.1% of Llama 3 8B (untied, two tables).
  5. The same sentence can take several times as many tokens under one tokenizer as under another (measured here for 67 Russian characters: 75, 24 and 21 tokens), so context, cost and cross-model evaluation all have to account for the tokenizer.

Quick self-check

1. What does each step of BPE training do?

  • Pick two adjacent symbols at random and merge them
  • Count the adjacent symbol pairs and merge the most frequent pair into a new symbol
  • Split the longest word into characters
  • Delete the least frequent symbol

Each step counts all adjacent symbol pairs (weighted by word frequency), merges the most frequent one, updates the corpus, and repeats until the vocabulary reaches the target size. To encode new text, the merges are applied in the same order.

2. What makes up GPT-2’s vocabulary of 50,257?

  • 50,257 complete English words
  • 256 bytes + 50,000 merges + 1 special token
  • 50,000 characters + 257 special tokens
  • 256 bytes + 50,257 merges

The code on this page counts them in tokenizer.json: 256 single-character tokens (exactly the 256 bytes), 50,000 merge rules and one special token, <|endoftext|>.

3. Why does a byte-level BPE tokenizer almost never need <unk>?

  • Its vocabulary is large enough to contain every Unicode character
  • Any string can be split losslessly into UTF-8 bytes, and all 256 bytes are in the base vocabulary
  • It replaces unknown characters with random tokens
  • It does no pre-tokenization

The base symbols are the 256 bytes, so any input can be represented. The price is that uncommon characters become several byte tokens: GPT-2 needs 7 tokens for the 6 letters of Привет.

4. With vocabulary size V=32,000 and hidden size d=4,096, and separate input embedding and output layer, how many parameters do the two tables hold together?

  • About 65 million
  • About 130 million
  • About 260 million
  • About 520 million

Each table is V×d = 32,000×4,096 = 131,072,000; untied means two tables, 262,144,000 in total, about 260 million. With tied weights only one table counts, about 130 million.

5. In this page’s measurements, which tokenizer produces the fewest tokens for the 67-character Russian sentence?

  • GPT-2, 75 tokens
  • The Llama SentencePiece tokenizer, 24 tokens
  • Qwen2.5, 21 tokens
  • All three are the same

How many common Cyrillic fragments the vocabulary holds sets the compression rate. Qwen2.5 has more than 150 thousand entries and cuts Russian most compactly; GPT-2’s training corpus filtered out non-English pages, so many Cyrillic letters end up split into single bytes.

6. Which statement about Hello and Hello (with a leading space) is correct?

  • The same token, the space is ignored
  • Two different tokens, because pre-tokenization glues the leading space to the word
  • The version with the space is split into a space token and a word token
  • Only GPT-2 does this; other tokenizers do not distinguish them

In GPT-2 they are Hello and ĠHello, and the Llama 3 tokenizer behaves the same way. One extra or missing space when you assemble a prompt can turn the input into a different token.

Exercises:

  1. The corpus is ▁low 5 times, ▁lower 2 times, ▁newest 6 times and ▁widest 3 times. Initially w+e occurs 8 times and e+s 9 times, so step 1 merges e+s. Why does step 3 pick ▁+l (7 times) rather than w+e?
  2. The vocabulary grows from 32,000 to 128,000, the hidden size is 4,096 and input and output are not tied. By how much do the embedding and output-layer parameters grow, and what percentage of Llama 3 8B’s total (8,030,261,248) is that?
  3. Llama 3’s tokenizer raises the English compression rate from 3.17 to 3.94 characters per token. For one million English characters, how many fewer tokens is that, and what does it mean for an 8K context window?
Reference answers
  1. The initial w+e occurs in lower (2 times) and newest (6 times), 8 in total. The first two steps merged e s t in newest into est, so newest became ▁ n e w est and the adjacency w+e disappeared, leaving only the 2 occurrences in lower. The pairs with 7 occurrences are now ▁+l, l+o and o+w, and ties go to the one seen first, ▁+l. A merge changes the counts of the pairs that follow, which is why every step has to recount.
  2. The increase is 2×(128,000−32,000)×4,096=786,432,0002 \times (128{,}000 - 32{,}000) \times 4{,}096 = 786{,}432{,}000, about 790 million, or about 9.8% of 8,030,261,248. If input and output share weights, it is half of that.
  3. 106/3.17≈315,45710^6 / 3.17 \approx 315{,}457 tokens versus 106/3.94≈253,80710^6 / 3.94 \approx 253{,}807 tokens, about 61,650 fewer, or 19.5%. Seen the other way, the same 8K window holds about 24% more English characters (3.94/3.17≈1.243.94 / 3.17 \approx 1.24), and the same training compute reads more text.

Further reading

FAQ

Why does an LLM need a tokenizer?
A model can only process numbers. The tokenizer splits text into tokens from a vocabulary and maps them to integer ids, and the embedding table turns each id into a vector for the Transformer. Splitting by character makes sequences too long, splitting by whole word needs a huge vocabulary and cannot represent new words, and subword methods balance sequence length against vocabulary size.
How does BPE work?
BPE starts from the smallest base symbols (characters or bytes), counts which pair of symbols occurs next to each other most often in the corpus, merges that pair into a new symbol, and repeats until the vocabulary reaches the target size. Frequent fragments become stable units and rare words are split into subwords; at encoding time the merges are applied in the order they were learned. Byte-level BPE uses the 256 bytes as base symbols, so every input can be represented and out-of-vocabulary words practically disappear.
How are SentencePiece and BPE related?
BPE is a subword merging algorithm, while SentencePiece is a library for training and running tokenizers that implements both BPE and Unigram. It trains directly on raw text and treats the space as an ordinary symbol (written as ▁), so encoding and decoding are exact inverses, which also suits languages written without spaces such as Chinese and Japanese.
Is a bigger vocabulary always better?
No. A larger vocabulary shortens sequences: Llama 3 grew its vocabulary to 128K and raised the English compression rate from 3.17 to 3.94 characters per token. But the embedding table and output layer grow with it, so in Qwen2.5-0.5B the embedding table alone holds about 27.6% of all parameters, and rare tokens get too little training signal. The right size depends on the languages, the share of code, the model size and the context cost.
Why does the same sentence take a different number of tokens in different models?
Each tokenizer has its own vocabulary, training corpus and pre-tokenization rules. In this page's measurements a 67-character Russian sentence takes 75 tokens with GPT-2's tokenizer, 24 with the Llama SentencePiece tokenizer and 21 with Qwen2.5, while the English sentence takes 12 to 13 tokens in all three. The token count decides how much content fits in the context window and what an API call costs.