File size: 9,304 Bytes
195f84f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/env python3
"""Official deterministic evaluator for SABRE-Prior."""

from __future__ import annotations

import argparse
import json
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any


SUBSETS = ("context", "texture", "attribute", "language")
PAIRED_PROBES = {
    "context": ("base_source", "base_target", "edited_source", "edited_target"),
    "texture": (
        "base_normal",
        "base_counterfactual",
        "edited_normal",
        "edited_counterfactual",
    ),
}
NUMBER_WORDS = {
    "zero": "0",
    "one": "1",
    "two": "2",
    "three": "3",
    "four": "4",
    "five": "5",
    "six": "6",
    "seven": "7",
    "eight": "8",
    "nine": "9",
    "ten": "10",
    "eleven": "11",
    "twelve": "12",
    "thirteen": "13",
    "fourteen": "14",
    "fifteen": "15",
    "sixteen": "16",
    "seventeen": "17",
    "eighteen": "18",
    "nineteen": "19",
    "twenty": "20",
}


def load_jsonl(path: Path) -> list[dict[str, Any]]:
    if not path.is_file():
        raise FileNotFoundError(path)
    rows: list[dict[str, Any]] = []
    for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        if not line.strip():
            continue
        try:
            row = json.loads(line)
        except json.JSONDecodeError as exc:
            raise ValueError(f"Invalid JSON in {path}:{line_number}: {exc}") from exc
        if not isinstance(row, dict):
            raise ValueError(f"Expected an object in {path}:{line_number}")
        rows.append(row)
    return rows


def index_unique(rows: list[dict[str, Any]], path: Path) -> dict[str, dict[str, Any]]:
    indexed: dict[str, dict[str, Any]] = {}
    for row in rows:
        item_id = str(row.get("id") or "").strip()
        if not item_id:
            raise ValueError(f"A row in {path} has no id")
        if item_id in indexed:
            raise ValueError(f"Duplicate id in {path}: {item_id}")
        indexed[item_id] = row
    return indexed


def normalize_yes_no(value: Any) -> str:
    text = str(value or "").strip().casefold()
    if text.startswith("yes"):
        return "yes"
    if text.startswith("no"):
        return "no"
    return "unknown"


def normalize_count(value: Any) -> str:
    text = str(value or "").strip().lower().replace("×", "x")
    text = re.sub(r"[^a-z0-9+\- x]+", " ", text)
    text = re.sub(r"\s+", " ", text).strip()
    text = text.split(" instead of ", 1)[0].strip()

    pair = re.search(r"\b(\d+)\s+and\s+(\d+)\b", text)
    if pair:
        return f"{pair.group(1)} and {pair.group(2)}"
    for word1, digit1 in NUMBER_WORDS.items():
        for word2, digit2 in NUMBER_WORDS.items():
            if re.search(rf"\b{word1}\s+and\s+{word2}\b", text):
                return f"{digit1} and {digit2}"

    grid = re.search(r"\b(\d+)\s*(?:x|by|-by-)\s*(\d+)\b", text)
    if grid:
        return f"{grid.group(1)}x{grid.group(2)}"
    for word1, digit1 in NUMBER_WORDS.items():
        for word2, digit2 in NUMBER_WORDS.items():
            if re.search(rf"\b{word1}\s*(?:x|by|-by-)\s*{word2}\b", text):
                return f"{digit1}x{digit2}"

    numbers = re.findall(r"\b\d+\b", text)
    if numbers:
        return numbers[0]
    for word, digit in NUMBER_WORDS.items():
        if re.search(rf"\b{word}\b", text):
            return digit
    return text


def normalize_choice(value: Any) -> str:
    match = re.search(r"(?:^|[^A-Z])([A-D])(?:[^A-Z]|$)", str(value or "").strip().upper())
    return match.group(1) if match else "UNKNOWN"


def ratio(correct: int, total: int) -> dict[str, Any]:
    accuracy = correct / total if total else None
    return {
        "correct": correct,
        "total": total,
        "accuracy": accuracy,
        "accuracy_percent": round(accuracy * 100, 1) if accuracy is not None else None,
    }


def checked_predictions(
    questions: dict[str, dict[str, Any]], path: Path
) -> dict[str, dict[str, Any]]:
    predictions = index_unique(load_jsonl(path), path)
    missing = sorted(set(questions) - set(predictions))
    extra = sorted(set(predictions) - set(questions))
    if missing:
        raise ValueError(f"Missing {len(missing)} predictions; first missing id: {missing[0]}")
    if extra:
        raise ValueError(f"Found {len(extra)} unknown predictions; first unknown id: {extra[0]}")
    for item_id, row in predictions.items():
        if "prediction" not in row and "raw_prediction" not in row:
            raise ValueError(f"Prediction row {item_id} has no prediction field")
    return predictions


