Skip to content
wordpiece.org

Reading the WordPiece model section of tokenizer.json

Parse JSON to inspect model type, unknown token, prefix, max word length, and vocabulary without treating all JSON fields as tokens

Published 8 min read Verified

tokenizer.json is an execution recipe, not a flat list of tokens. The engineering problem is to explain an observed [UNK] or a changed input_ids length without confusing WordPiece configuration, vocabulary entries, content pieces, and postprocessor-added tokens. For the two exact revisions below, begin with the top-level model object: it contains the WordPiece backend contract. The surrounding objects describe transformations that occur before or after that backend runs.

Verified: 2026-10-05. The evidence boundary is the pinned English uncased tokenizer.json, the pinned multilingual cased tokenizer.json, and the Transformers 4.56.2 tokenizer API. This verifies the source files and API contract; it does not claim that the script below was run while preparing the article. All token behavior, offsets, and sequence counts discussed here apply to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8 with transformers==4.56.2.

Start with the model object

In both pinned files, model.type is WordPiece, model.unk_token is [UNK], and model.continuing_subword_prefix is ##. Each file also supplies model.max_input_chars_per_word; read its value from the exact artifact rather than copying a threshold from another tokenizer. These fields answer different questions:

  • unk_token names the fallback emitted when WordPiece cannot represent a pre-tokenized word.
  • continuing_subword_prefix marks pieces after the first piece of a word.
  • max_input_chars_per_word controls how many characters may be considered for one such word before the unknown path is used.
  • vocab maps every WordPiece vocabulary string to an integer ID.

The vocabulary itself is the relevant inventory: read its entries and IDs directly from model.vocab. Its reported size is an inventory size, not the number of tokens in an input. The map includes registered special strings such as [CLS], [SEP], [PAD], [MASK], and [UNK]; it is not a list of words extracted from a document.

Do not blindly add strings from every JSON field. The uncased file’s normalizer lowercases text, while the multilingual-cased file preserves case. A pre-tokenizer defines candidate words. The post-processor inserts model-input special tokens. The decoder describes reconstruction. An added_tokens declaration is token-related metadata and may refer to an ID already present in model.vocab; it is not automatically another disjoint vocabulary. Read model.vocab for the base inventory, then inspect the other sections for behavior.

Cross-check the file against the runtime tokenizer

Static parsing establishes configuration, but it does not prove which tokenizer implementation AutoTokenizer loaded. The following self-contained diagnostic downloads each immutable revision, rejects duplicate JSON keys, checks the model fields and vocabulary IDs, and then asks the fast tokenizer to encode a controlled probe. Install the exact dependency with python -m pip install transformers==4.56.2 before running it.

import hashlib
import json
from importlib.metadata import version
from pathlib import Path

from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer

assert version("transformers") == "4.56.2", version("transformers")

UNCASED_FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
MULTILINGUAL_FULL_COMMIT = "3f076fdb1ab68d5b2880cb87a0886f315b8146f8"

MODELS = (
    ("uncased", "google-bert/bert-base-uncased", UNCASED_FULL_COMMIT),
    (
        "multilingual-cased",
        "google-bert/bert-base-multilingual-cased",
        MULTILINGUAL_FULL_COMMIT,
    ),
)


def unique_json_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key: {key!r}")
        result[key] = value
    return result


def inspect_text(tokenizer, text):
    content = tokenizer(
        text,
        add_special_tokens=False,
        padding=False,
        truncation=False,
        return_offsets_mapping=True,
    )
    full = tokenizer(
        text,
        add_special_tokens=True,
        padding=False,
        truncation=False,
        return_special_tokens_mask=True,
        return_offsets_mapping=True,
    )

    # Both pinned single-sequence BERT tokenizers add [CLS] and [SEP].
    assert full["input_ids"][1:-1] == content["input_ids"]
    assert sum(full["special_tokens_mask"]) == 2

    return {
        "content_tokens": tokenizer.convert_ids_to_tokens(content["input_ids"]),
        "content_offsets": content["offset_mapping"],
        "model_input_tokens": tokenizer.convert_ids_to_tokens(full["input_ids"]),
        "special_tokens_mask": full["special_tokens_mask"],
    }


