Skip to content
wordpiece.org

Testing whitespace collapse in a BERT tokenizer

Probe spaces, tabs, line breaks, and leading whitespace; compare output ids with raw offsets and document data-cleaning implications

Published 8 min read Verified

Whitespace collapse in a BERT tokenizer is the observation that strings differing only in spaces, tabs, or line breaks can produce the same sequence of WordPiece content ids. The tokenizer does not emit tokens for whitespace. It normalizes whitespace, uses it as a separator, and then applies WordPiece to the resulting words. That is convenient for many pipelines, but it is a trap when token ids are used as a proxy for the exact input string. The following diagnostic probes spaces, tabs, line breaks, and leading whitespace against the pinned fast tokenizer, then compares ids with raw offsets.

Scope and verification

All token behavior and counts here are scoped to google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. Verified: 2026-10-05. The pinned uncased vocabulary contains 30,522 entries; use that number only for this checkpoint. The diagnostic uses AutoTokenizer.from_pretrained(…, use_fast=True) because the fast path exposes offset mappings and is built from the pinned tokenizer.json. The slow Python tokenizer follows the versioned source, but production comparisons usually target the fast tokenizer’s normalization and pre-tokenization.

What whitespace collapse actually does

In the pinned tokenizer.json, BERT’s normalizer handles whitespace before WordPiece runs. For the uncased model, text is cleaned and lowercased. Cleaning replaces whitespace characters with a space and removes control characters. The pre-tokenizer then splits on whitespace and punctuation. Because empty strings from repeated separators are discarded, "hello world" and "hello world" reach WordPiece with the same two words. A tab or newline also becomes a separator, so "hello\tworld" and "hello\nworld" can produce the same content ids. Leading whitespace has no word to attach to, so " hello" tokenizes like "hello" from the id perspective. The original whitespace is not gone from the string; it is ignored for the token sequence and represented only in alignment metadata. This means whitespace is not a token class in the same sense as a word or subword; it is a boundary marker that the tokenizer normalizes away.

A diagnostic you can run

from transformers import AutoTokenizer
import transformers

FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
MODEL = "google-bert/bert-base-uncased"

print(f"transformers=={transformers.__version__}")
tok = AutoTokenizer.from_pretrained(MODEL, revision=FULL_COMMIT, use_fast=True)

variants = {
    "single_space": "hello world",
    "double_space": "hello  world",
    "tab": "hello\tworld",
    "newline": "hello\nworld",
    "leading_spaces": "   hello world",
}

def probe(text):
    content = tok(text, add_special_tokens=False, return_offsets_mapping=True)
    model_input = tok(text, add_special_tokens=True, return_offsets_mapping=True)
    return content, model_input

rows = {}
for name, text in variants.items():
    content, model_input = probe(text)
    rows[name] = content
    content_tokens = tok.convert_ids_to_tokens(content["input_ids"])
    model_tokens = tok.convert_ids_to_tokens(model_input["input_ids"])
    print(f"\n{name!r}: {text!r}")
    print(f"  content ids: {content['input_ids']}")
    print(f"  content tokens: {content_tokens}")
    print(f"  content offsets: {content['offset_mapping']}")
    print(f"  model-input ids: {model_input['input_ids']}")
    print(f"  model-input tokens: {model_tokens}")
    print(f"  model-input offsets: {model_input['offset_mapping']}")

base = rows["single_space"]["input_ids"]
all_equal = all(rows[name]["input_ids"] == base for name in variants)
print(f"\nAll content-id tuples equal single_space? {all_equal}")
for name in variants:
    print(f"  {name}: {rows[name]['input_ids'] == base}")

The script prints the loaded Transformers version, content ids, content tokens, offsets, model-input ids, model-input tokens, and model-input offsets for each variant. It also prints whether every content-id tuple equals the single-space case. Because the script uses the pinned revision, the result is tied to that file. Run it locally and read the printed values rather than assuming an output.

Reading the output

If the pinned tokenizer follows the documented BERT normalizer, the content-id tuples for the five variants should be identical after special tokens are excluded, while the offset spans should differ. For example, the world token in "hello world" may start at an index that reflects two spaces, while in "hello world" it reflects one. Leading spaces may produce no tokens, so the first content token’s start offset can be greater than zero. The model-input sequence adds [CLS] and [SEP] around the content tokens; those are model-input tokens, not content tokens. The diagnostic prints both so you can see the two-token overhead for a single sequence. The script does not assert exact ids because the observation belongs to the pinned tokenizer and your installed runtime.

Content tokens, unknown tokens, and fragmentation

Whitespace collapse does not create unknown tokens. The unknown token is reserved for text that WordPiece cannot map to the vocabulary after normalization. Fragmentation is different: WordPiece may split a word into multiple subword tokens, often marked with ## for non-initial pieces. Whitespace has already disappeared before WordPiece, so it cannot cause fragmentation. If you see [UNK], inspect the characters, case handling, accent stripping, and control-character cleaning for the pinned checkpoint. If you see multiple tokens for one word, that is fragmentation, not an unknown. Keep the distinction when you report token counts: content tokens exclude special tokens; model-input tokens include them. For a single sequence in this BERT family, the model input adds two special tokens, [CLS] and [SEP].

Limitations

This diagnostic covers a small set of ASCII whitespace forms. It does not exhaustively test Unicode spaces such as no-break space, em space, or ideographic space. The pinned normalizer may treat some Unicode space categories differently, and handle_chinese_chars can insert spaces around CJK characters before WordPiece. The offsets are from the fast tokenizer and refer to the original string, but behavior can change if tokenizer.json changes or if you use a different revision. The slow tokenizer can be useful for checking the algorithm, but it does not expose the same offset mapping API. This article does not claim behavior for any other checkpoint or for an LLM. The vocabulary size 30,522 applies to the pinned uncased model, not to unrelated models.

How to re-check

When the pinned file or dependency changes, re-run the diagnostic with the new full commit hash and the new Transformers version. Compare the printed content-id tuples, the offset spans, and the model-input token sequences. If the content ids no longer collapse for the same variants, or if offsets shift in a way that changes alignment, update the conclusions above. You can also inspect the loaded normalizer and pre-tokenizer objects from the fast tokenizer to confirm which normalization is active, but the printed ids and offsets are the operational evidence. Treat any change in tokenizer.json as a change in the contract, even if the model weights are identical.

Whitespace collapse is therefore a normalization property, not a WordPiece property. The tokenizer intentionally discards whitespace as a token and uses it as a separator. If you need the original spacing, keep the original string and use offsets. If you need stable content-token ids, expect whitespace variants to collapse. The test is cheap to run and belongs in the update procedure whenever the pinned tokenizer file or Transformers version moves.

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