Chapter 26 Summarisation Contents Course home

Worked exampleExtractive scores, ROUGE and a false claim

One six-sentence article summarised three ways, scored by ROUGE, checked for faithfulness by two cheap tests, then pushed through a long-input hierarchy and a padded loss.

File summarization.py Chapter 26. Summarisation Needs nothing but Python 3

What to try

  1. python3 summarization.py

    All six stages in order.

  2. python3 summarization.py --extract

    Lead-2 picks S1 and S2. A frequency score picks S2 and S3, because S1 is background. Three sentences tie at 1.167 and the earlier one wins.

  3. python3 summarization.py --rouge

    ROUGE-1 F1 is 0.270 for lead-2 and 0.526 for the frequency summary. A summary with one number changed, 21 for 12, scores 0.944, higher than either.

  4. python3 summarization.py --faithful

    The number check catches 21. A false claim made only of words the article contains, residents approved the first repairs, passes both checks.

  5. python3 summarization.py --long

    30,000 tokens through a 5,000 token window takes 2 levels and 7 calls. A step that keeps 90 per cent of claims leaves 0.8100 after two levels and 0.6561 after four.

  6. python3 summarization.py --mask

    Four summaries padded to 100 tokens are 40 per cent padding. Unmasked, a real loss of 2.800 reads as 1.680.

The source

"""Summarisation, worked as Chapter 26 works it.

Six things, each reproducing a table in the chapter:

    extractive      a lead baseline against a frequency score, sentence by sentence
    rouge           ROUGE-1 and ROUGE-2 of four candidate summaries
    faithfulness    two cheap checks, and the false claim they both miss
    long input      a 30,000 token document through a 5,000 token window
    compounding     how a 90 per cent faithful step decays over levels
    the loss mask   what padding does to an unmasked loss

    python3 summarization.py              # all six
    python3 summarization.py --extract    # lead against frequency scoring
    python3 summarization.py --rouge      # the overlap scores
    python3 summarization.py --faithful   # the novelty and number checks
    python3 summarization.py --long       # chunks, levels and model calls
    python3 summarization.py --mask       # the loss with and without a mask

Install:  nothing, the Python standard library is enough
"""

import argparse
import math
import re
from collections import Counter

ARTICLE = [
    "Heavy rain fell across the region on Tuesday.",
    "The city council approved a new budget after a long debate.",
    "The budget raises spending on roads by 12 percent.",
    "Council members from the northern wards argued that the increase was too small.",
    "Residents had asked for repairs to the bridge for three years.",
    "The mayor said the first repairs will begin in March.",
    "A public meeting on the plan will be held next month.",
]

REFERENCE = ("The council approved a budget that raises road spending by 12 percent, "
             "and repairs will begin in March.")

STOP = {"the", "a", "an", "on", "in", "to", "of", "for", "by", "from", "that",
        "was", "will", "be", "had", "after", "next", "new", "and", "more", "into"}


def words(text):
    return re.findall(r"[a-z0-9]+", text.lower())


def content(text):
    return [w for w in words(text) if w not in STOP]


# --------------------------------------------------------------- extractive

def sentence_scores(sentences):
    """Score of a sentence: the mean document frequency of its content words.

    A word's document frequency here is its count over the whole article, so a
    sentence made of words the article keeps returning to scores high.
    """
    freq = Counter(w for s in sentences for w in content(s))
    scores = []
    for s in sentences:
        cw = content(s)
        scores.append(sum(freq[w] for w in cw) / len(cw))
    return freq, scores


def pick(sentences, scores, k=2):
    """The k best sentences, returned in their original order."""
    best = sorted(range(len(sentences)), key=lambda i: (-scores[i], i))[:k]
    return sorted(best)


