Skip to content
wordpiece.org

Checking batch versus single-input BERT encodings

Encode a fixture one by one and as a batch, asserting equality before padding and documenting tensor shape after padding

Published 8 min read Verified

A single text and the same text inside a batch should have identical token IDs before padding. A wider batch tensor does not by itself indicate inconsistent tokenization: batch padding adds model-input positions so that rectangular tensors can be stored together. The precise diagnostic is therefore to separate tokenization from padding, compare like with like, and then inspect the padded tensor and attention mask.

Scope and evidence

Verified: 2026-10-05. This procedure applies specifically to google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594, using transformers==4.56.2 and its fast-tokenizer path. The pinned tokenizer.json is the authority for this model’s vocabulary and normalization settings. The comparison uses the Transformers v4.56.2 tokenizer API and the corresponding BertTokenizerFast implementation.

Do not transfer observed IDs, token strings, or lengths to another BERT checkpoint merely because it also uses WordPiece. Uncasing, normalization, vocabulary entries, and post-processing are properties of the pinned tokenizer files.

Here, content tokens means the unpadded positions between the boundary tokens added by the tokenizer. Those positions can contain ordinary vocabulary pieces or [UNK]. Model-input tokens means the complete sequence presented in the encoding, including [CLS], [SEP], and any padding added later. Unknown-token handling and subword fragmentation are different observations: fragmentation produces recognized pieces such as a word prefix and continuation pieces, while [UNK] reports that the tokenizer could not represent some input material from its vocabulary.

Run the comparison

Install Transformers 4.56.2 in an environment containing NumPy, then save the following as a Python 3 file. The fixtures are deliberately varied: they include punctuation, digits, an accented word, contractions, and an emoji. Their purpose is to make local tokenization visible, not to establish a benchmark or claim a particular output in advance.

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 isinstance(tokenizer, BertTokenizerFast), type(tokenizer)

fixtures = [
    "A dry sentence stays simple.",
    "Punctuation, numbers, and café test normalization.",
    "BERT's subword prefixes must not depend on batching.",
    "The emoji 🙂 is intentionally included.",
]

options = {
    "add_special_tokens": True,
    "truncation": False,
}


def first_row(encoding):
    """Convert a one-item BatchEncoding into a plain row dictionary."""
    return {name: values[0] for name, values in encoding.items()}


# Phase 1: compare one-by-one and batch encodings with no padding.
single_before = [
    first_row(tokenizer(text, padding=False, **options))
    for text in fixtures
]
batch_before = tokenizer(fixtures, padding=False, **options)

batch_before_rows = {
    name: values for name, values in batch_before.items()
}
assert batch_before_rows == single_before, (
    "Unpadded single-input and batch encodings differ"
)

for text, row in zip(fixtures, single_before):
    ids = row["input_ids"]
    special_mask = row["special_tokens_mask"]
    content_ids = [
        token_id
        for token_id, is_special in zip(ids, special_mask)
        if is_special == 0
    ]
    print("TEXT:", text)
    print("MODEL-INPUT IDS:", ids)
    print("CONTENT IDS:", content_ids)
    print("TOKENS:", tokenizer.convert_ids_to_tokens(ids))

# Phase 2: pad both routes to the same locally derived width.
padded_width = max(len(row["input_ids"]) for row in single_before)

single_after = [
    first_row(
        tokenizer(
            text,
            padding="max_length",
            max_length=padded_width,
            **options,
        )
    )
    for text in fixtures
]
batch_after = tokenizer(
    fixtures,
    padding=True,
    return_tensors="np",
    **options,
)

for name, tensor in batch_after.items():
    expected_rows = [row[name] for row in single_after]
    assert tensor.tolist() == expected_rows, (
        f"Padded field differs between routes: {name}"
    )

assert tuple(batch_after["input_ids"].shape) == (
    len(fixtures),
    padded_width,
)

# Removing positions whose attention mask is zero must recover phase 1.
for ids, expected_ids, mask in zip(
    batch_after["input_ids"].tolist(),
    [row["input_ids"] for row in single_before],
    batch_after["attention_mask"].tolist(),
):
    retained_ids = [
        token_id
        for token_id, keep in zip(ids, mask)
        if keep == 1
    ]
    assert retained_ids == expected_ids

print("PADDED input_ids shape:", tuple(batch_after["input_ids"].shape))
print(
    "PADDED attention-mask lengths:",
    batch_after["attention_mask"].sum(axis=1).tolist(),
)
print("All single/batch equality assertions passed.")

The first assertion compares all fields returned in the unpadded encodings, including input_ids, token_type_ids, attention_mask, and special_tokens_mask. Keeping truncation=False is important: a length-sensitive operation would make the routes harder to compare and could conceal the property under examination. padding=False also prevents rectangular storage from obscuring whether the underlying token decisions changed.

The second phase derives padded_width from the unpadded rows rather than inserting a claimed length. padding=True pads the batch to its longest member, while the single-input calls explicitly pad to that same width. Comparing every returned padded field then prevents a matching input_ids array from hiding a disagreement in masks or token-type information. The final reconstruction check is the clearest statement of the expected invariant: attention-mask zeros may be added, but retained positions must reproduce the original IDs exactly.

Interpret the observations

If the phase-one assertion succeeds, these fixtures do not exhibit batch-dependent tokenization in the pinned environment. If phase two also succeeds and mask-zero removal restores each phase-one row, the only observed difference is padding. The printed shape is determined locally; it should be recorded rather than replaced with an assumed sequence length.

If phase one fails, inspect the printed tokens for the smallest failing fixture. First confirm that both calls use the same tokenizer object, revision, special-token policy, and truncation setting. Then compare normalized text and vocabulary pieces. A known sequence made from multiple pieces indicates subword fragmentation. An [UNK] instead indicates an unmatched input unit; it should not be described as successful fragmentation. Because this is a fast tokenizer, return_offsets_mapping=True can help locate the original character span associated with a piece, although normalization and uncasing can make that span less intuitive for accented text.

If phase one passes but phase two fails, padding—not token selection—is the immediate suspect. Check that every comparison uses the same derived width, inspect attention_mask, and ensure that the batch’s longest sequence is the width intended for the single-input calls. Also verify that no downstream collator has replaced or further processed the tokenizer output.

Limits and re-check procedure

This is a finite regression diagnostic, not proof that every possible string behaves identically. It checks the named uncased checkpoint, the listed fixtures, and the selected Transformers version. It does not test another checkpoint, model predictions, attention scores, generation quality, or throughput. The snippet also does not lock the separately installed tokenizers backend version; record that version in a fully reproducible environment because the fast-tokenizer implementation ultimately delegates to it.

Re-check whenever the pinned tokenizer.json, model commit, Transformers version, or fast-tokenizer backend changes. Use a clean environment, install transformers==4.56.2, update FULL_COMMIT only with its matching model identity, and retain the locally printed tokens, IDs, mask lengths, tensor shape, and dependency versions. Review changes to normalization, vocabulary, post-processing, padding, and truncation before accepting new results. Update the verification date only after the same before-padding and after-padding assertions have been rerun.

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