Skip to content
wordpiece.org

Reserving room for BERT special tokens under max_length

Test truncation on a pinned tokenizer with and without special tokens; derive content budget from masks rather than guessing

Published 8 min read Verified

max_length is a ceiling on the sequence handed to the model, not a promise that max_length source words survive. With the pinned google-bert/bert-base-uncased tokenizer at revision 86b5e0934494bd15c9632b12f734a8a67f723594, a non-pair BERT input is framed by [CLS] and [SEP], so the effective content budget is smaller than the numeric limit. The reliable engineering rule is to derive that budget from returned masks for the exact tokenizer and library version, rather than counting words or subtracting a remembered constant.

Separate tokens from positions

Keep three quantities separate. A model-input token is an ID in input_ids; for this tokenizer it can include inserted special tokens and, in a padded batch, padding. A content token is a live, non-padding ID representing source text. An active position is indicated by attention_mask. special_tokens_mask identifies the tokenizer’s special-token treatment.

With padding=False, an active position has attention value 1, and this probe can derive content as active AND not special. The script still prints offsets so the classification can be checked rather than inferred from token strings.

Unknown handling and fragmentation are different observations. [UNK] is a fallback ID for source text that the tokenizer cannot represent as known WordPieces; it consumes a position but is not the same event as a word being split into several IDs. A continuation piece such as a token beginning with ## evidences fragmentation, and every resulting piece consumes a position. A third event is truncation: the remaining source suffix is absent.

Because [UNK] is registered as a BERT special token, production code should not blindly interpret every special_tokens_mask value of 1 as an inserted wrapper. The controlled sample below asserts that no unknown occurs. For arbitrary data, compare with an add_special_tokens=False encoding and use fast-tokenizer offsets to retain source-derived unknowns as content.

Reproduce the reservation

Install the exact library with python -m pip install "transformers==4.56.2", then run the following in a clean Python 3 environment. It requests the full tokenizer commit through AutoTokenizer, deliberately uses a source longer than the cap, and prints both the model-input and mask-derived content views.

import transformers
from transformers import AutoTokenizer

MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
TRANSFORMERS_VERSION = "4.56.2"
MAX_LENGTH = 8

assert transformers.__version__ == TRANSFORMERS_VERSION, (
    f"Expected Transformers {TRANSFORMERS_VERSION}, "
    f"got {transformers.__version__}"
)

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    revision=FULL_COMMIT,
    use_fast=True,
)
assert tokenizer.is_fast
assert tokenizer.unk_token_id is not None

# A long, known-token stream ensures that both final calls really truncate.
text = " the" * (MAX_LENGTH * 8)
source = tokenizer(
    text,
    add_special_tokens=False,
    truncation=False,
)
assert len(source["input_ids"]) > MAX_LENGTH
assert tokenizer.unk_token_id not in source["input_ids"]

options = {
    "text": text,
    "max_length": MAX_LENGTH,
    "truncation": True,
    "padding": False,
    "return_attention_mask": True,
    "return_special_tokens_mask": True,
    "return_offsets_mapping": True,
}

with_special = tokenizer(**options, add_special_tokens=True)
without_special = tokenizer(**options, add_special_tokens=False)


def describe(label, encoded):
    ids = encoded["input_ids"]
    attention = encoded["attention_mask"]
    special = encoded["special_tokens_mask"]
    offsets = encoded["offset_mapping"]
    tokens = tokenizer.convert_ids_to_tokens(ids)

    assert len(ids) == len(attention) == len(special) == len(offsets)

    content_mask = [
        int(active == 1 and is_special == 0)
        for active, is_special in zip(attention, special)
    ]
    live_special_positions = [
        i for i, (active, is_special) in enumerate(zip(attention, special))
        if active == 1 and is_special == 1
    ]
    unknown_positions = [
        i for i, token_id in enumerate(ids)
        if token_id == tokenizer.unk_token_id
    ]
    continuation_positions = [
        i for i, token in enumerate(tokens)
        if token.startswith("##")
    ]

    print(f"\n{label}")
    print("Transformers:", transformers.__version__)
    print("model-input token count:", len(ids))
    print("input_ids:", ids)
    print("tokens:", tokens)
    print("attention_mask:", attention)
    print("special_tokens_mask:", special)
    print("content_mask:", content_mask)
    print("offset_mapping:", offsets)
    print("live special positions:", live_special_positions)
    print("[UNK] positions:", unknown_positions)
    print("WordPiece continuation positions:", continuation_positions)

    return {
        "input_count": len(ids),
        "content_count": sum(content_mask),
        "live_special_count": len(live_special_positions),
    }