def show_extract():
    print("\nSTEP 1  extractive summaries of one article\n")
    for i, s in enumerate(ARTICLE, 1):
        print(f"  S{i}  {s}")
    freq, scores = sentence_scores(ARTICLE)
    print("\n  Content words that occur more than once:",
          ", ".join(f"{w} ({n})" for w, n in sorted(freq.items()) if n > 1))
    print(f"\n  {'sentence':<10}{'content words':>15}{'sum of counts':>16}{'score':>9}")
    print("  " + "-" * 50)
    for i, s in enumerate(ARTICLE):
        cw = content(s)
        tot = sum(freq[w] for w in cw)
        print(f"  S{i + 1:<9}{len(cw):>15}{tot:>16}{scores[i]:>9.3f}")
    chosen = pick(ARTICLE, scores)
    print(f"\n  lead-2 baseline picks   S1, S2")
    print(f"  frequency score picks   " + ", ".join(f"S{i + 1}" for i in chosen))
    print("\n  The lead baseline needs no model. The scored summary has to beat it")
    print("  on the same reference before anyone calls it an improvement.")


# -------------------------------------------------------------------- rouge

def ngrams(tokens, n):
    return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))


def rouge(cand, ref, n):
    c, r = ngrams(words(cand), n), ngrams(words(ref), n)
    overlap = sum(min(c[g], r[g]) for g in c)
    p = overlap / sum(c.values()) if c else 0.0
    rec = overlap / sum(r.values()) if r else 0.0
    f = 2 * p * rec / (p + rec) if p + rec else 0.0
    return overlap, p, rec, f


FAITHFUL_PARA = ("Lawmakers passed a spending plan that puts 12 percent more into "
                 "roads, and work starts in March.")
WRONG_NUMBER = ("The council approved a budget that raises road spending by 21 percent, "
                "and repairs will begin in March.")
WRONG_CLAIM = "Residents approved the first repairs on Tuesday."


def candidates():
    _, scores = sentence_scores(ARTICLE)
    lead = " ".join(ARTICLE[:2])
    scored = " ".join(ARTICLE[i] for i in pick(ARTICLE, scores))
    return [("lead-2", lead), ("frequency-2", scored),
            ("faithful paraphrase", FAITHFUL_PARA),
            ("wrong number", WRONG_NUMBER)]


def show_rouge():
    print("\n\nSTEP 2  ROUGE of four candidates against one reference\n")
    print(f"  reference: {REFERENCE}\n")
    print(f"  {'candidate':<22}{'R1 overlap':>11}{'R1 F1':>8}{'R2 overlap':>12}{'R2 F1':>8}")
    print("  " + "-" * 62)
    for name, text in candidates():
        o1, _, _, f1 = rouge(text, REFERENCE, 1)
        o2, _, _, f2 = rouge(text, REFERENCE, 2)
        print(f"  {name:<22}{o1:>11}{f1:>8.3f}{o2:>12}{f2:>8.3f}")
    print(f"\n  The reference has {len(words(REFERENCE))} words, so {len(words(REFERENCE)) - 1} bigrams.")
    print("  The wrong number differs from the reference in one word of")
    print("  the summary, and ROUGE barely notices.")


# ------------------------------------------------------------- faithfulness

def novel_words(summary, source):
    src = set(words(" ".join(source)))
    return [w for w in content(summary) if w not in src]


def numbers(text):
    return re.findall(r"\d+", text)


def show_faithful():
    print("\n\nSTEP 3  two cheap faithfulness checks, and what they miss\n")
    print("  Check 1: a word in the summary that never appears in the source.")
    print("  Check 2: a number in the summary that never appears in the source.\n")
    rows = [("faithful paraphrase", FAITHFUL_PARA), ("wrong number", WRONG_NUMBER),
            ("wrong claim", WRONG_CLAIM)]
    print(f"  {'summary':<22}{'novel content words':<40}{'unsupported numbers'}")
    print("  " + "-" * 82)
    src_nums = set(numbers(" ".join(ARTICLE)))
    for name, text in rows:
        nw = novel_words(text, ARTICLE)
        un = [n for n in numbers(text) if n not in src_nums]
        print(f"  {name:<22}{', '.join(nw) or 'none':<40}{', '.join(un) or 'none'}")
    print("\n  'faithful paraphrase' is flagged for words that are fine: lawmakers,")
    print("  passed, puts, work, starts. The check cannot tell a paraphrase from an")
    print("  invention. 'wrong number' is caught by the number check, which is narrow")
    print("  but exact. It is also flagged for 'road', a plural that lost its s.")
    print("  'wrong claim' passes both. Every word and no number is new, yet the")
    print("  article never says residents approved anything. Catching that takes")
    print("  a model that reads the source and the claim together.")


