AI Logic

Tokenization

WordPiece

Updated:

WordPiece procedure. The left side shows training: the Japanese words 機械学習, 機械, 深層, 学ぶ, and を are split into characters (with ## from the second character onward), and the pairs with the highest score are merged five times to build the vocabulary. The right side shows application: the new Japanese sentence 深層学習を学ぶ ("learn deep learning") is split into words, and 深層学習 is cut out from the vocabulary by longest match into 深層 and ##学習

What Is WordPiece?

WordPiece is a tokenization method that starts from characters, builds a vocabulary by merging, one at a time, the symbol pair that most increases the likelihood of a language model on the training data, and splits text into subwords (parts of words) from that vocabulary. It was created in 2012 by Schuster and Nakajima for Google's Japanese and Korean voice search. It later became widely known through its use in Google's machine translation (GNMT, 2016) and BERT (2018).

Japanese and Korean text has no spaces between words, which makes it hard to compile a fixed word list. Relying on a word list inevitably produces words not on the list (unknown words). On the other hand, handling text character by character makes the search in speech recognition heavy, because a single Japanese character has too many possible readings. WordPiece solved this problem by learning "frequently used units" from data alone, so that any character sequence can be represented as a combination of vocabulary symbols.

The idea is very similar to BPE. Both start from characters and merge symbol pairs one at a time. There are two differences.

  • How the pair to merge is chosen: BPE chooses the most frequent pair, while WordPiece chooses the pair that most increases the language model's likelihood.
  • How new text is split: BPE applies the learned merges in the same order, while BERT's WordPiece cuts out, from the beginning, the longest symbol in the finished vocabulary that matches.

Building the Vocabulary

The procedure in the original paper (Section 3 of Schuster and Nakajima) is as follows.

  1. Initialize the vocabulary with the basic characters.
    • For Japanese, the original paper starts with about 22,000 characters, covering kanji, hiragana, katakana, and ASCII (about 11,000 for Korean).
  2. Segment the training data with this vocabulary and build a language model.
  3. Among the candidate new symbols formed by combining two symbols in the current vocabulary, choose the one that most increases the likelihood of the training data when added to the vocabulary, and add it.
  4. Repeat steps 2–3 until the vocabulary reaches the chosen size or the likelihood gain falls below a chosen threshold.

Rebuilding the language model for every candidate costs O(K2)O(K^2) per round (KK is the current vocabulary size). The original paper builds a 200,000-word vocabulary in a few hours on a single machine with techniques such as testing only pairs that actually occur in the training data, merging pairs that do not affect one another in a batch, and recounting only the affected counts.

Which Pairs Increase the Likelihood?

Choosing by language-model likelihood tends to select pairs that are strongly associated with each other, not merely frequent pairs. For example, the Japanese characters を (an object particle) and 学 ("learn") both occur often, so they also happen to be adjacent many times. Merging them into one symbol does little to improve the explanation of the text's probability. Conversely, if 学 is almost always followed by 習, making 学習 (gakushū, "learning") a single symbol explains the text much better with far fewer symbols.

Google has not released its WordPiece training program. Hugging Face's explanation presents, as an approximation of the likelihood gain, the approach of merging the pair that maximizes the following score.

score(a,b)=count of pair ab(count of symbol a)×(count of symbol b)\mathrm{score}(a, b) = \frac{\text{count of pair } ab}{(\text{count of symbol } a) \times (\text{count of symbol } b)}

The denominator discounts for how frequent each symbol already is, so "pairs that often occur together" are chosen over "pairs of frequent symbols that happen to be adjacent."

Example: Five Merges on a Small Training Set

The left side of the figure at the top of the article splits the training data into characters and performs five merges with this score. The training words are Japanese: 機械学習 (kikai gakushū, "machine learning") 4 times, 機械 ("machine") 3 times, 深層 ("deep") 5 times, 学ぶ ("learn") 6 times, and を (object particle) 10 times. The example is kept in Japanese because the counts and scores below were computed from it. As in BERT, symbols from the second character of a word onward are prefixed with ##.

StepPair mergedPair countScore
1##学 + ##習44 ÷ (4 × 4) = 1/4
2深 + ##層55 ÷ (5 × 5) = 1/5
3学 + ##ぶ66 ÷ (6 × 6) = 1/6
4機 + ##械77 ÷ (7 × 7) = 1/7
5機械 + ##学習44 ÷ (7 × 4) = 1/7

In step 1, the most frequent pair is "機 + ##械" (7 times), which BPE would merge first. However, "機" and "##械" each occur 7 times, so the score stays at 1/7. "##学 + ##習" occurs only 4 times, but "##学" and "##習" always occur together, so its score of 1/4 is the highest. In step 4, "機 + ##械" and "##械 + ##学習" are tied at 1/7, and the pair counted first is chosen.

BPE saves "the merge rules and their order," whereas BERT's WordPiece saves only the finished vocabulary. Splitting new text uses only the vocabulary, not the order of merges.

Splitting New Text

BERT's WordPiece first splits text into words on whitespace and punctuation, then splits each word with the following procedure (WordpieceTokenizer in BERT's official implementation).

  1. From the beginning of the word, find and cut out the longest symbol present in the vocabulary.
    • Symbols cut out from the second character of the word onward are looked up in their ##-prefixed form.
  2. Repeat the same on the remaining part.
  3. If some part cannot be found in the vocabulary at any length, the whole word becomes [UNK] (unknown).

