Skip to content
Skip to lesson
Back to Topics
LearnCore LLM FoundationsBPE, WordPiece, and SentencePiece
📝MediumNLP Fundamentals

BPE, WordPiece, and SentencePiece

See why a word like unexpectedly should split into reusable pieces, and why a new tokenizer can still point an old checkpoint at the wrong vector.

33 min read
Learning path
Step 54 of 199 in the full curriculum

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

Before a language model can process the sentence rain falls softly, a tokenizer slices that text into discrete pieces and assigns each piece an integer ID. An ID is a model-local vocabulary index: it selects a row of a learned embedding table WE∈RV×dW_E \in \mathbb{R}^{V \times d}. It isn't a physical memory address or a meaning shared by all models.

Suppose ID 5 represented falls during training, but a replacement tokenizer assigns it to soft. The replacement now selects the vector learned for the wrong piece. Other changes may affect only certain strings, or preserve every encoding; a different file doesn't automatically scramble every ID. The compatibility requirement is that text segmentation, ID meanings, special tokens, and decoding agree with the checkpoint.

Three algorithms do that segmentation: Byte-Pair Encoding (BPE), WordPiece, and Unigram. SentencePiece is a toolkit that implements both BPE and Unigram, along with normalization and decoding. The classroom examples expose their mechanics. Their invented IDs and small vocabularies aren't outputs from a commercial model's tokenizer. The first choice is coarser than any merge table. Should the model see whole words, characters, or pieces of words?

Four token pieces rain, space-falls, space-soft, and ly receive invented IDs 2, 5, 1, and 6. Matching colors select those rows from an eight-row, three-column embedding table. The output matrix gathers the selected rows in token order, making shape 4 by 3. IDs index rows and carry no semantic order.
Four illustrative pieces select four rows from a synthetic eight-row embedding table. IDs are model-local row indices, and the selected vectors keep the original token order.

The granularity trade-off: characters, subwords, and words

Whole words, raw characters, and subword pieces do not fail in the same way. You could feed raw characters, whole words, or subword chunks. Each choice changes sequence length, vocabulary requirements, and coverage.

Why not whole words? The OOV trade-off

At first glance, splitting text on spaces into whole words (rain, falls, softly) feels intuitive. Natural language, however, has an open, constantly expanding vocabulary:

  1. Out-of-Vocabulary (OOV) failures: Any rare word, technical jargon, typo, new compound word, or code identifier (like tokenCount or deserialize_payload) that didn't appear in a fixed word dictionary can't be represented directly. Without a fallback, the tokenizer replaces it with an unknown token (<UNK>) and loses that word's identity.
  2. Vocabulary memory: A broad word vocabulary can grow to millions of entries. For an illustrative vocabulary with V=1,000,000V = 1{,}000{,}000, hidden dimension d=4096d = 4096, input embeddings WE∈RV×dW_E \in \mathbb{R}^{V \times d}, and an untied output matrix Whead∈RV×dW_{\text{head}} \in \mathbb{R}^{V \times d} in 16-bit precision, the two tables would consume:
Memoryvocab=2×1,000,000×4096×2 bytes≈16.38 GB\text{Memory}_{\text{vocab}} = 2 \times 1,000,000 \times 4096 \times 2\text{ bytes} \approx 16.38\text{ GB}

That is over 16 GB of weight memory before loading a transformer layer, a substantial fixed cost even though the practical limit depends on the hardware and deployment.

Why not raw bytes or characters? The quadratic attention cost

Going to the opposite extreme can solve the OOV problem. A byte-level tokenizer needs only 256 base byte values to represent any UTF-8 string, while a character-level tokenizer needs a defined character inventory or fallback. Either approach keeps the base vocabulary small.

The catch is sequence length (LL). Dense self-attention over a full sequence, as in training or prompt prefill, has a quadratic sequence-length term:

Attention Compute=O(L2⋅d)\text{Attention Compute} = O(L^2 \cdot d)

With a key-value (KV) cache, attending from one newly generated position to LL cached positions instead takes O(L⋅d)O(L \cdot d) attention work. KV storage grows linearly with cached length, with constants set by the number and size of KV heads and the layer count. In the running example below, character tokenization produces 17 positions while the illustrative subword segmentation produces 4. Their conceptual dense score matrices contain 172=28917^2 = 289 and 42=164^2 = 16 cells per head. This 18.1-fold difference isn't an end-to-end speedup; causal masking and implementations that avoid materializing the full matrix also affect actual work and memory.

The subword balance

Subword tokenization usually provides a practical balance:

  • High-frequency strings such as rain and falls can remain single, compact tokens.
  • Rare, technical, or inflected words can decompose into reusable fragments (soft + ly).
  • Vocabulary size stays fixed after training. At fixed hidden size, vocabulary-weight memory grows linearly with VV.
Aligned boundaries over rain falls softly show seventeen character positions, four subword pieces, or three words. Below each strip an attention score grid uses the same cell size: 289, 16, or 9 cells per head. Spaces count as character positions and attach to the following subword. A word absent from a whole-word vocabulary has no row.
The same 17-character sentence uses 4 illustrative subword pieces or 3 words. Its conceptual dense attention grids contain 289, 16, or 9 cells per head. Coverage still depends on the base alphabet and fallback policy.

Measure this sequence-length trade-off on the same sentence:

sentence.txt
rain falls softly
01-count-token-units.py
message = "rain falls softly"

characters = list(message)
words = message.split()
subwords = ["rain", " falls", " soft", "ly"]

print("characters:", len(characters))
print("words:", len(words))
print("candidate subwords:", len(subwords), [piece.replace(" ", "·") for piece in subwords])
assert "".join(subwords) == message
Output
characters: 17
words: 3
candidate subwords: 4 ['rain', '·falls', '·soft', 'ly']

The hand-written segmentation reconstructs this fixture in four positions. A word dictionary missing softly would lose its identity without a fallback. Neither example establishes coverage of arbitrary future text: that requires checking the actual base alphabet and unknown-token policy.

Byte pair encoding: bottom-up frequency merges

Philip Gage originally developed Byte Pair Encoding (BPE) in 1994 as a data compression algorithm that repeatedly replaces the most frequent adjacent pair of bytes with an unused byte symbol.[1] Sennrich, Haddow, and Birch adapted the algorithm to neural machine translation in 2016, establishing the foundation for modern subword modeling.[2]

How BPE training works

