Skip to content
wordpiece.org

Building WordPiece regression vectors from real inputs

Create JSON fixtures of input, ids, tokens, and masks; show how to rerun them after dependency or asset changes

Published 8 min read Verified

A regression vector for a WordPiece tokenizer is not a file of expected input_ids alone. It is a reproducible record of one real input, the exact encoding flags, the pinned model revision, and every tokenizer-visible field you intend to compare later: ids, token strings, token type ids, attention mask, special-token mask, and, for fast tokenizers, offsets. Build that record first; then rerunning it after a dependency or asset change becomes a mechanical diff instead of a memory test.

What the fixture must pin

For google-bert/bert-base-uncased, pin the revision 86b5e0934494bd15c9632b12f734a8a67f723594 and transformers==4.56.2. The fast tokenizer loads tokenizer.json from that revision; that file is the version authority for vocabulary and normalization. Record model_id, revision, transformers_version, use_fast, add_special_tokens, truncation, padding, max_length, and return flags. Store the input string exactly, including whitespace and Unicode. Then store input_ids, tokens, token_type_ids, attention_mask, special_tokens_mask, and offset_mapping when available. A fixture that omits flags is not a regression vector; it is an anecdote.

Keep one fixture file per tokenizer identity, not one global file. A tokenizer identity is the tuple (model_id, revision, use_fast, transformers version). If any member changes, the old expected values are historical evidence, not current truth. Within the file, each record should carry its own config so a reader can rerun one case without reconstructing the whole matrix. JSON is a good container because it preserves order for array fields and can represent nulls for unavailable masks. Do not round-trip through a tokenizer method that changes type, such as converting ids to tokens and back, unless that round-trip is itself the behavior under test. Compare the fields returned by the encoding call.

Content tokens vs model-input tokens: the original text’s meaningful pieces are content. The tokenizer inserts special tokens such as classification and separator markers, and padding tokens can appear under a fixed max_length. Those are model-input tokens. When a diff appears, first ask whether it changed content tokenization or only model-input framing. Unknown tokens vs fragmentation: an unknown token is the tokenizer’s fallback for a unit it cannot map. Fragmentation is the opposite kind of event: a unit was mapped, but split into several WordPiece units. For BERT WordPiece, continuation pieces are commonly marked with ##, but the token strings in the fixture, not the visual mark alone, are the diagnostic.

Diagnostic procedure

Choose real inputs, not synthetic single words. Include mixed case, punctuation, repeated whitespace, a plausible out-of-vocabulary string, a word likely to fragment, and a two-sentence example. For each input, encode under several flag sets: no special tokens; special tokens; truncation with a small max_length; padding to a fixed max_length. The code below builds those records in memory and prints one JSON record plus structural assertions. The assertions check only internal consistency: the id, token, mask, special-token-mask, and offset lists must have the same length. They do not assert exact token values, because those values are what you are measuring.

# Python 3; requires transformers==4.56.2
import json
import transformers
from transformers import AutoTokenizer

MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
assert transformers.__version__ == "4.56.2", transformers.__version__

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

COMMON = {
    "return_special_tokens_mask": True,
    "return_offsets_mapping": True,
}

def vector(text, config):
    enc = tok(text, **config)
    ids = enc["input_ids"]
    tokens = tok.convert_ids_to_tokens(ids)
    out = {
        "input": text,
        "config": config,
        "input_ids": ids,
        "tokens": tokens,
        "token_type_ids": enc.get("token_type_ids"),
        "attention_mask": enc.get("attention_mask"),
        "special_tokens_mask": enc.get("special_tokens_mask"),
        "offset_mapping": enc.get("offset_mapping"),
    }
    assert len(ids) == len(tokens)
    assert len(ids) == len(out["attention_mask"])
    for field in ("token_type_ids", "special_tokens_mask", "offset_mapping"):
        if out[field] is not None:
            assert len(ids) == len(out[field])
    return out

inputs = [
    "WordPiece regression vectors",
    "Uncased BERT keeps case in normalization metadata.",
    "The tokenizer may fragment embeddings into wordpieces.",
    "zqxjkvbwplmnop",
    "Two sentences can share one sequence. [SEP] Literally?",
]

configs = [
    {"add_special_tokens": False, **COMMON},
    {"add_special_tokens": True, **COMMON},
    {"add_special_tokens": True, "truncation": True, "max_length": 8, **COMMON},
    {"add_special_tokens": True, "padding": "max_length", "max_length": 12, **COMMON},
]

fixtures = [vector(text, cfg) for text in inputs for cfg in configs]

print("model_id:", MODEL_ID)
print("revision:", FULL_COMMIT)
print("transformers:", transformers.__version__)
print("fixture_count:", len(fixtures))
print(json.dumps(fixtures[0], ensure_ascii=False, indent=2))

The printed record is the beginning of a JSON fixture set. Serialize the full list with json.dump(fixtures, f, ensure_ascii=False, indent=2). On a later run, load the fixture list and rebuild each record with the same model, revision, transformers version, and config. Compare stable fields in this order: config, input, input_ids, tokens, token_type_ids, attention_mask, special_tokens_mask, offset_mapping. A shorter or longer input_ids list is not automatically an error; it may be a truncation or padding difference. A changed token list at the same positions is the more specific signal. If an ## token appears where a whole word used to be, inspect fragmentation. If the unknown token appears, inspect coverage or normalization. If only special-token positions change, inspect add_special_tokens, truncation, and padding.

When comparing, separate structural differences from value differences. Length differences usually come from special tokens, truncation, or padding. Value differences with equal length usually come from normalization, vocabulary coverage, or WordPiece segmentation. Offsets can explain both: if a token’s span moves while the input string is unchanged, normalization changed; if one span splits into several adjacent spans, fragmentation changed. If the unknown token replaces a span, coverage changed. Record the observed offsets beside the diff so the next reader does not have to guess.

Interpret before accepting

The purpose of the fixture is to make tokenizer behavior observable, not to freeze it forever. If a dependency upgrade changes input_ids, do not update the expected JSON immediately. First verify that model_id, revision, transformers version, and flags are identical. If they are, the change is a real behavioral difference in your environment. Decide whether it is acceptable for your application. If it is not, pin the older dependency or vendor the fixture with an explicit note. If it is acceptable, update the fixture and record why. Do not treat a passing comparison as proof that the tokenizer is correct for all inputs; it only proves this input and these flags reproduce.

Limitations are important. A regression vector covers only the strings you captured. It cannot represent all Unicode normalization cases, all long-document truncation boundaries, or all padding combinations. It also does not evaluate the downstream model. The fast tokenizer’s offset mappings help you locate fragmentation and normalization effects, but offsets are not semantic labels. Store the original input as a string, not as a pre-tokenized list. If you store words, you have already made tokenization decisions. Also store the exact flag dictionary; dictionaries with equivalent Python values but different keys are not equivalent fixtures. For multilingual work, use google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8 and repeat the same method; its pinned vocabulary size is 119,547, while the English uncased vocabulary size is 30,522. Those numbers are vocabulary sizes, not sequence limits.

Verified: 2026-10-05. This guide is scoped to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2, using the pinned tokenizer.json, the v4.56.2 tokenizer API, and the v4.56.2 BertTokenizerFast source as its evidence boundary. Re-check when the pinned file or dependency changes: update FULL_COMMIT if the revision moves, update the transformers version, rerun the fixture code, and diff the fields above. If the diff is intentional, write a new expected fixture and note the change; if it is not, pin the prior combination. That is the complete regression loop.

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