Skip to content
wordpiece.org

Testing the maximum input characters per WordPiece word

Read max_input_chars_per_word from pinned tokenizer.json; probe the boundary using programmatically generated strings and distinguish pre-tokenized words from whole inputs

Published 8 min read Verified

max_input_chars_per_word is a guard on a word presented to WordPiece, not a limit on the number of characters accepted by a model and not a context-window setting. The engineering task is narrower: read the guard from each pinned checkpoint, exercise the transition around it with generated strings, and distinguish a length rejection from ordinary vocabulary failure or harmless fragmentation. This procedure covers google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased at revision 3f076fdb1ab68d5b2880cb87a0886f315b8146f8, using transformers==4.56.2. Verified: 2026-10-05. The pinned uncased tokenizer.json and multilingual tokenizer.json are the configuration authorities; the versioned BERT tokenizer source explains the corresponding tokenization design.

What the setting measures

A whole-input call first runs the normalization and pre-tokenization stages selected by that file. WordPiece then receives each resulting word separately. The length guard therefore applies to a pre-tokenized word, not blindly to the complete string. A long input made from many ordinary space-separated words can pass each per-word check while still exceeding a model position limit. Conversely, one uninterrupted candidate can be rejected when its tokenizer character count exceeds the configured value. For the uncased snapshot, normalization can lowercase and otherwise transform text; the cased snapshot has different normalization settings. Repeating ASCII a characters avoids relying on accent handling, Chinese-character spacing, Unicode normalization, or byte length.

The versioned Python implementation uses a strict > comparison: a word whose length equals the limit is still eligible for greedy vocabulary matching; a longer word returns [UNK]. Equality does not guarantee a useful tokenization, though. A word at or below the limit can still become unknown if greedy matching cannot cover it. At or below the limit, several recognized pieces are fragmentation, not failure.

Those pieces become content tokens. Model-input tokens are a different accounting: BERT’s postprocessor can add [CLS] and [SEP]. The diagnostic below sets add_special_tokens=False, so both reported content counts exclude those postprocessor tokens. Padding, if requested, is also not content; truncation can change a model-input view without changing the pre-tokenized-word diagnosis.

Do not infer this value from model_max_length, from a class default, or from a previous run. Read model.max_input_chars_per_word from the exact raw tokenizer.json. Calling only the backend WordPiece model supplies an already-segmented word and bypasses normalization and pre-tokenization. Calling AutoTokenizer.encode supplies a whole input and exercises the complete path. For an ASCII run containing no separators, the pre-tokenizer should produce one span, so the two paths should agree; checking that premise prevents a whole-input result from being mislabeled as a model-only result. is_split_into_words=True is not an alternative here: that option consumes token IDs supplied by the caller rather than raw words.

Run the boundary diagnostic

Install Transformers with python -m pip install transformers==4.56.2, then run this Python 3 script in an environment with network access. It refuses a different Transformers release, downloads each immutable file, prints its SHA-256, reads the limit instead of embedding it, loads the exact revision with the fast tokenizer, and asserts the boundary. It also prints the separately resolved tokenizers backend version because the Transformers pin alone does not fully freeze runtime behavior.

import hashlib
import json
import platform
from importlib.metadata import version
from urllib.request import Request, urlopen

from transformers import AutoTokenizer

REQUIRED_TRANSFORMERS = "4.56.2"
installed_transformers = version("transformers")
if installed_transformers != REQUIRED_TRANSFORMERS:
    raise SystemExit(
        f"Install transformers=={REQUIRED_TRANSFORMERS}; "
        f"found {installed_transformers}"
    )

PINNED = {
    "google-bert/bert-base-uncased":
        "86b5e0934494bd15c9632b12f734a8a67f723594",
    "google-bert/bert-base-multilingual-cased":
        "3f076fdb1ab68d5b2880cb87a0886f315b8146f8",
}

print(
    f"python={platform.python_version()} "
    f"transformers={installed_transformers} "
    f"tokenizers={version('tokenizers')}"
)