BPE training is a greedy, bottom-up algorithm:

  1. Initialize the alphabet: Start with all unique base characters (or bytes) in the training corpus. Every word is represented as a sequence of individual characters.
  2. Count adjacent pairs: Count the occurrences of all adjacent symbol pairs across the corpus, weighted by word frequencies.
  3. Merge the winner: Find the pair with the highest frequency and merge it into a single new vocabulary token.
  4. Append to merge rules: Record the merge rule in an ordered merge table.
  5. Iterate: Repeat until reaching the requested vocabulary size or a stopping condition, such as no remaining eligible pairs.
BPE trains on rain three times, rainy twice, and rail twice. Four successive stages preserve these frequencies. First-seen tie breaking merges r plus a with count seven, ra plus i with count seven, then rai plus n with count five. Weighted token positions fall from thirty to twenty-three, sixteen, and eleven; common-scale bars show that reduction.
On rain ×3, rainy ×2, and rail ×2, the first-seen winner r + a has count 7 and ties a + i. The next selected counts are 7 and 5; recounting after each merge reduces weighted token positions from 30 to 23, 16, and 11.

Tracing this step by step on a small vocabulary:

TermCount
rain3
rainy2
rail2

At initialization, the words are r a i n, r a i n y, and r a i l. Their weighted character count is 4×3+5×2+4×2=304\times3 + 5\times2 + 4\times2 = 30.

The adjacent pairs r + a and a + i each occur seven times after weighting by word frequency. Our classroom trainer breaks ties by first-seen order, so it merges r + a into ra. A production trainer must also specify a deterministic tie policy.

Recount the current pieces. The pair ra + i occurs seven times, so it becomes rai. Recount again: rai + n occurs in rain three times and rainy twice, giving a count of five. That merge creates rain. The weighted token count falls from 30 to 23, then 16, then 11.

This three-merge classroom trainer omits end-of-word markers, special-token assignment, vocabulary export, and a general stopping condition. Sennrich's original word-based formulation includes an end-of-word symbol.[2]

02-train-mini-bpe.py
from collections import Counter

frequencies = {
    "rain": 3,
    "rainy": 2,
    "rail": 2,
}
state = {tuple(word): count for word, count in frequencies.items()}

def count_pairs(words: dict[tuple[str, ...], int]) -> Counter[tuple[str, str]]:
    pairs: Counter[tuple[str, str]] = Counter()
    for pieces, count in words.items():
        for pair in zip(pieces, pieces[1:]):
            pairs[pair] += count
    return pairs

def merge_pair(
    pieces: tuple[str, ...], pair: tuple[str, str]
) -> tuple[str, ...]:
    merged: list[str] = []
    i = 0
    while i < len(pieces):
        if i + 1 < len(pieces) and pieces[i : i + 2] == pair:
            merged.append("".join(pair))
            i += 2
        else:
            merged.append(pieces[i])
            i += 1
    return tuple(merged)

merges: list[tuple[str, str]] = []
for step in range(3):
    pair, count = count_pairs(state).most_common(1)[0]
    state = {merge_pair(pieces, pair): freq for pieces, freq in state.items()}
    merges.append(pair)
    print(step + 1, pair, "->", "".join(pair), "count", count)

print("learned merges:", merges)
Output
1 ('r', 'a') -> ra count 7
2 ('ra', 'i') -> rai count 7
3 ('rai', 'n') -> rain count 5
learned merges: [('r', 'a'), ('ra', 'i'), ('rai', 'n')]

Replaying merges at inference time

Ordinary deterministic BPE encoding uses fixed learned merge ranks, without fitting new rules to each prompt. This lab replays its three rules in order; production implementations can use more efficient rank-based operations. Learning a new vocabulary piece during serving wouldn't create a trained embedding for it.

For our classroom encoder, that means applying the three saved rules in order:

03-replay-bpe-merges.py
def apply_rule(pieces: list[str], pair: tuple[str, str]) -> list[str]:
    result: list[str] = []
    i = 0
    while i < len(pieces):
        if i + 1 < len(pieces) and tuple(pieces[i : i + 2]) == pair:
            result.append("".join(pair))
            i += 2
        else:
            result.append(pieces[i])
            i += 1
    return result

rules = [("r", "a"), ("ra", "i"), ("rai", "n")]

def encode(term: str) -> list[str]:
    pieces = list(term)
    for rule in rules:
        pieces = apply_rule(pieces, rule)
    return pieces

for term in ["rain", "rainy", "rail", "airy"]:
    print(term, "->", encode(term))
Output
rain -> ['rain']
rainy -> ['rain', 'y']
rail -> ['rai', 'l']
airy -> ['a', 'i', 'r', 'y']

The fixed rules encode rain as one piece, rainy as rain plus y, and rail as rai plus l. The unseen word airy uses four characters from this corpus's base alphabet. The encoder doesn't invent a whole-word merge for it.

Token counts aren't generally additive across arbitrary text chunks: a boundary can prevent a learned merge. For exact counts and prompt-cache comparisons, encode the actual serialized input. A streaming tokenizer needs a way to retain or revise an unfinished boundary; concatenating independent chunk encodings doesn't generally reproduce whole-string encoding.

Byte-level BPE and UTF-8 fallbacks

Character BPE with a corpus-derived alphabet can encounter unseen characters. Without an additional fallback, an obscure glyph, emoji, or script may map to <UNK>.

GPT-2 uses byte-level BPE, whose base alphabet covers all 256 byte values.[3] Each Unicode scalar value encodes as one to four UTF-8 bytes, so valid Unicode text is representable without an unknown-character token. An API can still reject reserved special-token text or invalid inputs according to its policy.

Llama 2 uses SentencePiece BPE and decomposes unknown UTF-8 characters into bytes.[4] Llama 3 instead uses a tiktoken-based tokenizer, so the two generations don't share the same tokenizer implementation or pre-tokenization rules.[5][6]

Testing this byte round-trip property on a Japanese string with an emoji:

04-utf8-byte-round-trip.py
message = "関数✨"
byte_ids = list(message.encode("utf-8"))
reconstructed = bytes(byte_ids).decode("utf-8")

print("byte count:", len(byte_ids))
print("first byte ids:", byte_ids[:8])
print("round trip:", reconstructed)
assert reconstructed == message
assert all(0 <= value <= 255 for value in byte_ids)

# A byte token can contain only part of a Unicode character.
decoded_separately = "".join(
    bytes([value]).decode("utf-8", errors="replace") for value in byte_ids
)
print("per-byte decode exact:", decoded_separately == message)
assert decoded_separately != message
Output
byte count: 9
first byte ids: [233, 150, 162, 230, 149, 176, 226, 156]
round trip: 関数✨
per-byte decode exact: False

Joining the bytes before UTF-8 decoding preserves this string. Decoding each byte separately with replacement errors loses it: token boundaries needn't be Unicode character boundaries.[7] Byte fallback guarantees representation rather than compression. A rarely learned script can use several byte tokens per character, increasing sequence length.

