Testing longest-first truncation on BERT text pairs
Inspect which side loses tokens under a chosen max_length and contrast only_first/only_second options with printed evidence
Longest-first does not divide the available BERT input budget equally between two texts, and it does not measure which text matters more. The precise engineering problem is whether a paired encoding made with max_length=24 actually stays within that limit, and which side supplied the removed content tokens. A related failure is selecting only_first or only_second and moving overflow to the untouched side. The procedure below prints those facts for a deliberately short first text and a long second text.
Verified: 2026-10-05 for google-bert/bert-base-uncased at full revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. The evidence boundary is the pinned tokenizer.json, the versioned Tokenizer API documentation, and the versioned BertTokenizerFast implementation. This is a reproducible diagnostic, not a captured run: no resulting count or token string is claimed in advance.
Count content and model-input tokens separately
For this pinned BERT WordPiece tokenizer, a non-empty text pair with special tokens has the layout [CLS] first [SEP] second [SEP]. At max_length=24, three positions are reserved for those special tokens, leaving 21 positions for pair content.
A content token is a non-special token attributed to the first or second sequence by the fast tokenizer’s sequence_ids() method. It is not necessarily a source word: normalization, pre-tokenization, and WordPiece matching can produce several content tokens for one word. A model-input token is any entry in input_ids, including [CLS] and both [SEP] tokens. token_type_ids are metadata, not additional tokens.
The script disables padding so that len(input_ids) is directly comparable with the configured limit. Production code that pads to max_length will always have an input-ID length of 24, even when its content is shorter. In that case, use the attention mask and special_tokens_mask to distinguish real tokens from padding and special tokens; special_tokens_mask is not an attention mask.
Run the paired diagnostic
Install the exact dependency with python -m pip install transformers==4.56.2, then run this self-contained script. The tokenizer-class assertion confirms that the diagnostic uses the fast implementation before it inspects the paired encoding. The text includes an emoji and an unusual alphanumeric word so that unknown and fragmented output can be inspected, but the script does not assume that either condition will occur.
import transformers
from transformers import AutoTokenizer
MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
MAX_LENGTH = 24
PAIR_SPECIAL_TOKENS = 3
assert transformers.__version__ == "4.56.2", (
f"Expected transformers==4.56.2, got {transformers.__version__}"
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.__class__.__name__ == "BertTokenizerFast"
assert tokenizer.is_fast
FIRST = (
"Can the emoji 🧪 and word Xylophonic42 stay visible "
"in this customer question?"
)
SECOND = " ".join(
[
"The support transcript says that a long context is useful only "
"when the classifier can see both fields.",
"Please preserve the diagnostic reason codes and compare them "
"with the account history before deciding.",
]
* 4
)
def encode(strategy):
options = {}
if strategy is not False:
options["max_length"] = MAX_LENGTH
return tokenizer(
FIRST,
SECOND,
add_special_tokens=True,
truncation=strategy,
padding=False,
return_length=True,
return_special_tokens_mask=True,
return_offsets_mapping=True,
**options,
)
def side_info(encoding, side):
indices = [
index
for index, sequence_id in enumerate(encoding.sequence_ids())
if sequence_id == side
]
input_ids = [encoding["input_ids"][index] for index in indices]
tokens = tokenizer.convert_ids_to_tokens(input_ids)
offsets = [encoding["offset_mapping"][index] for index in indices]
return {
"tokens": tokens,
"unknowns": [
token for token in tokens if token == tokenizer.unk_token_id
],
"fragments": [
token for token in tokens if token.startswith("##")
],
"source_span": (offsets[0], offsets[-1]) if offsets else None,
}
def token_preview(tokens):
if not tokens:
return "<none>"
if len(tokens) <= 18:
return " ".join(tokens)
return " ".join(tokens[:12]) + " ... " + " ".join(tokens[-4:])
baseline = encode(False)
content_budget = MAX_LENGTH - PAIR_SPECIAL_TOKENS
baseline_counts = {
side: len(side_info(baseline, side)["tokens"])
for side in (0, 1)
}
# Ensure this test exercises overflow from the second side and leaves
# enough first-side content to fit by itself.
assert sum(baseline_counts.values()) > content_budget
assert baseline_counts[0] <= content_budget < baseline_counts[1]
encodings = {
"untruncated": baseline,
"longest_first": encode("longest_first"),
"only_first": encode("only_first"),
"only_second": encode("only_second"),
}
for name, encoding in encodings.items():
model_length = len(encoding["input_ids"])
assert model_length == encoding["length"]
assert sum(encoding["special_tokens_mask"]) == PAIR_SPECIAL_TOKENS
assert (
PAIR_SPECIAL_TOKENS
+ sum(sequence_id is not None
for sequence_id in encoding.sequence_ids())
== model_length
)
# These assertions express the consequences of the checked preconditions.
assert encodings["longest_first"]["length"] == MAX_LENGTH
assert encodings["only_second"]["length"] == MAX_LENGTH
assert encodings["only_first"]["length"] > MAX_LENGTH
print(f"model={MODEL_ID}@{FULL_COMMIT}")
print(f"transformers={transformers.__version__}")
print(f"vocab_size={tokenizer.vocab_size}; content_budget={content_budget}")
print(
"baseline specials:",
tokenizer.convert_ids_to_tokens(
[
index
for index, mask in enumerate(baseline["special_tokens_mask"])
if mask
]
),
)
for name, encoding in encodings.items():
model_length = len(encoding["input_ids"])
fits = "yes" if model_length <= MAX_LENGTH else "NO"
print(f"\n{name}: model_input_tokens={model_length}, fits={fits}")
for side, label in ((0, "first"), (1, "second")):
info = side_info(encoding, side)
kept = len(info["tokens"])
lost = baseline_counts[side] - kept
print(
f" {label}: kept={kept}/{baseline_counts[side]}, "
f"lost={lost}"
)
print(f" tokens: {token_preview(info['tokens'])}")
print(f" source offsets: {info['source_span']}")
print(f" [UNK] tokens: {info['unknowns']}")
print(f" ## continuation tokens: {info['fragments']}")
Interpret the printed evidence
Begin with the untruncated row. It establishes the first and second content-token counts under the same normalization and WordPiece vocabulary. For every other row, lost is the baseline count for that side minus its retained count. This identifies which side supplied the overflow; it does not imply that the side was semantically less important.
With longest_first, the tokenizer repeatedly removes tokens from the currently longer content sequence until the pair, including special tokens, fits. It has no per-side quota and does not preserve a fixed textual ratio. In this setup, all necessary removal can come from the second side, so its result may match only_second. If the second side cannot absorb all overflow, the first side may also be shortened.
only_second leaves the first sequence untouched and truncates the second to the space remaining after the first sequence and three special tokens. only_first performs the converse operation. Because the script first verifies that the untruncated second sequence alone exceeds the 21-token content budget, an only_first result remains longer than 24 once its untouched second side and the special tokens are restored. The explicit assertion and printed length make that edge behavior visible. Production validation must therefore inspect the returned length rather than treating a non-None truncation option as proof that the pair obeyed max_length.
The token previews also show the prefix-retention effect: ordinary truncation removes tokens from the end. The first and last fast-tokenizer offsets provide a compact source-character span, but their difference is not a character-loss percentage because normalization and subword matching are not character-preserving operations.
Distinguish unknowns from fragmentation
An [UNK] entry is an unknown token: the tokenizer could not represent the relevant normalized text with a known WordPiece vocabulary item. A token beginning with ##, such as a continuation piece, represents fragmentation rather than an unknown. A source word may therefore be rejected as [UNK], divided into several known pieces, or handled through some combination of normalization and subword pieces.
The separate diagnostic lists expose both conditions. An increase in [UNK] or ## tokens after truncation would indicate a changed side representation, but not automatically a changed source meaning. The lists also avoid the misleading assumption that one printed token equals one source word.
Limitations
All behavioral claims and example counts in this procedure are limited to the exact uncased model revision, its pinned tokenizer files, and transformers==4.56.2. They do not extend to another BERT checkpoint, revision, tokenizer backend, or dependency version. The value 24 and the two example strings are a controlled diagnostic, not a benchmark or a recommended production limit.
The procedure tests tokenizer output, not model accuracy, attention, padding behavior, or downstream task quality. A data collator or model wrapper may apply another length policy after tokenization, so the final batch should also be checked when this code is adapted to a training or inference pipeline.
Re-check after a pinned-file or dependency change
Create a clean environment for the candidate tokenizer file and Transformers version, then rerun the unchanged text pair, budget, and assertions. Record the printed library version, tokenizer class, vocabulary size, special-token count, baseline side counts, retained token lists, source spans, and final model-input lengths. These values form a behavioral snapshot rather than a general tokenizer guarantee.
When changing the tokenizer pin, replace FULL_COMMIT with the new full 40-character commit and inspect tokenizer.json and the tokenizer configuration at that same revision before comparing results. When changing Transformers, test the new version in isolation and review its versioned tokenizer documentation and BERT implementation. Re-run the production collator afterward and add a final assertion that each example’s non-padding model-input length does not exceed the intended budget. Update the “Verified” date only after those observations have been reviewed; do not silently combine results from two tokenizer revisions or dependency versions.
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.