The right side of the figure at the top of the article shows how 深層学習 ("deep learning"), which is not in the training data, is split (assume the sentence 深層学習を学ぶ, "learn deep learning," has been split into the words 深層学習 / を / 学ぶ).

  1. Check from the beginning in order of length: neither 深層学習 nor 深層学 is in the vocabulary, but 深層 is.
  2. The remaining 学習 does not start the word, so look up ##学習. It is in the vocabulary, so cut it out.
  3. を and 学ぶ are in the vocabulary as they are.

The result is four subwords: "深層 ##学習 を 学ぶ." A symbol with ## indicates that it "continues the previous symbol," so removing ## and joining it to the previous symbol restores the original word.

Longest match is the same approach as "looking for the longest possible headword first" when consulting a dictionary. Because only the vocabulary is needed to split text, the mechanism is simple and fast.

Marking Word Boundaries

After splitting into subwords, WordPiece marks word boundaries so that the spaces of the original text can be restored. How the marks are placed differs by application.

ApplicationHow marks are placedExample
Voice search (original paper, 2012)Attach _ to the side touching a space. Each unit has four variants—left, right, both, or none—so the vocabulary can grow up to fourfoldSpace positions can be restored even when Japanese (without spaces) is mixed with English words (with spaces)
GNMT (2016)Attach _ only to the beginning of a word_J et _makers _fe ud (Jet makers feud)
BERT (2018)Attach ## to symbols from the second piece of a word onwardplay ##ing (playing)

The GNMT paper states that it changed the marking from both sides of a unit, as in the original paper, to the beginning of a word only. BERT's ## points the other way, marking "a continuation of the previous symbol." In every case, following the marks restores the word boundaries.

Experimental Results

The GNMT paper compares word, character, and WordPiece (WPM) vocabularies on WMT English→French and English→German translation (Tables 4 and 5. WPM uses a vocabulary shared by source and target; BLEU is the average of 8 models).

VocabularyEn→Fr BLEUEn→Fr decoding time per sentence (s)En→De BLEUEn→De decoding time per sentence (s)
Word37.900.222623.120.2972
Character38.011.053022.620.8011
WPM 8K38.270.191923.500.2079
WPM 16K37.600.187424.360.1931
WPM 32K38.950.211824.610.1882

WordPiece achieved higher BLEU than the word vocabulary and translated 4–5 times faster than characters. Characters produce long sequences, which slows down both training and translation. The gap is large for German, which has many inflected forms that a word vocabulary handles poorly; WPM 32K is about 1.5 points higher than words. The paper states that vocabularies of 8K–32K balanced accuracy and speed across a variety of language pairs.

In the original voice search paper, a 200,000-word vocabulary was used, and because unknown words never occur, building the pronunciation dictionary also became simple (about 4% of words have multiple pronunciations).

Practical Caveats

A library named "WordPiece" does not necessarily train the same way as the original paper. Google has not released its training program; for example, the WordPieceTrainer in Hugging Face's tokenizers internally uses a BPE trainer (which chooses pairs by frequency) and prefixes symbols with ##. What clearly characterizes WordPiece is rather its segmentation by longest match against the vocabulary.

  • An unknown character turns the whole word into [UNK]: if even one character cannot be cut out by longest match, BERT's implementation turns the whole word into [UNK]. This differs from methods such as byte-level BPE, which can represent any character by splitting it into bytes.
  • Preprocessing is part of the tokenizer: before WordPiece, BERT's official implementation splits text into words on whitespace and punctuation, and inserts spaces around kanji (CJK unified ideographs) to split them into single characters. As a result, in multilingual BERT the kanji of 深層学習 become single characters, and only runs of hiragana are split by WordPiece. For Japanese, always check which preprocessing a tokenizer is combined with.
  • Use the same tokenizer as the model: when using a pretrained model, use its vocabulary and preprocessing as is. If the vocabulary or preprocessing differs even slightly, the same text becomes a different sequence of IDs.
  • Vocabulary size: BERT uses 30,000 and GNMT uses 8K–32K. A larger vocabulary shortens sequences but enlarges the embedding matrix.

Comparison with Other Tokenization Methods

The table below compares representative subword segmentation methods from the same perspectives.

MethodHow the vocabulary is builtHow new text is splitWhat is savedMain uses
BPEMerge the most frequent pairApply merge rules in the same orderMerge rules (ordered)Machine translation, the original Transformer
WordPiece (this article)Merge the pair that most increases the likelihoodLongest-match lookup in the vocabularyVocabularyBERT and its derivatives
Unigram language modelStarting from a large vocabulary, remove symbols with little effect on the likelihoodChoose the most probable segmentation (can also output multiple segmentations)Vocabulary and symbol probabilitiesAvailable in SentencePiece
Byte-level BPESame as BPE (initial symbols are the 256 byte values)Same as BPEMerge rulesThe GPT family from GPT-2 onward