# ---------------------------------------------------------------- long input

def hierarchy(total, window, out):
    """Levels, calls and tokens per level when each chunk becomes `out` tokens."""
    levels, calls, size = [], 0, total
    while True:
        chunks = math.ceil(size / window)
        calls += chunks
        levels.append((chunks, chunks * out))
        if chunks == 1:
            return levels, calls
        size = chunks * out


def show_long(total=30000, window=5000, out=500):
    print(f"\n\nSTEP 4  a {total:,} token document, a {window:,} token window\n")
    levels, calls = hierarchy(total, window, out)
    print(f"  Each chunk is summarised into {out} tokens.\n")
    print(f"  {'level':>6}{'input tokens':>15}{'chunks':>9}{'output tokens':>16}")
    print("  " + "-" * 46)
    size = total
    for k, (chunks, outtok) in enumerate(levels, 1):
        print(f"  {k:>6}{size:>15,}{chunks:>9}{outtok:>16,}")
        size = outtok
    print(f"\n  {len(levels)} levels and {calls} model calls.")
    print("  The second level reads six summaries, so a mistake in any one of")
    print("  them is something the second level cannot see.")


def show_compound(keep=0.90, levels=(1, 2, 4)):
    print(f"\n\nSTEP 5  a step that keeps {keep:.0%} of claims, repeated\n")
    print(f"  {'levels':>7}{'faithful share':>17}")
    print("  " + "-" * 25)
    for k in levels:
        print(f"  {k:>7}{keep ** k:>17.4f}")
    print("\n  Two levels already lose about a fifth of the claims.")


# ----------------------------------------------------------------- loss mask

def show_mask(lengths=(62, 48, 90, 40), padded=100, real_loss=2.8, pad_loss=0.0):
    print(f"\n\nSTEP 6  the loss with and without a mask\n")
    print(f"  A batch of {len(lengths)} summaries padded to {padded} tokens.")
    print(f"  Real tokens cost {real_loss} nats each. Padding costs {pad_loss}, because it is")
    print("  trivially predictable.\n")
    real = sum(lengths)
    total = len(lengths) * padded
    print(f"  {'summary':>8}{'real':>7}{'padding':>9}")
    print("  " + "-" * 24)
    for i, L in enumerate(lengths, 1):
        print(f"  {i:>8}{L:>7}{padded - L:>9}")
    print("  " + "-" * 24)
    print(f"  {'total':>8}{real:>7}{total - real:>9}")
    unmasked = (real * real_loss + (total - real) * pad_loss) / total
    masked = (real * real_loss) / real
    print(f"\n  padding share of positions   {(total - real) / total:.1%}")
    print(f"  unmasked mean loss           {unmasked:.3f}")
    print(f"  masked mean loss             {masked:.3f}")
    print("\n  The unmasked curve looks 40 per cent better than the model is.")


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    for f in ("extract", "rouge", "faithful", "long", "mask"):
        ap.add_argument(f"--{f}", action="store_true")
    a = ap.parse_args()
    picked = a.extract or a.rouge or a.faithful or a.long or a.mask
    if a.extract or not picked:
        show_extract()
    if a.rouge or not picked:
        show_rouge()
    if a.faithful or not picked:
        show_faithful()
    if a.long or not picked:
        show_long()
        show_compound()
    if a.mask or not picked:
        show_mask()
    print()


if __name__ == "__main__":
    main()