BERT Tokenization Explained: WordPiece, Subwords, and What It Means for Evals

How the BERT tokenizer splits text with WordPiece, what ## and special tokens mean, slow vs fast classes, and why token counts break cross-model evals.

BERT Tokenization Explained: WordPiece, Subwords, and What It Means for Evals
Written by TechnoLynx Published on 11 Jul 2026

The BERT tokenizer turns raw text into WordPiece tokens in three steps. It normalises the text (for uncased checkpoints such as bert-base-uncased, that means lowercasing and stripping accents), splits punctuation off, then breaks each remaining word into the longest pieces its vocabulary contains, marking every piece that continues a word with ##. The pieces are wrapped in [CLS] and [SEP] and mapped to integer IDs from a fixed vocabulary. Because the split depends on that particular vocabulary, the same text gives different token counts under different tokenizers.

The BERT paper describes the vocabulary as 30,000 WordPiece tokens. Hugging Face’s BERT configuration defaults the vocabulary size to 30,522. If you need a refresher on tokenization in general, our explainer on how text becomes tokens for generative models covers the wider picture; this page stays with BERT.

How the BERT Tokenizer Splits a Word into Subword Tokens

WordPiece in BERT works one word at a time and greedily. When it tokenizes a single word it uses a longest-match-first strategy, also called maximum matching. Starting from the beginning of the word, it finds the longest prefix that exists in the vocabulary, emits it, and repeats on whatever is left. Everything after the first piece is looked up with the ## prefix, which marks a piece that sits inside a word rather than at its start.

The vocabulary holds word-initial characters and word-internal ## characters as separate entries. The ## marker is the reason you can rebuild word boundaries from a BERT token list, though the Hugging Face course notes this trick only works for BERT-like tokenizers.

Worked Example: “John Johanson’s,” Through an Uncased BERT Tokenizer

The original google-research BERT README walks one phrase through the full pipeline, and it shows each stage cleanly:

Stage Output
Raw input John Johanson's,
Normalisation (uncased: lowercase, strip accents) john johanson's,
Punctuation splitting john johanson ' s ,
WordPiece per whitespace token john johan ##son ' s ,
Special tokens added [CLS] john johan ##son ' s , [SEP]

Read the WordPiece row with longest-match-first in mind: “john” stays whole, while “johanson” splits into the prefix “johan” and the continuation piece ##son. The apostrophe and comma became tokens of their own before WordPiece ever ran, because punctuation is split on both sides first.

