AI Logic

Tokenization

Unigram Language Model

Updated:

Unigram language model procedure. The left side shows training: a large seed vocabulary is built from small Japanese training data, probabilities are estimated with EM, and symbols whose removal barely lowers the likelihood (such as 習の and 化学) are pruned. The right side shows application: the probabilities of candidate segmentations of the new Japanese sentence 深層学習を学ぶ ("learn deep learning") are compared, and the most probable one, 深層 / 学習 / を / 学ぶ, is chosen

What Is the Unigram Language Model?

Segmentation with a Unigram language model is a tokenization method that computes the probability of text by assuming each subword occurs independently, and splits the text into subwords so that this probability is maximized. It was proposed by Kudo in 2018 together with "subword regularization," which deliberately varies the segmentation during training. It is one of the two methods available in SentencePiece.

Even with the same vocabulary, a single piece of text can be segmented in many ways. For example, if the vocabulary contains the Japanese symbols 深層 (shinsō, "deep"), 学習 (gakushū, "learning"), and the single characters 深, 層, 学, and 習, then 深層学習 ("deep learning") can be split as "深層 / 学習" or as "深 / 層 / 学習." BPE and WordPiece settle on a single segmentation through a fixed procedure, so they cannot tell how plausible other segmentations are.

The Unigram language model assigns a probability to each segmentation. This makes two things possible.

  • Choosing the most plausible segmentation: the segmentation with the highest probability can be found efficiently.
  • Sampling various segmentations according to their probabilities: showing a different segmentation each time during training helps the model learn how words are composed and makes it robust to segmentation variation and noise (subword regularization).

The way the vocabulary is built is also the opposite of BPE. BPE starts from characters and adds symbols, whereas the Unigram language model starts from a large vocabulary and removes unnecessary symbols.

Computing the Probability of Text

Let VV be the vocabulary and p(x)p(x) the probability that symbol xx occurs (summing to 1 over the vocabulary). The probability of a subword sequence x=(x1,…,xM)\mathbf{x} = (x_1, \ldots, x_M) is the product of the probabilities, assuming each symbol occurs independently (Eq. 6 in the paper).

P(x)=∏i=1Mp(xi),xi∈V,∑x∈Vp(x)=1P(\mathbf{x}) = \prod_{i=1}^{M} p(x_i), \qquad x_i \in V, \quad \sum_{x \in V} p(x) = 1

If S(X)S(X) is the set of candidate segmentations of text XX, the most plausible segmentation is the one with the highest probability (Eq. 7).

x∗=arg maxx∈S(X)P(x)\mathbf{x}^{*} = \mathop{\mathrm{arg\,max}}_{\mathbf{x} \in S(X)} P(\mathbf{x})

The number of candidate segmentations grows rapidly with the length of the text, but x∗\mathbf{x}^{*} can be found with the Viterbi algorithm (dynamic programming) in time proportional to the text length. It suffices to move forward one character at a time from the beginning and remember only "the best segmentation so far."

The right side of the figure at the top of the article shows the example of the Japanese sentence 深層学習を学ぶ (shinsō gakushū o manabu, "learn deep learning"). The example is kept in Japanese because its probabilities were computed from Japanese training data. There are 8 segmentations that can be built from symbols in the vocabulary, and the log probability log⁡P(x)\log P(\mathbf{x}) is highest for "深層 / 学習 / を / 学ぶ" ("deep / learning / [object particle] / learn") at −8.23. Segmentations that use low-probability single-character symbols, such as "深層 / 学 / 習 / を / 学ぶ" (−18.53), have lower probabilities.

Maximizing the product of probabilities is equivalent to treating −log⁡p(x)-\log p(x) as the "length" of a symbol and minimizing the total length of the text. The paper explains that while BPE is compression that "represents text with fewer symbols," the Unigram language model corresponds to compression that "represents text with fewer bits" (entropy coding).

Building the Vocabulary

