Comparing BertTokenizer and BertTokenizerFast on the same fixture
Load both implementations at the same revision, compare token ids, and explain why offset APIs need the fast implementation
Comparing BertTokenizer and BertTokenizerFast on the same fixture means fixing every input except the implementation. Pin the model revision, pin Transformers 4.56.2, and feed both tokenizer classes the same string and encoding options. On google-bert/bert-base-uncased@86b5e0934494bd15c9632b12f734a8a67f723594, the useful diagnostic is not whether one class is generally better. It is whether the two implementations produce the same model-input token ids for a controlled fixture, and which output fields each can actually return. The fast wrapper can expose character offsets; the slow Python implementation cannot. That distinction is the reason to choose BertTokenizerFast when you need to align tokens to source text.
Verified: 2026-10-05. The statements here apply to google-bert/bert-base-uncased at revision 86b5e0934494bd15c9632b12f734a8a67f723594 with transformers==4.56.2. The pinned English uncased vocabulary has 30,522 entries. The same diagnostic shape applies to google-bert/bert-base-multilingual-cased@3f076fdb1ab68d5b2880cb87a0886f315b8146f8, but that checkpoint’s pinned vocabulary has 119,547 entries and different normalization; do not reuse token counts from one checkpoint for the other. The code below does not assert a universal result. It checks the fixture you run locally.
The controlled comparison
The fixture should include ordinary words, punctuation, a word that WordPiece splits into multiple known subwords, and, if you want, a character sequence that becomes the unknown token. The comparison then asks two questions. First: do input_ids match between BertTokenizer and BertTokenizerFast when both load the same revision? Second: can the tokenizer give you per-token spans into the original text?
# Requires transformers==4.56.2
import transformers
from transformers import AutoTokenizer
MODEL = "google-bert/bert-base-uncased"
FULL_COMMIT = "86b5e0934494bd15c9632b12f734a8a67f723594"
FIXTURE = "The quick brown fox jumps over the lazy dog. Tokenization isn't always one token: 42, naïve café, and [MASK]."
print("transformers:", transformers.__version__)
fast = AutoTokenizer.from_pretrained(MODEL, revision=FULL_COMMIT, use_fast=True)
slow = AutoTokenizer.from_pretrained(MODEL, revision=FULL_COMMIT, use_fast=False)
enc_fast = fast(
FIXTURE,
return_offsets_mapping=True,
return_special_tokens_mask=True,
)
enc_slow = slow(FIXTURE, return_special_tokens_mask=True)
print("fast class:", type(fast).__name__)
print("slow class:", type(slow).__name__)
print("fast input_ids:", enc_fast["input_ids"])
print("slow input_ids:", enc_slow["input_ids"])
print("input_ids equal:", enc_fast["input_ids"] == enc_slow["input_ids"])
if enc_fast["input_ids"] != enc_slow["input_ids"]:
fast_tokens = fast.convert_ids_to_tokens(enc_fast["input_ids"])
slow_tokens = slow.convert_ids_to_tokens(enc_slow["input_ids"])
for i, (ft, st, fi, si) in enumerate(zip(fast_tokens, slow_tokens, enc_fast["input_ids"], enc_slow["input_ids"])):
if fi != si:
print("first id mismatch", i, ft, fi, st, si)
break
raise SystemExit("id mismatch requires inspection")
print("tokens:", fast.convert_ids_to_tokens(enc_fast["input_ids"]))
print("special_tokens_mask:", enc_fast["special_tokens_mask"])
print("offset_mapping:", enc_fast["offset_mapping"])
special_spans = [
enc_fast["offset_mapping"][i]
for i, is_special in enumerate(enc_fast["special_tokens_mask"])
if is_special
]
print("special-token spans:", special_spans)
try:
slow(FIXTURE, return_offsets_mapping=True)
except Exception as exc:
print("slow offset_mapping failure:", type(exc).__name__, str(exc))
When you run this, the class names should identify the fast and slow implementations. The input_ids comparison is the core equality check. If they are equal, the pinned vocabulary and normalization are behaving consistently on this fixture. If they differ, the loop prints the first mismatching id and both tokens, which is the useful debugging signal. Do not treat a single equal fixture as a proof for all Unicode inputs; it is a regression check with a known scope.
What the output means
The input_ids list is the model-input sequence. By default, BERT tokenization adds [CLS] at the start and [SEP] at the end. Those are model-input tokens, not content tokens from your text. The special_tokens_mask separates them: positions marked 1 are special tokens added by the tokenizer; positions marked 0 correspond to content tokens. If you want to count content tokens, do not compare the raw len(input_ids) to the number of words in the fixture without subtracting those special positions.
The token list also shows fragmentation. WordPiece starts from the beginning of a word and uses ## for continuation pieces. A word such as “tokenization” may become token and ##ization; both are known vocabulary entries. That is fragmentation, not an unknown token. The unknown token is [UNK], which appears when the normalized text cannot be covered by WordPiece pieces under the pinned vocabulary. Unknown and fragmented are different failure modes: [UNK] loses surface information, while fragmentation preserves it across multiple known token ids. The fast tokenizer’s offset_mapping lets you see which original character span produced each token, including fragmented pieces and any [UNK] token.
The reason to require BertTokenizerFast is in that last field. In Transformers v4.56.2, return_offsets_mapping is a fast-tokenizer feature. BertTokenizer returns input_ids, token_type_ids, and attention masks, but it does not provide offset_mapping. The try block in the diagnostic demonstrates that directly: the slow tokenizer raises an exception for that request, and the script prints the error class. The fast wrapper also exposes alignment helpers such as word_ids, token_to_chars, and char_to_token through the fast tokenizer API. Those helpers depend on the same offset machinery. If your downstream task must map a predicted entity, a redaction span, or a highlighting range back to the original fixture string, the slow tokenizer is not sufficient without an external alignment layer.
Limitations and scope
This comparison is deliberately narrow. It uses one fixture, one model revision, and one Transformers version. The assertion checks id equality for that fixture. It does not prove that every possible string will tokenize identically across the two implementations, and it does not measure speed. Both implementations can still differ in behavior for edge cases outside the fixture, especially around Unicode normalization, added tokens, custom padding, or truncation side effects. The fast tokenizer’s offsets are also tied to the tokenizer’s normalization. For uncased BERT, lowercasing and accent stripping can mean that a token span refers to the original characters that produced the normalized piece, not to a slice that is already normalized. Always inspect offset_mapping for the exact add_special_tokens, padding, and truncation options you will use in production.
For multilingual cased BERT, the same diagnostic procedure applies, but the pinned vocabulary is 119,547 entries and the normalization is cased rather than uncased. The English uncased vocabulary size of 30,522 does not apply there. More generally, do not carry token counts from this article into an unrelated LLM or a different checkpoint.
How to re-check
When the pinned revision, tokenizer.json, or Transformers version changes, treat this as a new comparison. Record the new full commit and transformers.__version__, rerun the script, and check three things in order: the class names, the input_ids equality assertion, and the slow tokenizer’s offset-mapping failure. If the ids diverge, inspect the first mismatch printed by the loop and compare the paired tokens. If the slow tokenizer unexpectedly accepts return_offsets_mapping, confirm the method’s documented support for that version before relying on it. If the fast tokenizer’s offsets look wrong, print fast.convert_ids_to_tokens(enc_fast["input_ids"]) beside enc_fast["offset_mapping"] and verify the spans against the fixture manually. Verified: 2026-10-05. That date applies only to the model/revision and Transformers version named above; a later dependency change means you should re-run the diagnostic rather than assume the old observation still holds.
Sources
- google-bert/bert-base-uncased tokenizer.json at 86b5e093
Pinned WordPiece vocabulary and normalization settings for the English uncased model.
- Hugging Face Transformers v4.56.2 tokenizer API
Versioned reference for encoding options, output fields, and fast-tokenizer alignment methods.
- Transformers v4.56.2 BertTokenizerFast source
Versioned implementation of the BERT fast-tokenizer wrapper.
- Transformers v4.56.2 BertTokenizer source
Versioned Python implementation of BERT basic and WordPiece tokenization.
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.