Skip to content
wordpiece.org

Detecting tokenizer drift after a library upgrade

Hold model revision fixed, record installed Transformers version, and diff fixture outputs before approving an upgrade

Published 8 min read Verified

Tokenizer drift after a library upgrade is a data-contract problem. If you keep the tokenizer artifact fixed at a full commit revision, the model’s vocabulary and WordPiece rules stay pinned, but the installed Transformers version still controls the fast-tokenizer wrapper, which output fields are populated, and how alignment data is exposed. The upgrade can change the exact tensor inputs your serving path builds without any change to model weights or tokenizer.json.

Verified: 2026-10-05. The procedure below was verified against google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 and Transformers 4.56.2. The pinned tokenizer.json at that revision is the version authority for the WordPiece vocabulary and normalization settings. Transformers 4.56.2 defines the encoding options you can observe, including add_special_tokens, padding, truncation, special_tokens_mask, and fast-tokenizer offsets. The versioned BertTokenizerFast source implements the corresponding wrapper. Those files—not blog posts or remembered behavior—are the evidence boundary.

What to hold fixed, and what to diff

Hold the tokenizer revision fixed and vary the library. Record the installed Transformers version in the same artifact as the observation. Then diff fixture outputs before approving the upgrade. The comparison is not “old tokenizer versus new tokenizer”; it is “same pinned tokenizer artifact under old and new library behavior.” That distinction matters because a changed library can alter defaults, output fields, or fast-tokenizer alignment while the vocabulary stays byte-for-byte pinned.

Counts alone are not enough. Distinguish content tokens from model-input tokens. Content tokens are the subword pieces produced from the text without special tokens. Model-input tokens are what the model actually receives after special tokens, padding, and truncation. For a BERT uncased pipeline, a simple input may produce content tokens like ["hello"] and model-input tokens like ["[CLS]", "hello", "[SEP]"]. If you only compare sequence lengths, you can miss reordered or shifted pieces.

Also distinguish unknown tokens from fragmentation. In WordPiece, a word that cannot be matched against the pinned vocabulary may become [UNK]. Fragmentation is different: a known word may be split into multiple known subword pieces such as ["un", "##aff", "##able"]. A drift report should show the token strings, the token IDs, and the offsets, not just a count. A rise in [UNK] points at vocabulary or normalization behavior. A rise in segmentation points at WordPiece matching, case handling, or pre-tokenization.

The pinned bert-base-uncased vocabulary has 30,522 entries. The pinned google-bert/bert-base-multilingual-cased revision 3f076fdb1ab68d5b2880cb87a0886f315b8146f8 has 119,547 entries. Do not mix fixtures or expected values between the uncased English model and the cased multilingual model; their normalization and case behavior differ.

Run a fixture fingerprint

The script below pins the model revision, records the installed Transformers version, prints tokenizer facts, and writes a stable SHA-256 fingerprint over per-fixture outputs. It does not hardcode expected tokens or counts. Run it in a clean environment with transformers==4.56.2, save the output as a baseline, then run the identical script after an upgrade and diff the results.

# Requires: transformers==4.56.2
import hashlib
import json

import transformers
from transformers import AutoTokenizer

MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
EXPECTED_TRANSFORMERS = "4.56.2"

print(f"transformers={transformers.__version__}")
if transformers.__version__ != EXPECTED_TRANSFORMERS:
    print(
        f"note: this script was written for {EXPECTED_TRANSFORMERS}; "
        f"running under {transformers.__version__} for a drift comparison"
    )

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    revision=FULL_COMMIT,
    use_fast=True,
)

print(f"model={MODEL_ID}")
print(f"requested_revision={FULL_COMMIT}")
resolved = getattr(tokenizer, "_commit_hash", None)
if resolved is None:
    resolved = tokenizer.init_kwargs.get("_commit_hash")
print(f"resolved_revision={resolved}")
print(f"vocab_size={tokenizer.vocab_size}")
print(f"unk_token={tokenizer.unk_token}")