If the vocabulary VV is fixed, the probability p(x)p(x) of each symbol can be obtained by maximizing the following marginal likelihood L\mathcal{L} with the EM algorithm (X(s)X^{(s)} is the ss-th sentence of the training data). Because the segmentation is unknown (hidden), the probabilities of all segmentations are summed.

L=∑s=1∣D∣log⁡P(X(s))=∑s=1∣D∣log⁡(∑x∈S(X(s))P(x))\mathcal{L} = \sum_{s=1}^{|D|} \log P(X^{(s)}) = \sum_{s=1}^{|D|} \log \Bigl( \sum_{\mathbf{x} \in S(X^{(s)})} P(\mathbf{x}) \Bigr)

In practice, however, the vocabulary itself is not fixed either. Optimizing the vocabulary and the probabilities jointly is difficult, so the paper narrows down the vocabulary with the following procedure (Section 3.2).

  1. Build a sufficiently large seed vocabulary from the training data.
    • Collect all characters and frequent substrings (the paper enumerates them with an enhanced suffix array). Substrings that cross word boundaries are not used.
  2. Repeat the following until the vocabulary reaches the chosen size.
    1. Fix the vocabulary and estimate p(x)p(x) with the EM algorithm.
    2. For each symbol xix_i, compute how much the likelihood L\mathcal{L} would drop if that symbol were removed from the vocabulary (lossi\mathrm{loss}_i).
    3. Sort by lossi\mathrm{loss}_i in descending order and keep the top η\eta% (80% in the paper's example). Single-character symbols are always kept.

Because single-character symbols are always kept, any text made up only of characters found in the training data can be segmented. The resulting vocabulary mixes characters, subwords, and words, and character-by-character segmentation is also among the candidates.

Example: Pruning on a Small Training Set

The left side of the figure at the top of the article actually computes this procedure on 8 kinds of Japanese sentences (機械学習を学ぶ "learn machine learning," 深層強化学習 "deep reinforcement learning," and so on). The seed vocabulary consists of all 18 characters and the 12 two-character sequences that occur three or more times. Here, the probability of a removed symbol is redistributed to the remaining symbols to compute lossi=L(V)−L(V∖{xi})\mathrm{loss}_i = \mathcal{L}(V) - \mathcal{L}(V \setminus \{x_i\}), and the top half is kept.

SymbolLoss in round 1Result
学習 ("learning")85.1Kept
深層 ("deep")68.6Kept
機械 ("machine")54.1Kept
学ぶ ("learn")51.0Kept
強化 ("reinforcement")39.8Kept
基本 ("basics")31.8Kept
習の, 習を, の基, を学, 械学, 化学0.0Removed

"化学" (which happens to mean "chemistry") appears three times inside "深層強化学習," but splitting it as "強化 / 学習" explains the training data as a whole better, so EM drives its probability to nearly 0 and removing it does not lower the likelihood. In this way, substrings that are frequent but can be explained by combinations of other symbols are pruned.

Varying the Segmentation: Subword Regularization

Subword regularization is a method that, when training a model such as a machine translation model, resamples one segmentation of the text according to P(x∣X)P(\mathbf{x} \mid X) every time the parameters are updated. Because the same text is fed in as a different sequence of symbols each time, it acts like data augmentation. The model architecture stays the same; only the way the input is built changes.

There are two ways to sample a segmentation (Section 3.3).

  • Sample from the top ll: compute the ll most probable segmentations and sample one from the following distribution.
P(xi∣X)≅P(xi)α∑j=1lP(xj)αP(\mathbf{x}_i \mid X) \cong \frac{P(\mathbf{x}_i)^{\alpha}}{\sum_{j=1}^{l} P(\mathbf{x}_j)^{\alpha}}
  • Sample from all segmentations (l=∞l = \infty): arrange the candidate segmentations in a lattice and sample exactly from all segmentations using forward-filtering backward-sampling (FFBS), which computes probabilities forward and then selects symbols backward.

α\alpha controls the smoothness of the distribution. The smaller α\alpha is, the more evenly all segmentations are chosen; the larger it is, the more often the most probable segmentation is chosen. At translation time (inference), either the single most probable segmentation is used (one-best), or the top nn segmentations are translated and the best result is chosen (n-best).

Another method that varies the segmentation in the same way is BPE-dropout, which randomly skips BPE merges during training only. Because the Unigram language model holds the segmentation probabilities themselves, it can vary segmentations naturally in line with the language model.

Experimental Results

The paper compares BPE and the Unigram language model (with and without subword regularization) using the GNMT (Google's machine translation) implementation (part of Table 3; BLEU, one-best translation. The values with subword regularization are those the paper shows to differ significantly from BPE).

DataDirectionBPEUnigram (no regularization, l=1l=1)With regularization (l=64, α=0.1l=64,\ \alpha=0.1)
IWSLT15En→Vi25.6125.4927.68
IWSLT15En→Zh16.7016.9019.36
KFTTEn→Ja27.8528.9230.37
KFTTJa→En21.3721.4622.33
ASPECEn→Ja40.6240.6641.24
WMT14En→De24.5324.5025.04
WMT14En→Cs25.2525.5425.41

Three findings emerged.

  • Without regularization, results are nearly the same as BPE: both are based on the idea of data compression, so as long as only a single segmentation is used, there is no large difference in accuracy.
  • Subword regularization adds 1–2 points: scores rose for every pair except En→Cs, with larger gains on the smaller datasets IWSLT and KFTT.
  • The gap widens on out-of-domain data: evaluated on in-house data such as web text, patents, and search queries, scores rose by about 2 points on every dataset (Table 4).

As for the regularization hyperparameters, setting α=0\alpha = 0 (ignoring probabilities and sampling uniformly) reduced accuracy, especially with l=∞l = \infty. The paper states that l=64l = 64 is the safer choice for languages with abundant data.

Practical Caveats

Vary the segmentation only during training. At inference, the basic approach is to use the most probable segmentation (one-best). In the paper, for some language pairs, using n-best translation with a model trained without subword regularization actually lowered BLEU. A model that never saw perturbed inputs during training gets confused by multiple segmentations.

  • Do not make α\alpha too small: if α\alpha is very small, even implausible segmentations get sampled, and results can be worse than without regularization.
  • Single-character symbols remain in the vocabulary: characters absent from the training data cannot be represented by any symbol in the vocabulary. If every character must be handled, compare it with methods that use bytes as the initial symbols before choosing.
  • Vocabulary size: the paper's translation experiments use 8k–32k (shared by source and target) depending on the size of the data.
  • Use the same tokenizer as the model: when using a pretrained model, use the model file containing the vocabulary and probabilities as is.

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 segmentedSegmentation probabilitiesMain uses
BPEStarting from characters, add the most frequent pairsApply merge rules in the same orderNone (single segmentation)Machine translation, GPT family (byte-level)
WordPieceStarting from characters, add the pair that most increases the likelihoodLongest-match lookup in the vocabularyNone (single segmentation)BERT and its derivatives
Unigram language model (this article)Starting from a large vocabulary, remove symbols with little effect on the likelihoodMost probable segmentation (Viterbi)Yes (can output multiple segmentations)Available in SentencePiece
BPE-dropoutSame as BPEMerges are randomly skipped during training onlyNone (uniform perturbation)Building robustness to segmentation variation

Rough guidelines for choosing:

  • Building a model robust to segmentation variation, or working with little data: use the Unigram language model with subword regularization.
  • Handling languages without word boundaries: train the Unigram language model in SentencePiece directly from text.
  • Never wanting any character to be unknown: use byte-level BPE.

PyTorch example

Show code
python
import math

# 1) Find the most probable segmentation with the Viterbi algorithm (Eqs. 6 and 7 in the paper)
def viterbi(text, logp, max_len=8):
    n = len(text)
    best = [-math.inf] * (n + 1)  # best[i]: best log P for the first i characters
    back = [None] * (n + 1)       # back[i]: start of the last symbol in that best segmentation
    best[0] = 0.0
    for end in range(1, n + 1):
        for start in range(max(0, end - max_len), end):
            piece = text[start:end]
            if piece in logp and best[start] + logp[piece] > best[end]:
                best[end] = best[start] + logp[piece]
                back[end] = start
    pieces, end = [], n
    while end > 0:  # trace back from the end to recover the segmentation
        start = back[end]
        pieces.append(text[start:end])
        end = start
    return pieces[::-1], best[n]


# log p(x) of part of the vocabulary learned in the article's figure (Japanese example)
logp = {"学習": -1.63, "を": -1.95, "学ぶ": -2.24, "深層": -2.42,
        "学": -3.33, "習": -8.60, "ぶ": -8.60, "深": -8.63, "層": -8.63}
print(viterbi("深層学習を学ぶ", logp))  # (['深層', '学習', 'を', '学ぶ'], about -8.24)


# 2) Train a Unigram language model with sentencepiece and perturb the segmentation
import sentencepiece as spm

spm.SentencePieceTrainer.train(
    input="corpus.txt",          # raw text, one sentence per line (Japanese need not be split into words)
    model_prefix="unigram",
    vocab_size=8000,
    model_type="unigram",        # "bpe" is also available
    character_coverage=0.9995,   # typical value for languages with many characters, such as Japanese
)
sp = spm.SentencePieceProcessor(model_file="unigram.model")

print(sp.encode("深層学習を学ぶ", out_type=str))            # inference: most probable segmentation
print(sp.nbest_encode_as_pieces("深層学習を学ぶ", 3))       # top 3 segmentations
for _ in range(3):                                         # training: resample every time (subword regularization)
    print(sp.encode("深層学習を学ぶ", out_type=str,
                    enable_sampling=True, alpha=0.1, nbest_size=-1))  # nbest_size=-1 means l=∞


# 3) Perturb the segmentation only during training in a PyTorch dataset
import torch
from torch.utils.data import Dataset


class SubwordRegularizedDataset(Dataset):
    def __init__(self, texts, sp, alpha=0.1, nbest_size=-1):
        self.texts, self.sp = texts, sp
        self.alpha, self.nbest_size = alpha, nbest_size
        self.training = True  # set to False for evaluation to fix the most probable segmentation

    def __len__(self):
        return len(self.texts)

    def __getitem__(self, i):
        if self.training:
            ids = self.sp.encode(self.texts[i], enable_sampling=True,
                                 alpha=self.alpha, nbest_size=self.nbest_size)
        else:
            ids = self.sp.encode(self.texts[i])
        return torch.tensor(ids, dtype=torch.long)

FAQ

Q. Why is it called a "Unigram (1-gram)" language model?
A.

Because it assumes that each symbol occurs independently of the symbols around it. Unlike a bigram (2-gram) model, which depends on the immediately preceding word, the probability of text is determined solely by the product of each symbol's probability p(x)p(x). It is a simple model, but that simplicity lets the Viterbi algorithm find the most probable segmentation quickly.

Q. How much do the Unigram language model and BPE differ in accuracy?
A.

With a single segmentation, they are nearly the same. In the paper's translation experiments, the BLEU scores of the Unigram language model without subword regularization and of BPE hardly differed. The difference appears when subword regularization is used, which raised scores by 1–2 points for many language pairs.

Q. Does subword regularization slow down training?
A.

It adds the computation of resampling segmentations, but the model architecture does not change. The paper sets the number of sampled segmentations to k=1k = 1 and resamples just one segmentation for each parameter update. In SentencePiece, it can be used simply by passing enable_sampling=True when segmenting.

References

  1. T. Kudo, "Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates," Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (ACL), 2018.
  2. T. Kudo and J. Richardson, "SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing," EMNLP (System Demonstrations), 2018.
  3. R. Sennrich, B. Haddow, and A. Birch, "Neural Machine Translation of Rare Words with Subword Units," ACL, 2016.
  4. google/sentencepiece (Python usage)