Skip to content
wordpiece.org

Pinning a Hugging Face tokenizer revision for reproducible counts

Show AutoTokenizer.from_pretrained with exact repository revision and a check of name_or_path plus a reproducibility manifest

Published 8 min read Verified

Pin the tokenizer repository snapshot with a full commit hash, then archive the loader identity and a sample encoding beside the count. A model name or moving branch is not a reproducibility boundary: it can later resolve to different tokenizer files. The runnable target here is google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2 and use_fast=True. The pinned tokenizer.json is the behavior authority; the versioned Transformers tokenizer API supplies the encoding fields used below.

Verified: 2026-10-05. This verification covers the cited file and versioned API on that date. It is not a transcript of a local run: the snippet prints the observations it obtains, and this article does not hard-code an expected token list or count.

Make the pin observable

revision=FULL_COMMIT selects a specific repository snapshot rather than a branch name. use_fast=True requests the fast implementation whose word_ids() and offset mappings the diagnostic uses. Check tokenizer.name_or_path == MODEL, but do not treat that field as proof of the revision: it generally records the model label passed to the loader, not a portable resolved commit.

Record the requested model, full commit, observed name_or_path, package versions, tokenizer class, and a digest of the pinned JSON. The digest identifies the authoritative tokenizer bytes recorded by this run; the full commit also identifies the other repository files selected at that revision.

Run the diagnostic

Run the following with network access to the public Hugging Face repository after installing transformers==4.56.2. Standard output is one JSON manifest. The assertions check the applicable model label, fast-tokenizer path, agreement between the loaded and pinned vocabulary sizes, vocabulary IDs, and the relationship between content and special positions. They are local diagnostics, not benchmark claims.

import hashlib
import json
from urllib.request import Request, urlopen

import tokenizers as tokenizers_backend
import transformers
from transformers import AutoTokenizer

MODEL = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
REQUIRED_TRANSFORMERS = "4.56.2"
TEXT = "The café's reproducibility requires a stable WordPiece vocabulary."

if transformers.__version__ != REQUIRED_TRANSFORMERS:
    raise RuntimeError(
        f"Install transformers=={REQUIRED_TRANSFORMERS}; "
        f"found {transformers.__version__}"
    )

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

assert tokenizer.name_or_path == MODEL
assert tokenizer.is_fast
assert tokenizer.unk_token_id is not None

artifact_url = (
    f"https://huggingface.co/{MODEL}/resolve/{FULL_COMMIT}/tokenizer.json"
)
request = Request(
    artifact_url,
    headers={"User-Agent": "wordpiece-revision-diagnostic/1.0"},
)
with urlopen(request) as response:
    artifact_bytes = response.read()

pinned = json.loads(artifact_bytes.decode("utf-8"))
pinned_vocab = pinned["model"]["vocab"]

assert tokenizer.vocab_size == len(pinned_vocab)
assert all(
    tokenizer.convert_tokens_to_ids(token) == token_id
    for token, token_id in pinned_vocab.items()
)

encoding = tokenizer(
    TEXT,
    add_special_tokens=True,
    padding=False,
    truncation=False,
    return_offsets_mapping=True,
    return_special_tokens_mask=True,
)

input_ids = encoding["input_ids"]
tokens = tokenizer.convert_ids_to_tokens(input_ids)
word_ids = encoding.word_ids()
special_mask = encoding["special_tokens_mask"]

content_indices = [
    index for index, word_id in enumerate(word_ids) if word_id is not None
]
unknown_indices = [
    index
    for index in content_indices
    if input_ids[index] == tokenizer.unk_token_id
]
continuation_indices = [
    index
    for index in content_indices
    if tokens[index].startswith("##")
]

# With padding and truncation disabled, every position is either
# content-associated or marked as a special token.
assert len(input_ids) == len(content_indices) + sum(special_mask)

