File size: 6,308 Bytes
616cb74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""Recompute the archive's 192 primary native means without network access."""

import argparse
import csv
import json
import statistics
from pathlib import Path


def read_rows(path):
    rows = [json.loads(line) for line in path.open() if line.strip()]
    if not rows:
        raise ValueError(f"No native records: {path.name}")
    if len({row["page_key"] for row in rows}) != len(rows):
        raise ValueError("Duplicate native page keys")
    return rows


def aggregate(root, benchmark, condition, preset):
    base = root / benchmark
    rows = read_rows(base / "native" / condition / preset / "scores.jsonl")
    if benchmark == "olmocr_bench":
        totals = {}
        for row in rows:
            for _, suite, _, passed, _ in row["subscores"]["results"]:
                value = totals.setdefault(suite, [0, 0])
                value[0] += int(passed)
                value[1] += 1
        return statistics.mean(100 * a / n for a, n in totals.values()), "mean suite pass rate"
    if benchmark == "omniparsebench":
        totals = {}
        for row in rows:
            for family, counts in row["subscores"]["counts"].items():
                if family not in ("text", "tables"):
                    continue
                value = totals.setdefault(family, [0, 0])
                value[0] += counts["passed"]
                value[1] += counts["tests"]
        return statistics.mean(
            100 * a / n for a, n in totals.values() if n
        ), "pooled text/tables family rates"
    if benchmark == "parsebench2":
        if preset != "datalab_accurate":
            cohort = json.loads((base / "native" / "cohorts.json").read_text())["pages"][condition]
            scores = {row["page_key"]: row["score"] for row in rows}
            return statistics.mean(scores[key] for key in cohort), "historical complete-cohort page mean"
        official = json.loads(
            (base / "native_work" / condition / preset / benchmark / "official.json").read_text()
        )
        dimensions = [d["score"] for name, d in official["dimensions"].items() if name != "Layout"]
        return statistics.mean(dimensions), "mean of recorded official dimension components, no layout"
    if benchmark in ("omnidocbench", "real5_omnidocbench"):
        official = json.loads((base / "native" / condition / preset / "official.json").read_text())
        score = (
            100 * (1 - official["text_edit"]) + 100 * official["table_teds"] + 100 * official["formula_cdm"]
        ) / 3
        return score, "mean of official pooled text/table/formula components"
    if benchmark == "puredocbench":
        if preset != "datalab_accurate":
            pooled = json.loads((base / "native" / condition / preset / "pooled.json").read_text())
            return 100 * (
                1 - pooled["text_edit"] + pooled["formula_cdm"] + pooled["table_teds"]
            ) / 3, "mean of official pooled task components"

        def mean(key):
            return statistics.mean(row["subscores"][key] for row in rows if key in row["subscores"])

        return (
            100 * (1 - mean("text_edit")) + mean("formula_cdm") + mean("table_teds")
        ) / 3, "mean of page-averaged task components"
    scores = {row["page_key"]: row["score"] for row in rows if row.get("score") is not None}
    if preset != "datalab_accurate":
        other = "tilt_2_4" if condition == "clean" else "clean"
        paired = {
            r["page_key"]
            for r in read_rows(base / "native" / other / preset / "scores.jsonl")
            if r.get("score") is not None
        }
        scores = {k: v for k, v in scores.items() if k in paired}
    return statistics.mean(
        scores.values()
    ), "native page mean; historical presets use paired clean/tilt pages"


def validate(root):
    data = json.loads((root / "summary" / "data.json").read_text())
    inputs = {
        (r["benchmark"], r["preset"]): r
        for r in csv.DictReader((root / "summary" / "native_rotated_corrected.csv").open())
    }
    checks = []
    for benchmark in data["benchmarks"]:
        for vendor in benchmark["vendors"]:
            preset = vendor["preset"]
            for condition, field in (("clean", "native_clean"), ("tilt_2_4", "native_tilt")):
                cell = inputs.get((benchmark["id"], preset), {}).get(field, "")
                precision = max(2, len(cell.partition(".")[2])) if cell else 2
                tolerance = 1e-8 if preset == "datalab_accurate" else 0.5 * 10**-precision + 1e-10
                row = {
                    "benchmark": benchmark["id"],
                    "preset": preset,
                    "condition": condition,
                    "published": vendor[field],
                    "absolute_tolerance": tolerance,
                }
                try:
                    actual, method = aggregate(root, benchmark["id"], condition, preset)
                    row.update(
                        recomputed=actual,
                        aggregation=method,
                        delta=actual - vendor[field],
                        match=abs(actual - vendor[field]) <= tolerance,
                    )
                except (
                    FileNotFoundError,
                    KeyError,
                    ValueError,
                    TypeError,
                    statistics.StatisticsError,
                    ZeroDivisionError,
                ) as error:
                    row.update(match=False, error=type(error).__name__)
                checks.append(row)
    return {"checked": len(checks), "mismatch_count": sum(not r["match"] for r in checks), "checks": checks}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("root", nargs="?", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()
    result = validate(args.root)
    if args.output:
        args.output.write_text(json.dumps(result, indent=2) + "\n")
    print("Native mean checks:", result["checked"], "mismatches:", result["mismatch_count"])
    for row in result["checks"]:
        if not row["match"]:
            print(json.dumps(row))
    raise SystemExit(bool(result["mismatch_count"]))


if __name__ == "__main__":
    main()