A unigram language-model tokeniser has the vocabulary and probabilities h 0.10, u 0.10, g 0.10, s 0.10, hu 0.10, ug 0.10, hug 0.20, gs 0.05, ugs 0.15. Which segmentation of "hugs" does it choose, how is it found efficiently, and how does this differ from BPE?

Sequence models and transformers, Tokenisation
Level L3 Intermediate. Length Medium. Nature Mat Mathematical.

What's being asked

Whether you can compute the most probable segmentation under a unigram model with dynamic programming, and contrast it with merge-rule tokenisation.

Key idea

A unigram tokeniser treats a segmentation x=(x1,…,xk) as having probability ∏ip(xi) and picks the maximiser. The Viterbi recursion best[j]=max⁡i<j best[i]⋅p(wi:j) finds it in O(n⋅L) for word length n and maximum token length L.

Steps

  1. Positions 0,1,2,3,4 lie before and between the letters h, u, g, s. Set best[0]=1.
  2. best[1]: "h" gives 0.10. best[2]: "hu" gives 1×0.10=0.10, and "h","u" gives 0.10×0.10=0.01. So 0.10 with token "hu".
  3. best[3]: "hug" gives 0.20; "hu"+"g" gives 0.10×0.10=0.01; "h"+"ug" gives 0.10×0.10=0.01. So 0.20 with "hug".
  4. best[4]: "hug"+"s" gives 0.20×0.10=0.02; "hu"+"gs" gives 0.10×0.05=0.005; "h"+"ugs" gives 0.10×0.15=0.015. The maximum is 0.02.
  5. Backtracking gives "hug" + "s", with probability 0.02. The next best is "h"+"ugs" at 0.015.
  6. Contrast with BPE. BPE starts from characters and applies learnt merges in order, giving one deterministic segmentation. A unigram model scores whole segmentations, so it can also sample alternatives in proportion to probability (subword regularisation) and is trained by starting from a large vocabulary and pruning tokens that raise the corpus loss least.

Common mistakes

How long your answer should be

Half a page with the DP table; 4 minutes.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: ALiBi adds no positional embedding. It adds a bias −m(i−j) to the attention score between query position i and key position j≤i, with a head-specific slope m. For a query at position 4 whose four raw scores are all equal, what attention weights result when m=0.5 and when m=1/16? Give the slopes for 8 heads, and explain why ALiBi can help a model run on longer sequences than it was trained on?
Next in Sequence models and transformers: A mixture-of-experts layer has 4 experts, each a feed-forward block with dmodel=1024 and hidden width 4096 (two weight matrices, no biases), and a router that picks the top 2 experts per token. For router logits (2,1,0.5,−1) over the four experts, what are the gate weights of the top-2 experts? Compare the total and active parameters of the layer with one dense feed-forward block, and compute the load-balancing loss N∑ifiPi for f=(0.4,0.3,0.2,0.1) and P=(0.35,0.30,0.20,0.15) for these N=4 experts?