Skip to content
wordpiece.org

Measuring WordPiece fragmentation on a developer corpus

Define a corpus-level pieces-per-pretokenized-unit diagnostic with zero-denominator handling and per-model results

Published 8 min read Verified

A developer corpus does not fragment like prose. Log lines, stack traces, identifiers, version strings, and mixed-language comments create many short pretokenized units, and WordPiece may split each into several pieces. This article defines a corpus-level diagnostic called pieces per pretokenized unit (PPU), gives a runnable procedure with pinned BERT tokenizers, and explains how to interpret the result without confusing fragmentation with unknown tokens.

Developer corpora are not natural language. A stack trace contains file paths, line numbers, hexadecimal addresses, and punctuation. A code comment may mix English with identifiers. BERT’s WordPiece vocabulary was trained on Wikipedia and BooksCorpus, so those units are not guaranteed to align with source-code tokens. The relevant engineering question is not whether some model can encode the corpus, but how many WordPiece pieces each pretokenized unit costs with a specific pinned BERT tokenizer. That cost affects sequence length, throughput, and whether you hit truncation limits. PPU gives a corpus-level answer.

What PPU measures

WordPiece first pre-tokenizes text: it splits on whitespace and punctuation, then applies normalization (for uncased BERT, lowercasing and accent stripping). Each resulting pretokenized unit is then matched against the vocabulary. A unit can map to one piece, multiple pieces, or a single [UNK] piece. PPU is the total number of content pieces divided by the total number of pretokenized units. A PPU of 1.0 means each unit needed one piece on average; higher values mean more fragmentation.

Unknown tokens are different. [UNK] is what WordPiece emits when no vocabulary match exists. A unit that becomes [UNK] contributes one piece and one unknown. A unit that becomes two known pieces contributes two pieces and zero unknowns. Therefore a corpus can have high unknown rate and low PPU, or low unknown rate and high PPU. Report them separately.

Also separate content tokens from model-input tokens. The diagnostic uses content tokens: the pieces returned by the tokenizer without special tokens. Model-input tokens include [CLS], [SEP], attention masks, and padding. For a single BERT sequence with add_special_tokens=True, model-input length is content length plus two, but that +2 is not fragmentation. Use add_special_tokens=False or inspect special_tokens_mask when you need the content-only view.

If you batch documents, remember that padding creates model-input tokens that are not content pieces. Compute PPU from content pieces only; compute model-input length separately with padding and special tokens if you are estimating memory.

Procedure

The procedure is corpus-level. Keep documents as strings. For each document, ask the fast tokenizer’s pre-tokenizer for the units. For each unit, call tokenizer.tokenize(unit) to get its content pieces. Sum units, pieces, and unknown pieces across the corpus. Then compute PPU = total pieces / total units. If total units is zero, PPU is undefined; return None rather than 0. A zero would falsely look like perfect one-piece-per-unit behavior. The same rule applies per document: an empty or whitespace-only document has no units, so its per-document PPU is undefined.

The following script is self-contained. It pins both BERT models to the revisions named here, asserts their known vocabulary sizes, and prints the diagnostic. Run it with transformers==4.56.2.

# pip install transformers==4.56.2
from transformers import AutoTokenizer

MODELS = {
    "google-bert/bert-base-uncased": {
        "revision": "86b5e0934494bd15c9632b12f734a8a67f723594",
        "vocab_size": 30522,
    },
    "google-bert/bert-base-multilingual-cased": {
        "revision": "3f076fdb1ab68d5b2880cb87a0886f315b8146f8",
        "vocab_size": 119547,
    },
}

CORPUS = [
    "def calculate_total(user_id: int) -> float:",
    "return sum(order.amount for order in orders)",
    "HTTP error: upstream timeout",
    "the quick brown fox jumps over the lazy dog",
    "Привет, мир! 你好,世界。",
    "",
]

