Chunking long documents for BERT without cutting a word blindly
Use fast-tokenizer overflow mapping and offsets to keep raw-text provenance through overlapping windows
Modern machine learning pipelines must reliably map truncated text segments back to their original source positions. This practice requires tokenizing long documents to preserve accurate offset mappings and account for both overlapping windows and token-level sequence differences. By utilizing the pinned fast tokenizer over the complete raw string with overflow enabled, systems retain source offsets beside every window to ensure accurate character tracing. Instead of imposing an arbitrary character limit and slicing the source, the engineering goal dictates recognizing that BERT boundary accounting, WordPiece normalization, and overlap all operate below the character-counting layer. This approach makes every model-input window traceable to one source record and a character interval while identifying repeated overlap so it is not mistaken for new text.
Verified: 2026-10-05 for google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. All token behavior and every token count below refer to that exact tokenizer revision; the script derives its observations locally instead of embedding expected output. Its pinned WordPiece vocabulary has 30,522 entries. A content token is a non-special token belonging to the source sequence. A model-input token is any position in input_ids, including the two BERT boundary tokens and any requested padding. The diagnostic requests no padding, but a production batch must not infer source coverage from tensor width.
Define a traceable window
Invoke the tokenizer with truncation=True, return_overflowing_tokens=True, a max_length for the complete model input, and a stride expressed in tokens. For this tokenizer’s postprocessor, [CLS] and [SEP] are included in that maximum length. For window i, overflow_to_sample_mapping[i] identifies the source item. With one source string, every value is zero; in a corpus, retain that mapping because token positions alone cannot identify documents. sequence_ids(i) separates original-sequence content from inserted features, while special_tokens_mask[i] marks special positions. For this fast tokenizer, offset_mapping[k] is a half-open source interval. Preserve those offsets with the window and use them to slice the unchanged source; do not decode, re-encode, or concatenate normalized token surfaces to establish provenance.
The following self-contained diagnostic uses a deliberately small limit so overflow occurs. In an environment containing exactly transformers==4.56.2, it prints locally obtained counts and spans and asserts provenance invariants rather than claiming a precomputed transcript.
from transformers import AutoTokenizer, __version__
MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
MAX_LENGTH = 16
STRIDE = 4
assert __version__ == "4.56.2", __version__
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.is_fast
text = " ".join([
"Alpha", "beta", "gamma", "delta", "epsilon",
"internationalization", "naïve", "café", "🧪",
"omicron", "pi", "rho", "sigma", "tau", "upsilon",
"phi", "chi", "psi", "omega", "retrieval", "provenance",
"overlap", "offsets",
])
encoded = tokenizer(
text,
add_special_tokens=True,
truncation=True,
max_length=MAX_LENGTH,
stride=STRIDE,
return_overflowing_tokens=True,
return_offsets_mapping=True,
return_special_tokens_mask=True,
padding=False,
)
input_windows = encoded["input_ids"]
assert len(input_windows) > 1, "The fixture did not overflow."
assert all(
source_id == 0
for source_id in encoded["overflow_to_sample_mapping"]
)
previous_spans = set()
for window_index, ids in enumerate(input_windows):
sequence_ids = encoded.sequence_ids(window_index)
special = encoded["special_tokens_mask"][window_index]
offsets = encoded["offset_mapping"][window_index]
assert len(ids) == len(sequence_ids) == len(special) == len(offsets)
assert all(
(sequence_id is None) == bool(is_special)
for sequence_id, is_special in zip(sequence_ids, special)
)
content_positions = [
position
for position, (sequence_id, is_special)
in enumerate(zip(sequence_ids, special))
if sequence_id == 0 and is_special == 0
]
assert content_positions
spans = [tuple(offsets[position]) for position in content_positions]
assert all(0 <= start < end <= len(text) for start, end in spans)
assert spans == sorted(spans)
content_ids = [ids[position] for position in content_positions]
token_strings = tokenizer.convert_ids_to_tokens(content_ids)
overlap_offsets = sorted(previous_spans.intersection(spans))
if window_index:
assert overlap_offsets, "Adjacent windows have no exact token overlap."
envelope = (spans[0][0], spans[-1][1])
unknown_count = sum(
ids[position] == tokenizer.unk_token_id
for position in content_positions
)
print({
"window": window_index,
"source_id": encoded["overflow_to_sample_mapping"][window_index],
"input_ids": ids,
"model_input_tokens": len(ids),
"special_token_count": sum(special),
"content_tokens": len(content_positions),
"content_token_strings": token_strings,
"content_offsets": spans,
"overlap_offsets": overlap_offsets,
"starts_with_continuation": token_strings[0].startswith("##"),
"ends_with_continuation": token_strings[-1].startswith("##"),
"unknown_content_tokens": unknown_count,
})
print("source_envelope=", text[envelope[0]:envelope[1]])
previous_spans = set(spans)
probe_text = "internationalization 🧪"
probe = tokenizer(
probe_text,
add_special_tokens=False,
return_offsets_mapping=True,
)
probe_ids = probe["input_ids"][0]
probe_rows = []
for token_id, offset in zip(probe_ids, probe["offset_mapping"][0]):
start, end = offset
assert 0 <= start < end <= len(probe_text)
probe_rows.append({
"token_id": token_id,
"token": tokenizer.convert_ids_to_tokens([token_id])[0],
"offset": offset,
"source_slice": probe_text[start:end],
"is_unknown": token_id == tokenizer.unk_token_id,
})
print("probe_rows=", probe_rows)
Interpret the windows
When the script passes, more than one window and a nonempty intersection of adjacent content-offset sets establish that this local tokenizer run produced overflow with token overlap. The envelope text[first_start:last_end] preserves whitespace and punctuation between the extreme token offsets. A shared envelope is not enough evidence of overlap, because consecutive lexical units can occupy one continuous character interval; exact repeated offset tuples provide that evidence. The envelope need not start at zero or end at the source length because leading or trailing whitespace may have no token. If an overlap assertion fails, inspect the returned window count, masks, and sequence IDs before changing production chunk logic.
Persist a window record with at least source_id, window_index, input_ids, content positions, offset pairs, and the original raw text or an immutable reference to it. Keep window_index separate from overflow_to_sample_mapping: the former orders truncations, while the latter selects the document. When batching, calculate content coverage before padding and keep padding out of aggregation. This schema allows rebuilding a display string from the source, identifying which token produced a model position, and reprocessing the window if tokenizer policy changes.
Separate unknowns from split words
The printed model_input value is len(input_ids); content excludes special positions. These counts should not be stored under the same name downstream. The continuation flags show whether a window starts or ends on a WordPiece token marked ##. The separate probe prints each token, source slice, offset, and whether its ID equals the pinned unknown-token ID. Several known pieces covering one lexical item indicate fragmentation, whereas a row whose ID equals unk_token_id records an unknown fallback. A tokenization can exhibit both phenomena, so report them separately. The 30,522-entry vocabulary size measures neither condition.
A ## flag is only a subword diagnostic, not a universal word-boundary oracle. Punctuation, contractions, hyphenation, and the corpus’s definition of a “word” require an explicit lexical policy. If windows must not split lexical units, group source offsets with a scanner appropriate to the document, detect boundaries inside a lexical span, and rebuild the cut at a legal boundary. Re-tokenize that candidate and recheck its input length and special-token budget. Increasing overlap can move a boundary, but a fixed stride does not guarantee whole-word cuts. If split WordPiece boundaries are acceptable, downstream code must still understand that windows overlap and that their outputs belong to original source spans.
Limits and re-verification
Offsets are tokenizer output, not claims about UTF-8 bytes, text decoded after uncasing, or semantic sentence boundaries. Normalization can change surface text, especially outside ordinary ASCII. Unknown tokens can also cover source characters, so retain the unchanged source alongside derived text. Offset support depends on the fast-tokenizer path and is not interchangeable with the slow tokenizer. Overlapping windows can repeat predictions or evidence; deduplicate by source and offset only when that matches the downstream task.
The behavior authority is the pinned tokenizer.json. Encoding fields and fast alignment options are defined by the Transformers 4.56.2 tokenizer API, while the BertTokenizerFast source defines the wrapper. These primary references form the evidence boundary; the verification date concerns those references, not a claim that the script was run in production.
When a pinned file or dependency changes, archive the new full commit and the previous tokenizer.json, compute a local SHA-256 for each, and review the vocabulary, normalizer, pre-tokenizer, WordPiece model, and postprocessor fields. Install the intended exact Transformers version and rerun the script with saved cases containing accents, punctuation, an unknown character, and a long lexical item. Diff token IDs, token strings, special masks, source mappings, offsets, envelopes, and overlap sets. Keep the structural assertions, then review any output diff before replacing regression baselines. Update FULL_COMMIT when the tokenizer revision changes; update the version assertion and consult the corresponding versioned documentation and source when Transformers changes. Revalidate any assumed model-input limit separately rather than inheriting the diagnostic’s 16-token setting.
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.