A unigram language-model tokeniser has the vocabulary and probabilities h , u , g , s , hu , ug , hug , gs , ugs . 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 as having probability and picks the maximiser. The Viterbi recursion finds it in for word length and maximum token length .
Steps
- Positions lie before and between the letters h, u, g, s. Set .
- : "h" gives . : "hu" gives , and "h","u" gives . So with token "hu".
- : "hug" gives ; "hu"+"g" gives ; "h"+"ug" gives . So with "hug".
- : "hug"+"s" gives ; "hu"+"gs" gives ; "h"+"ugs" gives . The maximum is .
- Backtracking gives "hug" + "s", with probability . The next best is "h"+"ugs" at .
- 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
- Choosing the segmentation with the fewest tokens or the longest first token. Here "ugs" after "h" has two tokens, like "hug"+"s", but its probability is lower.
- Adding probabilities instead of multiplying them (or comparing sums of log-probabilities with products).
- Running the DP greedily from the left, which can pick "hu" first and miss "hug".
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 to the attention score between query position and key position , with a head-specific slope . For a query at position 4 whose four raw scores are all equal, what attention weights result when and when ? 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 and hidden width (two weight matrices, no biases), and a router that picks the top 2 experts per token. For router logits 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 for and for these experts?