Compute ROUGE-L F1 from the longest common subsequence

Why it matters Summarisation evals and many LLM-as-product dashboards still log ROUGE-L.

ROUGE-L compares a generated summary to a reference by their longest common subsequence of tokens.

Write rouge_l(cand, ref), both token lists. Let L be the LCS length. Precision P = L / len(cand), recall R = L / len(ref), return F1 = 2PR / (P + R), or 0.0 if L is 0.

Signaturedef rouge_l(cand, ref)

Example

rouge_l(["the", "cat", "sat"], ["the", "cat", "on", "mat"]) has L 2, P 2/3, R 1/2, F1 about 0.5714.

Understand the idea

ROUGE-L measures how much of a reference text a summary keeps in the same order. It uses the longest common subsequence (LCS): the longest list of tokens that appear in both texts in order, with gaps allowed. Worked example: cand = [a, b, c, d], ref = [a, c, d, e, f]. The LCS is [a, c, d], length 3. Precision P = 3 / 4 = 0.75 and recall R = 3 / 5 = 0.6. F1 = 2 * 0.75 * 0.6 / (0.75 + 0.6) = 0.9 / 1.35 = about 0.667. Rule: fill a dynamic programming table where dp[i][j] = dp[i-1][j-1] + 1 if the tokens match, else max(dp[i-1][j], dp[i][j-1]). L is the bottom-right value. P = L / len(cand), R = L / len(ref), F1 = 2PR / (P + R), and return 0.0 if L is 0. On a mismatch carry the best of skipping a token from either side; carrying the diagonal gives a substring count instead. Used in: summarisation benchmarks and quick automatic checks of LLM output against a reference.

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

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplerouge_l(['the', 'cat', 'sat'], ['the', 'cat', 'on', 'mat'])
  • Sample 2: reorderedrouge_l(['b', 'a', 'c', 'd'], ['a', 'b', 'c', 'd'])
  • Test 3: nonerouge_l(['x'], ['y'])
  • Test 4: gapsrouge_l(['a', 'x', 'b', 'y', 'c'], ['a', 'b', 'c'])