Rough guidelines for choosing:

  • Using or further training a BERT-family model: use that model's WordPiece vocabulary as is.
  • Building a vocabulary from scratch: since WordPiece training differs by implementation, choosing BPE or the Unigram language model, whose procedures are well defined, makes the results easier to explain.
  • Never wanting unknown characters: use byte-level BPE.

PyTorch example

Show code
python
# 1) A minimal longest-match segmenter (same idea as BERT's WordpieceTokenizer)
def wordpiece_tokenize(word, vocab, unk="[UNK]", max_chars=200):
    if len(word) > max_chars:
        return [unk]
    pieces, start = [], 0
    while start < len(word):
        end, piece = len(word), None
        while start < end:  # check the vocabulary from the longest candidate down
            sub = word[start:end]
            if start > 0:
                sub = "##" + sub  # from the second character onward, look up with ##
            if sub in vocab:
                piece = sub
                break
            end -= 1
        if piece is None:  # if any part cannot be matched, the whole word becomes [UNK]
            return [unk]
        pieces.append(piece)
        start = end
    return pieces


# Vocabulary built in the article's figure (Japanese example: characters + symbols from 5 merges)
vocab = {"機", "##械", "##学", "##習", "深", "##層", "学", "##ぶ", "を",
         "##学習", "深層", "学ぶ", "機械", "機械学習"}
for w in ["深層学習", "を", "学ぶ"]:
    print(w, wordpiece_tokenize(w, vocab))
# 深層学習 ['深層', '##学習'] / を ['を'] / 学ぶ ['学ぶ']


# 2) Learn a WordPiece vocabulary with Hugging Face tokenizers
from tokenizers import Tokenizer, decoders, models, normalizers, pre_tokenizers, trainers

tokenizer = Tokenizer(models.WordPiece(unk_token="[UNK]"))
tokenizer.normalizer = normalizers.NFKC()
tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()  # split into words on whitespace and punctuation
tokenizer.decoder = decoders.WordPiece(prefix="##")    # remove ## and join to the previous piece
trainer = trainers.WordPieceTrainer(
    vocab_size=8000,
    special_tokens=["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"],
    continuing_subword_prefix="##",
)
# Note: internally this trainer merges the "most frequent pairs," just like BPE
texts = ["深層学習 を 学ぶ", "機械学習 の 基本"]  # in practice, pass a large amount of text
tokenizer.train_from_iterator(texts, trainer=trainer)
enc = tokenizer.encode("深層学習 を 学ぶ")
print(enc.tokens, enc.ids)


# 3) Use a pretrained BERT tokenizer and feed the IDs into a PyTorch embedding layer
import torch
import torch.nn as nn
from transformers import AutoTokenizer

bert_tok = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
batch = bert_tok(["深層学習を学ぶ"], return_tensors="pt")  # kanji are split into single characters by preprocessing
print(bert_tok.convert_ids_to_tokens(batch["input_ids"][0]))  # [CLS] is added at the start and [SEP] at the end

embed = nn.Embedding(bert_tok.vocab_size, 768)
x = embed(batch["input_ids"])  # (1, sequence length, 768)

FAQ

Q. How do WordPiece and BPE differ?
A.

They differ in how the vocabulary is built and how new text is split. BPE merges the most frequent pair and, when splitting, applies the merge rules in the same order. WordPiece merges the pair that most increases the language model's likelihood, and in BERT's implementation, splitting cuts out symbols from the vocabulary by longest match. Because it chooses by likelihood, pairs that always occur together are merged before pairs of frequent symbols that happen to be adjacent.

Q. What does `##` mean?
A.

It indicates that the symbol starts in the middle of a word and continues the previous symbol. For example, play ##ing turns back into playing when ## is removed and the piece is joined to the previous one. Word-initial and word-internal symbols enter the vocabulary as different symbols, so even the same "ing" can be distinguished at the start and in the middle of a word.

Q. What happens when Japanese text is split with BERT's WordPiece?
A.

It depends on the preprocessing. For example, the official implementation of multilingual BERT inserts spaces around kanji before splitting, so kanji become single characters, and only runs of hiragana or katakana are split by WordPiece. Preprocessing differs from model to model, so use the tokenizer distributed with the model.

References

  1. M. Schuster and K. Nakajima, "Japanese and Korean Voice Search," IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), pp. 5149–5152, 2012.
  2. Y. Wu, M. Schuster, Z. Chen, Q. V. Le, M. Norouzi, et al., "Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation," arXiv:1609.08144, 2016.
  3. J. Devlin, M.-W. Chang, K. Lee, and K. Toutanova, "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding," NAACL-HLT, 2019.
  4. google-research/bert, tokenization.py (implementation of WordpieceTokenizer and BasicTokenizer)
  5. Hugging Face, "WordPiece tokenization," LLM Course, Chapter 6.
  6. T. Kudo, "Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates," ACL, 2018.