Auditing mixed-script identifiers in BERT WordPiece
Build a mixed Latin/CJK/Greek fixture and report per-span tokens, unknowns, and effects of pre-tokenization
An audit of a mixed-script identifier must separate three results: source characters altered or discarded by normalization, characters with no vocabulary symbol, and pieces created by boundary-aware WordPiece segmentation. [UNK] is an unknown-vocabulary result; it is not fragmentation. Conversely, several non-unknown pieces may be normal word continuation, script separation, or punctuation handling. The procedure below uses identical Latin, CJK, Greek, and transition spans with both pinned tokenizers, then compares an unsegmented concatenation with caller-defined span boundaries. It prints observations on the reader’s machine; no execution result is claimed here.
Verified: 2026-10-05. The applicable models are google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, with transformers==4.56.2. The two pinned tokenizer.json files are the behavior authority; the versioned Transformers API defines how the fast tokenizer is loaded and which diagnostics can be requested.
Pin the behavior boundary
Treat each span call as one un-padded, untruncated sequence. “Content tokens” here means every non-special position, including an [UNK] placeholder. “Known pieces” means content tokens other than [UNK]. “Model-input tokens” means the complete input_ids, including [CLS] and [SEP]; a production batch may also include padding. This definition prevents a vocabulary failure from being hidden inside a content count and prevents special or padding positions from being reported as identifier complexity. The pinned inventory is an artifact check, not direct evidence about how this fixture tokenizes.
The fixture deliberately includes a camel-cased Latin identifier, CJK characters plus an ASCII letter and digits, accented Greek, and underscore-delimited script transitions. Its no-boundary form concatenates those spans directly. That form is adversarial rather than a recommended input format: it lets the tokenizer encounter Latin/Greek transitions without a caller boundary. The alternate call supplies the four original strings through is_split_into_words=True. This flag models pre-segmented words and exposes word_ids(); it does not suppress BERT’s internal Chinese-character splitting, punctuation handling, normalization, or unknown fallback. Fast-tokenizer offsets are printed for standalone spans so an emitted piece can be traced back to source text.
In production, log the original span, the model/revision, the resulting IDs, and whether the span was caller-segmented. Preserve the source-to-piece alignment when investigating a failure; rendered tokens alone lose distinctions that matter to a downstream program, such as two pieces mapping to the same source character after normalization. If the goal is to reconstruct or compare identifiers, evaluate any normalization as a transformation, not as harmless cleanup. In particular, do not strip accents or case merely to reduce an audit count without defining whether reconstruction is lossy.
Run in a clean Python 3 environment after installing transformers==4.56.2:
import transformers
from transformers import AutoTokenizer
assert transformers.__version__ == "4.56.2", (
f"This audit requires transformers==4.56.2; "
f"found {transformers.__version__}"
)
MODELS = (
(
"uncased",
"google-bert/bert-base-uncased",
"86b5e0934494bd15c9632b12f734a8a67f723594",
),
(
"multilingual-cased",
"google-bert/bert-base-multilingual-cased",
"3f076fdb1ab68d5b2880cb87a0886f315b8146f8",
),
)
SPANS = (
("Latin identifier", "invoiceRef42"),
("CJK identifier", "订单编号A42"),
("Greek identifier", "Παραλαβή42"),
("script transitions", "ord_订单_παρ42"),
)
def summarize(encoding, tokenizer):
input_ids = list(encoding["input_ids"])
special_mask = list(encoding["special_tokens_mask"])
content_ids = [
token_id
for token_id, is_special in zip(input_ids, special_mask)
if not is_special
]
content_tokens = tokenizer.convert_ids_to_tokens(content_ids)
unknown_count = sum(
token == tokenizer.unk_token for token in content_tokens
)
raw_offsets = encoding.get("offset_mapping")
content_offsets = None
if raw_offsets is not None:
content_offsets = [
tuple(raw_offsets[index])
for index, is_special in enumerate(special_mask)
if not is_special
]
attention_mask = encoding.get("attention_mask")
if attention_mask is not None:
assert all(attention_mask), "This diagnostic does not request padding"
model_input_count = len(input_ids)
special_count = sum(special_mask)
assert model_input_count == len(content_ids) + special_count
return {
"content_ids": content_ids,
"content_tokens": content_tokens,
"content_offsets": content_offsets,
"unknown_count": unknown_count,
"known_piece_count": len(content_tokens) - unknown_count,
"model_input_count": model_input_count,
"special_count": special_count,
}
def show_summary(label, result):
print(f" {label}")
print(f" content_tokens={result['content_tokens']}")
print(f" content_ids={result['content_ids']}")
print(
f" unknown_count={result['unknown_count']} "
f"known_piece_count={result['known_piece_count']} "
f"model_input_count={result['model_input_count']} "
f"special_count={result['special_count']}"
)
if result["content_offsets"] is not None:
print(f" content_offsets={result['content_offsets']}")
for model_label, model_id, FULL_COMMIT in MODELS:
tokenizer = AutoTokenizer.from_pretrained(
model_id,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.is_fast
print(f"\n{model_label}: {model_id}@{FULL_COMMIT}")
standalone_pieces = []
for span_label, text in SPANS:
encoding = tokenizer(
text,
add_special_tokens=True,
padding=False,
truncation=False,
return_special_tokens_mask=True,
return_offsets_mapping=True,
)
result = summarize(encoding, tokenizer)
standalone_pieces.append(result["content_tokens"])
show_summary(span_label, result)
# Deliberately remove every caller boundary.
joined_text = "".join(text for _, text in SPANS)
joined_encoding = tokenizer(
joined_text,
add_special_tokens=True,
padding=False,
truncation=False,
return_special_tokens_mask=True,
)
joined = summarize(joined_encoding, tokenizer)
# Supply the intended span boundaries through the fast-tokenizer API.
presplit_encoding = tokenizer(
[text for _, text in SPANS],
is_split_into_words=True,
add_special_tokens=True,
padding=False,
truncation=False,
return_special_tokens_mask=True,
)
presplit = summarize(presplit_encoding, tokenizer)
groups = [[] for _ in SPANS]
owned_word_ids = set()
for word_id, token_id, is_special in zip(
presplit_encoding.word_ids(),
presplit_encoding["input_ids"],
presplit_encoding["special_tokens_mask"],
):
if not is_special:
assert word_id is not None
assert 0 <= word_id < len(SPANS)
groups[word_id].append(tokenizer.convert_ids_to_tokens(token_id))
owned_word_ids.add(word_id)
assert owned_word_ids == set(range(len(SPANS)))
assert all(groups)
print(f"joined_text={joined_text!r}")
show_summary("no caller boundaries", joined)
show_summary("caller span boundaries", presplit)
for (span_label, _), pieces in zip(SPANS, groups):
unknown_count = sum(piece == tokenizer.unk_token for piece in pieces)
print(
f" pre-split / {span_label}: tokens={pieces} "
f"unknown_count={unknown_count} "
f"known_piece_count={len(pieces) - unknown_count}"
)
standalone_matches = [
standalone == grouped
for standalone, grouped in zip(standalone_pieces, groups)
]
print(f"standalone_equals_presplit_per_span={standalone_matches}")
print(
"pre-split minus joined: "
f"content={len(presplit['content_tokens']) - len(joined['content_tokens'])}, "
f"unknown={presplit['unknown_count'] - joined['unknown_count']}"
)
Interpret the report
Read each span’s content_tokens and content_ids together. A nonzero unknown_count localizes a fallback after normalization and pre-tokenization; it does not mean the span was merely too long. WordPiece also uses [UNK] for characters or accent-normalized forms absent from the vocabulary, so an unknown can coexist with known pieces. Inspect the offset ranges to determine which source region was replaced. Do not infer the missing grapheme from the raw fixture alone: case folding or accent removal can make two source characters lead to the same normalized form. Conversely, a span can have zero unknowns and several known tokens. That is fragmentation or boundary splitting, not an out-of-vocabulary result. The underscores and CJK characters make some splitting expected by construction.
The joined and pre-split summaries answer a separate question. If the pre-split call has more content tokens, caller boundaries force new WordPiece starts that the joined input did not need. If it has fewer, the joined tokenizer was able to continue a match across what the caller considered a boundary. Equal counts can still hide a different token-to-word_id assignment, which is why the block prints both. An unknown-count change is especially important: segmentation cannot be assumed harmless merely because it improves attribution. Conversely, an unchanged unknown count does not prove segmentation is irrelevant, because a known continuation can still have been replaced by a short piece. Record all four signals—content sequence, unknown count, model-input count, and span ownership—before changing production behavior.
The two models answer coverage questions separately. Do not transfer a conclusion from bert-base-uncased to bert-base-multilingual-cased, or assume that a larger inventory guarantees every character is covered. The Latin span also probes normalization: the uncased artifact can fold case and handle accents differently from the cased artifact; the Greek span makes that difference visible where its vocabulary permits. Use the local output to decide whether the immediate defect is missing vocabulary, normalization, or boundary policy. None of those findings is a benchmark of downstream model quality.
Limitations
This is a tokenizer audit, not a full Unicode conformance test. The strings are short, contain no invisible controls, and test only the script transitions and normalization cases written above. It does not establish coverage for other CJK characters, compatibility forms, emoji, combining marks, malformed normalization, very long identifiers, truncation, or padding. is_split_into_words=True represents one caller policy, not necessarily production segmentation. Offset ranges are tokenizer alignment metadata, not byte offsets or evidence that a model uses a piece in a particular way. Results are limited to the two named immutable revisions and the fast-tokenizer wrapper in Transformers 4.56.2; another backend or library release may serialize or expose the same vocabulary differently.
Recheck after a change
Store the printed report with the exact model ID, full commit, Transformers version, Python version, fixture, and command. When the pinned tokenizer.json changes, update FULL_COMMIT, review the new normalizer, pre-tokenizer, and vocabulary, and run both models again; treat it as a new baseline rather than editing expected tokens in place. When transformers changes, install that version in a clean environment and rerun the same block. Compare len(tokenizer), piece-to-ID mappings, IDs, unknown counts, offsets, and word_ids(), not just formatted token strings. A vocabulary-size match is only a coarse identity check. If behavior changes, isolate whether tokenizer.json or the wrapper changed before attributing it to WordPiece. Preserve the old report so script-coverage regressions and serialization changes remain distinguishable.
Primary references
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.