Using special_tokens_mask to compute content length
Derive content-token length from the returned mask for single and paired inputs without hardcoding overhead
Count the zero entries in special_tokens_mask returned by the same tokenizer call that builds the model input. This is more reliable than subtracting a remembered “two special tokens for text, three for a text pair” rule: the mask describes the sequence actually produced after BERT normalization, WordPiece segmentation, and post-processing.
All token behavior below is limited to google-bert/bert-base-uncased at full commit 86b5e0934494bd15c9632b12f734a8a67f723594, used with transformers==4.56.2. Verified: 2026-10-05. The evidence boundary is the pinned tokenizer.json, the Transformers v4.56.2 tokenizer API, and the versioned BertTokenizerFast implementation. The examples make no count claim for another model, tokenizer revision, or unrelated LLM.
Define the count before measuring it
len(input_ids) is the prepared model-input length. It can include [CLS], one or two [SEP] tokens, padding when requested, and any [UNK] replacements. It is not, by itself, a content length. attention_mask.sum() is different again: non-padding special tokens normally have attention value 1, so that sum includes structural tokens.
For this pinned BERT tokenizer, special_tokens_mask is binary. A value of 0 identifies a position that is not a special-token ID; 1 identifies a special position, including wrapper tokens, [PAD], and [UNK]. The operational content length is:
content_length = sum(flag == 0 for flag in special_tokens_mask)
Equivalently, use len(input_ids) - sum(special_tokens_mask). Apply that subtraction to one unbatched sequence. Masks in a padded batch have an outer batch dimension and must be counted row by row.
For a single input, the zero positions cover the body tokens between the wrapper specials. For a pair, the returned mask describes one flattened sequence, so its zero count is the combined body length of both segments. The mask alone does not divide that total into segment A and segment B. Inspecting the actual special positions is preferable to maintaining a fixed overhead constant across tokenizer options, post-processor changes, and revisions.
Use a clean Python 3 environment containing transformers==4.56.2, for example by running python -m pip install "transformers==4.56.2". This script pins the full commit, exercises single and paired calls, checks mask invariants, and prints local results. It does not embed an output transcript or expected count.
from importlib.metadata import version
import tokenizers
from transformers import AutoTokenizer, BertTokenizerFast
MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
EXPECTED_TRANSFORMERS = "4.56.2"
installed = version("transformers")
if installed != EXPECTED_TRANSFORMERS:
raise RuntimeError(
f"Install transformers=={EXPECTED_TRANSFORMERS}; found {installed}."
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
revision=FULL_COMMIT,
use_fast=True,
)
assert isinstance(tokenizer, BertTokenizerFast)
print(f"transformers={installed}; tokenizers={tokenizers.__version__}")
common = {
"add_special_tokens": True,
"padding": False,
"truncation": False,
"return_attention_mask": True,
"return_token_type_ids": True,
"return_special_tokens_mask": True,
}
cases = [
("single", "A compact input can still become several WordPiece tokens.", None),
(
"pair",
"The first segment records its own tokens.",
"The second segment belongs to the same prepared input.",
),
]
for label, first, second in cases:
call_options = dict(common)
if second is not None:
call_options["text_pair"] = second
encoded = tokenizer(first, **call_options)
ids = encoded["input_ids"]
mask = encoded["special_tokens_mask"]
attention = encoded["attention_mask"]
type_ids = encoded["token_type_ids"]
assert len(ids) == len(mask) == len(attention) == len(type_ids)
assert all(flag in (0, 1) for flag in mask)
content_length = sum(flag == 0 for flag in mask)
special_count = sum(mask)
assert content_length == len(ids) - special_count
special_ids = set(tokenizer.all_special_ids)
assert all(
(flag == 1) == (token_id in special_ids)
for token_id, flag in zip(ids, mask)
)
unknown_count = sum(token_id == tokenizer.unk_token_id for token_id in ids)
print(f"\n{label}:")
print(" tokens:", encoded.tokens())
print(
f" model_input={len(ids)}; mask0={content_length}; "
f"mask1={special_count}; attention_positions={sum(attention)}"
)
print(
f" UNK={unknown_count}; "
f"content_with_UNK={content_length + unknown_count}"
)
print(
" mask=1 positions:",
[
(index, token)
for index, (token, flag) in enumerate(zip(encoded.tokens(), mask))
if flag == 1
],
)
if second is not None:
per_type = {
segment: sum(
flag == 0 and type_id == segment
for flag, type_id in zip(mask, type_ids)
)
for segment in (0, 1)
}
print(" non-special content by token type:", per_type)
Interpret the diagnostic
The printed model_input value is the length of the actual prepared sequence. The mask0 value is its non-special content length, while mask=1 positions exposes the structural overhead instead of assuming it. Comparing attention_positions with model_input also makes the distinction visible: with no padding, attention generally accepts every prepared position, including special tokens.
For the paired call, non-special content by token type is a BERT-specific diagnostic partition. Token type 0 identifies the first segment and its wrapper positions; token type 1 identifies the second segment and its wrapper positions. Filtering both lists by mask == 0 gives per-segment non-special counts. The flattened mask remains the source of the inclusion decision.
For a padded batch, retain the same zero-count rule for each row and verify that len(mask[row]) == len(input_ids[row]). If a downstream data collator adds padding, ensure it also returns or correctly extends special_tokens_mask; the length assertion will expose an omitted or misaligned mask. Do not sum a nested batch mask and subtract it from one flattened input length.
Distinguish unknowns from fragmentation
WordPiece fragmentation produces ordinary known token IDs. In BERT’s token display, a continuation commonly begins with ##. Each resulting piece occupies a normal sequence position and contributes one to the zero-masked content length. The resulting count is therefore a token count, not a source-word count: one word may produce no tokens, one token, or several pieces.
[UNK] is different. It belongs to this tokenizer’s special-token inventory, so an unknown replacement contributes to len(input_ids) but not to the strict non-special count. If the product metric defines an unknown replacement as a consumed content slot, add the separately reported UNK count. Do not call that revised quantity the mask-only length, and do not confuse it with fragmentation.
If the required metric is source words, characters, or coverage, special_tokens_mask is insufficient. For this fast tokenizer, request return_offsets_mapping=True and use offsets to group pieces and inspect normalization gaps. Offsets still do not turn the metric into a semantic notion of “content.”
Limitations and re-check procedure
The central limitation is that this is a structural count of retained, non-special positions. Truncation does not appear in the mask: it reports only the body that survived. Request num_truncated_tokens=True or inspect tokenizer warnings when the engineering requirement is to detect or reject discarded input. Likewise, an unknown replacement and a known subword piece can both be necessary to interpret a surprising count, but only the latter is mask-zero content.
Whenever FULL_COMMIT or a dependency changes, treat the change as a tokenizer-behavior change. Keep the Transformers version in source control, record the tokenizers backend version printed by the script, and lock the complete resolved environment; pinning Transformers alone does not record every fast-tokenizer backend detail.
Re-run the diagnostic against the new full commit. Extend it with a known fragmented word, source that produces [UNK], a padded batch, and a deliberately long pair with truncation. Check binary masks, row lengths, special-token IDs, unknown positions, tokens, and offsets before accepting new counts. If the Transformers version itself changes, update EXPECTED_TRANSFORMERS and review the corresponding versioned API and source together. Until that re-check passes, retain the old commit and dependency locks rather than silently moving to main or a newer package.
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.