Isolating the effect of case folding in BERT tokenization
Build paired uppercase/lowercase probes for the uncased and multilingual cased tokenizer; separate normalization from vocabulary coverage
Case folding is easiest to isolate when a lowercase/uppercase pair reaches the tokenizer with lexical choice, punctuation, and whitespace fixed. The diagnostic compares three layers in order: BERT normalizer output, content-token IDs, and model-input IDs. A difference appearing only after special tokens are added is a count-convention difference, not evidence of case folding. The same ASCII probes are then run against two pinned BERT fast tokenizers, separating normalization from case-sensitive WordPiece behavior without borrowing counts from an unrelated model.
Pin the tokenizer scope
Verified: 2026-10-05. The runtime scope is Transformers 4.56.2 with AutoTokenizer.from_pretrained(..., revision=FULL_COMMIT, use_fast=True). The exact model scopes are google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594 and google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8; no other tokenizer is used.
The pinned uncased tokenizer.json configures accent stripping and lowercasing. The pinned multilingual cased tokenizer.json configures neither lowercasing nor accent stripping. These files are the authority for normalization and vocabulary behavior.
Here, “case folding” is shorthand for BERT’s lowercase option, not Python’s full Unicode str.casefold() operation. The probes therefore use ASCII words: converting arbitrary Unicode text to uppercase can change length or compatibility forms, introducing a second variable. The relevant Transformers 4.56.2 tokenizer reference defines the encoding options used below, but it does not replace the pinned tokenizer files as the tokenization authority.
Run the paired probe
Install the exact Transformers release in an isolated Python 3 environment, then run this self-contained diagnostic. It prints normalized text, content tokens and IDs, offsets, full model-input tokens, and the special-token mask. Its assertions check representation consistency; no locally obtained token list or count is hardcoded.
import tokenizers
import transformers
from transformers import AutoTokenizer
TRANSFORMERS_VERSION = "4.56.2"
UNCASED_FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
ML_CASED_FULL_COMMIT = "3f076fdb1ab68d5b2880cb87a0886f315b8146f8"
PROBES = ("case", "tokenizer", "embedding", "network", "unstructured")
if transformers.__version__ != TRANSFORMERS_VERSION:
raise RuntimeError(
f"Expected transformers=={TRANSFORMERS_VERSION}, "
f"got {transformers.__version__}"
)
print("transformers:", transformers.__version__)
print("tokenizers:", tokenizers.__version__)
def load_tokenizer(model_id, full_commit):
tokenizer = AutoTokenizer.from_pretrained(
model_id,
revision=full_commit,
use_fast=True,
trust_remote_code=False,
)
if not tokenizer.is_fast:
raise AssertionError("A fast tokenizer is required for offset mappings")
if tokenizer.unk_token_id is None:
raise AssertionError("The tokenizer has no unknown-token ID")
return tokenizer
def snapshot(tokenizer, text):
normalizer = tokenizer.backend_tokenizer.normalizer
if normalizer is None:
raise AssertionError("This diagnostic requires a configured normalizer")
content = tokenizer(
text,
add_special_tokens=False,
padding=False,
truncation=False,
return_offsets_mapping=True,
return_special_tokens_mask=True,
)
model_input = tokenizer(
text,
add_special_tokens=True,
padding=False,
truncation=False,
return_special_tokens_mask=True,
)
content_ids = content["input_ids"]
input_ids = model_input["input_ids"]
special_mask = model_input["special_tokens_mask"]
assert not any(content["special_tokens_mask"])
assert len(content_ids) + sum(special_mask) == len(input_ids)
return {
"text": text,
"normalized": normalizer.normalize_str(text),
"content_ids": content_ids,
"content_tokens": content.tokens(),
"offsets": content["offset_mapping"],
"input_ids": input_ids,
"input_tokens": model_input.tokens(),
"special_mask": special_mask,
"unk_id": tokenizer.unk_token_id,
}
def unknown_positions(row):
return [
index
for index, token_id in enumerate(row["content_ids"])
if token_id == row["unk_id"]
]
def continuation_count(row):
return sum(token.startswith("##") for token in row["content_tokens"])
def classify(lower, upper):
if lower["normalized"] == upper["normalized"]:
assert lower["content_ids"] == upper["content_ids"]
return "case erased before WordPiece"
if unknown_positions(lower) != unknown_positions(upper):
return "case reaches WordPiece; unknown-token outcome differs"
if (
len(lower["content_ids"]) != len(upper["content_ids"])
or continuation_count(lower) != continuation_count(upper)
):
return "case reaches WordPiece; known-piece segmentation differs"
if lower["content_ids"] != upper["content_ids"]:
return "case reaches WordPiece; token selection differs"
return "case survives normalization; no token difference for this probe"
model_cases = (
("google-bert/bert-base-uncased", UNCASED_FULL_COMMIT),
("google-bert/bert-base-multilingual-cased", ML_CASED_FULL_COMMIT),
)
for model_id, full_commit in model_cases:
tokenizer = load_tokenizer(model_id, full_commit)
print(f"\n{model_id}@{full_commit}")
print("vocabulary entries:", len(tokenizer.get_vocab()))
for word in PROBES:
assert word.isascii()
lower = snapshot(tokenizer, word.lower())
upper = snapshot(tokenizer, word.upper())
assert lower["text"] != upper["text"]
print(f"\n {word}: {classify(lower, upper)}")
for label, row in (("lower", lower), ("upper", upper)):
print(f" {label} normalized={row['normalized']!r}")
print(f" {label} content={row['content_tokens']!r}")
print(f" {label} content_ids={row['content_ids']!r}")
print(f" {label} offsets={row['offsets']!r}")
print(f" {label} model_input={row['input_tokens']!r}")
print(f" {label} input_ids={row['input_ids']!r}")
print(f" {label} special_mask={row['special_mask']!r}")
Interpret each layer
Begin with normalized. If the lowercase and uppercase forms become identical, normalization has erased their case difference before WordPiece selection. If the normalized strings remain distinct, case has passed through the normalizer and can affect token lookup. Equal token IDs despite equal normalized text would be internally inconsistent; the script treats that as an assertion failure rather than a tokenizer result.
For the uncased file, lowercasing and accent stripping are configured. Equality of the normalized ASCII pair—and then equality of its content IDs—is therefore the relevant downstream result. If that equality fails, preserve the printed evidence and investigate the loaded file, dependency, or probe; do not immediately attribute the discrepancy to vocabulary coverage.
For the multilingual cased file, lowercasing is disabled. If the normalized pair differs, the difference now enters BERT’s pre-tokenization and WordPiece path. The token strings show how that path handled the case-sensitive text.
An [UNK] content token means that the relevant unit could not be represented by a complete WordPiece sequence using the configured vocabulary and matching procedure. It does not enumerate which characters or candidate pieces were missing. By contrast, a ## token is a known continuation piece. Multiple known pieces therefore indicate fragmentation, while [UNK] indicates failed representability; the two conditions should not be reported as the same event.
For example, an uppercase [UNK] paired with a known lowercase token indicates a case-dependent representability difference. Multiple ## pieces on both sides, with no [UNK], indicate a segmentation difference among known vocabulary entries. Different IDs with equal lengths indicate different token choices rather than a simple count increase.
Compare IDs only within one tokenizer. The two pinned models have different vocabularies and embedding matrices, so an ID from one is not evidence about the meaning or availability of the same numeric ID in the other.
Keep content and model-input counts separate
add_special_tokens=False defines the content-token view used for normalization and segmentation comparisons. add_special_tokens=True defines the sequence supplied to the model; for these single-sequence inputs, it includes the configured [CLS] and [SEP] tokens. The printed mask makes the boundary explicit instead of assuming a count. Padding and truncation are disabled, so neither changes the observed length.
Offsets provide a second check on token spans, but they are not character counts. Fast-tokenizer offsets refer to the original string, and normalization—especially accent stripping—can prevent a one-to-one relationship between normalized characters and input positions. The ASCII probes avoid most of that complication.
Limitations
This is a small diagnostic sample, not evidence about every English or multilingual word. It does not exercise punctuation, whitespace cleanup, Chinese-character spacing, combining marks, scripts with complex case mappings, or words near tokenizer limits. Adding an accented or non-Latin pair to the uncased model would also test accent stripping, so it would no longer isolate case alone.
The results concern these two fast-tokenizer revisions only. They do not establish tokenization behavior for another BERT checkpoint, language, Transformers release, or resolved tokenizers dependency, and they say nothing about model accuracy or downstream quality.
Re-check after a file or dependency change
When a pinned tokenizer file or dependency changes, create a new recorded baseline rather than editing the old conclusion. Install the reviewed revision in a fresh environment, print both transformers and tokenizers versions, and rerun every pair against both models. Save the complete output, package versions, model identifiers, and full commit constants.
The pinned known vocabulary sizes are 30,522 for the uncased tokenizer and 119,547 for the multilingual cased tokenizer. They are useful change detectors, not proof of case behavior. A different len(get_vocab()) under the same commit warrants investigation of cache, file loading, or dependency state. If Transformers must change, run the previous and new versions side by side; an output change confined to the dependency should not be described as a change in the pinned normalization configuration. Recheck the versioned tokenizer documentation as well, especially offset, mask, padding, and truncation behavior.
Sources
- google-bert/bert-base-uncased tokenizer.json at 86b5e093
Pinned WordPiece vocabulary and normalization settings for the English uncased model.
- google-bert/bert-base-multilingual-cased tokenizer.json at 3f076fdb
Pinned WordPiece vocabulary and normalization settings for the multilingual cased model.
- Hugging Face Transformers v4.56.2 tokenizer API
Versioned reference for encoding options, output fields, and fast-tokenizer alignment methods.
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.