Skip to content
wordpiece.org

Greedy WordPiece versus the shortest possible segmentation

Construct a vocabulary-search experiment that compares greedy output with dynamic programming on one pinned BERT vocabulary; explain why the deployed tokenizer must be treated as the oracle

Published 8 min read Verified

Greedy WordPiece and a minimum-token dynamic program answer different questions: greedy consumes the longest vocabulary match at the current position, while dynamic programming minimizes the number of pieces across the whole remaining string. A locally longest match can leave a suffix that requires several pieces even though another first piece would permit a shorter segmentation. The engineering problem here is therefore to construct a reproducible counterexample from one pinned vocabulary and then confirm the actual greedy result through the deployed tokenizer—not to replace that tokenizer with a textbook implementation.

Verified: 2026-10-05 against the supplied primary artifacts. Every behavioral statement and count below applies only to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594, loaded with transformers==4.56.2 through AutoTokenizer, revision=FULL_COMMIT, and use_fast=True. The pinned tokenizer.json is the authority for this model’s vocabulary and tokenizer settings; no other checkpoint, revision, or dependency set is in scope.

Define the comparison at the tokenizer boundary

The comparison must happen after the tokenizer’s normalizer and pre-tokenizer have divided the text. In BERT, each resulting word is processed independently. At its first position, a valid piece has no ## prefix; every later piece must use a continuation token such as ##ing. The greedy implementation selects the longest matching entry at each cursor and advances. If it cannot represent the word, its fallback is the unknown token.

The experiment avoids those complications only where it can prove they are absent. Its generated surfaces contain lowercase ASCII letters and no whitespace or punctuation. The final offset-mapping assertion then confirms that all accepted pieces cover one contiguous input span. A hand-written dynamic program can consequently search over one pre-tokenized word while the fast tokenizer remains responsible for normalization, pre-tokenization, WordPiece behavior, and special tokens.

For a string (s), the dynamic program uses:

[ D[n]=0,\qquad D[i]=1+\min_{p}D[i+|p|] ]

where (p) ranges over ordinary vocabulary pieces when (i=0), and over ## continuation pieces otherwise. Reconstructing the chosen edges produces a minimum-content-token segmentation. “Minimum” describes token count only; several different segmentations can tie, and the code chooses one deterministically.

Search for a witness

The code searches for a strong, easy-to-audit form of disagreement. Let left be an ordinary token and cross be a longer ordinary token beginning with left. Find a continuation token whose text starts with the remaining suffix of cross. Concatenating left with that continuation creates a surface for which dynamic programming has an explicit two-piece solution.

If greedy instead starts with cross or an even longer crossing token and needs more than two pieces, the surface is a witness. Search over an initial token, an ordinary crossing token, and a continuation token. It deliberately examines a deterministic, finite subset of lowercase ASCII-letter surfaces; it does not claim to characterize every possible tokenizer input.

Runnable diagnostic

Install the exact dependency in a clean Python 3 environment with python -m pip install transformers==4.56.2, then run:

import transformers
from transformers import AutoTokenizer
from itertools import islice

MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"

if transformers.__version__ != "4.56.2":
    raise RuntimeError(
        f"Expected transformers==4.56.2, got {transformers.__version__}"
    )

oracle = AutoTokenizer.from_pretrained(
    MODEL_ID,
    revision=FULL_COMMIT,
    use_fast=True,
)
assert oracle.is_fast

vocab = oracle.get_vocab()

# Only alphabetic pieces are searchable; every generated surface is one word.
initial = {
    token for token in vocab
    if token.isascii() and token.islower() and token.isalpha()
}
continuations = {
    token[2:] for token in vocab
    if token.startswith("##") and len(token) > 2
    and token[2:].isascii() and token[2:].islower()
    and token[2:].isalpha()
}

# Index continuation bodies by every nonempty prefix.
rights_by_prefix = {}
for body in sorted(continuations):
    for end in range(1, len(body) + 1):
        rights_by_prefix.setdefault(body[:end], []).append(body)

# left + right must begin with cross and have the two-piece solution
# [left, "##" + right].
relations = []
for cross in sorted(initial):
    for cut in range(1, len(cross)):
        left = cross[:cut]
        if left not in initial:
            continue
        bridge = cross[cut:]
        rights = rights_by_prefix.get(bridge)
        if rights:
            relations.append((cross, left, bridge, rights))

relations.sort(
    key=lambda row: (len(row[0]), len(row[2]), len(row[3]), row[0], row[1])
)

def candidate_surfaces():
    seen = set()
    for _, left, bridge, rights in relations:
        for right in rights:
            if len(right) == len(bridge):
                continue
            surface = left + right
            if surface in seen:
                continue
            seen.add(surface)
            yield surface

def first_fragmentation(batch):
    encoded = oracle(batch, add_special_tokens=False)["input_ids"]
    for surface, ids in zip(batch, encoded):
        tokens = oracle.convert_ids_to_tokens(ids)
        if len(ids) > 2 and oracle.unk_token not in tokens:
            return surface, ids, tokens
    return None

# The deployed tokenizer, not a local greedy simulation, chooses the witness.
found, examined = None, 0
candidates = candidate_surfaces()
while found is None:
    batch = list(islice(candidates, 256))
    if not batch:
        break
    found = first_fragmentation(batch)
    examined += len(batch)

