WordPiece Tokenization with Code Examples
How the WordPiece tokenizer splits words into subword pieces, with Python code, training and decoding examples, BPE comparison and round-trip caveats.
WordPiece is a subword tokenization method used by BERT and many models derived from it. It splits text into pieces drawn from a fixed vocabulary. A piece that continues a word, rather than starting one, is marked with a leading "##". This review explains what the method does to your text, shows working code for encoding, pretrained use and training, compares it with related tokenizers, and covers what is lost when token output is turned back into text.
Short verdict: when WordPiece fits
WordPiece suits one main job: preparing text for a model that was trained with a WordPiece vocabulary. In that case it is not optional. You must use that model's own tokenizer and vocabulary, or the token IDs will not mean what the model expects. Its main benefit is a compact vocabulary that still covers rare and novel words by breaking them into known parts. The decisive tradeoff is that the token sequence is a model input, not a faithful copy of your text. Depending on configuration, case, accents, spacing and unknown characters can be lost.
- Good fit: feeding text to BERT-family models, or building a classifier or encoder on top of one.
- Good fit: counting tokens to stay within a WordPiece model's input length limit.
- Poor fit: any workflow that needs an exact round trip back to the original string.
- Poor fit: a new tokenizer for open-ended text with many symbols or emoji, where byte-level schemes avoid unknown tokens entirely.
- Keep plain text instead: for storage, display, search indexes meant for people, logs, accessibility, and anything a reader will copy or edit.
What WordPiece actually changes
WordPiece does not edit your stored text. It produces a separate representation: a list of vocabulary strings and their integer IDs. It also does not reverse, mirror or restyle characters. Reversal swaps character order, mirrored text imitates flipped glyphs, and Unicode "font" generators substitute look-alike code points; all of those change the characters a reader sees. When people talk about "reversing" a tokenizer, they almost always mean decoding: turning token IDs back into a readable string.
In practice, WordPiece runs as one stage in a pipeline, and most surprises come from the stages around it. Normalization comes first. For uncased BERT models this lowercases text, decomposes accented letters and strips the accent marks, and removes control characters. Pre-tokenization then splits on whitespace and punctuation. Next, the WordPiece model splits each resulting word into vocabulary pieces. Post-processing adds special tokens such as [CLS] and [SEP]. Cased models skip the lowercasing and accent stripping.
The encoding algorithm in plain Python
Encoding uses greedy longest-match-first. Starting at the beginning of a word, it takes the longest substring found in the vocabulary, then repeats from where that match ended, adding "##" to every non-initial candidate. The sketch below follows the logic of the reference BERT implementation and uses a small toy vocabulary so that every result can be checked by hand.
def wordpiece_tokenize(word, vocab, unk_token='[UNK]', max_chars=100):
if len(word) > max_chars:
return [unk_token]
tokens = []
start = 0
while start < len(word):
end = len(word)
piece = None
while start < end:
candidate = word[start:end]
if start > 0:
candidate = '##' + candidate
if candidate in vocab:
piece = candidate
break
end -= 1
if piece is None:
return [unk_token]
tokens.append(piece)
start = end
return tokens
vocab = {'[UNK]', 'play', '##ing', '##ed', 'un', '##play', '##able',
'token', '##ization', '##ize'}
print(wordpiece_tokenize('playing', vocab)) # ['play', '##ing']
print(wordpiece_tokenize('unplayable', vocab)) # ['un', '##play', '##able']
print(wordpiece_tokenize('tokenization', vocab)) # ['token', '##ization']
print(wordpiece_tokenize('playz', vocab)) # ['[UNK]']
The last example shows the behavior that matters most. The word starts with a valid piece, "play", but no vocabulary entry matches the remaining "z". As a result, the whole word becomes [UNK], not just the unmatched part. The reference implementation also maps any word longer than a set character limit (100 by default) to [UNK]. Note that Python's len and slicing count code points, not visible characters. This matters for the Unicode cases covered below.
Using a pretrained WordPiece tokenizer
For real work, load the tokenizer that ships with the model. With the Hugging Face transformers library, the same object handles normalization, splitting, special tokens and decoding. Fast tokenizers can also return character offsets, which link each token back to a span of the original text.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained('bert-base-uncased')
text = 'Tokenization isn\'t magic, café owners.'
print(tok.tokenize(text))
enc = tok(text, return_offsets_mapping=True)
print(enc['input_ids'])
print(enc['offset_mapping'])
print(tok.decode(enc['input_ids'], skip_special_tokens=True))
The output of this snippet is not reproduced here because it was not run for this article, and exact splits depend on the vocabulary file. When you run it, check three things. Does the decoded string still contain uppercase letters and the accent in "café"? An uncased model is expected to drop both. How is the apostrophe in "isn't" spaced after decoding? Do the offsets point back to the spans you expect in the original string?
Training a WordPiece vocabulary
Training builds the vocabulary that encoding later uses. BPE merges the most frequent adjacent pair. WordPiece instead is usually described as merging the pair with the highest score, where the score is the pair's frequency divided by the product of its parts' frequencies. This favors pairs whose parts rarely appear apart. Google did not publish a full implementation of its original training procedure, so open-source trainers are reconstructions. Vocabularies trained with different libraries on the same corpus may not match exactly.
from tokenizers import Tokenizer, models, normalizers, pre_tokenizers, trainers, decoders
tokenizer = Tokenizer(models.WordPiece(unk_token='[UNK]'))
tokenizer.normalizer = normalizers.BertNormalizer(lowercase=True)
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
tokenizer.decoder = decoders.WordPiece(prefix='##')
trainer = trainers.WordPieceTrainer(
vocab_size=8000, # example value; tune for your corpus
special_tokens=['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]'],
)
tokenizer.train(['corpus.txt'], trainer)
enc = tokenizer.encode('Unplayable levels')
print(enc.tokens)
print(tokenizer.decode(enc.ids))
How WordPiece differs from BPE and Unigram
| Aspect | WordPiece | BPE | Unigram (SentencePiece) |
| Building the vocabulary | Merges pairs by a score that favors parts that rarely appear apart | Merges the most frequent adjacent pair | Starts with many candidates and prunes those that contribute least to corpus likelihood |
| Splitting new text | Greedy longest match from the left, word by word | Replays learned merges in order | Chooses the most probable segmentation |
| Marking word boundaries | "##" prefix on word-continuing pieces | Varies; byte-level variants mark a leading space | "▁" symbol stands in for a preceding space |
| Unknown input | An entire word can become [UNK] | Byte-level variants have no unknowns | Configurable; byte fallback in some setups |
| Typical models | BERT and its derivatives | GPT-2-style models | Models built with SentencePiece, such as T5 |
Boundary marking affects how well text can be restored. WordPiece marks continuation and relies on its pre-tokenizer to have split on whitespace, so the original spacing is not stored. SentencePiece-style schemes encode the space itself as a symbol, which lets them restore spacing more faithfully.
Will the text survive decoding, copying and sharing?
Decoding joins "##" pieces back onto the preceding token and puts spaces between the rest. That gives a readable approximation, but not always the original string. Typical losses are listed below; which ones apply depends on the model's configuration.
- Case and accents: uncased models lowercase text and strip combining accent marks, so "Café" decodes as "cafe".
- Whitespace: runs of spaces, tabs and line breaks are not preserved as typed.
- Punctuation spacing: punctuation is split off as separate tokens, and decoders rely on cleanup rules that may not restore the original spacing.
- Unknown words: any word mapped to [UNK] cannot be recovered from the IDs.
- Truncation: text beyond the model's maximum sequence length is gone unless you handle overflow explicitly.
Unicode input needs particular care. Because splitting works on code points, a letter followed by a combining mark is two units unless normalization composes or removes the mark. Emoji built from several code points, such as sequences joined with a zero-width joiner, can be broken apart. The reference BERT cleaning step treats format characters like the joiner as control characters and drops them, so the original sequence may not survive. Styled "font" letters, such as mathematical bold, are separate code points that canonical decomposition does not fold to plain letters, so they are likely to become [UNK] in a vocabulary built from ordinary text. None of these cases were tested for this article. Run your own samples through the exact tokenizer you plan to deploy.
Token strings such as "un ##play ##able" are meant for models, not readers. Do not show them in interfaces, paste them into documents, or index them for human search. How assistive technology announces symbols like "##" depends on the screen reader and its punctuation settings, and that was not tested here. Whenever people will read, edit, copy or search text, keep the original plain text and treat tokens as derived data. If you need to map model results back to the source, such as highlighting an entity, use character offsets into the original string rather than decoded output.
Gaps in this review
The toy-vocabulary outputs above follow directly from the code and can be checked by hand. No pretrained tokenizer was run, so no real-vocabulary splits, token counts or decoded strings are reported. Behavior can also differ between library versions and between cased and uncased vocabularies. No measurements of speed, vocabulary quality or downstream accuracy were available. Confirm any of these for your own model and data before relying on them.