Splits are vocabulary-specific, so examples from tutorials (such as “summarize” becoming sum ##mar ##ize in one WordPiece illustration) tell you the shape of the behaviour, not what bert-base-uncased will do with your word. Running the actual tokenizer on the actual string is the only check we would trust. Pre-processing can also work against you: the README warns that input tokenization schemes which split contractions like do n't create a mismatch with how BERT was pre-trained.

What Do ##, [CLS], [SEP], [PAD], [MASK] and [UNK] Mean in BERT?

## is a prefix marking a piece that continues a word rather than starting one. The bracketed names are special tokens: reserved vocabulary entries that carry structure rather than meaning, and which the tokenizer never splits.

Token ID in the BERT vocabulary What it does
[PAD] 0 Fills shorter sequences so a batch stacks into one tensor; masked out by attention_mask
[UNK] 100 Stands in for anything that cannot be converted to a vocabulary ID
[CLS] 101 First token of every sequence; its final hidden state is the aggregate representation used for classification
[SEP] 102 Separates two sentences in one input and closes the sequence
[MASK] 103 Replaces tokens during masked language model pre-training; the model predicts what was there

A BERT input has the form [CLS] X [SEP] for one sequence and [CLS] A [SEP] B [SEP] for a pair. In a pair, token_type_ids are 0 for the [CLS], sentence A and the first [SEP], and 1 for sentence B and its closing [SEP].

[MASK] is used in pre-training but never during fine-tuning or inference. The BERT paper picks 15% of token positions for prediction and replaces a chosen token with [MASK] 80% of the time, a random token 10% of the time and leaves it unchanged 10% of the time. Masking is applied after WordPiece with no special treatment of partial word pieces; the google-research README also describes Whole Word Masking, masking every piece of a word at once.

Loading Bert-Base-Uncased with from_pretrained, and What It Returns

AutoTokenizer is the recommended entry point: it works out which tokenizer class a checkpoint needs and returns an instance of it.

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")

enc = tokenizer("The cat sat on the mat.", "A cat was resting.")
print(enc.keys())   # input_ids, token_type_ids, attention_mask
print(tokenizer.convert_ids_to_tokens(enc["input_ids"]))

batch = tokenizer(["short one", "a somewhat longer sentence"],
                  padding=True, truncation=True, return_tensors="pt")

Calling the tokenizer returns a BatchEncoding. Its input_ids start with [CLS] and end with [SEP] because add_special_tokens=True is the default, token_type_ids mark sentence A and B, and attention_mask is 1 for real tokens. With padding=True, shorter sequences are filled with [PAD] to the longest in the batch and the mask marks those positions 0, so attention ignores them. The README allows sequences of up to 512 tokens and suggests going shorter where you can for memory and speed.

BertTokenizer or BertTokenizerFast?

BertTokenizer is the pure-Python implementation inside Transformers; BertTokenizerFast is backed by the Rust-based Hugging Face Tokenizers library. Both implement BERT’s WordPiece tokenizer.

  BertTokenizer (slow) BertTokenizerFast
Implementation Python Rust Tokenizers library
Algorithm WordPiece WordPiece
Batch speed Slower Significant speed-up, especially batched
Offset mapping, word_ids() Not provided Yes: maps tokens to characters and words
Picked by AutoTokenizer Not by default By default

In Transformers v5 the split is being folded into one file per model, with the Rust backend as the default and the Python implementation kept behind an explicit PythonBackend for custom logic or legacy compatibility. Since both classes run WordPiece, the choice is about speed and alignment features; we would use the fast class unless a pipeline depends on Python-specific behaviour, and confirm on a sample of your own text that the outputs match before switching an existing system.

Aligning Subword Tokens with Word-Level Labels

Offset mapping is what makes the fast tokenizer the practical choice for token classification. Once “Sylvain” becomes several pieces, one word label has to cover several tokens, and the Hugging Face token-classification guide aligns them in a fixed way: map each token back to its word with word_ids(), give [CLS] and [SEP] the label -100 so PyTorch’s cross-entropy loss ignores them, label only the first sub-token of each word, and set the remaining sub-tokens to -100. Special tokens get the offset (0, 0), which is reserved for them.

Why Does BERT Produce [UNK] Tokens?

BERT emits [UNK] when WordPiece reaches a point where no piece in the vocabulary matches, and then the whole word becomes [UNK], not just the unmatched part. The Hugging Face course gives the example of a word where b and ##u exist but ##m does not: the result is ["[UNK]"], never ["b", "##u", "[UNK]"]. That whole-word behaviour is a real difference from BPE, which marks only the individual unknown characters.

[UNK] is rare in well-designed tokenizers with character-level coverage, which can fall back to encoding a word character by character. It shows up for characters outside that coverage (a rare CJK character in a tokenizer trained mostly on English, for instance), for encoding errors, unusual Unicode sequences or control characters, and for vocabularies built from a domain that lacked certain tokens. BPE as implemented in OpenAI’s tiktoken is reversible and works on arbitrary text, including text absent from its training data.

The cost is total when it happens: every word mapped to [UNK] gets the same embedding, so the model cannot tell them apart. A rising [UNK] rate is worth tracking in production as a sign the input distribution has moved.

WordPiece Versus BPE: Likelihood Against Frequency

WordPiece and byte-pair encoding are close relatives that both build a vocabulary by merging pairs from the bottom up; they differ in which pair they merge. BPE picks the most frequent symbol pair, while WordPiece picks the pair that most increases the likelihood of the training data. The Hugging Face course states the WordPiece criterion as a score:

score(a, b) = freq(ab) / (freq(a) × freq(b))

Dividing by the frequency of each part favours pairs whose parts are individually rare. The course’s example: ("un", "##able") may not merge quickly even if common, because both halves appear in many words, while ("hu", "##gging") merges faster if “hugging” is frequent.

  WordPiece (BERT) BPE (GPT-style)
Merge criterion Likelihood score above Most frequent pair
What is stored Final vocabulary only Vocabulary and merge rules
Tokenizing a word Greedy longest match against the vocabulary Applies learned merges
Unknown input Whole word becomes [UNK] Only unknown characters; byte-level variants handle any text

One caveat if you plan to train your own: the Hugging Face course notes that its Tokenizers library trains with BPE instead, because the authors are not completely sure of WordPiece’s training internals, so the same corpus would not reproduce the vocabulary exactly.

Why BERT and GPT Token Counts Differ, and What That Changes in Eval Results

Token counts differ because each tokenizer has its own vocabulary, so the same string becomes a different number of pieces. Petrov et al. (2023) found the same text translated into different languages can differ in tokenized length by up to 15 times, and the disparity held across all 17 tokenizers they evaluated. Language moves the ratio too: a textkit.tech measurement put English prose at about 1.17 tokens per word on GPT-5’s encoding and German at 1.71. We go further into average tokens per word and what tokenisation ratios do to inference cost and into GPT token counts elsewhere.

For reading evaluation results, three consequences follow.

  • Per-token metrics are not portable. Hugging Face’s own documentation says tokenization has a direct impact on perplexity, which should always be taken into account when comparing models, and adds that perplexity is not well defined for masked language models like BERT at all.
  • Context limits bite at different places. BERT’s 512-token window holds a different amount of text than another model’s window, so the same document can be truncated for one model and seen whole by another.
  • Cost and latency figures inherit the tokenizer. Petrov et al. tie the longer tokenizations some languages receive to higher cost, processing time and latency, and less content fitting in context.

None of this says a BERT-based system is better or worse than a GPT-style generative AI system. It says a number computed over tokens only means something next to numbers computed over the same tokens, by the same tokenizer. When a leaderboard places an encoder and a decoder side by side, the first question we would ask is what unit each score was averaged over, because the tokenizer is part of the model and the result changes when you change either one.