Skip to content
wordpiece.org

Auditing punctuation boundaries before WordPiece runs

Test punctuation beside words, prices, and paths; explain which differences arise in pre-tokenization rather than the greedy loop

Published 8 min read Verified

Audit the punctuation boundary before attributing a token-count change to WordPiece. A comma, decimal point, slash, colon, dollar sign, or backslash can change the unit presented to the greedy matcher even when the letters around it are unchanged. The procedure below records each unit twice: as a pre-tokenized source span and as resulting tokens with offsets and IDs. That comparison locates the cause before anyone interprets the sequence length.

Verified: 2026-10-05. This review is scoped exclusively to google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2 and its fast tokenizer. The date records inspection of the cited primary files, not execution of the script; the script intentionally reports local observations. The pinned tokenizer.json is the configuration authority. The Transformers v4.56.2 BERT source establishes the Python wrapper and stage ordering; Google’s original implementation explains greedy longest-match behavior and [UNK] fallback.

Separate the stages before interpreting length

For this pin, normalization lowercases text and strips accents before BertPreTokenizer exposes punctuation and whitespace boundaries. The resulting lexical atoms—not raw input strings—are independently passed to WordPiece. Within an atom, WordPiece chooses the longest available piece and then continues with ## pieces. A count can therefore change for two independent reasons: new punctuation atoms, or a different number of pieces for a lexical atom. The fast backend may execute this configured pipeline in compiled code; it should not be described as calling the Python functions at runtime.

Keep normalization out of this first probe by using lowercase ASCII. If the pre-tokenized line for $price.usd contains $, price, ., and usd, the decimal point has already become its own unit before greedy matching. The tokens for those marks are direct pre-tokenization evidence; the number of pieces for price or usd is WordPiece evidence. Likewise, slashes, colons, commas, and dots can split a visually continuous path. This pin has no semantic price or filesystem-path rule.

Run the following in a clean Python 3 environment after installing python -m pip install transformers==4.56.2. It downloads the named commit and prints all diagnostic layers without hardcoding an observed token sequence.

from importlib.metadata import version

import transformers
from transformers import AutoTokenizer


MODEL_ID = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
EXPECTED_TRANSFORMERS = "4.56.2"

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

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID,
    revision=FULL_COMMIT,
    use_fast=True,
)
assert tokenizer.is_fast
assert tokenizer.unk_token is not None

backend = tokenizer.backend_tokenizer
assert backend.pre_tokenizer is not None

AUDITED_PUNCTUATION = frozenset({",", ".", "/", "\\", ":", "$"})
CASES = (
    ("word, spaced", "release hold"),
    ("word, joined", "release,hold"),
    ("price, plain", "price"),
    ("price, marked", "$price.usd"),
    ("price, separated", "$price,usd"),
    ("path, plain", "/var/log/app"),
    ("path, dotted", "/var/log/app.log"),
    ("path, backslashes", r"C:\tmp\app.log"),
    ("URL punctuation", "https://example.test/a,b"),
)

print("Transformers:", transformers.__version__)
print("tokenizers runtime:", version("tokenizers"))
print("Model:", MODEL_ID)
print("Requested revision:", FULL_COMMIT)
print("Tokenizer class:", tokenizer.__class__.__name__)
print("Vocabulary entries:", tokenizer.vocab_size)
print("Normalizer:", backend.normalizer)
print("Pre-tokenizer:", backend.pre_tokenizer)


