Separating BERT attention masks from padding and special tokens
Batch unequal samples with padding and inspect masks and ids; explain why a CLS or SEP is attended while PAD is not
A BERT attention mask identifies positions that belong to an unpadded sequence; it does not rank words or report the attention weights learned by the model. Verified: 2026-10-05. The procedure below applies to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. That date records review of the pinned tokenizer and versioned API, not execution of the script.
Separate content, structure, and padding
For a single input sequence, let C be the number of tokens returned with add_special_tokens=False. C is the content-token count: it includes punctuation, individual WordPieces, and any [UNK] produced from the source. With no truncation, the unpadded model-input length is:
D = C + 2
The two additional model-input tokens are [CLS] and [SEP]. When unequal examples are batched, the tokenizer pads their input_ids to the longest D in the batch. For sample i in a batch of width L, the number of added [PAD] positions is L - D_i, while its attention-mask sum remains D_i.
Padding exists only to make the batch rectangular. The attention mask is 1 for every original sequence position, including [CLS] and [SEP], and 0 for newly inserted [PAD] positions. Thus [CLS] and [SEP] are eligible to participate in computation, whereas padding is excluded. “Eligible” does not mean that an attention head necessarily assigns either special token a large weight.
special_tokens_mask is not the inverse of attention_mask. It is a tokenizer-defined special-token view, not a record of only the boundary tokens inserted by add_special_tokens=True. In particular, [UNK] can be special vocabulary while still representing actual source text and carrying attention 1. Likewise, token_type_ids describe segment type and must not be used as an attention mask.
Reproducible batch diagnostic
In a clean Python 3 environment, install transformers==4.56.2, then run this self-contained diagnostic. It prints the observed rows and checks the relationships described above rather than embedding presumed output.
import transformers
from transformers import AutoTokenizer
MODEL = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
assert transformers.__version__ == "4.56.2", transformers.__version__
tokenizer = AutoTokenizer.from_pretrained(
MODEL,
revision=FULL_COMMIT,
use_fast=True,
)
# The pinned tokenizer.json records a 30,522-entry WordPiece vocabulary.
texts = [
"BERT tokenization.",
"🐍", # A source character useful for inspecting [UNK] handling.
]
encoded = tokenizer(
texts,
add_special_tokens=True,
padding=True,
truncation=False,
return_attention_mask=True,
return_special_tokens_mask=True,
return_offsets_mapping=True,
)
boundary_tokens = {"[CLS]", "[SEP]"}
for sample_index, text in enumerate(texts):
ids = encoded["input_ids"][sample_index]
attention = encoded["attention_mask"][sample_index]
special = encoded["special_tokens_mask"][sample_index]
offsets = encoded["offset_mapping"][sample_index]
tokens = tokenizer.convert_ids_to_tokens(ids)
# For these single-sequence examples, the inserted structural tokens
# are precisely the boundary tokens, not every special vocabulary item.
structural = [token in boundary_tokens for token in tokens]
content_ids = [
token_id
for token_id, attn, is_structural in zip(ids, attention, structural)
if attn == 1 and not is_structural
]
without_special = tokenizer(
text,
add_special_tokens=False,
truncation=False,
)["input_ids"]
pad_positions = [pos for pos, attn in enumerate(attention) if attn == 0]
boundary_positions = [pos for pos, value in enumerate(structural) if value]
unknown_positions = [pos for pos, token in enumerate(tokens) if token == "[UNK]"]
fragment_positions = [
pos for pos, token in enumerate(tokens) if token.startswith("##")
]
assert len(ids) == len(attention) == len(special) == len(offsets) == len(tokens)
assert set(attention) <= {0, 1}
assert content_ids == without_special
assert sum(attention) == len(without_special) + 2
assert len(boundary_positions) == 2
assert all(attention[pos] == 1 for pos in boundary_positions)
assert all(ids[pos] == tokenizer.pad_token_id for pos in pad_positions)
assert all(attention[pos] == 1 for pos in unknown_positions)
print(f"\nsample={sample_index}: {text!r}")
print("input_ids: ", ids)
print("tokens: ", tokens)
print("attention_mask:", attention)
print("special_mask: ", special)
print("token_type_ids:", encoded["token_type_ids"][sample_index])
print("content tokens:", len(without_special))
print("model-input positions before padding:", sum(attention))
print("added padding positions:", len(pad_positions))
print("[UNK] positions:", unknown_positions)
print("WordPiece continuation positions:", fragment_positions)
for pos, (token_id, token, attn, is_special, offset, is_structural) in enumerate(
zip(ids, tokens, attention, special, offsets, structural)
):
role = "PAD" if attn == 0 else "STRUCT" if is_structural else "CONTENT"
print(
f"{pos:>3} id={token_id:<6} token={token!r:<16} "
f"attention={attn} special={is_special} "
f"offset={offset} role={role}"
)
print("\nfast tokenizer:", type(tokenizer).__name__)
print("vocabulary size:", len(tokenizer))
Read the observations row by row
The useful observation is the alignment among IDs, tokens, attention values, and offsets—not any particular tokenization result. A shorter sample should have attention 1 over its content and inserted boundary tokens, plus attention 0 wherever the batch required padding. The longest sample has no added padding. The number of 1 values should equal the no-special tokenization length plus two.
If attention.sum() is smaller than that expected model-input length, a pipeline may have dropped or overwritten mask entries. If an added [PAD] position has attention 1, padding can enter the model. If a source-content position has attention 0, inspect later collation, truncation, slicing, serialization, or model-adapter code rather than reconstructing a replacement mask from token IDs.
The printed special_mask can overlap attention 1 at boundary tokens. If the source-derived [UNK] row also has special_mask=1 and attention=1, the two fields are doing different jobs. Comparing a token ID with pad_token_id is also not a general substitute for the returned mask: token identity and batch membership are separate concepts.
The offset column is a fast-tokenizer alignment aid. It can show how several WordPieces cover portions of one source span, but it should not be used alone to classify a position as content, structure, or padding.
[UNK] is not fragmentation
An unknown token means normalization or token preparation encountered source text for which the tokenizer could not select a vocabulary unit; that span becomes one [UNK] model-input token. Fragmentation means a known lexical item was divided into several vocabulary units, normally an initial token followed by tokens beginning with ##. Fragmentation therefore increases the content-token count, while [UNK] does not split into several rows.
Neither condition is padding. A source-derived [UNK] remains a sequence position with attention 1. Offsets and the printed token pieces let the local run reveal which case occurred without assuming a count in advance.
Preserve the mask through the pipeline
Use the tokenizer or collator’s returned attention_mask, and preserve it through batching, concatenation, padding, truncation, tensor serialization, and model conversion. Keep an ID and mask dimension aligned after every operation. If downstream code needs the number of source-content tokens, retain the add_special_tokens=False length or another explicit content-span representation; do not derive it by subtracting every special_tokens_mask entry from the attention mask.
For paired sequences, the expected structural-token count changes, and token_type_ids become relevant to segment identity. For truncated inputs, compare against the tokenizer’s actual output rather than the formula C + 2. After changing any preprocessing component, rerun the row diagnostic on unequal examples and inspect the model input again.
Re-check scope and changes
Treat a change to tokenizer.json, the full commit, or transformers as a new tokenization target. Update both pinned constants, use a clean environment with the required dependency version, and rerun the script. Compare the no-special token IDs, boundary and padding IDs, mask sums, offsets, and row classifications with the previous saved output. Also inspect the fast tokenizer’s normalizer, pre-tokenizer, and WordPiece model when normalization or segmentation changes.
For google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, switch both constants and generate a fresh diagnostic: casing, normalization, vocabulary, and segmentation differ, so uncased observations must not be transferred. Update the reader-facing verification date only after reviewing the new pins.
This procedure is limited to short, single-sequence, untruncated fast-tokenizer inputs. It diagnoses mask construction, not learned attention behavior. Its evidence boundary is the pinned tokenizer.json, the Transformers 4.56.2 tokenizer API, and the versioned BertTokenizerFast source.
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.