SABRE-Prior / evaluate.py
zixuanlan's picture
Upload folder using huggingface_hub (part 3)
195f84f verified
Raw
History Blame Contribute Delete
9.3 kB
#!/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())