Skip to content
wordpiece.org

Property tests for a WordPiece tokenizer implementation

Specify invariants for ids, masks, offsets, and deterministic re-encoding; include generated edge cases without asserting unmeasured output

Published 8 min read Verified

A tokenizer can return plausible ids for a few sentences and still break a structural contract. Property tests target invariants that must hold for every input: array lengths agree, masks line up, offsets stay inside the original text, and re-encoding is deterministic. This article specifies one such invariant set for a fast WordPiece tokenizer and gives a self-contained diagnostic script pinned to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. Verified: 2026-10-05.

The invariant set

Length coherence is first. For a single string with add_special_tokens=True, truncation=False, and no padding, input_ids, attention_mask, token_type_ids, special_tokens_mask, and offset_mapping must have the same length. A mismatch makes the encoding structurally invalid regardless of token strings.

Mask semantics comes next. Without padding, attention_mask should be all ones. For a single sequence, token_type_ids should be all zeros. special_tokens_mask should mark model-input tokens added by the tokenizer, such as the [CLS] and [SEP] that BERT wraps around content. The remaining positions are content tokens. The diagnostic separates them because a raw token count that mixes both is misleading when testing WordPiece segmentation.

Offset geometry is third. For fast tokenizers, offset_mapping gives one (start, end) pair per id. Special tokens should be zero-width, conventionally (0, 0). Content tokens should satisfy 0 <= start <= end <= len(text). Among content tokens, offsets should be ordered and non-overlapping: each start should be greater than or equal to the previous end. For example, if a word is split into two pieces, the second piece’s start should be at least the first piece’s end. A gap is allowed where whitespace or punctuation was removed, but overlap is not. This catches alignment bugs where a piece points to the wrong span or normalization shifts offsets outside the original string.

Deterministic re-encoding is fourth. Encoding the same text twice with the same options must produce the same input_ids. State leakage or incorrect caching fails this.

Fifth, unknown tokens and fragmentation are different. An unknown token is a content token equal to tokenizer.unk_token_id, usually [UNK]. Fragmentation is a word split into multiple known WordPiece pieces, often with continuation pieces beginning with ##. A rare word can fragment without becoming unknown; an unknown token can appear without fragmentation. The diagnostic prints both counts per case.

Diagnostic procedure

The script below downloads the pinned tokenizer with use_fast=True, which is required for offsets and special_tokens_mask in this form. The slow tokenizer path does not expose offset_mapping in the same way, so this check is intentionally fast-only. If you need to compare slow and fast behavior, do that as a separate test rather than weakening this one. The script generates edge cases: empty string, whitespace, punctuation, contractions, long words, accented text, CJK, emoji, repeated words, and deterministic random ASCII strings. For each case it runs the assertions above and prints one summary line only if the invariants hold. Exact counts are not baked in; they depend on the pinned tokenizer.json and the installed Transformers wrapper.

import random
import string
import transformers
from transformers import AutoTokenizer

MODEL_ID = "google-bert/bert-base-uncased"
REVISION = "86b5e0934494bd15c9632b12f734a8a67f723594"

def gen_cases():
    cases = [
        "", " ", "\t\n", "hello", "Hello, world!", "don't",
        "playplaying", "antidisestablishmentarianism", "C++", "naïve café",
        "東京", "🙂 emoji", "word " * 20, "..." * 10,
    ]
    rng = random.Random(0)
    alphabet = string.ascii_letters + string.digits + " .,!?'-"
    for _ in range(20):
        n = rng.randrange(0, 40)
        cases.append("".join(rng.choice(alphabet) for _ in range(n)))
    return cases

