Skip to content
wordpiece.org

Verifying CLS and SEP placement for single BERT inputs

Compare add_special_tokens true/false and print special_tokens_mask; distinguish content count and model-input length

Published 8 min read Verified

For a single, unpaired BERT text, the precise check is the encoding wrapper: one [CLS] must precede the content IDs and one [SEP] must follow them. This procedure applies exactly to google-bert/bert-base-uncased at full revision 86b5e0934494bd15c9632b12f734a8a67f723594, loaded as a fast tokenizer with transformers==4.56.2. Verified: 2026-10-05. It checks placement and token accounting, not model quality, and leaves the example sentence’s locally produced count to execution rather than hard-coding an unperformed result.

Keep content tokens and model-input tokens separate

A content token is an ID produced with add_special_tokens=False. For the ordinary text used below, each content ID has a corresponding 0 in special_tokens_mask. The content count is therefore the number of IDs in that encoding, or equivalently the number of zero-mask entries when no padding is requested. Methods such as tokenize() also expose content pieces; they do not demonstrate that a model-input wrapper was applied.

A model-input token is every element of input_ids after the BERT wrapper runs. In this unpadded example, the model-input sequence is:

[CLS] content token 0 ... content token n [SEP]

Consequently, len(input_ids) is the model-input count, while the content count is two smaller. The attention_mask does not locate the boundary markers: every token, including [CLS] and [SEP], has value 1 when padding is disabled. Likewise, token_type_ids are all zero for this single unpaired BERT sequence; they identify sequence type, not special-token position.

Runnable structural check

Run this in a Python 3 environment containing exactly transformers==4.56.2. It prints every sample-dependent value and asserts the structural relationship.

import tokenizers
import transformers
from transformers import AutoTokenizer

MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
TEXT = "BERT places a marker at each sequence boundary."

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.is_fast, "The diagnostic requires the fast tokenizer."
assert tokenizer.cls_token_id is not None
assert tokenizer.sep_token_id is not None
assert tokenizer.unk_token_id is not None

common = {
    "padding": False,
    "truncation": False,
    "return_attention_mask": True,
    "return_special_tokens_mask": True,
    "return_offsets_mapping": True,
    "return_token_type_ids": True,
}

without_specials = tokenizer(
    TEXT,
    add_special_tokens=False,
    **common,
)
with_specials = tokenizer(
    TEXT,
    add_special_tokens=True,
    **common,
)

content_ids = without_specials["input_ids"]
input_ids = with_specials["input_ids"]
content_mask = without_specials["special_tokens_mask"]
special_mask = with_specials["special_tokens_mask"]
content_count = len(content_ids)
model_input_count = len(input_ids)

assert content_mask == [0] * content_count
assert input_ids == [
    tokenizer.cls_token_id,
    *content_ids,
    tokenizer.sep_token_id,
]
assert special_mask == [1] + [0] * content_count + [1]
assert model_input_count == content_count + 2
assert with_specials["attention_mask"] == [1] * model_input_count
assert set(with_specials["token_type_ids"]) == {0}

word_ids = with_specials.word_ids()
assert all(
    word_id is None
    for word_id, mask in zip(word_ids, special_mask)
    if mask == 1
)
assert all(
    word_id is not None
    for word_id, mask in zip(word_ids, special_mask)
    if mask == 0
)

content_tokens = tokenizer.convert_ids_to_tokens(content_ids)
input_tokens = tokenizer.convert_ids_to_tokens(input_ids)

print("Transformers version:", transformers.__version__)
print("Tokenizers backend version:", tokenizers.__version__)
print("Model:", MODEL_ID)
print("Revision:", FULL_COMMIT)
print("Tokenizer class:", tokenizer.__class__.__name__)
print("Vocabulary entries:", len(tokenizer))
print("Content count:", content_count)
print("Model-input count:", model_input_count)
print("Content IDs:", content_ids)
print("Content tokens:", content_tokens)
print("Model-input IDs:", input_ids)
print("Model-input tokens:", input_tokens)
print("Content special_tokens_mask:", content_mask)
print("Model-input special_tokens_mask:", special_mask)
print("Model-input attention_mask:", with_specials["attention_mask"])
print("Content offsets:", without_specials["offset_mapping"])
print("Model-input offsets:", with_specials["offset_mapping"])
print("Model-input word IDs:", word_ids)