assert found is not None, "No non-[UNK] witness found in the bounded search"
surface, greedy_ids, greedy_tokens = found

# Verify that the accepted result covers one contiguous normalized span.
detail = oracle(
    surface,
    add_special_tokens=False,
    return_offsets_mapping=True,
)
offsets = detail["offset_mapping"]
assert detail["input_ids"] == greedy_ids
assert offsets[0][0] == 0 and offsets[-1][1] == len(surface)
assert all(
    offsets[i][1] == offsets[i + 1][0]
    for i in range(len(offsets) - 1)
)

# Find a minimum-count segmentation over the same single word.
def shortest_segmentation(text):
    n = len(text)
    best = [n + 1] * (n + 1)
    following = [None] * (n + 1)
    best[n] = 0

    for start in range(n - 1, -1, -1):
        allowed = initial if start == 0 else continuations
        for end in range(start + 1, n + 1):
            piece = text[start:end]
            if piece in allowed:
                candidate = 1 + best[end]
                if candidate < best[start]:
                    best[start] = candidate
                    following[start] = (
                        piece if start == 0 else "##" + piece
                    )

    if best[0] > n:
        return None

    result, position = [], 0
    while position < n:
        token = following[position]
        result.append(token)
        position += len(token[2:] if token.startswith("##") else token)
    return result

shortest_tokens = shortest_segmentation(surface)
assert shortest_tokens is not None and len(shortest_tokens) == 2
assert len(greedy_tokens) > len(shortest_tokens)
assert oracle.unk_token not in greedy_tokens

model_encoding = oracle(
    surface,
    add_special_tokens=True,
    return_special_tokens_mask=True,
)
model_ids = model_encoding["input_ids"]
assert model_ids == [oracle.cls_token_id, *greedy_ids, oracle.sep_token_id]
assert model_encoding["special_tokens_mask"] == (
    [1] + [0] * len(greedy_ids) + [1]
)

print({
    "target": f"{MODEL_ID}@{FULL_COMMIT}",
    "surface": surface,
    "greedy_content_tokens": greedy_tokens,
    "greedy_content_count": len(greedy_ids),
    "dp_minimum_tokens": shortest_tokens,
    "dp_minimum_count": len(shortest_tokens),
    "model_input_tokens": oracle.convert_ids_to_tokens(model_ids),
    "model_input_count": len(model_ids),
    "greedy_contains_UNK": oracle.unk_token in greedy_tokens,
    "candidate_surfaces_examined": examined,
})

Read the result correctly

A successful local run prints the discovered surface, the tokenizer’s greedy content tokens, the dynamic program’s minimum segmentation, and separate model-input tokens. The assertions establish the intended relationship: the greedy output has more content pieces, the dynamic program has an explicit two-piece path, and neither contains [UNK]. The snippet does not embed or claim a particular output.

[UNK] must not be described as fragmentation. An unknown token is a fallback for a word the WordPiece model could not represent. Fragmentation means a successful sequence of multiple ordinary vocabulary pieces. The search intentionally excludes unknown results so that the diagnostic isolates greedy suboptimality rather than fallback behavior.

Content tokens are those returned with add_special_tokens=False. The model-input sequence in this scope also includes [CLS] and [SEP], so its length is two greater for this single, unpadded sequence. In a batch, padding length and truncation are separate concerns; the number of non-padding model positions is represented by the attention mask, not by the allocated tensor width.

The deployed tokenizer remains the oracle because the vocabulary search knows only piece membership. It does not independently guarantee lowercasing, accent handling, punctuation splitting, the configured word-character limit, unknown fallback, special-token insertion, or the behavior of the selected fast-tokenizer backend. Those rules must be confirmed through AutoTokenizer. This is also why the code asserts contiguous offsets and compares model-input tokens separately instead of treating every integer in the final tensor as content.

Limitations and re-check procedure

The search is limited to lowercase ASCII-letter surfaces of a special two-piece construction. It stops when it finds a qualifying witness; if the loop ends without one, it exhausts the finite candidate generator. It does not assess accents, CJK handling, punctuation, whitespace, added tokens, or long words. Dynamic programming minimizes piece count, not linguistic quality, model loss, latency, or downstream accuracy. Equal-count dynamic segmentations can also differ, so a count-only experiment does not define a unique replacement policy.

When the pinned file or dependency changes, do not preserve the old prose or expected output. Start from a clean environment, change the full commit and Transformers version explicitly, and rerun the diagnostic unchanged in its behavioral assertions. Review the new tokenizer.json fields for vocabulary, normalizer, pre-tokenizer, unknown token, prefix, and word-character limit. A changed vocabulary size, lack of fast-tokenizer support, different offsets, or different special-token behavior requires investigation and a newly scoped article. Also lock the compatible backend dependency in production, because the Transformers version alone does not fully describe a fast-tokenizer runtime.

The implementation references are the pinned tokenizer.json, Transformers v4.56.2 BERT tokenizer source, and Google Research’s original tokenization.py. The original file explains greedy WordPiece; the pinned JSON remains the authority for this site’s exact vocabulary and settings.

Sources

Token counts in this article were produced by the tokenizers pinned on the sources page and are checked by the site's test suite. If a count ever stops matching the pinned vocabulary, the build fails.

Check it yourself

Open the tokenizer

Every count in this guide comes from a vocabulary pinned by checksum. Paste the same text into the tool and you will get the same output.

Related guides