Inspecting BERT separator placement for text pairs
Encode a pair and inspect tokens and special_tokens_mask; explain the two SEP markers and counting implications
Verified: 2026-10-05. The source-defined pattern for an ordinary, unpadded text pair is [CLS] A [SEP] B [SEP], where A and B are separately tokenized inputs, not one concatenated string. For the controlled check below, exactly three tokens are tokenizer-added: [CLS] and the two [SEP] tokens. This statement applies only to google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594, loaded as a fast tokenizer with transformers==4.56.2. The pinned tokenizer.json is the authority for vocabulary and normalization; the versioned Transformers API and BERT fast-tokenizer source govern the wrapper behavior. The code reveals observations when executed rather than presenting a captured run.
Establish the boundary
Use a pair with no literal [CLS], [SEP], or [PAD] strings. For this first pass, keep padding and truncation off. Compare the returned IDs with IDs produced from each segment using add_special_tokens=False. This isolates postprocessor work from length policies. The assertion checks the complete sequence; the table shows actual indices, IDs, segment labels, and mask values. Counts are computed at runtime because the committed tokenizer file should determine piece IDs rather than a memorized example.
Run this in a clean environment containing transformers==4.56.2. Access to the pinned model file, either online or through the Hugging Face cache, is required.
import transformers
from transformers import AutoTokenizer, BertTokenizerFast
MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
EXPECTED_TRANSFORMERS = "4.56.2"
assert transformers.__version__ == EXPECTED_TRANSFORMERS, (
f"Expected transformers=={EXPECTED_TRANSFORMERS}, "
f"found {transformers.__version__}"
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
revision=FULL_COMMIT,
use_fast=True,
)
assert tokenizer.is_fast
assert isinstance(tokenizer, BertTokenizerFast)
first_text = "Inspect the pair boundary."
second_text = "Count model inputs separately."
a_ids = tokenizer.encode(first_text, add_special_tokens=False)
b_ids = tokenizer.encode(second_text, add_special_tokens=False)
encoded = tokenizer(
first_text,
text_pair=second_text,
add_special_tokens=True,
padding=False,
truncation=False,
return_attention_mask=True,
return_special_tokens_mask=True,
return_token_type_ids=True,
)
input_ids = encoded["input_ids"]
special_mask = encoded["special_tokens_mask"]
sequence_ids = encoded.sequence_ids()
expected_ids = (
[tokenizer.cls_token_id]
+ a_ids
+ [tokenizer.sep_token_id]
+ b_ids
+ [tokenizer.sep_token_id]
)
expected_mask = (
[1]
+ [0] * len(a_ids)
+ [1]
+ [0] * len(b_ids)
+ [1]
)
expected_sequence_ids = (
[None]
+ [0] * len(a_ids)
+ [None]
+ [1] * len(b_ids)
+ [None]
)
assert input_ids == expected_ids
assert special_mask == expected_mask
assert sequence_ids == expected_sequence_ids
sep_positions = [
i for i, token_id in enumerate(input_ids)
if token_id == tokenizer.sep_token_id
]
assert sep_positions == [len(a_ids) + 1, len(a_ids) + len(b_ids) + 2]
without_specials = tokenizer(
first_text,
text_pair=second_text,
add_special_tokens=False,
padding=False,
truncation=False,
)
assert without_specials["input_ids"] == a_ids + b_ids
tokens = tokenizer.convert_ids_to_tokens(input_ids)
content_count = sum(segment_id is not None for segment_id in sequence_ids)
first_count = sum(segment_id == 0 for segment_id in sequence_ids)
second_count = sum(segment_id == 1 for segment_id in sequence_ids)
assert content_count == len(a_ids) + len(b_ids)
assert content_count == sum(mask == 0 for mask in special_mask)
unknown_positions = [
i for i, token in enumerate(tokens)
if token == tokenizer.unk_token
]
continuation_positions = [
i for i, token in enumerate(tokens)
if token.startswith("##")
]
print(f"model={MODEL_ID}")
print(f"revision={FULL_COMMIT}")
print(f"transformers={transformers.__version__}")
print(f"tokenizer_class={tokenizer.__class__.__name__}")
print()
print("index token_id token segment special")
for i, (token_id, token, segment_id, special) in enumerate(
zip(input_ids, tokens, sequence_ids, special_mask)
):
segment_label = "-" if segment_id is None else str(segment_id)
print(f"{i:>5} {token_id:>8} {token:<12} {segment_label:>7} {special:>7}")
print()
print(f"first_segment_content={first_count}")
print(f"second_segment_content={second_count}")
print(f"content_tokens={content_count}")
print(f"model_input_tokens={len(input_ids)}")
print(f"structural_special_tokens={sum(special_mask)}")
print(f"attention_mask_sum={sum(encoded['attention_mask'])}")
print(f"separator_positions={sep_positions}")
print(f"without_specials_model_input_tokens={len(without_specials['input_ids'])}")
print(f"unknown_positions={unknown_positions}")
print(f"wordpiece_continuation_positions={continuation_positions}")
Interpret tokens and masks
The two separator positions are not duplicate labels. The first closes A and marks the transition into B; the second closes B and marks the end of the pair. Both use the same sep_token_id, so their roles come from ordering and segment metadata, not from different token values. Counting separator strings establishes their presence but, without positions, does not establish segment placement.
encoded.sequence_ids() provides the stronger check: it returns None for inserted control tokens, 0 for A’s ordinary tokens, and 1 for B’s ordinary tokens. Segment content counts should not be inferred by counting token_type_ids == 0, because BERT also uses type zero for special positions while assigning type one to B’s content. sequence_ids() answers a boundary question; token_type_ids is a model-input field.
The special_tokens_mask is categorical. In this controlled call, zero occurs on the two segments and one occurs on [CLS] and both separators. It neither names the special token nor distinguishes the first separator from the second. Compare it with input_ids and sequence_ids(). A padded call can add further one entries for padding, so “three ones” is an assertion for this no-padding diagnostic, not a universal identity.
Count what enters the model
Content tokens are the pieces of A and B. Model-input tokens are every slot in input_ids. Here, without padding, len(input_ids) equals the two segment counts plus three structural tokens. The script derives segment A from sequence_ids() == 0, segment B from sequence_ids() == 1, and total content from non-None segment IDs. Under these conditions, content also equals the number of zero mask entries. A report about WordPiece content length is therefore not automatically a report about full sequence length.
In a padded batch, len(input_ids) measures the rectangular allocation for the sample, not its original tokenization length. attention_mask identifies retained non-padding positions, while special_tokens_mask identifies tokenizer-added tokens, including padding. Do not substitute either mask for the other, and do not assume every one-valued entry means [CLS]; it can mark padding. Report content, structural specials, and padding separately when a context or cache calculation depends on them.
Truncation changes the observation again. With an explicit max_length and truncation=True, the paired strategy removes content from the longer segment until the complete encoded pair, including its structural tokens, fits. The API also exposes only_first and only_second, but they remain disabled above. After enabling production settings, rerun the inspection. A surviving pair may have unequal or empty segments, so two final [SEP] tokens alone do not prove that all original content survived.
Diagnose unknown tokens and fragmentation
An unknown token and WordPiece fragmentation are different observations. The script counts tokens equal to tokenizer.unk_token separately from continuation pieces beginning with ##. A WordPiece [UNK] means a normalized, pre-tokenized word could not be assembled from known vocabulary pieces. Multiple known pieces using the continuing-subword prefix instead indicate fragmentation of a representable word. Neither observation identifies a separator; separator placement is checked by token ID, order, and segment metadata.
Do not infer lexical coverage from special_tokens_mask alone. In this fast-tokenizer diagnostic, the mask describes tokenizer-added control tokens; it is not an in-vocabulary flag. Inspect the converted token and its source context when distinguishing fallback from fragmentation. A literal registered control string in user text is a separate edge case: the first probe deliberately excludes it, and production analysis should establish its provenance rather than silently treating every special ID as a postprocessor insertion.
Re-check settings and revisions
Repeat the diagnostic with the exact strings, options, and batch shape used in production. Print sequence length, the attention-mask sum, segment content counts, separator positions, unknown positions, and continuation-piece positions. Exercise a pair that exceeds the intended max_length, then test a specific truncation policy only where the application permits it. This separates deliberate truncation from a missing separator or a reporting error.
When the pinned file or dependency changes, retain the model ID, new full commit, tokenizer class, exact Transformers version, and raw tokenizer file. Run the probe in a clean environment. Compare the segment IDs without specials as well as the final pattern: the structural assertion can continue passing while a normalization rule, vocabulary entry, special-token ID, or piece count changes. Review the new pinned JSON, versioned tokenizer API, and BERT wrapper source, then refresh the verification date. A mutable branch reference is not sufficient audit evidence.
Limits and evidence
This procedure diagnoses serialization for the exact English uncased revision above and the dependency named at verification. It does not reveal which attention interactions occur between separator positions and content, and it makes no prediction-quality claim. Token IDs, casing, unknown-word behavior, and counts do not transfer to google-bert/bert-base-multilingual-cased at 3f076fdb1ab68d5b2880cb87a0886f315b8146f8; that revision requires a separate probe. Checking only clean, short, nonempty pairs also misses padding, truncation, alignment, and literal-special-token edge cases.
The evidence boundary is the pinned tokenizer.json, the Transformers 4.56.2 Tokenizer API, and the versioned BertTokenizerFast implementation. The assertions encode that boundary; the printed tokenization remains a local observation.
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.