Skip to content
wordpiece.org

Comparing two BERT vocabularies without conflating their outputs

Run the same fixture under both pinned commits and report tokens, unknowns, and ids in separate columns

Published 8 min read Verified

Comparing two BERT vocabularies without conflating their outputs starts with refusing the easy comparison. If you tokenize the same fixture with google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, you can produce two lists of integers. The engineering problem is that those lists do not represent the same thing unless you label each column. A model-input list includes special tokens. A content list excludes them. A high token count can come from [UNK] replacements or from known pieces fragmenting one surface word. If you collapse these into one number, you cannot tell whether a vocabulary lacks a form or merely splits it. The diagnostic below keeps tokens, unknown flags, ids, and per-word fragmentation separate.

Separate content tokens from model-input tokens

For BERT, AutoTokenizer.from_pretrained(..., use_fast=True) returns a fast tokenizer. With add_special_tokens=False, input_ids represent content tokens: the pieces the tokenizer produced for your text, without [CLS], [SEP], or padding. With add_special_tokens=True, as BERT’s wrappers do by default, the sequence becomes model-input tokens: [CLS], content pieces, [SEP], and any padding if you pad. The difference is often exactly two for a single sequence, but batch padding changes it. A vocabulary comparison that uses the default call and compares lengths is really comparing special-token policy plus content, not vocabulary behavior. Always record both counts and name which one you are comparing.

Unknown tokens are a separate axis. An unknown token is the tokenizer’s fallback when no WordPiece piece matches under the pinned vocabulary. It appears as the token string [UNK] and as the tokenizer’s unk_token_id. Fragmentation is different: a surface word may match several known pieces, such as a stem plus a continuation prefix. Both raise the token count, but they imply different fixes. Unknowns suggest missing vocabulary entries or normalization that removed a needed form. Fragmentation suggests the vocabulary covers the word only as pieces. If you compare vocabularies by total token count alone, you conflate these.

A diagnostic that prints separate columns

The following Python 3 script uses transformers==4.56.2. It loads both pinned tokenizers with revision=FULL_COMMIT and use_fast=True, tokenizes one fixture with is_split_into_words=True, and prints one row per content token: word index, piece, id, and unknown flag. It also prints model-input tokens, content-token count, model-input-token count, unknown count, fragmented surface units, and vocabulary size. It does not assert output values, because those depend on the pinned files and the installed dependency.

import transformers
from transformers import AutoTokenizer

assert transformers.__version__ == "4.56.2", transformers.__version__

MODELS = [
    ("uncased", "google-bert/bert-base-uncased", "86b5e0934494bd15c9632b12f734a8a67f723594"),
    ("multilingual", "google-bert/bert-base-multilingual-cased", "3f076fdb1ab68d5b2880cb87a0886f315b8146f8"),
]
FIXTURE = "The naïve café in Zürich costs €5. 東京 北京."

for label, model_id, revision in MODELS:
    tok = AutoTokenizer.from_pretrained(model_id, revision=revision, use_fast=True)
    words = FIXTURE.split()
    enc = tok(words, is_split_into_words=True, add_special_tokens=False,
              return_attention_mask=False, return_token_type_ids=False)
    input_ids = enc["input_ids"]
    pieces = tok.convert_ids_to_tokens(input_ids)
    word_ids = enc.word_ids()
    unk_id = tok.unk_token_id

    print(f"\n=== {label}: {model_id}@{revision} ===")
    print(f"{'idx':>4} {'word':>4} {'piece':>14} {'id':>6} {'is_unk':>6}")
    for i, (piece, token_id, wid) in enumerate(zip(pieces, input_ids, word_ids)):
        word = words[wid] if wid is not None else "<special>"
        print(f"{i:>4} {wid if wid is not None else -1:>4} {piece!r:>14} {token_id:>6} {str(token_id == unk_id):>6}")

    model_input = tok(FIXTURE, add_special_tokens=True, return_attention_mask=False,
                      return_token_type_ids=False)["input_ids"]
    model_pieces = tok.convert_ids_to_tokens(model_input)
    unknown_count = sum(1 for i in input_ids if i == unk_id)

    by_word = {}
    for piece, token_id, wid in zip(pieces, input_ids, word_ids):
        if wid is None:
            continue
        by_word.setdefault(wid, []).append((piece, token_id))
    fragmented = []
    for wid, items in by_word.items():
        if len(items) > 1:
            fragmented.append((words[wid], len(items), [p for p, _ in items]))

    print(f"content_token_count={len(input_ids)}")
    print(f"model_input_token_count={len(model_input)}")
    print(f"model_input_tokens={model_pieces}")
    print(f"unknown_count={unknown_count}")
    print(f"fragmented_surface_units={fragmented}")
    print(f"vocab_size={tok.vocab_size}")

The fixture intentionally mixes English, diacritics, currency, and CJK. Those categories exercise normalization, known-piece fragmentation, and fallback unknown behavior without requiring a large corpus. You can replace the fixture with your own text, but keep the same reporting columns. If you add padding, report attention_mask.sum() separately from input_ids length; otherwise pad tokens will look like vocabulary output.

Interpret the two models column by column

Run the script and read the columns rather than a single total. For each model, content_token_count is the number of WordPiece pieces for the fixture. model_input_token_count adds BERT’s special tokens. unknown_count counts content pieces whose id equals unk_token_id. fragmented_surface_units lists whitespace-delimited words that became more than one content piece; it is a local fragmentation view, not a full-sentence segmentation. vocab_size reports the loaded vocabulary size. The pinned known vocabulary sizes are 30,522 for the uncased English model and 119,547 for the multilingual cased model, but the script prints the values actually loaded, which is what should be compared.

If the uncased model returns more [UNK] entries for a non-English fixture, that can reflect its English, accent-stripping normalization and vocabulary. If the multilingual model returns fewer unknowns but more fragments for the same word, that is not automatically a win for the multilingual vocabulary; it means the word is represented as pieces rather than missing. If the counts differ only by two, check whether you accidentally compared add_special_tokens=True with add_special_tokens=False. If model_input_token_count is much larger than content_token_count + 2, check padding, truncation, or a batch encoding. The diagnostic is designed to expose those confusions.

Limitations and the update check

This is a local diagnostic, not a model-quality benchmark. It uses one fixture, one tokenization mode, and fast tokenizers. is_split_into_words=True pre-splits on whitespace, so punctuation attached to a word remains part of that word; a full-sentence tokenization may group or split differently. The output does not measure downstream accuracy, embedding quality, or task performance. It also does not cover padding, truncation, or token_type_ids; add those only behind separate columns if your comparison needs them. Unknown tokens and fragmentation are related to vocabulary coverage and normalization, but the diagnostic cannot prove why a piece is absent or split. The comparison is also symmetric only if both tokenizers are called with the same options. If one call uses do_lower_case from the model config and the other uses a modified tokenizer, the columns are not comparable. Reload from the pinned revisions before each comparison.

Verified: 2026-10-05. The applicable models and revisions are google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, with transformers==4.56.2. The code asserts that Transformers version and passes the full commit revision to from_pretrained, so it is pinned to the tokenizer files that were checked. When either tokenizer.json at those revisions changes, or when you change the Transformers version, re-run the script and re-read the columns. Check tok.vocab_size, tok.unk_token_id, model_input_tokens, and the per-token table against the new files. Do not compare a count from one revision with a count from another revision without recording both. If the assertion fails, install the pinned dependency or deliberately adopt a new version and update the stated verification date and limitation.

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