Skip to content
wordpiece.org

Inspecting overflowing BERT windows and stride

Use return_overflowing_tokens and stride on a long synthetic input; report mapping and overlap computed by code, not invented results

Published 8 min read Verified

An overflowing BERT encoding is not, by itself, evidence that text was lost. It means one source sample has become multiple model-input sequences. The exact scope of this procedure is google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594, using transformers==4.56.2. Verified: 2026-10-05. The diagnostic sets max_length from the tokenizer’s configured maximum, creates enough synthetic English to force overflow, and reports mapping, content-token overlap, offsets, and unknown tokens. It does not present invented console values; readers obtain those values by running the script.

Keep the counting units separate

For each returned feature, len(input_ids) is the model-input token count. It includes special tokens such as [CLS] and [SEP], and would include padding if padding were requested. Content tokens are the positions whose special_tokens_mask value is zero. A content token can still be [UNK]: unknown status and membership in the content region are different questions. The pinned uncased tokenizer has a known WordPiece vocabulary of 30,522 entries, but that vocabulary size is not a window-size or source-word count.

Fast-tokenizer alignment supplies two further views. word_ids(feature_index) associates each content position with a word in the original tokenizer input. An offset pair associates it with a character span in the original string. Consequently, several content tokens can map to one source word without any of them being [UNK]. That is fragmentation, not unknown-word fallback. Requiring use_fast=True is important because the diagnostic relies on these alignment methods.

Stride is measured in reused content-token positions, not source words. It therefore cannot guarantee that the same number of complete words appears in adjacent windows. The procedure encodes the same input twice: once with stride=0 to establish a non-overlapping baseline, and once with stride=32 to inspect reuse. Offset intersections measure overlapping content tokens without confusing repeated text elsewhere in the synthetic input for boundary overlap.

Run the mapping and overlap diagnostic

Run the following in an environment containing transformers==4.56.2:

import transformers
from transformers import AutoTokenizer

MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
EXPECTED_TRANSFORMERS = "4.56.2"
STRIDE = 32

if transformers.__version__ != EXPECTED_TRANSFORMERS:
    raise RuntimeError(
        f"Expected transformers=={EXPECTED_TRANSFORMERS}, "
        f"got {transformers.__version__}"
    )

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    revision=FULL_COMMIT,
    use_fast=True,
)
assert tokenizer.is_fast

MAX_LENGTH = tokenizer.model_max_length

# Each whitespace-delimited item produces at least one content token,
# so this source is guaranteed to exceed the configured model-input limit.
unit = "the quick brown fox jumps over the lazy dog"
text = " ".join([unit] * 80)
assert len(text.split()) > MAX_LENGTH

full = tokenizer(
    text,
    add_special_tokens=False,
    return_offsets_mapping=True,
)
source_offsets = [tuple(pair) for pair in full["offsets"]]
source_offset_set = set(source_offsets)
assert len(source_offset_set) == len(source_offsets)


def encode_with_overflow(stride):
    return 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,
    )