manifest = {
    "reference_verified": "2026-10-05",
    "load": {
        "requested_model": MODEL,
        "requested_revision": FULL_COMMIT,
        "observed_name_or_path": tokenizer.name_or_path,
        "tokenizer_class": tokenizer.__class__.__name__,
        "use_fast": True,
    },
    "versions": {
        "transformers": transformers.__version__,
        "tokenizers": getattr(
            tokenizers_backend, "__version__", "not exposed"
        ),
    },
    "tokenizer_json_url": artifact_url,
    "tokenizer_json_sha256": hashlib.sha256(artifact_bytes).hexdigest(),
    "vocabulary_entries": len(pinned_vocab),
    "special_token_ids": {
        "pad": tokenizer.pad_token_id,
        "unknown": tokenizer.unk_token_id,
        "cls": tokenizer.cls_token_id,
        "sep": tokenizer.sep_token_id,
        "mask": tokenizer.mask_token_id,
    },
    "sample": TEXT,
    "encoding_options": {
        "add_special_tokens": True,
        "padding": False,
        "truncation": False,
        "max_length": None,
    },
    "counts": {
        "content_tokens": len(content_indices),
        "model_input_tokens": len(input_ids),
        "marked_special_tokens": sum(special_mask),
        "unknown_content_tokens": len(unknown_indices),
        "wordpiece_continuations": len(continuation_indices),
    },
    "tokens": [
        {
            "input_index": index,
            "token": tokens[index],
            "token_id": input_ids[index],
            "word_id": word_ids[index],
            "offset": list(encoding["offset_mapping"][index]),
            "special": special_mask[index],
            "is_unknown": index in unknown_indices,
            "is_wordpiece_continuation": index in continuation_indices,
        }
        for index in range(len(input_ids))
    ],
}

print(json.dumps(manifest, ensure_ascii=False, indent=2))

The separate download is intentional. from_pretrained may satisfy the request from a local cache, so hashing the exact revision’s JSON supplies a byte-level reference that can be compared with an archive. It does not turn name_or_path into a commit field, and it does not hash auxiliary files such as tokenizer_config.json. Archive the JSON and dependency lock when the count must remain auditable; use the full commit as the loader selector and the digest as the recorded tokenizer-artifact identity.

Start with load.observed_name_or_path, load.tokenizer_class, and the two version fields. A model-label mismatch means the loader was not given the intended identity. A vocabulary-size or token-ID mismatch means the loaded tokenizer does not agree with the downloaded pinned JSON. Neither observation should be repaired by accepting a count. Save the computed tokenizer_json_sha256 and compare it with the archived manifest before comparing tokens. reference_verified records the evidence date, not the script’s execution date.

Each tokens row aligns an input position with its token string, source word_id, character offsets, unknown flag, and WordPiece-continuation flag. Offsets are useful when the uncased tokenizer’s case or accent handling makes a token look unlike the original text. They should be inspected rather than treated as guaranteed UTF-8 byte spans. If IDs or offsets fail, preserve the complete manifest and resolve the environment or cache mismatch before publishing a count.

Keep count categories separate

Here, a content token means a model-input position with a non-None word_id. It is not a source word, vocabulary type, or successful lookup. An unknown token still occupies a content position. A model-input token is every element of input_ids; for this uncased BERT example it includes inserted special tokens. With padding=False and truncation=False, the diagnostic asserts that input length equals content positions plus the special-token mask sum.

unknown_content_tokens and wordpiece_continuations answer different questions. [UNK] at a content position means the relevant word or pre-tokenized unit was not representable by the pinned WordPiece vocabulary. A token beginning with ## is a continuation piece: it records successful fragmentation, not failure. Diagnose fragmentation by grouping rows that share a word_id; diagnose unknowns by inspecting the flagged token and its offsets.

Keep production batching policy in a separate manifest. Padding adds model-input positions without adding content positions, while truncation can remove source positions before postprocessing. Re-run the diagnostic with the actual add_special_tokens, padding, truncation, and maximum-length settings rather than adjusting a no-padding count manually.

Scope and update procedure

The result is specific to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 under Transformers 4.56.2; it is not a general property of BERT or of a tokenizer loaded by model name. A multilingual deployment must instead pin google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, whose pinned JSON has 119,547 vocabulary entries. Do not transfer the sample’s casing, normalization, token IDs, or counts. Record the backend version, archive the environment lock, and retain the JSON digest because cache state and dependency resolution are outside the repository commit.

For an intentional tokenizer update, replace FULL_COMMIT with another full commit for the same model and inspect the tokenizer.json diff. Review vocabulary, normalizer, pre-tokenizer, postprocessor, and special-token changes before comparing IDs, strings, offsets, and counts. If Transformers or its tokenizers backend changes, record the new versions and rerun the case, or explicitly retain the historical scope.

Re-check immediately if the pinned file changes, the recorded digest differs, a dependency is upgraded, or padding or truncation changes. If bytes retrieved for the exact revision no longer match the archive, stop and investigate rather than falling back to main. Keep old manifests with their artifacts and lockfiles so an older count remains attributable instead of being silently rewritten.

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