def fragmentation_report(texts, tokenizer):
    total_units = 0
    total_pieces = 0
    total_unknown = 0
    per_doc_ppu = []

    for text in texts:
        pretok = tokenizer.backend_tokenizer.pre_tokenizer
        units = [tok for tok, _ in pretok.pre_tokenize_str(text)]
        pieces = []
        for unit in units:
            pieces.extend(tokenizer.tokenize(unit))

        n_units = len(units)
        n_pieces = len(pieces)
        n_unknown = sum(1 for p in pieces if p == tokenizer.unk_token)

        per_doc_ppu.append(None if n_units == 0 else n_pieces / n_units)
        total_units += n_units
        total_pieces += n_pieces
        total_unknown += n_unknown

    ppu = None if total_units == 0 else total_pieces / total_units
    unknown_rate = None if total_pieces == 0 else total_unknown / total_pieces

    return {
        "units": total_units,
        "content_pieces": total_pieces,
        "unknown_pieces": total_unknown,
        "pieces_per_pretoken_unit": ppu,
        "unknown_piece_rate": unknown_rate,
        "per_document_ppu": per_doc_ppu,
    }

for model_name, spec in MODELS.items():
    tok = AutoTokenizer.from_pretrained(
        model_name,
        revision=spec["revision"],
        use_fast=True,
    )
    assert tok.vocab_size == spec["vocab_size"], (model_name, tok.vocab_size)

    report = fragmentation_report(CORPUS, tok)
    print(model_name, spec["revision"])
    print("  vocab_size:", tok.vocab_size)
    print("  units:", report["units"])
    print("  content_pieces:", report["content_pieces"])
    print("  unknown_pieces:", report["unknown_pieces"])
    print("  pieces_per_pretoken_unit:", report["pieces_per_pretoken_unit"])
    print("  unknown_piece_rate:", report["unknown_piece_rate"])
    print("  per_document_ppu:", report["per_document_ppu"])

Reading per-model results

Run the same corpus through both pinned tokenizers. The multilingual cased model has a larger vocabulary—119,547 versus 30,522 for the uncased English model—but that does not automatically lower PPU on your corpus. The uncased model lowercases and strips accents; the multilingual cased model keeps case. For code, case and punctuation can dominate. An identifier like calculateTotal may become multiple pieces in either model, while a language-specific word may fragment differently because of normalization and vocabulary coverage. The script prints PPU and unknown rate per model, so compare them as separate signals. A model with lower PPU may still have more unknowns if its vocabulary misses domain terms; a model with higher PPU may have fewer unknowns because it covers a word with several known pieces.

Per-document PPU is useful for spotting outlier documents, but the corpus-level ratio is the headline number. Aggregate sums avoid a subtle bias: averaging per-document ratios would give equal weight to a one-unit document and a thousand-unit document. The script returns per-document values only for inspection. The zero-denominator rule applies there too.

The diagnostic does not claim that lower PPU is better. A tokenizer that maps everything to [UNK] can have PPU 1.0 but useless representations. Always read PPU alongside unknown rate and the actual pieces.

Limitations and re-check

A limitation of this diagnostic is that it measures tokenization behavior on your chosen corpus, not downstream accuracy. It also depends on BERT’s pre-tokenizer, which splits on whitespace and punctuation; if your corpus is source code, camelCase, snake_case, or long hex strings may be treated as single units and then fragmented internally. Changing the pre-tokenizer, normalizer, or vocabulary changes the result. The metric is not portable to models with different pre-tokenization rules unless you recompute the unit count with that model’s own pre-tokenizer. The fast-tokenizer backend API used here (backend_tokenizer.pre_tokenizer.pre_tokenize_str) is stable in Transformers 4.56.2 but is not the same as the high-level tokenizer.tokenize API; verify it if you upgrade. The evidence boundary for this article is the pinned tokenizer.json files and the Transformers 4.56.2 tokenizer documentation; if those files change, the diagnostic must be rerun.

Verified: 2026-10-05 against Transformers 4.56.2 and the pinned revisions google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8. The known vocabulary sizes for those pinned files are 30,522 and 119,547. When a pinned tokenizer.json or Transformers version changes, re-run the script and compare vocab_size, units, content_pieces, pieces_per_pretoken_unit, and unknown_piece_rate. If the assertions fail or the pre-tokenizer output changes, treat the new numbers as a new diagnostic, not a continuation of the old one. For a quick cross-check, also tokenize each full document with add_special_tokens=False and confirm that the total content pieces match the sum from per-unit tokenization; a mismatch means the normalization or pre-tokenization assumptions need review.

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