Skip to content
wordpiece.org

When a WordPiece suffix fails after a valid prefix

Use a code probe to locate a suffix that cannot be matched; explain whole-word [UNK] fallback instead of partial-prefix output

Published 8 min read Verified

A valid WordPiece prefix does not guarantee that the remainder of the same basic token can be emitted. For google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594, a matching first piece followed by an unmatchable continuation produces one [UNK] for the entire basic token; it does not return the valid prefix beside that unknown token. Verified: 2026-10-05. The verification scope is the fast tokenizer loaded with transformers==4.56.2. It does not automatically describe google-bert/bert-base-multilingual-cased at 3f076fdb1ab68d5b2880cb87a0886f315b8146f8 or another commit.

Failure boundary

Before WordPiece lookup, the pinned pipeline normalizes text and divides it into basic tokens. Punctuation, whitespace, and the tokenizer’s other split rules can create a boundary before matching. Within one resulting token, BERT’s WordPiece procedure performs greedy longest-match lookup. The first candidate is an ordinary vocabulary item; every later candidate must use ##. If a later span has no match, the implementation appends [UNK] for the entire basic token. The earlier match is not returned as partial output.

The pinned tokenizer.json is the authority for this site’s exact WordPiece vocabulary and normalization settings. That vocabulary is neither an input length nor a guarantee that an arbitrary continuation is representable. Fragmentation is successful tokenization into several vocabulary pieces and does not produce [UNK]. This failure is different: after a first piece is found, WordPiece cannot finish, so fallback does not emit partial output for that basic token. A punctuation character that pre-tokenizes the text first can instead produce multiple tokens; that is not the failure analyzed here.

Pinned diagnostic

Use a corpus-free probe so the conclusion does not depend on a guessed example. In a clean environment, install transformers==4.56.2 and run the following Python 3. It needs the pinned model asset in the local cache or network access, but no dataset. The code pins the commit, requires a fast tokenizer, and inspects the pinned vocabulary. For each candidate suffix, it first asks whether the suffix has any greedy decomposition made from ## entries. It then requires normalization and pre-tokenization to leave the probe as one basic token, and requires the public tokenizer to return one unknown token. The code prints the selected suffix and actual token sequences when executed.

from importlib.metadata import version

import transformers
from transformers import AutoTokenizer

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

if transformers.__version__ != EXPECTED_TRANSFORMERS:
    raise RuntimeError(
        f"Install transformers=={EXPECTED_TRANSFORMERS}; "
        f"found {transformers.__version__}"
    )

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    revision=FULL_COMMIT,
    use_fast=True,
)

assert tokenizer.is_fast
vocab = tokenizer.get_vocab()

prefix = "token"
assert prefix in vocab
assert tokenizer.tokenize(prefix) == [prefix]
assert tokenizer.encode(prefix, add_special_tokens=False) == [vocab[prefix]]


def continuation_pieces(suffix):
    """Apply greedy lookup using only continuation entries."""
    pieces = []
    start = 0

    while start < len(suffix):
        end = len(suffix)
        match = None

        while end > start:
            candidate = "##" + suffix[start:end]
            if candidate in vocab:
                match = candidate
                break
            end -= 1

        if match is None:
            return None

        pieces.append(match)
        start = end

    return pieces


backend = tokenizer.backend_tokenizer
candidate_suffixes = ("☃", "🧪", "🛰", "🪐", "🧿", "🦕")
selected_suffix = None

for suffix in candidate_suffixes:
    if continuation_pieces(suffix) is not None:
        continue

    word = prefix + suffix
    normalized = backend.normalizer.normalize_str(word)
    if normalized != word:
        continue

    parts = [
        part
        for part, _ in backend.pre_tokenizer.pre_tokenize_str(normalized)
    ]
    if parts != [normalized]:
        continue

    if tokenizer.tokenize(word) != [tokenizer.unk_token]:
        continue

    selected_suffix = suffix
    break

if selected_suffix is None:
    raise RuntimeError("No qualifying unmatchable suffix was found")

word = prefix + selected_suffix
content_ids = tokenizer.encode(word, add_special_tokens=False)
model_input = tokenizer(
    word,
    add_special_tokens=True,
    return_special_tokens_mask=True,
)

expected_model_ids = [
    tokenizer.cls_token_id,
    tokenizer.unk_token_id,
    tokenizer.sep_token_id,
]

