File size: 3,409 Bytes
f16ab55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""Score a system on REVEALED.

Implement one of two functions and pass it in.

    rank(texts: list[str]) -> list[float]     higher means more clicks
    judge(a: str, b: str) -> str              returns "A" or "B"

A judge is asked twice per pair with the headlines swapped, and a pair counts
only when both orders name the same headline. Models favour the first option
regardless of content, so a single-order run scores itself on a subset it
picked.

    python score.py --demo                    scores a length baseline
"""

from __future__ import annotations

import argparse
import csv
from pathlib import Path
from typing import Callable

PAIRS = Path(__file__).resolve().parent / "holdout-pairs.csv"


def load(path: Path = PAIRS) -> list[dict]:
    with open(path, newline="", encoding="utf-8") as fh:
        rows = list(csv.DictReader(fh))
    for r in rows:
        r["decidable"] = r["decidable"] == "True"
    return rows


def score_ranker(rank: Callable[[list[str]], list[float]],
                 rows: list[dict]) -> dict:
    texts = sorted({r[side] for r in rows for side in ("winner", "loser")})
    lookup = dict(zip(texts, rank(texts)))
    hits = [(lookup[r["winner"]] > lookup[r["loser"]], r["decidable"])
            for r in rows]
    return summarise(hits, consistent=None)


def score_judge(judge: Callable[[str, str], str], rows: list[dict]) -> dict:
    hits, asked = [], 0
    for r in rows:
        asked += 1
        first = judge(r["winner"], r["loser"])
        second = judge(r["loser"], r["winner"])
        # "first" places the winner at A, "second" places it at B. The two
        # orders name the same headline when those agree.
        if (first == "A") != (second == "B"):
            continue
        hits.append((first == "A", r["decidable"]))
    return summarise(hits, consistent=len(hits) / asked if asked else 0.0)


def summarise(hits: list[tuple[bool, bool]], consistent: float | None) -> dict:
    def acc(subset: list[tuple[bool, bool]]) -> float | None:
        return sum(h for h, _ in subset) / len(subset) if subset else None

    out = {
        "decidable": acc([h for h in hits if h[1]]),
        "undecidable": acc([h for h in hits if not h[1]]),
        "n_decidable": sum(1 for h in hits if h[1]),
        "n_undecidable": sum(1 for h in hits if not h[1]),
    }
    if consistent is not None:
        out["self_consistent"] = consistent
    return out


def report(name: str, numbers: dict) -> None:
    print(f"\n{name}")
    for key in ("decidable", "undecidable"):
        value = numbers[key]
        n = numbers[f"n_{key}"]
        shown = f"{value:.3f}" if value is not None else "—"
        print(f"  {key:16} {shown}   (n={n})")
    if "self_consistent" in numbers:
        print(f"  {'self-consistent':16} {numbers['self_consistent']:.1%}")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--pairs", type=Path, default=PAIRS)
    ap.add_argument("--demo", action="store_true",
                    help="score the longer-headline-wins baseline")
    args = ap.parse_args()

    rows = load(args.pairs)
    print(f"pairs {len(rows)}")
    if args.demo:
        report("length baseline", score_ranker(
            lambda texts: [float(len(t)) for t in texts], rows))
        return
    print("import score.py and call score_ranker or score_judge with your system")


if __name__ == "__main__":
    main()