Debugging char_to_token gaps in BERT encodings
Probe punctuation, whitespace, and removed characters; handle None safely in annotation pipelines
A char_to_token gap is a source character for which the fast encoding exposes no covering content-token offset. It is not synonymous with a lost input: the character may be whitespace, or it may be removed or merged during normalization. The engineering task is to classify the gap, not to assume a one-to-one mapping between characters and tokens. This article applies only to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2.
Verified: 2026-10-05. This date applies to the pinned tokenizer.json, the versioned tokenizer API, and the versioned fast-tokenizer implementation. The script derives its observations locally; it does not embed output from an assumed run.
Define the alignment being diagnosed
Begin with one unpaired string, add_special_tokens=True, and both padding=False and truncation=False. Disabling padding and truncation prevents a masked suffix or padded coordinate from looking like a tokenizer defect. Request special_tokens_mask and offset mappings from the same call, and obtain word IDs with encoding.word_ids().
Several token categories must be distinguished in this diagnostic process. ID positions represent every entry in input_ids, which can include padding. Active model-input tokens are positions where attention_mask equals 1, meaning they include [CLS] and [SEP]. Content tokens indicate active positions where special_tokens_mask is 0. Finally, padding occurs at positions where attention_mask is 0.
An unknown token such as [UNK] is a content token, not an added special token. Consequently, excluding special tokens must not accidentally exclude unknowns.
Each nonzero offset is an interval in the original Python string, not a token ID. One token can cover several source characters, while several tokens can partition one word. word_ids() answers a different question: it groups tokens by pre-tokenized word. It returns None for added specials and other non-content positions, but a non-None value for a content token, including a generated [UNK].
The pinned tokenizer configuration cleans control characters and whitespace, strips accents, lowercases text, separates punctuation during pre-tokenization, and then applies WordPiece. Those stages explain most legitimate gaps. Punctuation may receive its own token, whitespace may receive no token span, and a cleaned control character may vanish. A generated [UNK] represents fallback over a source span; it is different from fragmentation into known pieces such as a prefix followed by ## continuation pieces. Neither case should be diagnosed from token count alone.
Run a self-contained probe
In an environment installed with python -m pip install transformers==4.56.2, run the following. It checks the dependency and fast implementation, prints token and character tables, compares the API lookup with an offset-based lookup, and reports whitespace, control-character, and punctuation gaps without hardcoding their counts.
from collections import Counter
import unicodedata
import transformers
from transformers import AutoTokenizer
MODEL = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
assert transformers.__version__ == "4.56.2", (
f"Expected transformers 4.56.2, got {transformers.__version__}"
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.is_fast
assert tokenizer.__class__.__name__ == "BertTokenizerFast"
sample = "Mail:\tA\x00B—don't stop; Café🙂.\r\nNext?"
encoded = tokenizer(
sample,
add_special_tokens=True,
padding=False,
truncation=False,
return_offsets_mapping=True,
return_special_tokens_mask=True,
)
ids = encoded["input_ids"]
attention = encoded["attention_mask"]
special = encoded["special_tokens_mask"]
offsets = encoded["offset_mapping"]
word_ids = encoded.word_ids(batch_index=0)
tokens = encoded.tokens()
width = len(ids)
assert all(
len(row) == width
for row in (attention, special, offsets, word_ids, tokens)
)
assert all(0 <= start <= end <= len(sample) for start, end in offsets)
active = [mask == 1 for mask in attention]
content = [active[i] and not special[i] for i in range(width)]
for i in range(width):
if special[i]:
assert word_ids[i] is None
if content[i]:
assert word_ids[i] is not None
unknown_indices = {
i for i in range(width)
if content[i] and tokens[i] == tokenizer.unk_token
}
def offset_lookup(char_index):
"""Return a content-token index, preserving None as an alignment gap."""
if char_index is None or not 0 <= char_index < len(sample):
return None
for token_index, span in enumerate(offsets):
if not content[token_index] or span is None or len(span) != 2:
continue
start, end = span
if start is None or end is None:
continue
if start < end and start <= char_index < end:
return token_index
return None
print("transformers:", transformers.__version__)
print("model:", MODEL)
print("requested revision:", FULL_COMMIT)
print("resolved commit attribute:", getattr(tokenizer, "_commit_hash", None))
print("tokenizer class:", tokenizer.__class__.__name__)
print("unk_token:", tokenizer.unk_token)
print("source:", sample.encode("unicode_escape").decode("ascii"))
print("active model-input positions:", sum(active))
print("content tokens:", sum(content))
print("added special tokens:", sum(special))
print("content unknown positions:", sorted(unknown_indices))
print("\nid role token word_id offset source")
for i in range(width):
if not active[i]:
role = "padding"
elif special[i]:
role = "added-special"
else:
role = "content"
start, end = offsets[i]
source = (
sample[start:end].encode("unicode_escape").decode("ascii")
if end > start
else "<empty>"
)
marker = " [unknown]" if i in unknown_indices else ""
print(
f"{i:>2} {role:<13} {tokens[i] + marker:<20} "
f"{str(word_ids[i]):>7} {str(offsets[i]):<7} {source}"
)
def gap_kind(char):
category = unicodedata.category(char)
if char.isspace():
return "whitespace"
if category == "Cc":
return "control/cleaning-candidate"
if category.startswith("P"):
return "punctuation"
if not char.isascii():
return "non-ASCII normalization-or-fallback"
return "other"
gap_counts = Counter()
punctuation_gaps = []
print("\nidx source category result word_id token")
for char_index, char in enumerate(sample):
manual = offset_lookup(char_index)
native = encoded.char_to_token(char_index)
assert manual == native, (char_index, manual, native)
if manual is None:
gap_counts[gap_kind(char)] += 1
if unicodedata.category(char).startswith("P"):
punctuation_gaps.append(char_index)
result = "None" if manual is None else str(manual)
word_id = None if manual is None else word_ids[manual]
token = "-" if manual is None else tokens[manual]
escaped = char.encode("unicode_escape").decode("ascii")
category = unicodedata.category(char)
print(
f"{char_index:>3} {escaped:<12} {category:<8} "
f"{result:<11} {str(word_id):>7} {token}"
)
print("\nNone mappings by source character:", dict(gap_counts))
print("punctuation gap indices:", punctuation_gaps)
Interpret the observations
Start with the two token counts. Active model-input positions include added specials. Content tokens exclude those specials but include generated unknowns. Comparing these counts with the token table immediately shows whether a discrepancy is merely [CLS] and [SEP], or something involving padding or unknown content. The script disables padding, so any padding observed would itself indicate a call or environment mismatch.
Next, inspect None mappings by source character. Tabs and line breaks are expected not to be inside token spans. The embedded null character is a control-cleaning candidate. Accent handling is more subtle: the original accented character can be absent from a narrow offset even though the normalized letter is represented. The output, rather than the mere presence of a Unicode code point, determines whether that source position is covered.
Ordinary punctuation in this sample should be probeable as content rather than silently disappearing. If the punctuation-gap list is nonempty, verify the full commit, Transformers version, fast-tokenizer class, and the fact that offsets and source slices came from the same original string. Do not attempt to repair this by reconstructing character positions from decoded tokens: decoding loses offsets and can obscure accent folding, unknown fallback, and added specials.
An emoji may appear as [UNK], but that is not a gap when its offset covers the source position. Every character in the unknown token’s span can map to the same token index. By contrast, fragmentation produces multiple known token spans, and word_ids() can group their continuation pieces. Inspect both the token string and its offset: a ## prefix is a fragmentation clue, while [UNK] is a fallback clue.
Preserve None in annotation pipelines
Treat a missing char_to_token result as an explicit optional value. Test token_index is None; do not use if not token_index, because zero is a valid list position in general and implicit conversion to -1 creates a false annotation. A JSON-oriented pipeline can retain null with a reason such as whitespace, or omit the token label while preserving the source span.
Keep this separate from word_ids()[token_index] is None. The first None means no content-token alignment was found. The second can mean the selected token has no pre-tokenized word, as added specials do. The diagnostic lookup also ignores malformed or absent offset spans rather than dereferencing them blindly.
Limitations and re-check procedure
Offset mapping is lexical alignment, not model reasoning, attention, or evidence that a token is semantically correct. This probe uses one unpaired, untruncated Python string. Paired sequences need explicit sequence disambiguation, truncation creates expected unmapped suffixes, and padding needs attention-mask-aware storage. Python character positions are also not grapheme clusters or byte offsets.
When the pinned repository file or dependency changes, create another exact environment rather than loosening the checks. For a tokenizer change, review the new full commit’s normalizer, pre-tokenizer, WordPiece model, unknown-token setting, and post-processor; rerun the probe and compare token strings, spans, and gap classes. For a Transformers change, record the new version, confirm that the returned fast-tokenizer class is still BertTokenizerFast, and revise the lookup only if the versioned API contract has changed. A green structural assertion does not prove that vocabulary or normalization behavior stayed unchanged.
The evidence boundary for this procedure includes the pinned tokenizer.json, the Transformers v4.56.2 tokenizer API, and the versioned BertTokenizerFast source.
Sources
- google-bert/bert-base-uncased tokenizer.json at 86b5e093
Pinned WordPiece vocabulary and normalization settings for the English uncased model.
- Hugging Face Transformers v4.56.2 tokenizer API
Versioned reference for encoding options, output fields, and fast-tokenizer alignment methods.
- Transformers v4.56.2 BertTokenizerFast source
Versioned implementation of the BERT fast-tokenizer wrapper.
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.