Why BERT token offsets can skip whitespace
Build a raw-span highlighting check for sentences with multiple spaces and punctuation; avoid assuming adjacent offsets
What “skip whitespace” means
A fast BERT tokenizer’s offset list is not required to cover every character in the original string. It is a list of half-open source spans for emitted tokens. If one token ends before the next token starts, the source between those boundaries has no token. Repeated spaces, tabs, and newlines can therefore appear as gaps. The offsets are not adjacent; they have not skipped a required boundary. A raw-span highlighter must preserve those gaps instead of assuming previous_end == next_start.
This does not mean whitespace was removed from the input or that the fast tokenizer returned incorrect coordinates. The coordinates describe tokens, not a partition of all source characters. For the exact tokenizer and ASCII cases used here, emitted punctuation has token spans while ignored whitespace remains available from the original text. Render each token with text[start:end]; do not reconstruct the source by concatenating token strings, which can lose spacing, casing, and other characters.
Scope and evidence
Verified: 2026-10-05. The applicable pair is google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594, loaded with transformers==4.56.2 and AutoTokenizer.from_pretrained(..., revision=FULL_COMMIT, use_fast=True). Every token behavior and count below is scoped to that pair. No count is hardcoded as an expected answer; the script derives model-input and content-token counts at runtime.
The evidence boundary is the pinned tokenizer.json, the Transformers 4.56.2 tokenizer API, and the versioned BertTokenizerFast implementation. The JSON file is the authority for this revision’s WordPiece vocabulary and normalization settings. The code is a diagnostic to run, not a transcript presented as a completed experiment.
Read the aligned arrays
With add_special_tokens=True, input_ids, offset_mapping, and special_tokens_mask are positionally aligned. Here [CLS] and [SEP] are model-input tokens but not content tokens. The mask, rather than token spelling or a guessed count, separates them. Consequently, len(input_ids) is the model-input token count, while the number of positions whose mask is zero is the content-token count. If only source tokens are needed, request add_special_tokens=False; otherwise, retain the mask during analysis.
Offsets use the original string as their coordinate system, even though an uncased tokenizer can return a lowercase or otherwise normalized token string. For highlighting, the source slice is authoritative. Do not search for the original casing inside the token string. Nor should special-token offset entries be treated as source spans; use special_tokens_mask to classify those positions.
Punctuation must be checked separately from whitespace. In these ASCII examples, BERT emits the comma, period, and exclamation mark as content tokens with nonempty spans. A gap between a word and punctuation would therefore be significant; a gap between two words can simply preserve ignored spaces. The following check makes both cases visible instead of treating all nonadjacent offsets as the same defect.
Runnable raw-span diagnostic
Install transformers==4.56.2 in an isolated environment, save this as a Python 3 file, and run it. It prints a source-preserving rendering, every raw span, derived counts, gaps, unknown positions, and adjacent WordPiece continuations. The assertions check structural properties rather than baking in a claimed output transcript.
import transformers
from transformers import AutoTokenizer
MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
PINNED_TRANSFORMERS = "4.56.2"
if transformers.__version__ != PINNED_TRANSFORMERS:
raise RuntimeError(
f"Expected transformers=={PINNED_TRANSFORMERS}, "
f"got {transformers.__version__}"
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.is_fast, "This diagnostic requires a fast tokenizer."
CASES = (
"Alpha beta, gamma.\n Delta!",
"unhyphenatable florbetgastropod.",
)
def render_source_spans(text, offsets, content_positions):
rendered = []
cursor = 0
for position in content_positions:
start, end = offsets[position]
rendered.append(text[cursor:start]) # Preserve gaps verbatim.
rendered.extend(("[", text[start:end], "]"))
cursor = end
rendered.append(text[cursor:])
return "".join(rendered)
print(f"transformers={transformers.__version__}")
print(f"model={MODEL_ID}@{FULL_COMMIT}")
for text in CASES:
encoded = tokenizer(
text,
add_special_tokens=True,
padding=False,
truncation=False,
return_offsets_mapping=True,
return_special_tokens_mask=True,
)
ids = encoded["ids"]
offsets = encoded["offset_mapping"]
special_mask = encoded["special_tokens_mask"]
tokens = tokenizer.convert_ids_to_tokens(ids)
content_positions = [i for i, mask in enumerate(special_mask) if mask == 0]
spans = [offsets[i] for i in content_positions]
assert len(ids) == len(offsets) == len(special_mask)
assert sum(special_mask) == tokenizer.num_special_tokens_to_add(pair=False)
assert special_mask[0] == special_mask[-1] == 1
assert ids[0] == tokenizer.cls_token_id
assert ids[-1] == tokenizer.sep_token_id
assert all(0 <= start < end <= len(text) for start, end in spans)
assert all(spans[i][1] <= spans[i + 1][0] for i in range(len(spans) - 1))
assert any(text[start:end] in {",", ".", "!"} for start, end in spans)
gaps = []
for left, right in zip(content_positions, content_positions[1:]):
left_end = offsets[left][1]
right_start = offsets[right][0]
if left_end < right_start:
gaps.append((left, right, text[left_end:right_start]))
if text == CASES[0]:
assert any(" " in gap for _, _, gap in gaps)
fragment_pairs = [
(left, right)
for left, right in zip(content_positions, content_positions[1:])
if offsets[left][1] == offsets[right][0]
and tokens[right].startswith("##")
]
unknown_positions = [
i for i in content_positions if ids[i] == tokenizer.unk_token_id
]
print("\nsource:", repr(text))
print("highlighted:", render_source_spans(text, offsets, content_positions))
print(f"model-input tokens={len(ids)}; content tokens={len(content_positions)}")
for i, (token_id, (start, end)) in enumerate(zip(ids, offsets)):
if special_mask[i]:
kind = "model special"
elif token_id == tokenizer.unk_token_id:
kind = "unknown"
elif tokens[i].startswith("##"):
kind = "WordPiece continuation"
else:
kind = "content"
print(
f" {i:>2} {kind:<21} id={token_id:<6} "
f"span=({start},{end}) raw={text[start:end]!r} token={tokens[i]!r}"
)
print("gaps:", gaps or "none")
print("unknown positions:", unknown_positions or "none")
print("adjacent WordPiece pairs:", fragment_pairs or "none")
The bracketed rendering appends the source between spans unchanged, so the first case visibly distinguishes “inside a token” from “between tokens.” A gap row displays the exact omitted source interval. In the first case, the assertion requires an interval containing two spaces; the punctuation assertion requires a nonempty comma, period, or exclamation-mark span. These are independent checks: preserving whitespace does not prove punctuation is represented, and finding punctuation does not prove that offsets are dense.
An unknown row and a WordPiece continuation row answer different questions. An unknown row has input_id == unk_token_id; it is the tokenizer’s replacement for a source unit it could not represent. It remains a content position for this accounting. A fragmentation row pairs a token beginning with ## with its immediately preceding content token and requires adjacent source spans. Multiple pieces are therefore not evidence of [UNK], and [UNK] should not be called fragmentation. The raw slice shows the source behind either result, although it cannot recover what the model lost through normalization or unknown-token replacement.
Build the highlighter from source intervals
Validate that offsets are in bounds and do not overlap for the input at hand. Then append any unassigned source unchanged, wrap each text[start:end] span independently, and append the untouched tail. Adjacent spans may share a boundary; nonadjacent spans must not be forced together. Escape the raw text for the output format, such as HTML. Use token IDs and masks for model-side classification, but use offsets and source slices for display.
Limitations
These conclusions apply only to the exact English uncased model revision and Transformers version above. They are not claims about the slow tokenizer or google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, which requires a separate pinned check. The examples are ASCII, single-sentence, unpaired, and untruncated. Padding adds model-input positions, while truncation leaves a source suffix without emitted tokens. An offset map locates tokenizer output; it does not measure model attention or semantic correctness.
Re-check after a pin or dependency change
When either pinned file or dependency changes, keep the model commit fixed while testing a candidate dependency in a clean environment, or keep Transformers fixed while inspecting a proposed full model commit. Adjust the version or revision guard in a diagnostic copy, run the same structural checks, and record the fully resolved environment. Inspect the new tokenizer.json vocabulary, normalization, unknown-token, special-token, and WordPiece settings before interpreting changed rows. Compare bounds, ordering, the repeated-space gap, punctuation spans, unknown positions, and fragmentation pairs. If an assertion fails, determine from the primary artifacts whether the change is intentional before modifying the highlighter; then update the commit, dependency version, evidence links, and article together.
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.