for label, model_id, FULL_COMMIT in MODELS:
    path = Path(
        hf_hub_download(
            repo_id=model_id,
            filename="tokenizer.json",
            revision=FULL_COMMIT,
        )
    )
    raw = path.read_bytes()
    payload = json.loads(
        raw.decode("utf-8"),
        object_pairs_hook=unique_json_object,
    )

    wordpiece = payload["model"]
    vocab = wordpiece["vocab"]
    max_word_chars = wordpiece["max_input_chars_per_word"]

    assert wordpiece["type"] == "WordPiece"
    assert wordpiece["unk_token"] == "[UNK]"
    assert wordpiece["continuing_subword_prefix"] == "##"
    assert isinstance(max_word_chars, int)
    assert len(set(vocab.values())) == len(vocab)

    tokenizer = AutoTokenizer.from_pretrained(
        model_id,
        revision=FULL_COMMIT,
        use_fast=True,
    )
    assert tokenizer.is_fast

    runtime_vocab = tokenizer.get_vocab()
    assert all(
        runtime_vocab.get(token) == index
        for token, index in vocab.items()
    )

    normalizer = payload["normalizer"]
    assert normalizer["lowercase"] is (label == "uncased")

    unk_id = vocab[wordpiece["unk_token"]]
    prefix = wordpiece["continuing_subword_prefix"]
    assert tokenizer.unk_token_id == unk_id

    fragmentation = inspect_text(tokenizer, "embeddings")
    assert unk_id not in tokenizer(
        "embeddings", add_special_tokens=False
    )["input_ids"]
    assert any(
        token.startswith(prefix)
        for token in fragmentation["content_tokens"]
    )

    print(json.dumps({
        "model": model_id,
        "revision": FULL_COMMIT,
        "tokenizer_json_sha256": hashlib.sha256(raw).hexdigest(),
        "top_level_fields": sorted(payload),
        "wordpiece": {
            "type": wordpiece["type"],
            "unk_token": wordpiece["unk_token"],
            "continuing_subword_prefix": prefix,
            "max_input_chars_per_word": max_word_chars,
            "vocabulary_entries": len(vocab),
            "runtime_vocabulary_entries": len(runtime_vocab),
            "runtime_only_keys": len(set(runtime_vocab) - set(vocab)),
            "lowercase": normalizer["lowercase"],
        },
        "fragmentation_probe": fragmentation,
    }, ensure_ascii=False, indent=2))

Interpret the observations

Start with the metadata block. Compare the printed type, unknown marker, prefix, maximum, and vocabulary size with the reviewed pinned artifact. A changed value means that the downloaded artifact is not the revision described here or that the source has been modified. The duplicate-key rejection and vocabulary-value uniqueness assertion provide additional structural checks: JSON keys identify strings, but their values are the IDs consumed by the model.

The successful fragmentation probe distinguishes successful subword decomposition from failure. Its content tokens include at least one ## continuation, but no generated [UNK]. That means the word was not present as one vocabulary item but could be assembled greedily from multiple pieces. Unknown fallback can still occur when a shorter word cannot be segmented, so the maximum-word-length setting and segmentation success are separate checks.

content_tokens comes from an encoding with add_special_tokens=False. model_input_tokens comes from the post-processed encoding. For the single-sequence probes in these two pinned tokenizers, the latter surrounds the content with [CLS] and [SEP]. special_tokens_mask identifies those additions. A generated [UNK] remains part of the content encoding even though it is also a registered special vocabulary string. Padding or truncation would make model-input length a poor substitute for content length, which is why the diagnostic disables both.

Offsets are printed only because the fast tokenizer is required. They map runtime pieces back toward the original text, not toward normalized token spellings. For these uncased or normalized inputs, offsets can overlap or fail to correspond to the visible characters used by a token. They are alignment evidence, not a reason to merge vocabulary entries or derive a sequence count.

Limitation and update procedure

Limitation: this procedure checks a deterministic fragmentation probe, not every input or backend configuration. The raw JSON cannot by itself predict every sequence result because normalization, pre-tokenization, post-processing, fast-backend behavior, padding, and truncation also participate. Conclusions must not be carried to another revision, another Transformers release, or an unrelated tokenizer.

When either pinned file or transformers==4.56.2 changes, retain the old artifact and environment first. For a new commit, diff the complete tokenizer.json, including normalizer, pre-tokenizer, post-processor, decoder, added-token declarations, and the entire model.vocab; a vocabulary-count change alone can hide ID remapping. Then run the same probes with AutoTokenizer.from_pretrained(..., revision=<new full commit>, use_fast=True). Compare content tokens, model-input tokens, special-token masks, and offsets using identical padding and truncation options.

Next, test the unchanged file revision in an isolated environment with the new Transformers version. A difference there belongs to the dependency or fast-backend path rather than the pinned file. Record the repository, full commit, printed tokenizer.json SHA-256, Transformers version, probe text, and encoding options. Update any recorded vocabulary size or field assertion only after reviewing the new pinned file; do not weaken an assertion merely to make a changed artifact pass.

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