Testing padding=max_length without confusing PAD for content
Compare fixed and longest-in-batch padding, attention masks, and real token counts in an inference fixture
If you set padding="max_length", the first thing to distrust is len(input_ids). That length includes [PAD] positions, and [PAD] is not content. The same texts encoded with padding="longest" can produce a different tensor length while representing the same content. The diagnostic below separates model-input length, non-PAD positions, and content WordPieces. It also separates unknown tokens from fragmentation.
The failure mode
padding="max_length" fills every row to max_length, or to a shorter effective length if truncation and other options change the contract. In Transformers v4.56.2, the encoding returns input_ids, attention_mask, and, when requested, special_tokens_mask and offset_mapping. input_ids is the model-input sequence. attention_mask marks 1 for tokens the model should attend to and 0 for padding. special_tokens_mask marks special tokens such as [CLS], [SEP], and usually [PAD]. Content tokens are not simply all ids; they are positions where attention_mask == 1 and special_tokens_mask == 0.
If you count input_ids to estimate text length, fixed padding makes every row look equally long. If you count attention_mask, you get non-PAD model-input tokens, but that still includes [CLS] and [SEP]. If you count attention_mask - special_non_pad, you get content WordPieces. That is the count to compare when the question is how much text a row contained. It is not the same as whitespace word count, because WordPiece can split one word into multiple pieces.
A diagnostic that keeps PAD out
The script pins the English uncased tokenizer and prints the relevant counts. Run it with Transformers 4.56.2 and the full revision.
from transformers import AutoTokenizer
MODEL = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"
MAX_LEN = 16
texts = ["attention masks explain padding", "PAD is not content"]
tok = AutoTokenizer.from_pretrained(MODEL, revision=REVISION, use_fast=True)
def report(enc, label):
print(f"\n{label}")
for i, ids in enumerate(enc["input_ids"]):
attn = enc["attention_mask"][i]
special = enc["special_tokens_mask"][i]
offsets = enc["offset_mapping"][i]
toks = tok.convert_ids_to_tokens(ids)
non_pad = sum(attn)
pad = sum(1 for a in attn if a == 0)
special_non_pad = sum(1 for a, s in zip(attn, special) if a == 1 and s == 1)
content = sum(1 for a, s in zip(attn, special) if a == 1 and s == 0)
unknown = sum(1 for t, a, s in zip(toks, attn, special)
if a == 1 and s == 0 and t == tok.unk_token)
continuation = sum(1 for t, a, s in zip(toks, attn, special)
if a == 1 and s == 0 and t.startswith("##"))
content_offsets = [o for o, a, s in zip(offsets, attn, special)
if a == 1 and s == 0]
print({
"row": i,
"model_input_tokens": len(ids),
"non_pad_model_input": non_pad,
"content_wordpieces": content,
"special_non_pad": special_non_pad,
"pad_positions": pad,
"unknown_tokens": unknown,
"continuation_pieces": continuation,
"content_offsets": content_offsets,
"decoded_non_pad": tok.decode(
[t for t, a in zip(ids, attn) if a == 1],
skip_special_tokens=False,
),
})
assert len(ids) == non_pad + pad
assert non_pad == special_non_pad + content
enc_max = tok(
texts,
padding="max_length",
max_length=MAX_LEN,
truncation=True,
return_attention_mask=True,
return_special_tokens_mask=True,
return_offsets_mapping=True,
)
enc_long = tok(
texts,
padding="longest",
truncation=True,
return_attention_mask=True,
return_special_tokens_mask=True,
return_offsets_mapping=True,
)
report(enc_max, "padding=max_length")
report(enc_long, "padding=longest")
assert all(len(ids) == MAX_LEN for ids in enc_max["input_ids"])
assert all(len(ids) <= MAX_LEN for ids in enc_long["input_ids"])
The assertions check local arithmetic: model-input length equals non-PAD plus PAD, and non-PAD equals special non-PAD plus content. The max_length run should have model_input_tokens == MAX_LEN for every row because truncation=True. The longest run should have lengths no greater than MAX_LEN and equal to that batch’s longest encoded row. Exact content, unknown, and continuation counts depend on the strings supplied; do not treat a number from different input as a property of BERT.
Reading the observations
model_input_tokens is tensor length. pad_positions is how many positions are padding. non_pad_model_input is what the attention mask protects. content_wordpieces removes both padding and non-PAD special tokens. If you compare sequence lengths for batching, model_input_tokens is the memory-relevant number. If you measure content, content_wordpieces is the honest tokenizer-side number. If you check whether the model ignores padding, attention_mask is the contract.
Fixed and longest-in-batch padding differ in shape, not in text. With padding="max_length", the shape is fixed by max_length, so batches stack without shape variation, but short rows carry many PAD positions. With padding="longest", the shape follows the longest row in the current batch, so shorter rows carry fewer PAD positions, but the shape changes when the batch changes. In both cases, attention_mask tells the model which positions are real. Counting PAD as content is a measurement bug, not a model bug.
Unknown tokens are not fragmentation
For google-bert/bert-base-uncased at the pinned revision, the WordPiece vocabulary has 30,522 entries. If a piece is not in that vocabulary, the tokenizer may emit [UNK]. That is an unknown token. Fragmentation is normal greedy WordPiece matching: a word such as tokenization may become token plus a ## continuation. The continuation is not unknown. In the script, unknown_tokens checks the token string against tok.unk_token; continuation_pieces counts content pieces starting with ##. Use both fields before concluding that a long token list means unknown text.
Limits and re-checking
This procedure reads tokenizer outputs. It does not prove that a downstream model ignores padding internally, and it does not convert WordPiece counts into word counts. It assumes a fast tokenizer, because offset_mapping requires use_fast=True. With truncation=True, content_wordpieces is surviving content after truncation; to measure what was removed, encode without truncation and compare. If you use google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, change both model string and revision; its vocabulary size is 119,547, and its fragmentation and unknown behavior should be treated as that model’s behavior, not inferred from English.
Verified: 2026-10-05. The applicable versions are google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and transformers==4.56.2. The evidence boundary is the pinned tokenizer.json, the v4.56.2 tokenizer documentation, and the v4.56.2 BERT fast-tokenizer source. When the pinned tokenizer file or Transformers version changes, re-run the script and confirm tok.pad_token_id, tok.unk_token_id, tok.model_max_length, and the assertion that padding="max_length" rows reach MAX_LEN. If special_tokens_mask semantics change, keep attention_mask as the authority for padding and identify non-PAD specials from convert_ids_to_tokens before computing content counts.
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.