Computing a useful unknown-token rate for WordPiece
Measure [UNK] per content token and per input, keeping punctuation and long-word failures distinct
A useful unknown-token rate answers a narrow question: how often does the pinned WordPiece vocabulary fail to cover a content token, and how often does that failure appear in an input? It is not the fraction of [UNK] IDs among all model-input IDs. Special tokens, padding, and truncation can change that denominator without changing vocabulary coverage. Fragmentation can also inflate token counts without producing any unknown tokens. The diagnostic below therefore counts unknown content units separately from fragmented content units and from punctuation/symbol failures.
What to count
Define a content token as a whitespace/punctuation-separated unit that contains at least one alphanumeric character. This is a heuristic, but it matches the common case where you care about words, identifiers, chemical names, and other lexical units. Model-input tokens are what the model actually receives: content subwords plus special tokens such as [CLS] and [SEP]. An unknown token is an actual [UNK] ID. Fragmentation is a known content unit split into multiple WordPiece subwords, usually marked by ##.
The distinction matters. If a content unit maps to [UNK], the vocabulary did not cover it. If it maps to several known subwords, the vocabulary covered it, but WordPiece chose to fragment it. A high unknown rate points to coverage, normalization, or a maximum-input-length fallback. A high fragmentation rate with a low unknown rate points to token-boundary behavior, not missing vocabulary. Punctuation and symbols should not be folded into the content-token denominator; unusual symbols can be unknown, but that is a different failure mode.
For a corpus, two rates are useful: unknown content units divided by total content units, and inputs with at least one unknown content unit divided by total inputs. The first measures global coverage. The second shows whether failures are concentrated in a few inputs. A low global rate with high input incidence means a small number of inputs are failing hard.
Diagnostic procedure
Pin the tokenizer. Use AutoTokenizer.from_pretrained(..., revision=FULL_COMMIT, use_fast=True). Fast tokenizers expose word_ids() and offsets, which let you group subwords back to pre-tokenized units. Tokenize with add_special_tokens=False so [CLS] and [SEP] do not enter the content-token denominator. Then classify each group by its surface text. Count [UNK] groups as unknown content units. Count known groups with more than one token as fragmented. Count non-alphanumeric groups separately as punctuation/symbol units, and record any [UNK] there as punctuation/symbol unknown. Print examples with lengths so long-word fallbacks are visible.
from collections import defaultdict
import transformers
from transformers import AutoTokenizer
MODEL = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"
print(f"transformers={transformers.__version__}")
tokenizer = AutoTokenizer.from_pretrained(
MODEL, revision=REVISION, use_fast=True
)
assert tokenizer.is_fast, "This diagnostic groups tokens by word_ids()."
texts = [
"The quick brown fox jumps over the lazy dog.",
"Tokenization can fragment long chemical names like methylenedioxymethamphetamine.",
"Punctuation, emoji 😀, and symbols like € often arrive with text.",
"A very long unbroken word: pneumonoultramicroscopicsilicovolcanoconiosis",
"Multilingual text may use accents: café, naïve, résumé.",
]
def non_content_surface(surface: str) -> bool:
return bool(surface) and not any(ch.isalnum() for ch in surface)
def analyze(text: str):
enc = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)
ids = enc["input_ids"]
offsets = enc["offsets"]
word_ids = enc.word_ids()
groups = defaultdict(list)
for token_index, word_index in enumerate(word_ids):
if word_index is not None:
groups[word_index].append(token_index)
content_units = []
punct_units = []
for word_index in sorted(groups):
token_indices = groups[word_index]
start = min(offsets[i][0] for i in token_indices)
end = max(offsets[i][1] for i in token_indices)
surface = text[start:end]
if not surface:
continue
if non_content_surface(surface):
punct_units.append((surface, token_indices))
else:
content_units.append((surface, token_indices))
unknown_content = []
fragmented_content = []
unknown_punct = []
for surface, token_indices in content_units:
group_ids = [ids[i] for i in token_indices]
if tokenizer.unk_token_id in group_ids:
unknown_content.append((surface, len(surface)))
elif len(token_indices) > 1:
fragmented_content.append((surface, len(token_indices)))
for surface, token_indices in punct_units:
group_ids = [ids[i] for i in token_indices]
if tokenizer.unk_token_id in group_ids:
unknown_punct.append((surface, len(surface)))
total_content = len(content_units)
unknown_count = len(unknown_content)
return {
"content_units": total_content,
"unknown_content_units": unknown_count,
"fragmented_content_units": len(fragmented_content),
"unknown_punctuation_units": len(unknown_punct),
"unknown_content_examples": unknown_content,
"fragmented_content_examples": fragmented_content[:5],
"unknown_punctuation_examples": unknown_punct,
"unk_rate_per_content_unit": (
unknown_count / total_content if total_content else 0.0
),
}
rows = [analyze(text) for text in texts]
total_content = sum(row["content_units"] for row in rows)
total_unknown = sum(row["unknown_content_units"] for row in rows)
inputs_with_unknown = sum(
1 for row in rows if row["unknown_content_units"] > 0
)
print(f"model={MODEL}@{REVISION}")
print(
"global_unk_rate_per_content_unit="
f"{total_unknown}/{total_content} = "
f"{total_unknown / total_content if total_content else 0.0:.4f}"
)
print(
"inputs_with_unknown_content_unit="
f"{inputs_with_unknown}/{len(rows)} = "
f"{inputs_with_unknown / len(rows):.4f}"
)
print(
"average_unknown_content_units_per_input="
f"{total_unknown / len(rows):.4f}"
)
for i, (text, row) in enumerate(zip(texts, rows), 1):
print(
f"input={i} content_units={row['content_units']} "
f"unknown={row['unknown_content_units']} "
f"fragmented={row['fragmented_content_units']} "
f"punct_unknown={row['unknown_punctuation_units']} "
f"unk_rate={row['unk_rate_per_content_unit']:.4f}"
)
if row["unknown_content_examples"]:
print(f" unknown_content_examples={row['unknown_content_examples']}")
if row["fragmented_content_examples"]:
print(f" fragmented_content_examples={row['fragmented_content_examples']}")
if row["unknown_punctuation_examples"]:
print(
" unknown_punctuation_examples="
f"{row['unknown_punctuation_examples']}"
)
Reading the output
When you run it, the output depends on the texts you supply. The code prints all relevant quantities and does not assert expected numbers. A global rate of zero means every content unit was covered by at least one known WordPiece token in that sample. A nonzero rate with long unknown examples suggests a maximum-input-character fallback or normalization difference. A nonzero rate with short unknown examples suggests missing subwords, rare script, diacritics, or typos. A high fragmentation count with zero unknowns means vocabulary coverage is working; WordPiece is just using multiple pieces.
Check the per-input rows. If one input has many unknown content units, the global rate may understate the failure. If many inputs have one unknown each, input incidence may be high while the per-token rate is low. If content_units is zero, the rate is undefined; the code returns 0.0 as a reporting convention, not as evidence of coverage. Punctuation/symbol unknowns should not be folded into content coverage. If they are high, fix normalizer or symbol handling before changing the vocabulary.
Limitations
The content-token heuristic is not universal. Languages without whitespace, code, URLs, or different punctuation conventions may need another unit definition. The fast tokenizer’s word_ids() follows the pre-tokenizer, not linguistic words. Normalization can change surface forms: uncased BERT lowercases and strips accents, so an unknown example may not look like the original input. The diagnostic measures tokenizer behavior only; it does not predict task accuracy or model quality, and it does not measure subword fertility per character. Do not compare counts across different tokenizer revisions or different models without re-running the diagnostic.
Verification and re-check
Verified: 2026-10-05. The code targets google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. The pinned vocab size for this model is 30,522; the multilingual counterpart, google-bert/bert-base-multilingual-cased at revision 3f076fdb1ab68d5b2880cb87a0886f315b8146f8, has a pinned vocab size of 119,547. Those numbers are context for coverage only; the diagnostic does not hardcode them. Limitation: the code’s outputs are environment- and corpus-dependent, and this article does not claim a specific rate for any corpus. Re-check when the pinned tokenizer.json revision, the normalizer, the pre-tokenizer, the maximum input characters per word, or the Transformers tokenizer API changes. Re-run the same script, compare unknown examples and rates, and if you switch to the multilingual checkpoint, update both constants and re-evaluate the content-token heuristic.
Sources
- google-bert/bert-base-uncased tokenizer.json at 86b5e093
Pinned WordPiece vocabulary and normalization settings for the English uncased model.
- google-bert/bert-base-multilingual-cased tokenizer.json at 3f076fdb
Pinned WordPiece vocabulary and normalization settings for the multilingual cased model.
- Hugging Face Transformers v4.56.2 tokenizer API
Versioned reference for encoding options, output fields, and fast-tokenizer alignment methods.
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.