Find the most likely segmentation with a unigram model and Viterbi

A unigram tokenizer (the model behind SentencePiece's unigram mode) gives every piece a log probability and picks the split of a word whose pieces have the highest total log probability. Greedy longest match is not guaranteed to find it, so you need dynamic programming.

Write unigram_segment(text, pieces, unk_score). pieces is a dict mapping strings to log probabilities (negative floats). Any single character not covered by pieces may still be used as the piece "<unk>" with score unk_score, so a segmentation always exists.

Let best[i] be the highest score of any segmentation of text[:i], with best[0] = 0. Fill it left to right, trying every piece that ends at i. Then backtrack to recover the pieces.

Return (list_of_pieces, total_score) with total_score rounded to 6 decimals. Ties: when two candidates for best[i] have exactly the same score, keep the one whose last piece is longest.

Signaturedef unigram_segment(text, pieces, unk_score)

Example

pieces = {"a": -2.0, "b": -2.0, "ab": -3.0, "abc": -9.0, "c": -2.5}, text = "abc" gives (["ab", "c"], -5.5).

Understand the idea

A unigram tokenizer gives each piece a log probability and wants the split of the text with the highest total. Grabbing the longest piece first can miss the best split, so you use dynamic programming: best[i] is the best score for the first i characters, built from shorter prefixes. Worked example: pieces t = -3, h = -3, e = -2, th = -4, the = -7.5. best[0] = 0. best[1] = -3 (t). best[2] = max(best[1] + h = -6, best[0] + th = -4) = -4. best[3] = max(best[2] + e = -6, best[0] + the = -7.5) = -6. Backtracking gives ['th', 'e'] with score -6, even though 'the' is one longer piece. Rule: for each end i, try every piece text[j:i] that exists (plus any single uncovered character as '<unk>' with unk_score), score best[j] + piece score, keep the max and remember j. On an exact tie keep the candidate whose last piece is longer. Then follow the stored j values back from the end. Round the total to 6 decimals. This is how SentencePiece unigram mode picks a tokenization.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleunigram_segment('abc', {'a': -2.0, 'b': -2.0, 'ab': -3.0, 'abc': -9.0, 'c': -2.5}, -10.0)
  • Sample 2: greedy is not optimalunigram_segment('hello', _p, -10.0)