def check(tok, text):
    enc = tok(
        text,
        add_special_tokens=True,
        return_attention_mask=True,
        return_token_type_ids=True,
        return_special_tokens_mask=True,
        return_offsets_mapping=True,
        truncation=False,
        padding=False,
    )
    ids = enc["input_ids"]
    mask = enc["attention_mask"]
    ttype = enc["token_type_ids"]
    smask = enc["special_tokens_mask"]
    offsets = enc["offset_mapping"]
    tokens = tok.convert_ids_to_tokens(ids)
    n = len(ids)

    assert len(mask) == n, (text, "attention_mask length")
    assert len(ttype) == n, (text, "token_type_ids length")
    assert len(smask) == n, (text, "special_tokens_mask length")
    assert len(offsets) == n, (text, "offset length")
    assert all(m == 1 for m in mask), (text, "attention mask not all ones")
    assert all(t == 0 for t in ttype), (text, "token type ids not zero")

    for tok_str, sm, (start, end) in zip(tokens, smask, offsets):
        if sm == 1:
            assert (start, end) == (0, 0), (text, tok_str, start, end)
        else:
            assert 0 <= start <= end <= len(text), (text, tok_str, start, end)

    content = [(s, e) for sm, (s, e) in zip(smask, offsets) if sm == 0]
    for (s0, e0), (s1, e1) in zip(content, content[1:]):
        assert s1 >= e0, (text, (s0, e0), (s1, e1))

    enc2 = tok(text, add_special_tokens=True, truncation=False, padding=False)
    assert enc2["input_ids"] == ids, (text, "nondeterministic ids")

    unk_id = tok.unk_token_id
    n_unk = sum(1 for i in ids if i == unk_id)
    n_cont = sum(1 for t in tokens if t.startswith("##"))
    n_content = sum(1 for m in smask if m == 0)
    print(f"ok len={len(text):3d} content={n_content:3d} "
          f"unk={n_unk:3d} cont={n_cont:3d} ids={n:3d} offsets={len(offsets):3d}")

def main():
    tok = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION, use_fast=True)
    assert tok.is_fast, "this diagnostic requires a fast tokenizer"
    print(f"transformers={transformers.__version__} model={MODEL_ID} "
          f"revision={REVISION} fast={tok.is_fast}")
    for text in gen_cases():
        check(tok, text)

if __name__ == "__main__":
    main()

Reading the observations

If the script exits without AssertionError, the invariants held for every generated case. The header reports the actual Transformers version and the pinned revision loaded. Each ok line reports input length, content-token count, unknown-token count, continuation count, total id count, and offset count. Because special_tokens_mask is checked, you can trust that content counts exclude [CLS] and [SEP]; if you want model-input counts, add them back explicitly. The numbers may differ from another run if the pinned file or wrapper changes; that is why they are printed.

A failure points to a specific contract break. A length mismatch suggests return flags are not producing aligned arrays. A content offset outside [0, len(text)] suggests alignment drift. Non-monotonic content offsets suggest a merge or cleanup step misaligned spans. A special token with a nonzero offset suggests inconsistent special-token handling. Nondeterministic ids suggest state leakage or a caching bug.

Unknown and continuation counts are diagnostic, not pass/fail by themselves. A high continuation count means WordPiece fragmented words into known pieces. A nonzero unknown count means the vocabulary lacks a matching piece for some content. Both can be legitimate for the pinned English uncased vocabulary, which has 30,522 entries. They do not measure downstream task quality.

Limitations and re-check procedure

These invariants are necessary but not sufficient. They do not prove vocabulary ordering is correct, that segmentation matches the original BERT algorithm, that offsets are exact for every Unicode normalization edge case, or that slow and fast tokenizers agree. They are scoped to use_fast=True and to the named revision. Offsets are indices into the Python string you passed, after the wrapper’s normalizer has run. They are not byte offsets and do not guarantee that text[start:end] equals the token string, especially for uncased normalization that strips accents or lowercases. The diagnostic covers only the generated cases; it is a property test, not an exhaustive proof.

The evidence boundary is the pinned tokenizer.json and the Transformers v4.56.2 tokenizer API. For the multilingual cased model, the corresponding pinned revision is 3f076fdb1ab68d5b2880cb87a0886f315b8146f8, with a 119,547-entry vocabulary, but this script pins the English uncased model.

To re-check after a change, update REVISION to the new full commit, install the intended transformers version, and rerun the script. If only the Transformers version changes, keep the same REVISION and rerun; a new failure then points to wrapper behavior rather than a vocabulary change. If the revision changes, expect vocabulary or normalizer changes and compare failure modes, not just pass/fail. If an assertion fails, reduce the failing string to the smallest text that reproduces, then inspect tokenizer.json for vocabulary or normalizer changes and compare the wrapper version. Do not compare counts to an unrelated model. The goal is a narrow, repeatable claim: for this pinned model and dependency, these structural invariants hold on these generated cases.

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