AudioSpan / evaluate /score.py
holvan's picture
Add files using upload-large-folder tool
57c7939 verified
Raw
History Blame Contribute Delete
8.18 kB
#!/usr/bin/env python3
"""Score model outputs on the AudioSpan release.
Two modes (both stdlib-only, no external dependencies):
accuracy — multiple choice on native audio, per-layer breakdown.
chain — first-error truncation over P->U->R chains on anchor audio.
For rubric scoring (which requires a judge model), use score_rubric.py.
The answer file carries only what the model produced, one record per
question: {"qa_id": ..., "answer": "..."}. For multiple choice the scorer
extracts the option letter from the answer text. Correct answers and
question profiles are joined in from metadata/<mode>/{S,M,L}.jsonl;
questions with no answer count as wrong.
Usage:
python score.py --mode accuracy --input results/<model>/accuracy.jsonl
python score.py --mode chain --input results/<model>/chain.jsonl
"""
import argparse
import json
import logging
import re
import sys
from collections import defaultdict
from pathlib import Path
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
RELEASE_ROOT = Path(__file__).resolve().parent.parent
TIERS = ("S", "M", "L")
LAYER_ORDER = ["perception", "understanding", "reasoning"]
LAYER_BY_CODE = {"P": "perception", "U": "understanding", "R": "reasoning"}
def load_questions(mode: str, data_root: Path) -> list[dict]:
questions = []
for tier in TIERS:
path = data_root / "metadata" / mode / f"{tier}.jsonl"
if not path.is_file():
sys.exit(f"ERROR: metadata not found: {path}")
with open(path, encoding="utf-8") as fh:
questions.extend(json.loads(line) for line in fh if line.strip())
return questions
def extract_option(answer) -> str | None:
"""Normalize a model answer to an option letter (A-D), or None."""
if answer is None:
return None
if not isinstance(answer, str):
answer = str(answer)
text = answer.strip()
if re.fullmatch(r"[A-Da-d]", text):
return text.upper()
m = re.search(r"\b(?:answer|option|choice)\s*(?:is|:)?\s*[\((]?([A-Da-d])[\))]?\b",
text, re.IGNORECASE)
if m:
return m.group(1).upper()
m = re.search(r"[\((]([A-Da-d])[\))]", text)
if m:
return m.group(1).upper()
m = re.fullmatch(r"([A-Da-d])[\.\)、::].*", text, re.DOTALL)
if m:
return m.group(1).upper()
return None
def load_answers(path: str) -> dict[str, str]:
"""Map qa_id -> raw answer; later duplicates win."""
preds: dict[str, str] = {}
with open(path, encoding="utf-8", errors="replace") as fh:
for lineno, line in enumerate(fh, 1):
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError as e:
logger.warning("Skipping bad line %d: %s", lineno, e)
continue
qa_id = rec.get("qa_id")
if not qa_id:
logger.warning("Skipping line %d: missing qa_id", lineno)
continue
preds[qa_id] = rec.get("answer")
return preds
def score_accuracy(questions: list[dict], preds: dict[str, str]) -> dict:
scored = []
layer_stats: dict[str, dict[str, int]] = defaultdict(lambda: {"correct": 0, "total": 0})
for q in questions:
predicted = extract_option(preds.get(q["qa_id"]))
is_correct = predicted is not None and predicted == q["correct_option"]
layer = (q.get("question_profile") or {}).get("level", "unknown")
layer_stats[layer]["total"] += 1
if is_correct:
layer_stats[layer]["correct"] += 1
scored.append({"qa_id": q["qa_id"], "predicted": predicted, "correct": is_correct})
total = len(scored)
correct = sum(1 for s in scored if s["correct"])
per_layer = {
layer: {
"accuracy": round(s["correct"] / s["total"] * 100, 2) if s["total"] else 0,
"correct": s["correct"], "total": s["total"],
}
for layer, s in sorted(layer_stats.items())
}
return {
"mode": "accuracy", "total": total, "correct": correct,
"accuracy": round(correct / total * 100, 2) if total else 0,
"per_layer": per_layer, "scored_records": scored,
}
def score_chain(questions: list[dict], preds: dict[str, str]) -> dict:
layer_correct: dict[str, int] = defaultdict(int)
layer_total: dict[str, int] = defaultdict(int)
chains: dict[str, dict[str, bool | None]] = defaultdict(lambda: {l: None for l in LAYER_ORDER})
for q in questions:
chain_key, layer_code = q["qa_id"].rsplit("_", 1)
layer = LAYER_BY_CODE.get(layer_code)
if layer not in LAYER_ORDER:
continue
predicted = extract_option(preds.get(q["qa_id"]))
is_correct = predicted is not None and predicted == q["correct_option"]
chains[chain_key][layer] = is_correct
layer_total[layer] += 1
if is_correct:
layer_correct[layer] += 1
complete = {cid: layers for cid, layers in chains.items()
if all(v is not None for v in layers.values())}
k = len(LAYER_ORDER)
n_dist = defaultdict(int)
scored = []
group_scores = []
for cid, layers in complete.items():
n = 0
for layer in LAYER_ORDER:
if layers[layer]:
n += 1
else:
break
n_dist[n] += 1
group_scores.append(n / k)
scored.append({
"chain_id": cid,
"per_layer": {l: bool(layers[l]) for l in LAYER_ORDER},
"n_correct": n,
"correct": n == k,
"chain_score": round(n / k * 100, 2),
})
chain_score = sum(group_scores) / len(group_scores) * 100 if group_scores else 0
per_layer = {
layer: {
"accuracy": round(layer_correct[layer] / layer_total[layer] * 100, 2) if layer_total[layer] else 0,
"correct": layer_correct[layer], "total": layer_total[layer],
}
for layer in LAYER_ORDER
}
return {
"mode": "chain", "total_chains": len(complete),
"chain_score": round(chain_score, 2),
"per_layer": per_layer,
"n_distribution": {str(n): cnt for n, cnt in sorted(n_dist.items())},
"scored_records": scored,
}
def main():
parser = argparse.ArgumentParser(description="Score AudioSpan model outputs (accuracy/chain)")
parser.add_argument("--input", required=True,
help="Prediction JSONL: {\"qa_id\": ..., \"answer\": \"...\"} per line")
parser.add_argument("--mode", required=True, choices=["accuracy", "chain"])
parser.add_argument("--data-root", type=Path, default=RELEASE_ROOT,
help="release root holding metadata/ (default: parent of evaluate/)")
parser.add_argument("--output", help="Scored output path (default: <input>_scored.jsonl)")
args = parser.parse_args()
preds = load_answers(args.input)
if not preds:
print(f"ERROR: no valid answers in {args.input}", file=sys.stderr)
sys.exit(1)
questions = load_questions(args.mode, args.data_root.resolve())
known = {q["qa_id"] for q in questions}
unknown = sorted(set(preds) - known)
if unknown:
logger.warning("Ignoring %d unknown qa_id(s), e.g. %s", len(unknown), unknown[0])
covered = sum(1 for q in questions if q["qa_id"] in preds)
logger.info("Answers cover %d/%d questions (missing count as wrong)", covered, len(questions))
summary = score_accuracy(questions, preds) if args.mode == "accuracy" else score_chain(questions, preds)
out_path = args.output or args.input.replace(".jsonl", "_scored.jsonl")
with open(out_path, "w", encoding="utf-8") as fh:
for s in summary.get("scored_records", []):
fh.write(json.dumps(s, ensure_ascii=False) + "\n")
logger.info("Scored records: %s", out_path)
print(json.dumps({k: v for k, v in summary.items() if k != "scored_records"},
indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()