with_result = describe("with special tokens", with_special)
without_result = describe("without special tokens", without_special)

assert with_result["input_count"] == MAX_LENGTH
assert without_result["input_count"] == MAX_LENGTH
assert without_result["content_count"] == MAX_LENGTH
assert (
    with_result["content_count"] + with_result["live_special_count"]
    == MAX_LENGTH
)

derived_reservation = (
    without_result["content_count"] - with_result["content_count"]
)
assert derived_reservation == with_result["live_special_count"]

print("\nDerived content budget:", with_result["content_count"])
print("Derived special-token reservation:", derived_reservation)

Interpret the masks

The untruncated assertion matters. If the source fits inside eight positions, both calls can look full-length without proving how truncation interacts with the wrapper. On a conforming local run, both input_ids lists should reach MAX_LENGTH; the with-special call should expose more live mask values of 1, while the without-special call should reserve none.

Read the printed token count and mask-derived reservation together. If the live special count is two, the content count must be six. The script never inserts six into the calculation: it obtains the count from masks and checks that the difference between the two content counts equals the live special count.

The no-special result is a diagnostic baseline, not a model-ready BERT classification input. Keep add_special_tokens=True in the final encoding. In a padded batch, first restrict every count to attention-mask positions; otherwise padding can be mistaken for content or reservation.

For a short input, use the probe-derived ceiling B = max_length - R, where R is the observed live wrapper count, and compare it with the untruncated no-special content count: retained content is min(B, C_raw). Run a separate probe if production tokenizes pairs, adds another sequence type, changes truncation strategy, or uses a different checkpoint.

Turn the probe into a regression check

Put the mask-derived budget in preprocessing configuration rather than repeating arithmetic at every call site. Log the revision, Transformers version, max_length, live special count, active content count, unknown count, continuation-piece count, and whether padding was enabled.

The repeated-the sample is deliberately boring: it creates a long, known-token stream, so the only expected reduction is the BERT frame. Real evaluation sets should add separate probes containing inputs that elicit [UNK] and words that fragment; do not combine those questions with the wrapper-reservation assertion.

Before deployment, turn the central relationship into a small regression test: on an overlong known-token probe, with_content + live_special == max_length, and without_content - with_content == live_special. Keep the full revision and library version in the test metadata. Treat a sudden change in retained IDs as a tokenizer contract change until reviewed, even if plain-text token counts appear stable.

Limitations

This result is limited to the fast English uncased tokenizer at the full commit above, one non-pair sequence, the default BERT template, and no padding. It does not establish a count for another checkpoint, a slow tokenizer, or a newer dependency stack. Offsets require the fast backend, which the script checks.

The pinned 30,522-entry WordPiece vocabulary is a lookup inventory, not sequence capacity. Pinning only Transformers also does not freeze every transitive dependency, so record the resolved environment when reproducibility matters. The code diagnoses token budgeting only; it makes no claim about task accuracy or whether a model can benefit from the retained text.

Verification and re-check

Verification boundary: Verified: 2026-10-05 for google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and Transformers 4.56.2. This records review of the pinned tokenizer.json, the versioned tokenizer API, and the versioned BertTokenizerFast source. The JSON is the file-level authority for this checkpoint; the API and implementation explain the encoding fields and wrapper behavior used here. This is not a claim that the code was executed for this article.

When the pinned file or dependency changes, re-check rather than extrapolating. Pin the new full commit in a fresh environment, install the intended Transformers version, and rerun the probe before changing production arithmetic. Review the new tokenizer.json special-token and WordPiece settings, then compare the new versioned API and source with the masks, offsets, and assertions printed locally. If the derived live-special count or retained-prefix relationship changes, update both the configured content budget and its regression test, and record the model revision, Transformers version, backend version, and verification date. A mutable branch name is not an adequate substitute for those recorded values.

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