def inspect(label, encoded, requested_stride):
    features = encoded["input_ids"]
    mapping = list(encoded["overflow_to_sample_mapping"])

    # One source sample can produce many overflowing features.
    assert len(features) >= 2
    assert mapping and set(mapping) == {0}

    covered_offsets = set()
    previous_offset_set = None
    overlap_sizes = []

    print(f"\n{label}")
    print(f"  overflow_to_sample_mapping={mapping}")
    print(
        f"  tokenizer.model_max_length={tokenizer.model_max_length}; "
        f"requested max_length={MAX_LENGTH}"
    )
    print(
        f"  vocab_size={tokenizer.vocab_size}; "
        f"unk_id={tokenizer.unk_token_id}; "
        f"cls_id={tokenizer.cls_token_id}; "
        f"sep_id={tokenizer.sep_token_id}"
    )

    for feature_index, input_ids in enumerate(features):
        special_mask = encoded["special_tokens_mask"][feature_index]
        offsets = encoded["offsets"][feature_index]
        word_ids = encoded.word_ids(feature_index)
        sequence_ids = encoded.sequence_ids(feature_index)

        assert all(value in (0, 1) for value in special_mask)
        content_positions = [
            index for index, value in enumerate(special_mask) if value == 0
        ]
        special_positions = [
            index for index, value in enumerate(special_mask) if value == 1
        ]

        assert len(content_positions) + len(special_positions) == len(input_ids)
        assert all(word_ids[index] is not None for index in content_positions)
        assert all(sequence_ids[index] is not None for index in content_positions)
        assert {
            index for index, value in enumerate(sequence_ids) if value is None
        } == set(special_positions)

        content_offsets = [
            tuple(offsets[index]) for index in content_positions
        ]
        assert set(content_offsets).issubset(source_offset_set)
        assert all(
            0 <= start <= end <= len(text)
            for start, end in content_offsets
        )

        content_word_ids = [word_ids[index] for index in content_positions]
        unknown_count = sum(
            token_id == tokenizer.unk_token_id for token_id in input_ids
        )
        current_offset_set = set(content_offsets)
        covered_offsets.update(current_offset_set)

        print(
            f"  feature[{feature_index}]: "
            f"sample={mapping[feature_index]}, "
            f"model_input_tokens={len(input_ids)}, "
            f"content_tokens={len(content_positions)}, "
            f"special_tokens={len(special_positions)}, "
            f"unknown_content_tokens={unknown_count}"
        )
        print(
            f"    source_word_ids="
            f"{content_word_ids[0]}..{content_word_ids[-1]}; "
            f"first_offset={content_offsets[0]}; "
            f"last_offset={content_offsets[-1]}"
        )

        if previous_offset_set is None:
            print("    overlap_with_previous_content_tokens=not_applicable")
        else:
            shared_offsets = [
                offset
                for offset in content_offsets
                if offset in previous_offset_set
            ]
            position_by_offset = dict(
                zip(content_offsets, content_positions)
            )
            overlap_source_words = [
                word_ids[position_by_offset[offset]]
                for offset in shared_offsets
            ]
            overlap_sizes.append(len(shared_offsets))

            print(
                "    overlap_with_previous_content_tokens="
                f"{len(shared_offsets)}"
            )
            if shared_offsets:
                print(
                    f"    overlap_offsets={shared_offsets[0]}"
                    f"..{shared_offsets[-1]}"
                )
                print(
                    "    overlap_source_word_ids="
                    f"{overlap_source_words}"
                )

        previous_offset_set = current_offset_set

    assert covered_offsets == source_offset_set

    if requested_stride == 0:
        assert all(size == 0 for size in overlap_sizes)
    else:
        assert all(
            0 < size <= requested_stride for size in overlap_sizes
        )

    print(
        f"  source_content_tokens={len(source_offsets)}; "
        f"covered_source_content_tokens={len(covered_offsets)}"
    )


inspect("stride=0 baseline", encode_with_overflow(0), 0)
inspect("stride=32 diagnostic", encode_with_overflow(STRIDE), STRIDE)

Interpret the mapping and overlap

overflow_to_sample_mapping answers only which element of the original batch produced a feature. Because the script submits one string, every value is required to be zero. That does not mean there is only one feature: one original sample may produce several overflowing sequences. The printed feature index and len(input_ids) establish how those sequences were divided.

The first and last source word IDs show which portion of the original word sequence each feature represents. Offset pairs provide the more precise boundary into the original characters. The script also compares the union of all content offsets with the complete, untruncated tokenization. Equality means the returned windows cover every source content token; it does not mean every token appears only once.

The stride comparison is an invariant check, not a hardcoded result transcript. The baseline asserts that adjacent features share no source offset. The strided encoding asserts that every adjacent pair shares at least one and no more than the requested stride. Its exact overlap count is printed because special-token placement, feature length, and future tokenizer changes should be inspected rather than assumed. overlap_source_word_ids is ordered mapping data and can contain repeated IDs because both the source text and a source word’s pieces can recur; do not deduplicate that list and call the result a token count.

An unknown is identified by an input ID equal to tokenizer.unk_token_id. Fragmentation is identified by multiple content positions mapping to one non-None source word ID. A long input can produce neither condition, one condition, or both. Likewise, summing per-window content counts includes reused stride tokens and is not the number of unique source tokens.

Limits and re-check procedure

This is a preprocessing diagnostic, not an evaluation of BERT attention, long-document reasoning, or prediction aggregation. Transformers returns separate windows; it does not combine their hidden states. A word may also be cut at a window boundary even when the stride is nonzero. The synthetic ASCII text isolates tokenizer mechanics, so its counts must not be transferred to the multilingual cased tokenizer or to another BERT revision.

When the pinned tokenizer file or dependency changes, update FULL_COMMIT or the Transformers version deliberately rather than loosening the assertions. Review the exact pinned tokenizer.json, run both encodings again, and retain the printed dependency version, vocabulary size, special-token IDs, feature lengths, offset coverage, overlap sizes, and unknown counts. For byte-for-byte reproducibility, also lock the tokenizer backend and the rest of the environment. Never update an expected count merely to make a changed run pass; determine whether the tokenizer data, wrapper implementation, or another dependency caused the difference.

The evidence boundary is the pinned tokenizer.json, the Transformers 4.56.2 tokenizer API, and the versioned BertTokenizerFast implementation. The script supplies the local verification rather than implying that an unshown execution occurred.

Sources

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.

Check it yourself

Open the tokenizer

Every count in this guide comes from a vocabulary pinned by checksum. Paste the same text into the tool and you will get the same output.

Related guides