fixtures = [
    "The quick brown fox jumps over the lazy dog.",
    "Tokenization isn't deterministic; it is a contract.",
    "COVID-19 vaccine-related research.",
    "unaffable",
    "naïve café résumé",
    "A long literal fixture string is enough to exercise the padding and truncation defaults, so keep it byte-identical between runs.",
]

records = []

for text in fixtures:
    full = tokenizer(
        text,
        add_special_tokens=True,
        return_offsets_mapping=True,
        return_special_tokens_mask=True,
        truncation=False,
        padding=False,
    )
    content = tokenizer(
        text,
        add_special_tokens=False,
        return_offsets_mapping=True,
        return_special_tokens_mask=True,
        truncation=False,
        padding=False,
    )

    assert len(full["input_ids"]) == len(full["offset_mapping"])
    assert len(full["input_ids"]) == len(full["special_tokens_mask"])
    assert len(content["input_ids"]) == len(content["offset_mapping"])
    assert len(content["input_ids"]) == len(content["special_tokens_mask"])

    content_tokens = tokenizer.convert_ids_to_tokens(content["input_ids"])
    unknown_count = sum(1 for token in content_tokens if token == tokenizer.unk_token)

    record = {
        "text": text,
        "model_input_tokens": full.tokens(),
        "model_input_ids": full["input_ids"],
        "content_tokens": content_tokens,
        "content_ids": content["input_ids"],
        "offsets": full["offset_mapping"],
        "special_tokens_mask": full["special_tokens_mask"],
        "content_token_count": len(content["input_ids"]),
        "model_input_token_count": len(full["input_ids"]),
        "unknown_count": unknown_count,
    }
    records.append(record)

    print(
        json.dumps(
            {
                "fixture": text[:40] + ("..." if len(text) > 40 else ""),
                "content_token_count": record["content_token_count"],
                "model_input_token_count": record["model_input_token_count"],
                "unknown_count": record["unknown_count"],
                "content_tokens": record["content_tokens"],
                "offsets": record["offsets"],
            },
            ensure_ascii=False,
            sort_keys=True,
        )
    )

blob = json.dumps(
    records,
    ensure_ascii=False,
    sort_keys=True,
    separators=(",", ":"),
).encode("utf-8")
print("fixture_sha256=" + hashlib.sha256(blob).hexdigest())

Interpreting the diff

If fixture_sha256 is identical and the per-fixture rows are identical, you have no observed drift for these fixtures under the same pinned revision. That is not proof of semantic equivalence for all text, but it is a useful gate before an upgrade. If the digest differs, inspect the rows before changing anything.

Changed token strings or IDs with the same revision usually means library behavior changed. Check whether the tokenizer resolved to the requested commit. Check whether add_special_tokens, padding side, truncation side, or default max_length changed in your call path. Check offsets separately: an offset shift can break question answering, token classification alignment, or span extraction even when token IDs are unchanged. Check special_tokens_mask separately: a mask change can affect loss masking or pooling.

If unknown_count changes, look for normalization or vocabulary behavior. If segmentation changes without new [UNK] tokens, look at WordPiece matching and pre-tokenization. If only model-input token counts change while content tokens stay fixed, inspect special tokens, padding, and truncation.

Limitations and re-check procedure

This procedure is limited to the fixtures you choose. It does not evaluate model quality, downstream accuracy, or behavior on long documents, batches, or language outside the fixture set. It covers fast-tokenizer output; a slow-tokenizer path can differ. It also assumes the resolved commit hash matches the requested revision. If the pinned tokenizer.json or dependency version changes, do not treat the comparison as an upgrade of the same artifact.

To re-check, keep the baseline JSON and the script under version control. When Transformers changes, create a separate environment with the new version, keep revision=FULL_COMMIT, run the same script, and compare both the digest and the per-fixture rows. If any field changes, decide whether the change is acceptable for your pipeline. If the pinned tokenizer revision changes, create a new baseline and treat it as a new tokenizer asset, not library drift. Only approve the upgrade after the diff is understood or after targeted downstream checks cover the changed behavior.

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