def prediction_value(row: dict[str, Any]) -> Any:
    return row["prediction"] if "prediction" in row else row.get("raw_prediction", "")


def score_paired(
    subset: str,
    questions: dict[str, dict[str, Any]],
    predictions: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    required_probes = PAIRED_PROBES[subset]
    by_pair: dict[str, dict[str, bool]] = defaultdict(dict)
    probe_correct: Counter[str] = Counter()

    for item_id, question in questions.items():
        pair_id = str(question.get("pair_id") or "")
        probe = str(question.get("probe") or "")
        if not pair_id or probe not in required_probes:
            raise ValueError(f"Invalid pair_id/probe for {item_id}")
        if probe in by_pair[pair_id]:
            raise ValueError(f"Duplicate probe {probe} in pair {pair_id}")
        prediction = normalize_yes_no(prediction_value(predictions[item_id]))
        expected = normalize_yes_no(question["answer"])
        correct = prediction == expected
        by_pair[pair_id][probe] = correct
        probe_correct[probe] += int(correct)

    for pair_id, probes in by_pair.items():
        if set(probes) != set(required_probes):
            raise ValueError(f"Pair {pair_id} does not contain exactly the four required probes")

    pair_correct = sum(all(probes[probe] for probe in required_probes) for probes in by_pair.values())
    question_correct = sum(probe_correct.values())
    return {
        "primary_metric": "strict_pair_accuracy",
        "primary": ratio(pair_correct, len(by_pair)),
        "diagnostics": {
            "question_accuracy": ratio(question_correct, len(questions)),
            "probe_accuracy": {
                probe: ratio(probe_correct[probe], len(by_pair)) for probe in required_probes
            },
        },
    }


def score_attribute(
    questions: dict[str, dict[str, Any]], predictions: dict[str, dict[str, Any]]
) -> dict[str, Any]:
    correct = sum(
        normalize_count(prediction_value(predictions[item_id]))
        == normalize_count(question["answer"])
        for item_id, question in questions.items()
    )
    return {"primary_metric": "exact_count_accuracy", "primary": ratio(correct, len(questions))}


def score_language(
    questions: dict[str, dict[str, Any]], predictions: dict[str, dict[str, Any]]
) -> dict[str, Any]:
    correct = sum(
        normalize_choice(prediction_value(predictions[item_id]))
        == normalize_choice(question["answer"])
        for item_id, question in questions.items()
    )
    return {"primary_metric": "exact_choice_accuracy", "primary": ratio(correct, len(questions))}


def evaluate_subset(root: Path, predictions_root: Path, subset: str) -> dict[str, Any]:
    metadata_path = root / "data" / subset / "metadata.jsonl"
    prediction_path = predictions_root / f"{subset}.jsonl"
    questions = index_unique(load_jsonl(metadata_path), metadata_path)
    predictions = checked_predictions(questions, prediction_path)
    if subset in PAIRED_PROBES:
        return score_paired(subset, questions, predictions)
    if subset == "attribute":
        return score_attribute(questions, predictions)
    if subset == "language":
        return score_language(questions, predictions)
    raise ValueError(f"Unknown subset: {subset}")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--predictions",
        type=Path,
        required=True,
        help="Directory containing context.jsonl, texture.jsonl, attribute.jsonl, and language.jsonl.",
    )
    parser.add_argument("--dataset-root", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--subset", choices=("all", *SUBSETS), default="all")
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    selected = SUBSETS if args.subset == "all" else (args.subset,)
    metrics: dict[str, Any] = {"metric_version": "sabre-prior-v1.0", "subsets": {}}
    for subset in selected:
        metrics["subsets"][subset] = evaluate_subset(
            args.dataset_root.resolve(), args.predictions.resolve(), subset
        )

    if args.subset == "all":
        accuracies = [metrics["subsets"][name]["primary"]["accuracy"] for name in SUBSETS]
        macro = sum(accuracies) / len(accuracies)
        metrics["macro_accuracy"] = macro
        metrics["macro_accuracy_percent"] = round(macro * 100, 1)

    output = json.dumps(metrics, indent=2, ensure_ascii=False) + "\n"
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(output, encoding="utf-8")
    print(output, end="")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())