Validating offset_mapping with BertTokenizerFast
Show fast-only offset return, raw string slicing, and handling of zero-length special-token offsets
Validating offset_mapping with BertTokenizerFast means checking that each content token’s (start, end) pair slices the original string into the surface form that produced that token, and that special tokens carry zero-length offsets you must not treat as text spans. The fast BERT tokenizer returns alignment data only when you explicitly request it. In transformers==4.56.2, the slow BERT tokenizer path does not expose the same return_offsets_mapping contract. The engineering risk is quiet: token IDs may decode correctly while offsets are used to build labels, highlights, or character-level mappings, and a zero-length special-token offset can silently become an empty span in downstream logic.
Verified: 2026-10-05. This article is scoped to google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. If you use google-bert/bert-base-multilingual-cased, the applicable pinned revision is 3f076fdb1ab68d5b2880cb87a0886f315b8146f8; do not assume the English uncased normalization or vocabulary behavior transfers. The pinned English uncased tokenizer.json defines a WordPiece vocabulary of 30,522 entries. The pinned multilingual cased vocabulary has 119,547 entries. Those numbers are properties of those pinned files, not of an unrelated LLM. The evidence boundary here is the pinned tokenizer.json files, the Transformers v4.56.2 tokenizer API documentation, and the v4.56.2 BertTokenizerFast source. The code below is a diagnostic you run locally; it does not claim a specific printed result.
The offset classes that matter
For BERT fast tokenization, offset_mapping returns one (start, end) pair per model-input token. Model-input tokens include special tokens such as [CLS], [SEP], and [PAD]. Content tokens are the pieces that correspond to raw text. Unknown tokens are [UNK] placeholders for out-of-vocabulary words. Fragmentation is different: WordPiece splits a known word into multiple content tokens, commonly with ## prefixes on continuation pieces. A single [UNK] is not fragmentation; a sequence like play and ##ing is fragmentation. Special tokens have zero-length offsets. Content tokens, including [UNK] when it covers a word, have non-zero spans. This distinction is the core of validation.
A diagnostic you can run
import transformers
assert transformers.__version__ == "4.56.2", transformers.__version__
from transformers import AutoTokenizer
MODEL_ID = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"
text = "Tokenization isn't trivial: BERT splits rare words."
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
revision=REVISION,
use_fast=True,
)
assert tokenizer.is_fast
enc = tokenizer(
text,
add_special_tokens=True,
return_offsets_mapping=True,
)
assert len(enc["input_ids"]) == len(enc["offset_mapping"])
special_ids = {
tokenizer.cls_token_id,
tokenizer.sep_token_id,
tokenizer.pad_token_id,
}
special_ids.discard(None)
for token_id, token_str, (start, end) in zip(
enc["input_ids"],
tokenizer.convert_ids_to_tokens(enc["input_ids"]),
enc["offset_mapping"],
):
if token_id in special_ids:
assert start == end, (token_str, start, end)
print(f"{token_str!r:>12} ids={token_id:<6} offsets=({start},{end}) special")
continue
assert start < end, (token_str, start, end)
raw = text[start:end]
if token_str == tokenizer.unk_token:
print(f"{token_str!r:>12} ids={token_id:<6} offsets=({start},{end}) raw={raw!r} UNK")
continue
surface = token_str[2:] if token_str.startswith("##") else token_str
assert raw.lower() == surface.lower(), (token_str, raw, surface, start, end)
print(f"{token_str!r:>12} ids={token_id:<6} offsets=({start},{end}) raw={raw!r}")
print("Diagnostic completed without assertion failures.")
When you run this against the pinned English uncased model, the assertions check three properties. First, every special token in the returned model-input sequence has a zero-length offset. Second, every non-special token has a non-empty raw span. Third, for every non-special token except [UNK], the lowercased raw slice matches the token surface after stripping a leading ##. The printout shows each token string, ID, offsets, and raw slice so you can inspect gaps and normalizations. If an assertion fails, the tuple in the assertion message identifies the token and offsets to investigate.
Interpreting the observations
Zero-length offsets are sentinels, not text. Slicing with (0, 0) yields an empty string, which is correct for a special token but wrong if you attach a label to that position. For content tokens, the raw slice is the substring from the original input. For a continuation token such as ##ing, the token string includes the continuation marker, but the offset points only at ing; do not include ## in raw text comparisons. For [UNK], the offset may cover the original out-of-vocabulary word, but the token string is the placeholder [UNK]; raw slicing recovers the original word, which is useful for provenance but not a vocabulary lookup. Content offsets are not guaranteed to tile the entire string: whitespace and normalization can leave gaps. Therefore, concatenating all non-special slices will not necessarily reconstruct the input.
Limitations and edge cases
This diagnostic validates one pinned model and library version. It does not prove stability across revisions. The uncased tokenizer lowercases and may strip accents; the code above uses ASCII and skips [UNK] equality. If you use padding, [PAD] offsets are zero-length model-input offsets, and their presence changes the sequence length without adding content. If you use truncation, tokens beyond the cutoff are removed, but the remaining offsets still refer to the original string. If you use return_overflowing_tokens, offsets refer to the current chunk unless you track the chunk offset yourself. The multilingual cased model uses a different vocabulary and normalization; rerun the diagnostic with cased text and the pinned multilingual revision. Also, offset_mapping is a fast-tokenizer feature in this version; the slow BERT tokenizer path does not provide the same return.
Re-checking after a pin or dependency change
When the pinned tokenizer.json or transformers version changes, rerun the diagnostic before trusting previous offset assumptions. Confirm the model ID, full revision hash, and transformers==4.56.2 or its replacement. Then check the same invariants: one offset per input ID, special tokens have start == end, content tokens have start < end, and non-[UNK] surfaces match lowercased raw slices after stripping ##. If the vocabulary size or normalization settings change, the set of fragmentation and unknown tokens can change even when the Python API looks identical. For the multilingual cased model, repeat the process at revision 3f076fdb1ab68d5b2880cb87a0886f315b8146f8 with representative cased text; do not reuse English uncased results. If any invariant fails, treat the offsets as unvalidated for that revision and update downstream span logic before shipping.
Validating offset_mapping is a small, repeatable contract check. It prevents zero-length special tokens and ## continuations from becoming incorrect character spans, and it separates unknown-token provenance from fragmentation. The pin and the test are what make the claim reproducible.
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.