def audit(label, text):
    encoded = tokenizer(
        text,
        add_special_tokens=True,
        padding=False,
        truncation=False,
        return_attention_mask=True,
        return_special_tokens_mask=True,
        return_offsets_mapping=True,
    )

    input_ids = encoded["input_ids"]
    tokens = tokenizer.convert_ids_to_tokens(input_ids)
    offsets = encoded["offset_mapping"]
    special_mask = encoded["special_tokens_mask"]

    content_rows = [
        (token, (start, end))
        for token, (start, end), is_special in zip(
            tokens, offsets, special_mask
        )
        if not is_special
    ]

    content_count = len(content_rows)
    special_count = sum(1 for value in special_mask if value == 1)
    model_input_count = sum(encoded["attention_mask"])

    # No padding was requested, so every submitted position is active.
    assert model_input_count == len(input_ids) == len(offsets)
    assert model_input_count == content_count + special_count

    pre_tokenized = backend.pre_tokenizer.pre_tokenize_str(text)
    assert pre_tokenized

    atom_pieces = []
    punctuation_offsets = set()

    for token, (start, end) in content_rows:
        if text[start:end] in AUDITED_PUNCTUATION:
            punctuation_offsets.add((start, end))

    for position, character in enumerate(text):
        if character in AUDITED_PUNCTUATION:
            assert (position, position + 1) in punctuation_offsets

    for atom, (start, end) in pre_tokenized:
        # All probes are already normalized lowercase ASCII.
        assert text[start:end] == atom

        if any(character in AUDITED_PUNCTUATION for character in atom):
            assert len(atom) == 1
            assert atom in AUDITED_PUNCTUATION

        pieces = [
            token
            for token, (piece_start, piece_end) in content_rows
            if piece_start < piece_end
            and start <= piece_start
            and piece_end <= end
        ]
        assert pieces, (atom, start, end)
        atom_pieces.append((atom, pieces))

    unknown_spans = [
        span
        for token, span in content_rows
        if token == tokenizer.unk_token
    ]

    print(f"\n{label}: {text!r}")
    print("  pre-tokenized:", pre_tokenized)
    print("  atom -> pieces:", atom_pieces)
    print("  IDs:", input_ids)
    print("  tokens:", tokens)
    print(
        "  content={content_count}; "
        "model-input={model_input_count}; "
        "special={special_count}".format(
            content_count=content_count,
            model_input_count=model_input_count,
            special_count=special_count,
        )
    )
    print("  [UNK] source spans:", unknown_spans)


for case_label, case_text in CASES:
    audit(case_label, case_text)

Read the two tokenization layers

Read the pre-tokenized line before the ID line. For release hold, lexical spans without punctuation establish the whitespace boundaries already available to WordPiece. If release,hold shows a separate comma span, the punctuation-derived token is not evidence that the greedy loop split either adjacent word. The paired prices and paths then apply the same test at every audited mark.

Interpret each observation according to its layer:

  • A new singleton pre-tokenized span that becomes a token is a punctuation-boundary cost, not greedy fragmentation of adjacent letters.
  • One lexical atom represented by several ordinary tokens is fragmentation. Later pieces normally carry ##; a changed count here belongs to the WordPiece vocabulary or runtime.
  • One lexical atom represented by [UNK] is the unknown-token fallback, not fragmentation. The source span identifies which unrepresentable unit triggered it.
  • A change only in total sequence length after the atom-to-pieces mapping remains fixed belongs to special-token processing, padding, or truncation. This script fixes those controls, but production batches may not.

content counts only positions whose special_tokens_mask value is zero. It includes punctuation and [UNK], but excludes the pinned tokenizer’s [CLS] and [SEP]. model-input counts active positions from attention_mask; because this script disables padding, it also equals the submitted tensor width. Do not report the content count as the model-input length. Offsets retain the connection to the original ASCII source even though the pipeline also exposes normalized pre-tokenized strings.

Limitations and re-check procedure

This is a focused ASCII probe, not a benchmark or a claim about every input. It does not cover combining marks, normalization length changes, literal special-token text, truncated long inputs, padded batches, or caller-supplied split words. Those settings can change offsets and counts before the final post-processor. The pinned uncased vocabulary has 30,522 entries, which is a useful identity check but does not prove that all token IDs or settings remain unchanged.

When the pinned file or dependency changes, first update FULL_COMMIT or EXPECTED_TRANSFORMERS deliberately. Retain a SHA-256 hash of the downloaded tokenizer.json, compare it with the previously reviewed artifact, and inspect changes to normalizer, pre_tokenizer, post_processor, decoder, and the WordPiece model section. Lock the complete environment, including the separately installed tokenizers runtime, because the same Transformers version under different dependency resolution is not a sufficient reproducibility record. Finally, rerun the unchanged probes and compare pre-tokenized spans first, atom-to-piece mappings second, and counts last. If those layers remain aligned, a count change is attributable to post-processing; if atoms changed first, investigate pre-tokenization; only a change within an unchanged atom belongs to WordPiece.

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