for repo_id, FULL_COMMIT in PINNED.items():
    url = (
        f"https://huggingface.co/{repo_id}/resolve/"
        f"{FULL_COMMIT}/tokenizer.json"
    )
    request = Request(url, headers={"User-Agent": "wordpiece-boundary-check"})
    with urlopen(request, timeout=60) as response:
        raw_file = response.read()

    digest = hashlib.sha256(raw_file).hexdigest()
    document = json.loads(raw_file)
    model_config = document["model"]
    assert model_config["type"] == "WordPiece"

    limit = model_config["max_input_chars_per_word"]
    unk = model_config["unk_token"]
    assert isinstance(limit, int) and limit >= 2

    fast = AutoTokenizer.from_pretrained(
        repo_id,
        revision=FULL_COMMIT,
        use_fast=True,
    )
    assert fast.is_fast
    assert fast.convert_tokens_to_ids(unk) == fast.unk_token_id

    print(f"\n{repo_id}@{FULL_COMMIT}")
    print(f"tokenizer_json_sha256={digest}")
    print(f"configured_limit={limit}")

    for char_count in (limit - 1, limit, limit + 1):
        word = "a" * char_count

        spans = list(
            fast.backend_tokenizer.pre_tokenizer.pre_tokenize_str(word)
        )
        direct = list(fast.backend_tokenizer.model.tokenize(word))
        whole_ids = fast.encode(word, add_special_tokens=False)
        whole = fast.convert_ids_to_tokens(whole_ids)

        print(
            f"chars={char_count} spans={len(spans)} "
            f"direct_count={len(direct)} whole_count={len(whole)} "
            f"direct_unknown={unk in direct} "
            f"whole_unknown={unk in whole}"
        )

        assert len(spans) == 1
        assert spans[0][1] == (0, char_count)
        assert whole == direct

        if char_count <= limit:
            assert direct
            assert unk not in direct
        else:
            assert direct == [unk]

    print("boundary assertions passed")

Read the configured_limit line first: that integer is the value under test, not a benchmark result. The rows at limit-1, limit, and limit+1 deliberately use one generated variable rather than three unrelated examples. direct_unknown=False at or below the limit means WordPiece returned no unknown. An over-limit direct_count=1 together with direct_unknown=True indicates length rejection. A multi-piece result with no unknown is successful WordPiece fragmentation. The assertion that whole-input tokens equal direct WordPiece tokens checks the generated-string premise and catches a changed pre-tokenizer or normalization outcome. If the at-limit row contains [UNK], do not call the next row the boundary: inspect the loaded file, vocabulary, and backend versions first.

A passing over-limit row is especially important to interpret correctly. It contains one unknown content token, not one token per input character and not a fragmented representation of the excessive word. Under the limit, the same [UNK] can instead report that no sequence of vocabulary pieces covered the candidate. Thus the marker identifies an encoding outcome, not its cause. A mismatch between direct and whole-input rows would mean that the supposedly single word was transformed or split, or that the backend and raw-file evidence no longer describe the same behavior. For real text, inspect normalized text and pre-tokenizer spans before transferring this conclusion to a particular word.

Limitations and re-checks

Three limitations matter. First, the direct backend_tokenizer.model.tokenize call is a focused diagnostic on the already-segmented WordPiece model, not a promise that arbitrary application text reaches it as one word. Real multilingual text can be normalized or split on whitespace, punctuation, and the BERT normalizer’s Chinese-character handling. The direct check also concerns the backend’s character count; it is not a byte count or a language-independent grapheme count. The all-a probe controls those variables but does not characterize every word in either vocabulary.

Second, the procedure is evidence only for the two repository/revision pairs named above and their serialized files. It does not transfer a count to another BERT checkpoint or any unrelated language model. Third, transformers==4.56.2 is exact, but its tokenizers dependency is separately resolved. The script records that backend version, and the fast implementation can change under the same Transformers version. The assertions establish the boundary for the backend actually installed, not a permanent guarantee from the Transformers release alone. A later tokenizers release, a different Python build, or a modified checkpoint therefore requires a fresh check.

To re-check after a pinned file or dependency changes, first diff the old and new tokenizer.json, especially max_input_chars_per_word, unk_token, continuing_subword_prefix, the vocabulary, and normalizer or pre-tokenizer configuration. Change the full commit in both the raw URL and AutoTokenizer.from_pretrained call together; never validate one revision while diagnosing another. Keep the limit data-driven in the script, and do not replace its assertions with a recorded value. Capture the printed file hash, Python and package versions, and all boundary rows with the new revision.

Then add representative probes for the behavior that changed: accents and case for normalization, CJK text for the multilingual pre-tokenizer, punctuation and whitespace for word boundaries, and known in-vocabulary and out-of-vocabulary candidates for fallback. Keep add_special_tokens=False while measuring content pieces; only afterward measure a default encoded sequence, recording [CLS], [SEP], padding, and any truncation as model-input accounting. If the new run passes, update the stated verification date and model revision; if it fails, retain the output as diagnostic evidence rather than weakening the boundary assertion.

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