print("Content token classifications:")
for token_id, token, offset in zip(
    content_ids,
    content_tokens,
    without_specials["offset_mapping"],
):
    if token_id == tokenizer.unk_token_id:
        kind = "unknown"
    elif token.startswith("##"):
        kind = "wordpiece-continuation"
    else:
        kind = "ordinary"
    print(f"  id={token_id!r}, token={token!r}, kind={kind}, offset={offset}")

The assertions establish that adding special tokens changes only the wrapper for this controlled input. The printed IDs, token strings, offsets, and counts come from the local execution. The (0, 0) offsets and None word IDs for inserted markers provide additional fast-tokenizer alignment evidence, but special_tokens_mask remains the direct placement signal.

Interpret the observations

  • If the wrapped IDs are not exactly [CLS] + content_ids + [SEP], inspect manual marker concatenation, a different tokenizer object, or encoding options that were not held constant.
  • If the marker IDs are correct but the full mask is not [1, 0, …, 0, 1], do not use that mask for downstream content accounting. Determine whether IDs and masks came from separate tokenizer calls or were modified downstream.
  • If a separator occurs between content regions, or more than two wrapper markers appear, check whether a text_pair argument, a literal registered special token, or a custom post-processor entered the call. The article’s contract is one unpaired text.
  • A difference other than two between the two counts is expected only when the encoded representations are no longer comparable—for example, when padding or truncation is enabled. With padding, tensor width is len(input_ids), but the row’s logical length is the sum of attention_mask; content length is the number of entries where attention is 1 and special_tokens_mask is 0.

The special-mask method is meaningful here because the diagnostic disables padding. With padding enabled, a zero special mask can mean either content or padding, so attention and special masks must be interpreted together.

Unknown tokens are not fragmentation

The pinned uncased tokenizer has a known 30,522-entry vocabulary, but inventory size says nothing about this sentence’s input length. Under the pinned WordPiece configuration, an unrepresentable tokenized unit can fall back to [UNK]; a representable unit can instead be divided into multiple known pieces. A token displayed with a leading ## is a WordPiece continuation, not an unknown token.

Count these independently:

unknown_count = sum(token_id == tokenizer.unk_token_id for token_id in content_ids)
fragment_count = sum(token.startswith("##") for token in content_tokens)

An occurrence of [UNK] remains content even though [UNK] is itself a vocabulary entry; it is not a wrapper-added [CLS] or [SEP]. One input can contain both unknown fallbacks and known continuation pieces, and the absence of one does not prove the absence of the other.

Limitations and re-check procedure

This check covers one ordinary, unpadded, untruncated, unpaired English input using the exact uncased model and revision named above. It does not validate paired-sequence placement, a custom post-processor, production padding and truncation policies, or the model’s downstream semantics. It also makes no claim for google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8; its normalization, inventory, IDs, and outputs require a separate run at that full revision. A network or cache-loading failure is not evidence of incorrect placement.

Keep both the full model revision and dependency versions in the deployment lock. In particular, record the installed tokenizers backend version as well as transformers==4.56.2; the latter alone may not freeze every transitive runtime detail. When selecting a new full commit or changing either dependency, create a clean environment, rerun this script, and retain its stdout, Python version, tokenizer class, and SHA-256 hashes of the downloaded tokenizer assets. Review changes to tokenizer.json, tokenizer configuration, special-token configuration, and the versioned API or source relevant to the new release before updating the verification date. If output changes while the same full commit is requested, treat it as dependency, loaded-asset, or environment drift until demonstrated otherwise.

Evidence boundary

The procedure is grounded in the pinned tokenizer.json, the Transformers 4.56.2 tokenizer API, and the versioned BertTokenizerFast source. The pinned JSON is the authority for that checkpoint’s vocabulary, normalization, and WordPiece configuration; the versioned documentation and source define the encoding options, returned mask, offsets, and fast-tokenizer behavior used here.

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