assert content_ids == [tokenizer.unk_token_id]
assert model_input["input_ids"] == expected_model_ids
assert model_input["special_tokens_mask"] == [0, 0, 0]

print("model:", f"{MODEL_ID}@{FULL_COMMIT}")
print("transformers:", transformers.__version__)
print("tokenizers backend:", version("tokenizers"))
print("tokenizer class:", type(tokenizer).__name__)
print("vocabulary size:", len(vocab))
print("prefix pieces:", tokenizer.tokenize(prefix))
print("selected suffix:", repr(selected_suffix))
print("suffix code point:", f"U+{ord(selected_suffix):04X}")
print("content pieces:", tokenizer.convert_ids_to_tokens(content_ids))
print("content IDs:", content_ids)
print("model-input pieces:", tokenizer.convert_ids_to_tokens(model_input["input_ids"]))
print("model-input IDs:", model_input["input_ids"])
print("special_tokens_mask:", model_input["special_tokens_mask"])

Reading the observations

The helper is a narrow vocabulary check, not a replacement tokenizer. None means that the candidate suffix has no greedy continuation decomposition in this file. The backend checks exclude a different case in which punctuation or another split rule created two basic tokens. Only after those gates does the probe require tokenizer.tokenize(prefix + suffix) to be exactly one [UNK]. Together, those observations establish the narrow claim: the first piece is valid, the continuation is not, and the public tokenizer chooses whole-token fallback.

The final assertions keep two counts separate. With add_special_tokens=False, encode represents content tokens only; the asserted content sequence has one ID, [UNK]. With add_special_tokens=True, the asserted model-input sequence has three positions: [CLS], [UNK], and [SEP]. The numeric IDs are read from the tokenizer rather than copied from a run. The printed special_tokens_mask also distinguishes these positions from padding, although this probe requests no padding or truncation. Neither one nor three is the vocabulary size; batching or wrapper settings can change model-input positions.

Interpret a different observation carefully. A result such as ["token", "[UNK]"] means the input was split before whole-token fallback. Several ordinary ## pieces mean successful fragmentation. An unknown result for the suffix tested alone is insufficient because testing it separately changes the basic-token context. Likewise, an [UNK] appearing only after model construction is not evidence of this WordPiece branch. In a production corpus probe, retain the original span, content tokens, model-input tokens, and special-token mask, and apply the same one-basic-token gate before labeling a suffix failure.

Limitations and re-check

This is a deliberately minimal synthetic probe, not evidence about how often natural text fails, tokenizer quality, or model accuracy. It exercises normalization, pre-tokenization, vocabulary lookup, and fallback, but says nothing about the learned meaning of [UNK]. The result is scoped to google-bert/bert-base-uncased at the full commit above and to the stated Transformers release. The multilingual model and its pinned revision require a separate probe; their token counts and settings must not be inferred from this run. The resolved tokenizers backend version is printed because it is a transitive dependency and a potential source of implementation variation.

When the pinned file or dependency changes, create a clean environment and re-check before updating production code or this article. Record transformers.__version__, tokenizers.__version__, the tokenizer class, is_fast, and the full model revision; also download and hash tokenizer.json. Inspect changes to the normalizer, pre-tokenizer, WordPiece vocabulary, maximum characters per WordPiece token, and special-token definitions. Re-run the probe and compare the selected suffix, content sequence, model-input sequence, and masks. The printed vocabulary size exposes vocabulary-size drift but cannot detect every settings change. If the repository pin moves, set a new full commit and revise every scoped claim; if only the dependency moves, keep the file pin and report the backend change separately.

Turn the probe into a regression test only after choosing the failure mode you intend to protect. Store the exact model ID, full revision, package versions, original failing span, and both content and model-input assertions. If token handling changes intentionally, update the expected sequence at the same pinned asset first; do not weaken the test to accept either prefix preservation or whole-token [UNK]. That distinction is the behavior the test exists to protect.

Evidence boundary

The pinned tokenizer file supplies the exact vocabulary and settings. The Transformers 4.56.2 BERT tokenizer source supplies versioned wrapper behavior, and Google’s original tokenization.py supplies the reference basic-token and greedy WordPiece algorithm. When descriptions differ, the pinned JSON governs this model and the versioned implementation governs wrapper behavior.

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