Finding control characters that disappear during BERT normalization
Create explicit control-character probes and inspect offsets to detect silently removed input without publishing invented output counts
A control character can be present in an input string, survive a transport layer, and still occupy no source span in the content tokens produced by the pinned English BERT tokenizer. That is the precise failure mode to detect: source text that normalization removes before WordPiece sees it, rather than a conspicuous unknown token. Verified: 2026-10-05. Source and configuration claims were checked against the primary references below; console output is generated locally. Every token, offset, and count here is scoped to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2; do not transfer results to the multilingual model or another revision.
The pinned tokenizer.json is the authority for the normalizer configuration, including clean_text, and for WordPiece model settings. The Transformers v4.56.2 BERT source defines the wrapper and encoding options used below; Google’s tokenization.py explains cleanup, token splitting, greedy WordPiece, and unknown fallback. In that reference cleanup, NUL and U+FFFD are explicitly skipped, other non-whitespace category-C characters are treated as controls, and whitespace is mapped to a space. These sources explain the mechanism, but they do not justify a universal table of results for every invisible character.
Make disappearance observable
Use the fast tokenizer’s offset mapping, not a decode-and-compare heuristic. Each offset is a half-open [start, end) range into the original Python string. Put ASCII sentinels around one candidate: left<char>right. The character is at len("left"). If offsets cover left and right but none includes that position, no surviving content token owns the character. repr or ascii makes the source visible without letting the terminal hide it.
Call the encoding with add_special_tokens=False to obtain content tokens only. Keep padding and truncation off. Otherwise, model-added [CLS] and [SEP], padding, or a truncated suffix can be mistaken for normalized-away input. In production batches, calculate coverage separately for each original sequence and retain its raw string.
The block uses the required pinned load, checks the Transformers version, hashes the resolved tokenizer file, and reports the installed backend version. It prints both normalizer output and offset coverage for several category-C characters, U+FFFD, tab, newline, and a space baseline. Its final call relates content and model-input counts without hard-coding either count.
import hashlib
import json
import unicodedata
from pathlib import Path
import tokenizers
import transformers
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer
MODEL = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
TRANSFORMERS_VERSION = "4.56.2"
if transformers.__version__ != TRANSFORMERS_VERSION:
raise RuntimeError(
f"Expected transformers=={TRANSFORMERS_VERSION}, "
f"got {transformers.__version__}"
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.is_fast
assert tokenizer.backend_tokenizer is not None
normalizer = tokenizer.backend_tokenizer.normalizer
assert normalizer is not None
tokenizer_path = Path(
hf_hub_download(
repo_id=MODEL,
filename="tokenizer.json",
revision=FULL_COMMIT,
)
)
tokenizer_json = json.loads(tokenizer_path.read_text(encoding="utf-8"))
file_digest = hashlib.sha256(tokenizer_path.read_bytes()).hexdigest()
print(f"model: {MODEL}@{FULL_COMMIT}")
print(f"tokenizer class: {type(tokenizer).__name__}")
print(f"transformers: {transformers.__version__}")
print(f"tokenizers backend: {tokenizers.__version__}")
print(f"tokenizer.json SHA-256: {file_digest}")
print("normalizer config:", tokenizer_json["normalizer"])
print("loaded normalizer:", repr(normalizer))
NUL = unicodedata.lookup("NULL")
PROBES = [
("NUL", NUL),
("BEL", unicodedata.lookup("BEL")),
("SOFT HYPHEN U+00AD", "\u00ad"),
("ZERO WIDTH SPACE", unicodedata.lookup("ZERO WIDTH SPACE")),
(
"RIGHT-TO-LEFT OVERRIDE",
unicodedata.lookup("RIGHT-TO-LEFT OVERRIDE"),
),
("REPLACEMENT CHARACTER U+FFFD", "\ufffd"),
("SPACE BASELINE", " "),
("TAB", "\t"),
("NEWLINE", "\n"),
]
NO_MODEL_AUGMENTATION = {
"padding": False,
"truncation": False,
}
LEFT = "left"
def covering_spans(offsets, position):
return [
(start, end)
for start, end in offsets
if start <= position < end
]
for name, character in PROBES:
source = LEFT + character + "right"
position = len(LEFT)
encoded = tokenizer(
source,
add_special_tokens=False,
return_offsets_mapping=True,
**NO_MODEL_AUGMENTATION,
)
offsets = encoded["offset_mapping"]
pieces = tokenizer.convert_ids_to_tokens(encoded["input_ids"])
spans = covering_spans(offsets, position)
normalized = normalizer.normalize_str(source)
print(f"\n{name}; Unicode category={unicodedata.category(character)}")
print(" source:", ascii(source))
print(" normalized:", ascii(normalized))
print(" result:", "covered" if spans else "uncovered")
print(" offsets:", offsets)
print(" pieces:", pieces)
print(" covering spans:", spans)
if name == "NUL":
assert NUL not in normalized, (
"NUL survived normalization; inspect the loaded normalizer."
)
assert not spans, (
"NUL is owned by a content-token span; inspect offset behavior."
)
nul_source = LEFT + NUL + "right"
nul_content = tokenizer(
nul_source,
add_special_tokens=False,
return_offsets_mapping=True,
**NO_MODEL_AUGMENTATION,
)
model_input = tokenizer(
nul_source,
add_special_tokens=True,
return_offsets_mapping=True,
return_special_tokens_mask=True,
return_attention_mask=True,
**NO_MODEL_AUGMENTATION,
)
content_count = len(nul_content["input_ids"])
model_input_count = len(model_input["input_ids"])
special_mask = model_input["special_tokens_mask"]
print("\ncontent-token count:", content_count)
print("model-input count:", model_input_count)
print("special-token mask:", special_mask)
print("attention mask:", model_input["attention_mask"])
print("model-input offsets:", model_input["offset_mapping"])
assert model_input_count == content_count + sum(special_mask)
Interpret the observations
Each report has two observations: normalized= is the backend normalizer’s escaped output, while uncovered means the inserted source position is owned by no content-token offset. For the NUL probe, absence from normalized output plus the offset gap is direct evidence of disappearance. The assertions are tripwires: failure means the loaded normalization or offset behavior needs investigation, not that the check should be removed.
Do not generalize that label to every line. Soft hyphen, zero-width space, bidi override, and replacement character can differ from ASCII controls, while tab and newline can become spaces. Even a space has no content-token span because it is a delimiter. For those probes, compare the escaped normalized string and normalizer configuration: no token offset alone does not distinguish deletion from conversion into a delimiter.
Offset coverage is not an edit diff. A covered character is attributed to a token span, but this test does not reconstruct every normalization change; an uncovered interval can have another cause if a custom normalizer, prefix, or external sanitizer ran. The block diagnoses the loaded tokenizer, not the whole ingestion chain.
add_special_tokens=False yields content IDs. The second call adds configured special tokens and prints the model-input length, special-token mask, and offsets. It checks that model-input length equals content length plus the returned special count without assuming how many specials exist. With padding or truncation, masks and per-sequence offsets must be respected; model-input count is never character count.
An unknown token and deletion are different observations. [UNK] means a surface token could not be represented by the WordPiece vocabulary. Fragmentation means one surface token was represented by several vocabulary pieces. A removed control can produce neither: only ordinary sentinel words remain. Inspect token IDs, unk_token_id, pieces, and source slices separately; do not use len(tokenizer.tokenize(text)) as proof that a particular character vanished.
Limitations
Offset mapping is a tokenizer source map, not a byte-level diff or complete security scanner. A single isolated probe reduces ambiguity, but clusters of controls, repeated spaces, combining marks, invalid text, and custom normalization need character-level review. Unicode category and whitespace decisions can vary with the Python Unicode database and tokenizer backend. The code prints the tokenizers version because pinning Transformers alone does not specify every installed backend detail.
Safe tokenization also does not imply semantic preservation. If a control separates values, its removal can make different raw strings yield the same token sequence. Reject, quarantine, or encode the input according to the system’s security policy. If preservation is required, use an explicit visible placeholder or upstream representation with its own tests; keep the raw value for audit rather than silently sanitizing it twice.
Re-check when the pin changes
For a reproducible re-check, install transformers==4.56.2, run the block, retain the printed tokenizers version and tokenizer-file SHA-256, and archive the output. The full model commit is passed to both artifact resolution and tokenizer loading. If the pinned file or dependency changes, do not reuse the old conclusion: inspect changes to the JSON normalizer, pre-tokenizer, decoder, special-token definitions, and vocabulary; review changed tokenizer source; and rerun the probes and count comparison. Stable sentinels do not prove an untested character or production corpus is unaffected.
To operationalize the check, log escaped raw input, compute uncovered source intervals, and flag intervals containing disallowed controls. Record the model revision, Transformers version, backend version, and file hash with the diagnostic. A changed NUL assertion should trigger review, and any tokenization dependency upgrade should create a new baseline rather than inherit this article’s claims.
Sources
- google-bert/bert-base-uncased tokenizer.json at 86b5e093
Pinned WordPiece vocabulary and normalization settings for the English uncased model.
- Transformers v4.56.2 BertTokenizer source
Versioned Python implementation of BERT basic and WordPiece tokenization.
- Google Research BERT tokenization.py
Original Google BERT preprocessing and greedy WordPiece implementation; consult the pinned JSON for this site’s exact vocabulary.
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.