Why regex pre-tokenization is critical

Without boundaries, BPE can learn pieces spanning letters, punctuation, or newlines when the training counts favor them. It doesn't necessarily merge every failed., failed!, or failed\n string. GPT-2's authors report vocabulary waste from such variants and constrain merges by character categories, with an exception for spaces.[3]

To control which text spans can participate in merges, many production BPE tokenizers apply a regular expression pre-tokenizer first. GPT-2 and tiktoken-style encodings use patterns that separate categories such as:

  • Contractions ('s, 't, 're, 've, 'm, 'll, 'd)
  • Letter sequences
  • Numeric digits
  • Punctuation marks
  • Whitespace runs

Merges stay within the spans produced by that encoding's regex. Don't generalize the listed categories into a universal punctuation rule: Llama 3's letter branch, for example, allows a preceding character outside its letter/number/newline categories. The exact pattern determines which boundaries exist.[6] Inside a span, frequency still picks the winner. Must that winner be a likely unit, or can two frequent pieces win only because each one is common?

WordPiece: likelihood-driven subword selection

BPE's winner inside those spans is still the most frequent eligible pair. A pair of common pieces can win that count without being a likely unit. WordPiece's published motivation asks about language-model likelihood instead.[8]

Schuster and Nakajima developed WordPiece in 2012 for Japanese and Korean speech recognition, and it later became the tokenizer behind BERT.[9][10]

Likelihood intuition and a teaching proxy

That likelihood target scores statistical prediction; linguistic analysis determines whether two fragments form a meaningful morpheme.

Be careful about implementation claims: Google didn't publish BERT's WordPiece trainer. Hugging Face labels its detailed training reconstruction a best guess from the literature. Its classroom reconstruction ranks eligible pairs using this association-score proxy:[11]

For piece-frequency counts and adjacent-pair counts in the current segmentation:

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

This ratio favors pairs whose components occur together relative to their individual frequencies. It isn't literally pointwise mutual information, which is a logarithm of normalized joint and marginal probabilities. Nor is it a documented exact likelihood-gain formula for every WordPiece trainer. Compare two hypothetical within-word candidates:

Candidate pairPair countIndividual countsProxy scoreInterpretation
rain + ##bow4250 and 440.0191Higher association score
t + ##h90900 and 3000.0003Higher count, lower association score

The proxy selects rain + ##bow despite its lower pair count. A phrase such as the model isn't an eligible within-word merge in BERT's pipeline, so comparing those two whole words would teach the wrong boundary.

Greedy longest-match inference and ## continuations

BERT's full tokenizer cleans text, handles Chinese-character boundaries, splits punctuation and whitespace, and optionally lowercases and strips accents before WordPiece. WordPiece then segments each resulting unit, using ## to mark continuations in BERT's vocabulary.[12] This prefix is a vocabulary convention; it isn't part of the original word.

At inference time, WordPiece matches greedily from left to right using longest-match-first:

The next two functions isolate that search. They don't implement BERT's basic tokenizer or its maximum-word-length limit.

05-wordpiece-longest-match.py
def wordpiece_tokenize(word: str, vocabulary: set[str]) -> list[str]:
    result: list[str] = []
    start = 0
    while start < len(word):
        chosen = None
        for end in range(len(word), start, -1):
            candidate = word[start:end]
            if start > 0:
                candidate = "##" + candidate
            if candidate in vocabulary:
                chosen = candidate
                start = end
                break
        if chosen is None:
            return ["[UNK]"]
        result.append(chosen)
    return result

vocabulary = {"rain", "##bow", "play", "##ing"}
for term in ["rain", "rainbow", "playing"]:
    print(term, "->", wordpiece_tokenize(term, vocabulary))
Output
rain -> ['rain']
rainbow -> ['rain', '##bow']
playing -> ['play', '##ing']

The greedy dead-end failure

Because BERT-style WordPiece matches greedily without backtracking, it has a notable failure mode: if the longest valid prefix leads to a dead end where no continuation token can finish the word, the tokenizer rejects the entire word and emits [UNK]. It won't backtrack to try a shorter initial match, even if a valid full decomposition exists.[12]

06-wordpiece-unknown-token.py
def encode_word(word: str, vocabulary: set[str]) -> list[str]:
    pieces: list[str] = []
    cursor = 0
    while cursor < len(word):
        match = None
        for end in range(len(word), cursor, -1):
            candidate = word[cursor:end]
            if cursor:
                candidate = "##" + candidate
            if candidate in vocabulary:
                match = candidate
                cursor = end
                break
        if match is None:
            return ["[UNK]"]
        pieces.append(match)
    return pieces

vocabulary = {"rain", "##bow", "play"}
known = encode_word("rainbow", vocabulary)
missing = encode_word("raincoat", vocabulary)

print("known term:", known)
print("missing continuation:", missing)
assert known == ["rain", "##bow"]
assert missing == ["[UNK]"]

# A complete alternative path exists, but greedy matching won't find it.
greedy_trap = {"rainb", "rain", "##bow"}
print("greedy dead end:", encode_word("rainbow", greedy_trap))
assert "rain" + "bow" == "rainbow"
assert encode_word("rainbow", greedy_trap) == ["[UNK]"]
Output
known term: ['rain', '##bow']
missing continuation: ['[UNK]']
greedy dead end: ['[UNK]']

In greedy_trap, rain + ##bow could segment rainbow completely. But WordPiece greedily consumes rainb, finds no continuation for ow, and collapses the whole word to [UNK]. The trap still starts from a word that whitespace already isolated. Text without those gaps needs a different cut.

The fixed WordPiece vocabulary has rainb, rain, and continuation piece ##bow. Greedy search takes rainb from rainbow and fails on missing ##ow, so the whole word becomes [UNK]. A second aligned lane shows the valid rain plus ##bow segmentation, which the greedy algorithm never tries.
For this fixed vocabulary, greedy WordPiece chooses rainb and gets stuck. It returns [UNK] for the entire word, even though rain plus ##bow could spell rainbow. That shorter path is not explored.

SentencePiece and the Unigram language model

Many BPE and WordPiece pipelines apply whitespace splitting or a language-specific segmenter before learning subwords. A naive whitespace boundary is a poor fit for languages that don't delimit every word with spaces, such as Japanese, Chinese, and Thai. SentencePiece instead trains from raw sentences and packages normalization with the model.

Kudo and Richardson's SentencePiece toolkit learns from raw sentences without requiring an external word segmenter.[13] Its default trainer still restricts pieces from crossing whitespace, script, and number boundaries.[14]

Raw stream processing and reversible whitespace detokenization

SentencePiece treats input text as a continuous raw stream of Unicode characters. It introduces two major innovations:

  1. Explicit whitespace character: Spaces in the normalized stream become ▁ (U+2581 Lower One Eighth Block). The default dummy-prefix option also adds an initial marker, so rain falls becomes ▁rain▁falls even without a raw leading space.
  2. Reversible whitespace encoding: After normalization, spaces remain explicit in the token stream, so decoding the normalized text is straightforward:
decode-normalized-text.py
decoded = "".join(tokens).removeprefix("▁").replace("▁", " ")

Explicit markers preserve spaces in the normalized stream. This string-join expression illustrates ordinary pieces with the default leading-space convention. Use the actual decoder for model-specific special tokens, byte pieces, and whitespace options. Recovery of normalized text requires that no content was collapsed into an unknown ID. A model without byte fallback can lose unseen characters, and normalization can remove distinctions before segmentation.[14]

The Unigram LM: top-down loss-minimizing pruning

SentencePiece can train BPE models and also implements the Unigram Language Model described by Kudo (2018a).[8]

Unlike BPE and WordPiece (which build vocabulary bottom-up by iteratively merging characters), Unigram operates top-down:

  1. Initialize an oversized seed vocabulary: Start with required individual characters plus frequent substrings extracted from the corpus, producing more candidates than the target vocabulary needs.
  2. Estimate piece probabilities: Use Expectation-Maximization (EM) to fit the candidate-token probabilities P(x)P(x) toward higher corpus log-likelihood. The result depends on initialization and candidate constraints:
L=∑s∈corpuslog⁡(∑x∈S(s)∏xi∈xP(xi))\mathcal{L} = \sum_{s \in \text{corpus}} \log \left( \sum_{\mathbf{x} \in \mathcal{S}(s)} \prod_{x_i \in \mathbf{x}} P(x_i) \right)

where S(s)\mathcal{S}(s) is the set of all valid segmentations of sentence ss. 3. Estimate pruning loss: Rank candidate pieces by the estimated likelihood reduction from removal. This pruning approximation avoids solving the intractable joint vocabulary/probability optimization exactly. 4. Remove a fraction of low-loss pieces: The paper illustrates keeping 80%. Retain required single-character pieces, which protect coverage of the selected character alphabet, not every future Unicode character. 5. Iterate: Recompute probabilities and repeat until reaching the target vocabulary size VV.

Viterbi decoding on candidate lattices

At inference time, an input string can be segmented across dozens of candidate boundaries. Unigram evaluates complete paths by joint probability:

arg⁡max⁡x∈S(s)∏i=1MP(xi)=arg⁡max⁡x∈S(s)∑i=1Mlog⁡P(xi)\arg\max_{\mathbf{x} \in \mathcal{S}(s)} \prod_{i=1}^{M} P(x_i) = \arg\max_{\mathbf{x} \in \mathcal{S}(s)} \sum_{i=1}^{M} \log P(x_i)

The Viterbi algorithm uses dynamic programming to find the optimal global segmentation without enumerating all combinatorial paths.

A lattice over normalized ▁rain shows three complete segmentations. The whole piece scores 0.30; ▁ then rain scores 0.15 times 0.10, or 0.015; ▁ then ra then in scores 0.15 times 0.02 times 0.03, or 0.00009. Negative log costs share one linear bar scale at 1.204, 4.200, and 9.316. Viterbi selects the whole piece, which has the lowest negative log cost.
The three legal paths for ▁rain have probabilities 0.30, 0.015, and 0.00009. The bars show negative log costs, so Viterbi selects the shortest bar and largest complete-path probability. The vocabulary assigns another 0.40 probability mass to pieces that cannot segment this input; optional training-time sampling can expose other legal paths.

Subword regularization: training with segmentation noise

Unigram also supports subword regularization.[8] During model training, instead of always taking the deterministic 1-best Viterbi path, SentencePiece can sample segmentations from the posterior distribution:

qα(x∣s)∝∏i=1MP(xi)α,x∈S(s)q_\alpha(\mathbf{x} \mid s) \propto \prod_{i=1}^{M} P(x_i)^\alpha, \qquad \mathbf{x} \in \mathcal{S}(s)

where α\alpha controls the sampling distribution. A model might see ['▁rain'] in one epoch and ['▁', 'rain'] in the next. This acts as data augmentation over valid segmentations and can make training less sensitive to which valid segmentation appears.

The sampling distribution qαq_\alpha is normalized over legal paths for this fixed input. Smaller positive α\alpha flattens it; larger values concentrate it toward the best path. The original paper studies neural machine translation training. Sampling is an option for model training, not something every pretrained SentencePiece-based LLM used. For reproducible serving, use the checkpoint's intended encoding mode.

Here's a miniature Viterbi decoder with hand-assigned piece probabilities. The single natural word rain gets an illustrative leading space marker. This isolates path selection; it isn't a SentencePiece normalizer or trainer. The vocabulary probabilities sum to one, including 0.40 on sun and cloud, which cannot segment this input.

07-unigram-viterbi.py
from math import inf, isclose, log

probabilities = {
    "▁rain": 0.30,
    "▁": 0.15,
    "rain": 0.10,
    "ra": 0.02,
    "in": 0.03,
    "sun": 0.20,
    "cloud": 0.20,
}
assert isclose(sum(probabilities.values()), 1.0)
logp = {piece: log(probability) for piece, probability in probabilities.items()}

def viterbi_segment(text: str, scores: dict[str, float]) -> list[str]:
    n = len(text)
    if "" in scores:
        raise ValueError("empty pieces are not supported")
    if not text:
        return []
    if not scores:
        raise ValueError("no legal segmentation")
    best = [(0.0, -1, "")] + [(-inf, -1, "")] * n
    max_len = max(map(len, scores))
    for start in range(n):
        if best[start][0] == -inf:
            continue
        for end in range(start + 1, min(n, start + max_len) + 1):
            piece = text[start:end]
            if piece not in scores:
                continue
            score = best[start][0] + scores[piece]
            if score > best[end][0]:
                best[end] = (score, start, piece)
    if best[n][0] == -inf:
        raise ValueError("no legal segmentation")
    pieces: list[str] = []
    cursor = n
    while cursor > 0:
        _, prev, piece = best[cursor]
        pieces.append(piece)
        cursor = prev
    pieces.reverse()
    return pieces

raw_message = "rain"
marked = "▁" + raw_message
pieces = viterbi_segment(marked, logp)
decoded = "".join(pieces).removeprefix("▁").replace("▁", " ")

print("raw:", raw_message)
print("normalized marker fixture:", marked)
print("pieces:", pieces)
print("decoded:", decoded)
assert marked == "▁rain"
assert pieces == ["▁rain"]
assert decoded == raw_message
Output
raw: rain
normalized marker fixture: ▁rain
pieces: ['▁rain']
decoded: rain

▁rain stays whole because its log-probability (−1.204-1.204) beats ▁ plus rain (−1.897+−2.303=−4.200-1.897 + -2.303 = -4.200). The three-piece route ▁ + ra + in scores 0.15×0.02×0.03=0.000090.15 \times 0.02 \times 0.03 = 0.00009, or −9.316-9.316 in natural log space. This is global path scoring, not a rule that always chooses the longest piece. Each vocabulary piece also costs an embedding row, and an output row when those weights are untied.

Vocabulary economics: parameter memory vs context efficiency

When designing a tokenizer, how big should VV be? Historical checkpoints illustrate different choices: GPT-2 uses 50,257 IDs; Llama 2 uses 32,000.[3][4] Llama 3's report describes 128K pieces, and its original implementation adds 256 reserved special-token IDs. Gemma 2's report describes 256K entries.[5][6][15] Inspect the actual vocabulary and weight shapes, including special IDs and padding, for an exact memory budget.

Every additional vocabulary token represents a trade-off between weight memory and sequence length.

Calculating the parameter memory bill

For hidden dimension dmodeld_{\text{model}}, the input embedding table WE∈RV×dmodelW_E \in \mathbb{R}^{V \times d_{\text{model}}} stores V×dmodelV \times d_{\text{model}} parameters. If the final output projection matrix (WheadW_{\text{head}}) is untied (not sharing weights with WEW_E), it stores another V×dmodelV \times d_{\text{model}} parameters:

Memoryvocab=2×V×dmodel×bytes per parameter\text{Memory}_{\text{vocab}} = 2 \times V \times d_{\text{model}} \times \text{bytes per parameter}
For hidden size 4096 and two untied 16-bit tables, 8,000, 32,000, and 128,000 vocabulary rows cost 125, 500, and 2,000 MiB. Every bar splits equally between input and output tables on one scale. For fixed English text, reported 3.17 versus 3.94 characters per token implies 80.5 percent as many token/KV positions and 64.7 percent as many dense attention score cells; a second common-scale chart shows those ratios.
The hypothetical untied FP16 budget uses two tables at hidden size 4096: 125, 500, and 2,000 MiB for 8k, 32k, and 128k rows. Separately, the Llama 3 report compares its tokenizer with Llama 2 on an English sample. Those rates imply 19.5% fewer token/KV positions and 35.3% fewer dense score cells for fixed text, without establishing a total speedup.[5]

Computing the exact memory footprint across vocabulary sizes:

08-vocabulary-memory-budget.py
def embedding_memory_mib(
    vocabulary_size: int, hidden_size: int, bytes_per_weight: int = 2
) -> float:
    return vocabulary_size * hidden_size * bytes_per_weight / (1024**2)

hidden_size = 4096
for vocabulary_size in [8_000, 32_000, 128_000]:
    input_mib = embedding_memory_mib(vocabulary_size, hidden_size)
    untied_mib = 2 * input_mib
    print(
        f"{vocabulary_size:>6,} tokens:",
        f"input={input_mib:>7.1f} MiB",
        f"input+untied-output={untied_mib:>7.1f} MiB",
    )
Output
 8,000 tokens: input=   62.5 MiB input+untied-output=  125.0 MiB
32,000 tokens: input=  250.0 MiB input+untied-output=  500.0 MiB
128,000 tokens: input= 1000.0 MiB input+untied-output= 2000.0 MiB

The sequence compression payoff

The illustrative untied 128,000-row budget above is 2,000 MiB, or 1.953 GiB. A larger, appropriately trained vocabulary can shorten sequences; measure compressed lengths on your corpus to see whether that trade improves compression:

  1. Sequence and attention savings: Llama 3's report measures 3.17 versus 3.94 characters per token on a sample of English data.[5] Treating those reported rates as representative of fixed text gives 1−3.17/3.94≈19.5%1 - 3.17 / 3.94 \approx 19.5\% fewer positions and 1−(3.17/3.94)2≈35.3%1 - (3.17 / 3.94)^2 \approx 35.3\% fewer conceptual dense attention score cells. That comparison covers two whole tokenizers, including different pre-tokenization, so it doesn't isolate the effect of adding rows. The report also says its 28K added non-English tokens had no impact on English tokenization. These ratios estimate potential reductions for similar text. Measure token counts and end-to-end speed on target requests to quantify the savings.
  2. KV cache savings: Holding model architecture and text fixed, 19.5% fewer token positions means 19.5% fewer key and value positions stored for that request.
  3. Context capacity: At the reported compression rates, a fixed token window holds about 3.94/3.17≈1.2433.94 / 3.17 \approx 1.243 times as many characters from the same content distribution. Word counts vary by language and corpus, so character compression shouldn't be converted into a universal words-per-window claim.

Modern tokenizer failure modes in production

Check the serialized token IDs before concluding what code the model saw. Fragmentation can also arise from the checkpoint's tokenizer, so inspect these four cases before attributing unexpected behavior to the weights.

1. Multilingual token inflation ("The fertility tax")

Fertility measures how many tokens a tokenizer requires per word or another chosen text unit. The value depends on both the tokenizer and the evaluation corpus, so comparisons should use parallel content and a consistent unit.

Tokenizers can use far more tokens for some languages than for English. Across parallel FLORES-200 translations, Petrov et al. measured a 15.05-fold token premium for Shan with the cl100k_base tokenizer used by ChatGPT and GPT-4 at the time.[16] This compares translations with the same underlying content, not identical text. Shan is the widest gap the paper reports for this tokenizer; Italian needs about 1.6 times as many tokens as English.

This creates three measurable risks:

  • Billing: Token-metered input charges scale with token count, although the monetary ratio depends on the provider's pricing policy.
  • Context capacity: A higher token ratio leaves proportionally less room for comparable content in a fixed token window.
  • Latency: Longer token sequences increase prefill work, and fragmented outputs can require more autoregressive decoding steps. Petrov et al. observed up to roughly twice the processing time for some languages; measure latency on the target model and runtime.[16]

Meta's Llama 3 combines the 100K-token tiktoken vocabulary with 28K additional tokens from selected non-English languages. The report describes improved compression and downstream performance for those languages.[5]

2. Arithmetic and numeric pre-tokenization

Tokenization is one factor that can make multi-digit arithmetic harder. It determines whether digit positions are exposed consistently or hidden inside variable-length pieces, but training data, model capacity, and learned algorithms matter too.

In byte-level BPE tokenizers such as GPT-2's, numeric substrings can be merged into pieces according to learned merge ranks. Similar-looking numbers can therefore receive different boundaries.

Llama 2 chose a different policy and split numbers into individual digits.[4] Llama 3 doesn't preserve every digit separately. Its official tokenizer uses the regex span \p{N}{1,3}, which groups one to three numeric characters before BPE.[6]

Single-digit spans expose each column explicitly, while bounded multi-digit spans limit how much numeric text enters one pre-tokenization chunk. Neither policy guarantees arithmetic correctness. Audit the exact regex and resulting token boundaries instead of assuming all modern tokenizers use the same rule.

3. Code indentation and whitespace handling

In languages such as Python, indentation changes program structure. Four levels of four-space indentation use 16 leading spaces on the deepest line. An encoding with only single-space pieces would spend 16 tokens on that run; other lines can have different indentation depths.

Code-aware tokenizers can learn pieces for multi-space runs. In a concrete example, representing 16 leading spaces as four 4-space pieces reduces indentation from 16 tokens to 4, a 75% reduction for that run. Actual savings depend on the tokenizer vocabulary and the code sample, and a real encoder can do better still: cl100k_base encodes 16 leading spaces as one token (checked November 2026).

Exact casing can change which learned pieces match. Our mini-BPE below produces these boundaries:

  • tokenCount →\to ['token', 'C', 'o', 'un', 't'] (5 tokens!)
  • encodePrompt →\to ['encode', 'P', 'rompt'] (3 tokens here)

Its corpus includes some code, but the limited merge budget doesn't learn whole Count or Prompt pieces. These counts aren't predictions for Llama, GPT, or another checkpoint's tokenizer. On cl100k_base, for example, tokenCount is two tokens.

4. Glitch tokens and under-trained vocabulary entries

Researchers have documented glitch tokens, vocabulary entries such as SolidGoldMagikarp that can trigger anomalous model behavior.[7]

The conclusion the measurements support is narrower than a single causal story. Tokenizer construction and neural model training use different objectives and may use different corpora. A token can enter the vocabulary yet be nearly or entirely absent during model training, leaving it under-trained. Weight-based signatures depend on the architecture: tied and untied input and output embeddings don't receive identical updates. Corpus counts, vector norms, and prompt behavior can help identify candidates, but they don't prove that a particular token received exactly zero gradients or that attention logits saturated.[7]

Testing these multilingual and camelCase behaviors on a trained mini-BPE:

09-audit-token-lengths.py
from collections import Counter
import re

PRETOK = re.compile(r"[^\W\d_]+|\d+|\s+|[^\s]")

def utf8_pieces(text: str) -> tuple[str, ...]:
    return tuple(bytes([b]).decode("latin-1") for b in text.encode("utf-8"))

def pretok(text: str) -> list[str]:
    return PRETOK.findall(text)

def count_pairs(words: dict[tuple[str, ...], int]) -> Counter[tuple[str, str]]:
    pairs: Counter[tuple[str, str]] = Counter()
    for pieces, count in words.items():
        for pair in zip(pieces, pieces[1:]):
            pairs[pair] += count
    return pairs

def merge_pair(pieces: tuple[str, ...], pair: tuple[str, str]) -> tuple[str, ...]:
    merged: list[str] = []
    i = 0
    while i < len(pieces):
        if i + 1 < len(pieces) and pieces[i : i + 2] == pair:
            merged.append(pieces[i] + pieces[i + 1])
            i += 2
        else:
            merged.append(pieces[i])
            i += 1
    return tuple(merged)

def encode(text: str, merges: list[tuple[str, str]]) -> list[str]:
    output: list[str] = []
    for span in pretok(text):
        pieces = list(utf8_pieces(span))
        for pair in merges:
            pieces = list(merge_pair(tuple(pieces), pair))
        output.extend(pieces)
    return output

def visible(pieces: list[str]) -> list[str]:
    shown: list[str] = []
    for piece in pieces:
        raw = piece.encode("latin-1")
        try:
            shown.append(raw.decode("ascii").replace(" ", "·"))
        except UnicodeDecodeError:
            shown.append("<byte>")
    return shown

corpus = {
    "const tokenCount = encodePrompt(prompt).length;": 3,
    "How do I tokenize this prompt?": 5,
    "prompt cache failed unexpectedly": 4,
    "token budget pending": 3,
    "encode the prompt cache": 3,
    "failed unexpectedly": 2,
}
state: dict[tuple[str, ...], int] = Counter()
for text, count in corpus.items():
    for span in pretok(text):
        state[utf8_pieces(span)] += count

merges: list[tuple[str, str]] = []
for _ in range(25):
    pair, _count = count_pairs(state).most_common(1)[0]
    state = {merge_pair(pieces, pair): freq for pieces, freq in state.items()}
    merges.append(pair)

fixtures = {
    "english": "How do I tokenize this prompt?",
    "portuguese": "Como tokenizo este prompt?",
    "japanese": "このプロンプトをトークン化するには?",
    "typescript": "const tokenCount = encodePrompt(prompt).length;",
}

english_tokens = len(encode(fixtures["english"], merges))
for name, text in fixtures.items():
    pieces = encode(text, merges)
    print(f"{name:>10}: {len(pieces):>2} tokens {len(pieces) / english_tokens:>4.2f}x english")
    assert "".join(pieces).encode("latin-1").decode("utf-8") == text

typescript = encode(fixtures["typescript"], merges)
print("typescript pieces:", visible(typescript))
assert [len(encode(text, merges)) for text in fixtures.values()] == [20, 17, 54, 25]
assert visible(typescript) == [
    "co", "n", "s", "t", "·", "token", "C", "o", "un", "t",
    "·", "=", "·", "encode", "P", "rompt", "(", "prompt", ")",
    ".", "l", "en", "g", "th", ";",
]
Output
   english: 20 tokens 1.00x english
portuguese: 17 tokens 0.85x english
  japanese: 54 tokens 2.70x english
typescript: 25 tokens 1.25x english
typescript pieces: ['co', 'n', 's', 't', '·', 'token', 'C', 'o', 'un', 't', '·', '=', '·', 'encode', 'P', 'rompt', '(', 'prompt', ')', '.', 'l', 'en', 'g', 'th', ';']

The regex is a classroom approximation using Unicode word characters, decimal digits, whitespace, and remaining characters. Unlike an ASCII-only letter branch, it keeps this Japanese sentence's letter sequences together. It isn't GPT-2's or Llama 3's exact pattern. The fixture audit shows:

  • Portuguese reuses token in tokenizo, keeping token count low (0.85x).
  • Japanese has no learned merges in this ASCII-centric corpus and uses 54 raw byte tokens (2.70x the English fixture).
  • tokenCount uses ['token', 'C', 'o', 'un', 't']; this limited vocabulary has no piece spanning the uppercase suffix.

These ratios cover token counts for four authored strings. They give no multilingual or per-word fertility estimate. The English string is also in the tokenizer's training corpus. Evaluate the real checkpoint on separate, representative parallel content before making deployment or billing claims; message formatting and special-token overhead can add tokens beyond raw text.

Unicode normalization policies: NFC vs NFKC

Two text strings can look identical on screen while holding completely different Unicode code points.

For example, café can be written as:

  • Composed form: c + a + f + é (\u00E9, single code point).
  • Decomposed form: c + a + f + e + ◌́ (\u0065\u0301, letter e plus combining acute accent).

If the configured tokenizer doesn't unify those forms, visually similar requests can produce different IDs and miss an exact-prefix cache match. If its normalizer already unifies them, they can encode identically. Cache results also depend on the full request prefix and the serving system's policy.

Composed café has four code points and five UTF-8 bytes. Decomposed cafe plus combining U+0301 has five points and six bytes. NFC and NFKC map both to the same four code points. The file ligature input has three code points and five bytes, remains unchanged under NFC, and becomes four letters under NFKC. Each cell is one code point.
NFC unifies the two café forms while preserving the fi ligature. NFKC also folds file into file. Code points, UTF-8 bytes, and tokenizer pieces are separate units; the SentencePiece space marker is not a raw U+0020 space byte.

Unicode defines four normalization forms: NFD, NFC, NFKD, and NFKC. Here we compare the two composition forms:[17]

  • NFC (Normalization Form C): Canonical decomposition followed by canonical composition where allowed. Some combining sequences have no precomposed equivalent. NFC preserves compatibility distinctions such as fi versus fi.
  • NFKC (Normalization Form Compatibility Composition): Compatibility decomposition followed by canonical composition where allowed. The ligature fi (U+FB01) becomes f + i, full-width Latin letters and digits become ASCII, and superscript digits become standard digits.

SentencePiece's current default is nmt_nfkc, a variant with additional whitespace handling; its implementation doesn't perform every part of standard Unicode NFKC. The model can specify another rule, including identity. Default whitespace options remove leading, trailing, and repeated spaces.[18][14] That matters for code and exact identifiers: don't substitute Python NFKC or assume every SentencePiece checkpoint uses the default.

Testing standard NFC and NFKC in Python makes their differences concrete:

10-normalize-before-tokenizing.py
import unicodedata

composed = "café"
decomposed = "cafe\u0301"
ligature = "file"

print("raw cafe equal:", composed == decomposed)
print("NFC cafe equal:", unicodedata.normalize("NFC", composed) == unicodedata.normalize("NFC", decomposed))
print("NFC ligature:", unicodedata.normalize("NFC", ligature))
print("NFKC ligature:", unicodedata.normalize("NFKC", ligature))

assert composed != decomposed
assert unicodedata.normalize("NFC", composed) == unicodedata.normalize("NFC", decomposed)
assert unicodedata.normalize("NFC", ligature) != "file"
assert unicodedata.normalize("NFKC", ligature) == "file"
Output
raw cafe equal: False
NFC cafe equal: True
NFC ligature: file
NFKC ligature: file

Use the normalizer bundled with the checkpoint consistently. Adding external normalization can change training-time distinctions, and applying it before every request isn't automatically beneficial. Neither NFC nor NFKC is a general visual-lookalike detector or a complete text-safety policy.

A tokenizer stays with its checkpoint

Training, inference, whitespace, and fallback do not travel as one package. A swap can keep the algorithm name and still point IDs at the wrong rows:

AlgorithmTraining ApproachInference MechanismWhitespace HandlingCoverage / Fallback
BPEBottom-up frequency mergingOrdered merge list replayRegex pre-tokenization (e.g. GPT-2/4)Byte-level BPE (BBPE) achieves 100% UTF-8 coverage with zero <UNK>
WordPieceLikelihood-motivated vocabulary growth; exact trainer mattersBERT-style greedy longest match using a fixed vocabularyBERT basic tokenizer handles spaces, punctuation, and configured normalization[UNK] for failed segmentation or a configured length limit
SentencePiece BPEBottom-up frequency mergingReplays packaged .modelReplaces whitespace with ▁ (U+2581)Configured character coverage with optional byte fallback or <unk>
SentencePiece UnigramProbability fitting by EM and approximate vocabulary pruningBest-path Viterbi, or optional segmentation samplingExplicit ▁ with configured whitespace normalizationSelected character alphabet; optional byte fallback or <unk>

Why a tokenizer swap can miss the learned rows

A checkpoint stores learned vectors and projections; the tokenizer bundle supplies the mapping between pieces and IDs:

  • Input embedding lookup selects row ii from WE∈RV×dmodelW_E \in \mathbb{R}^{V \times d_{\text{model}}}.
  • The final LM head computes dot products against row ii of Whead∈RV×dmodelW_{\text{head}} \in \mathbb{R}^{V \times d_{\text{model}}}.

Equal vocabulary size doesn't preserve token meanings. An incompatible replacement can severely degrade a model, but not every file change produces gibberish, and full retraining isn't the only possible adaptation. A pure bijective ID renaming can preserve behavior if all vocabulary-indexed weights, special IDs, and associated state are remapped consistently. New segmentation or new pieces generally require model adaptation and evaluation.

Try the simplest case: keep the pieces, reorder their IDs, and observe what happens if the table stays put.

11-remap-token-rows.py
ids_a = {"prompt": 0, "cache": 1, "failed": 2}
ids_b = {"failed": 0, "prompt": 1, "cache": 2}
rows_a = [(1.0, 0.0), (0.0, 1.0), (-1.0, -1.0)]
message = ["prompt", "cache"]

expected = [rows_a[ids_a[piece]] for piece in message]
wrong = [rows_a[ids_b[piece]] for piece in message]
rows_b = [None] * len(rows_a)
for piece, new_id in ids_b.items():
    rows_b[new_id] = rows_a[ids_a[piece]]
remapped = [rows_b[ids_b[piece]] for piece in message]

# Assume a tied input/output table and a supplied final hidden vector.
hidden = (0.8, 0.2)
def piece_logits(ids, rows):
    return {
        piece: sum(h * w for h, w in zip(hidden, rows[ids[piece]]))
        for piece in ids
    }

print("original vectors:", expected)
print("new IDs, old table:", wrong)
print("new IDs, remapped table:", remapped)
print("piece logits preserved:", piece_logits(ids_a, rows_a) == piece_logits(ids_b, rows_b))
assert wrong != expected
assert remapped == expected
assert piece_logits(ids_a, rows_a) == piece_logits(ids_b, rows_b)
Output
original vectors: [(1.0, 0.0), (0.0, 1.0)]
new IDs, old table: [(0.0, 1.0), (-1.0, -1.0)]
new IDs, remapped table: [(1.0, 0.0), (0.0, 1.0)]
piece logits preserved: True

The equality applies to piece-associated logits under this supplied hidden vector. No transformer is run here. For an untied model, both input and output tables need the same ID remapping; output biases and other indexed state, if present, also matter. This exercise doesn't license replacing an existing checkpoint's tokenizer with one that splits text differently.

Production review checklist

Observed symptomPossible tokenization causeCompatible verification or response
Model outputs complete gibberish after deploying a new tokenizerToken IDs select incompatible rows in WEW_ETest known text-to-ID/decoding fixtures; pin the verified tokenizer and checkpoint together by artifact hashes
API billing is unexpectedly higher for some languagesHigh token-count ratio on parallel contentAudit fertility across target languages and representative corpora
Model repeatedly fails simple multi-digit arithmeticNumeric token boundaries may obscure digit positionsInspect the exact pre-tokenizer regex and tokenization of arithmetic fixtures
Code context window exhausts much faster than expectedWhitespace or identifier fragmentationMeasure the checkpoint's actual encoding; select relevant code context or choose a compatible model trained for the workload
Prompt cache hit rate differs across request pathsUnicode normalization mismatch or bypassCompare the full serialized prefix and IDs; use the checkpoint's configured preprocessing and the serving system's cache contract
Model behaves anomalously on specific vocabulary entriesPossible under-trained tokens such as SolidGoldMagikarpCombine corpus-frequency, weight-based, and prompt-behavior audits

Bundle the chat template and special-token policy with the tokenizer too. Correct piece IDs don't help if one path inserts different role delimiters, beginning/end markers, padding, or truncation. Keep ordinary user text distinct from trusted control-token insertion.

Replay a merge, catch a greedy dead end, and reject a swap that matches only on vocabulary size.

Check the tokenizer contract

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.A migration swaps two token IDs: rain changes from 5 to 7, and falls changes from 7 to 5. The model's output head is untied from its input embeddings. The team swaps rows 5 and 7 in the input table but leaves the output head unchanged. With greedy decoding, at the first step where the old system would emit falls, what does the new system emit?
2.A BPE tokenizer has three merge rules, applied in this order: (a, i), then (r, a), then (ai, n). How does it encode rain?
3.A byte-level BPE tokenizer has learned no merges that apply to the string aé✨🙂. These four characters use 1, 2, 3, and 4 UTF-8 bytes. How many tokens does it produce, and are any of them unknown tokens?
4.A team is designing the normalizer for a new tokenizer. Composed café (é as U+00E9) and decomposed café (e plus U+0301) must become the same text, so exact-prefix caching treats them alike. The word file, written with the fi ligature (U+FB01), must stay different from file, because the two can be different identifiers. Which normalization form meets both needs?
5.BERT-style WordPiece encodes rainbow using only the vocabulary {'rainb', 'rain', '##bow'}. What happens?
6.In a SentencePiece Unigram model, ▁ marks a space. The vocabulary includes ▁rain (0.02), ▁ (0.15), rain (0.20), ▁ra (0.40), and in (0.01). The only complete paths for ▁rain are ▁rain, ▁ + rain, and ▁ra + in. Which path does deterministic encoding choose, and why?
7.A SentencePiece model uses default whitespace cleanup and has no byte fallback, and ✨ never appeared in its training data. It encodes text that contains a double space and ✨. ▁ marks each space that the model sees. What does decoding return?
8.A tokenizer proposal raises the vocabulary from 32,000 to 128,000 for a model with hidden size 4096, FP16 weights, and an untied output head. On a representative corpus, the average rises from 3 to 4 characters per token. How much do the vocabulary weights grow, and how many fewer token positions does the same text need?
9.BPE training starts from single characters on these words and frequencies: low x3, lot x2, not x1, note x1. After the first merge is applied, which pair is merged next, and what is its count?
10.A team plans to replace a checkpoint's tokenizer A with tokenizer B. Which check directly tests whether each piece of text still selects the embedding row the model learned for it?

10 questions remaining.

References

A New Algorithm for Data Compression.

Gage, P. · 1994

https://dl.acm.org/doi/10.5555/177910.177914

Neural Machine Translation of Rare Words with Subword Units.

Sennrich, R., Haddow, B., & Birch, A. · 2016 · ACL 2016

https://arxiv.org/abs/1508.07909

Language Models are Unsupervised Multitask Learners.

Radford, A., et al. · 2019

https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf

Llama 2: Open Foundation and Fine-Tuned Chat Models.

Touvron, H., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2307.09288

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

Llama 3 Tokenizer Implementation

Meta · 2024 · Official source code

https://github.com/meta-llama/llama3/blob/main/llama/tokenizer.py

Fishing for Magikarp: Automatically Detecting Under-trained Tokens in Large Language Models

Land, S. & Bartolo, M. · 2024 · arXiv preprint

https://arxiv.org/abs/2405.05417

Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates.

Kudo, T. · 2018 · ACL 2018

https://arxiv.org/abs/1804.10959

Japanese and Korean Voice Search.

Schuster, M. & Nakajima, K. · 2012

https://research.google/pubs/japanese-and-korean-voice-search/

BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.

Devlin, J., et al. · 2019 · NAACL 2019

https://arxiv.org/abs/1810.04805

WordPiece tokenization: training reconstruction and greedy encoding

Hugging Face · 2026

https://huggingface.co/learn/llm-course/en/chapter6/6

BERT Tokenization Implementation

Google Research · 2026

https://github.com/google-research/bert/blob/master/tokenization.py

SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing.

Kudo, T. & Richardson, J. · 2018 · EMNLP 2018

https://arxiv.org/abs/1808.06226

SentencePiece model specification: coverage, segmentation, and normalization options

Google · 2026

https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto

Gemma 2: Improving Open Language Models at a Practical Size

Gemma Team, Google DeepMind · 2024

https://storage.googleapis.com/deepmind-media/gemma/gemma-2-report.pdf

Language Model Tokenizers Introduce Unfairness Between Languages.

Petrov, A., La Malfa, E., Torr, P. H. S., & Bibi, A. · 2023 · NeurIPS 2023

https://arxiv.org/abs/2305.15425

Unicode Standard Annex 15: Unicode Normalization Forms

Unicode Consortium · 2026

https://unicode.org/reports/tr15/

Text Normalization in SentencePiece

Google · 2026

https://github.com/google/sentencepiece/blob/master/doc/normalization.md

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.