| """Score test-split predictions from a Spatial-Qwen bench run. |
| |
| This script is **evaluation-only** — it does not load the model. It consumes a |
| `predictions.jsonl` (produced by `scripts/bench_test_generate.py` or the older |
| `batch_bench_spatial_beats_qa.py`) plus the original QA split, joins on |
| `pair_id`, and computes per-task metrics. |
| |
| Supported task_names (see `all_qa_llm_by_difficulty_v2`): |
| estimate_azimuth / estimate_elevation - numeric angle |
| identify_source_by_doa - single source label |
| identify_source_by_location - single source label |
| detect_time - one time span per event |
| detect_source - list of (event, start, end) |
| |
| Key features: |
| * Robust regex-based extractors with per-task error categories. |
| * Optional LLM judge (OpenAI-compatible, uses `gpt4o_api.py` endpoint style) |
| for semantic equivalence on source-identification tasks where |
| surface-form exact match fails but the prediction might still be correct |
| (e.g. "bell" vs "church_bell"). LLM is ALSO used as a last-resort |
| answer-extractor for verbose generations before scoring. |
| * Detailed parse-fail tracking: every record records a |
| `parse_status` ∈ {"ok", "fail_regex", "fail_llm_extract", "fail_empty", |
| "fail_no_answer_meta"}. |
| * Aggregate report distinguishes task-correctness, parse rate, and |
| LLM-assist rate. |
| |
| Usage (no LLM): |
| python scripts/score_test_predictions.py \\ |
| --predictions-jsonl runs/.../bench/test/<ckpt>/predictions.jsonl \\ |
| --qa-root /apdcephfs.../easy_filtered \\ |
| --output-json runs/.../bench/test/<ckpt>/result.json |
| |
| Usage (LLM judge on ambiguous source identification): |
| python scripts/score_test_predictions.py \\ |
| --predictions-jsonl ... --qa-root ... \\ |
| --llm-judge --llm-model gemini-3.1-pro-preview \\ |
| --llm-concurrency 8 |
| |
| The LLM judge is only invoked when: |
| 1. exact match fails, |
| 2. the task is `identify_source_by_doa` / `identify_source_by_location` |
| (where synonyms are common) or the user passes `--llm-judge-all-tasks`. |
| 3. both prediction and answer are non-empty after cleaning. |
| |
| Fully deterministic regex path still runs regardless of --llm-judge, so the |
| non-LLM `correct` column is always populated as a fallback. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import math |
| import os |
| import re |
| import sys |
| import time |
| from collections import defaultdict |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from dataclasses import dataclass, field |
| from statistics import median |
| from typing import Any, Callable, Dict, List, Optional, Tuple |
|
|
|
|
| |
| |
| |
|
|
| FLOAT_RE = re.compile(r"[-+]?\d+(?:\.\d+)?") |
| |
| TIME_SPAN_RE = re.compile( |
| r"(?P<start>[-+]?\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?\s*(?:to|-|–|—|until)\s*(?P<end>[-+]?\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?", |
| re.IGNORECASE, |
| ) |
| |
| |
| EVENT_SPAN_RE = re.compile( |
| |
| r"(?P<label>[A-Za-z][A-Za-z\s_'-]{0,40})\s+" |
| r"(?:active\s+)?(?:from\s+)?(?P<start>[-+]?\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?\s*" |
| r"(?:to|-|–|—|until)\s*(?P<end>[-+]?\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?", |
| re.IGNORECASE, |
| ) |
| STOPWORDS = { |
| "the", "a", "an", "sound", "source", "is", "at", "from", "to", "and", |
| "of", "that", "which", "are", "can", "be", "heard", "coming", "audio", |
| "clip", "contains", "features", "active", "during", "this", "in", "with", |
| } |
|
|
|
|
| def normalize_text(text: Any) -> str: |
| return " ".join(str(text).strip().lower().split()) |
|
|
|
|
| def strip_stopwords(text: str) -> str: |
| return " ".join(w for w in normalize_text(text).split() if w not in STOPWORDS) |
|
|
|
|
| def canonicalize_label(text: str) -> str: |
| """Canonicalize a source/event label for comparison. |
| |
| Lowercase + underscore -> space + strip trailing punctuation + singularize |
| common plurals. This is intentionally simple; LLM judge handles harder |
| synonym cases. |
| """ |
| text = normalize_text(text).replace("_", " ") |
| text = text.strip(".,;:!?\"'()[]") |
| |
| for prefix in ("a ", "an ", "the "): |
| if text.startswith(prefix): |
| text = text[len(prefix):] |
| |
| if text.endswith("ies") and len(text) > 4: |
| text = text[:-3] + "y" |
| elif text.endswith(("sses", "shes", "ches", "xes")): |
| text = text[:-2] |
| elif text.endswith("s") and len(text) > 2 and not text.endswith(("ss", "us", "is", "os")): |
| text = text[:-1] |
| return text.strip() |
|
|
|
|
| _LABEL_LEADING_JUNK = re.compile( |
| r"^(?:the\s+audio\s+(?:contains|features|includes)|audio\s+(?:contains|features|includes)|" |
| r"the\s+clip\s+(?:contains|features)|this\s+(?:audio\s+)?(?:clip\s+)?(?:contains|features)|" |
| r"and\s+|followed\s+by\s+|then\s+|next\s+)\s*", |
| re.IGNORECASE, |
| ) |
| _LABEL_TRAILING_JUNK = re.compile( |
| r"\s*(?:active|audible|heard|happening|occurring|present|from)\s*$", |
| re.IGNORECASE, |
| ) |
|
|
|
|
| def _clean_event_label(raw: str) -> str: |
| """Trim connector phrases / filler from a raw label span.""" |
| s = raw.strip() |
| |
| while True: |
| new = _LABEL_LEADING_JUNK.sub("", s) |
| if new == s: |
| break |
| s = new |
| s = _LABEL_TRAILING_JUNK.sub("", s) |
| return canonicalize_label(s) |
|
|
|
|
| def parse_first_float(text: Any) -> Optional[float]: |
| match = FLOAT_RE.search(str(text)) |
| if match is None: |
| return None |
| return float(match.group(0)) |
|
|
|
|
| def parse_time_span_first(text: Any) -> Optional[Tuple[float, float]]: |
| m = TIME_SPAN_RE.search(str(text)) |
| if m is None: |
| |
| floats = [float(x) for x in FLOAT_RE.findall(str(text))] |
| if len(floats) < 2: |
| return None |
| s, e = floats[0], floats[1] |
| if e < s: |
| s, e = e, s |
| return s, e |
| s = float(m.group("start")) |
| e = float(m.group("end")) |
| if e < s: |
| s, e = e, s |
| return s, e |
|
|
|
|
| def parse_all_events(text: Any) -> List[Tuple[str, float, float]]: |
| """Extract (label, start, end) tuples from a detect_source-style answer.""" |
| events: List[Tuple[str, float, float]] = [] |
| for m in EVENT_SPAN_RE.finditer(str(text)): |
| label_raw = m.group("label") |
| label = _clean_event_label(label_raw) |
| if not label or label in STOPWORDS: |
| continue |
| try: |
| s = float(m.group("start")) |
| e = float(m.group("end")) |
| except ValueError: |
| continue |
| if e < s: |
| s, e = e, s |
| events.append((label, s, e)) |
| return events |
|
|
|
|
| def angle_err_deg(pred: float, target: float) -> float: |
| d = pred - target |
| while d > 180.0: |
| d -= 360.0 |
| while d <= -180.0: |
| d += 360.0 |
| return abs(d) |
|
|
|
|
| def interval_iou(ps: float, pe: float, gs: float, ge: float) -> float: |
| inter = max(0.0, min(pe, ge) - max(ps, gs)) |
| union = max(pe, ge) - min(ps, gs) |
| if union <= 0: |
| return 0.0 |
| return inter / union |
|
|
|
|
| def mean_or_none(xs: List[float]) -> Optional[float]: |
| if not xs: |
| return None |
| return float(sum(xs) / len(xs)) |
|
|
|
|
| def median_or_none(xs: List[float]) -> Optional[float]: |
| if not xs: |
| return None |
| return float(median(xs)) |
|
|
|
|
| |
| |
| |
|
|
|
|
| @dataclass |
| class LLMConfig: |
| enabled: bool = False |
| model: str = "gemini-3.1-pro-preview" |
| base_url: str = "https://yunwu.ai/v1" |
| api_key: str = os.environ.get( |
| "SPATIAL_QWEN_LLM_API_KEY", |
| "sk-uLLRM86XBL9hx5CJUfpW8POle3KFS5mJ1iAiGgiMOY6Xxbjj", |
| ) |
| concurrency: int = 4 |
| max_retries: int = 3 |
| timeout_s: float = 60.0 |
| judge_all_tasks: bool = False |
| |
| |
| judge_max_calls: int = 5000 |
|
|
|
|
| class LLMJudge: |
| """Thin OpenAI-compatible wrapper. Lazily imports openai to keep the |
| scorer runnable with no API deps when --llm-judge is off. |
| """ |
|
|
| def __init__(self, cfg: LLMConfig) -> None: |
| self.cfg = cfg |
| self._client = None |
| self._lock_calls = 0 |
|
|
| def _client_or_none(self): |
| if not self.cfg.enabled: |
| return None |
| if self._client is not None: |
| return self._client |
| try: |
| from openai import OpenAI |
| except ImportError as exc: |
| raise RuntimeError( |
| "--llm-judge requires `pip install openai`" |
| ) from exc |
| self._client = OpenAI(base_url=self.cfg.base_url, api_key=self.cfg.api_key) |
| return self._client |
|
|
| def _chat(self, prompt: str) -> Optional[str]: |
| if self._lock_calls >= self.cfg.judge_max_calls: |
| return None |
| self._lock_calls += 1 |
| client = self._client_or_none() |
| if client is None: |
| return None |
| last_exc: Optional[Exception] = None |
| for attempt in range(self.cfg.max_retries): |
| try: |
| completion = client.chat.completions.create( |
| model=self.cfg.model, |
| messages=[{"role": "user", "content": prompt}], |
| timeout=self.cfg.timeout_s, |
| ) |
| return (completion.choices[0].message.content or "").strip() |
| except Exception as exc: |
| last_exc = exc |
| time.sleep(min(2.0 * (attempt + 1), 10.0)) |
| sys.stderr.write(f"[llm-judge] call failed after {self.cfg.max_retries}: {last_exc}\n") |
| return None |
|
|
| |
|
|
| def extract_label(self, prediction: str, candidates: Optional[List[str]] = None) -> Optional[str]: |
| """Ask the LLM to boil a verbose prediction down to a single short |
| label (1-3 words). |
| """ |
| hint = "" |
| if candidates: |
| hint = ( |
| "The sound source should be one of these canonical names " |
| f"if possible: {', '.join(sorted(set(candidates))[:80])}. " |
| "If the text mentions something not in the list, return the " |
| "closest English name, 1-3 words, lowercase, no punctuation.\n" |
| ) |
| prompt = ( |
| "Extract the single sound-source name mentioned as the ANSWER " |
| "from the following text. Return ONLY the label in 1-3 English " |
| "words, lowercase, no punctuation, no explanation. If nothing " |
| "identifiable is mentioned, return the literal token UNKNOWN.\n" |
| f"{hint}" |
| f"TEXT:\n{prediction}\n" |
| "ANSWER:" |
| ) |
| out = self._chat(prompt) |
| if out is None: |
| return None |
| out = out.strip().splitlines()[0].strip(" \t\"'.,`").lower() |
| if not out or out == "unknown": |
| return None |
| return out |
|
|
| def judge_equivalent(self, prediction_label: str, gold_label: str, |
| task_name: str) -> Optional[bool]: |
| """Ask: is `prediction_label` a semantically valid rewording of |
| `gold_label`? Returns True/False or None on API failure. |
| """ |
| prompt = ( |
| "You are evaluating a spatial-audio QA system. Decide whether " |
| "the MODEL ANSWER and the GOLD ANSWER refer to the SAME sound " |
| "source / event category. Surface wording may differ " |
| "(e.g. 'footstep' vs 'footsteps', 'bell' vs 'church_bell' vs " |
| "'bell ringing'). Output exactly one token: YES or NO.\n\n" |
| f"TASK: {task_name}\n" |
| f"MODEL ANSWER: {prediction_label}\n" |
| f"GOLD ANSWER: {gold_label}\n\n" |
| "VERDICT:" |
| ) |
| out = self._chat(prompt) |
| if out is None: |
| return None |
| head = out.strip().splitlines()[0].upper() |
| if head.startswith("YES"): |
| return True |
| if head.startswith("NO"): |
| return False |
| return None |
|
|
|
|
| |
| |
| |
|
|
|
|
| @dataclass |
| class TaskScore: |
| """Result of scoring a single (prediction, qa) pair.""" |
| pair_id: Any |
| task_name: str |
| prediction: str |
| answer: str |
| canonical_answer: Optional[str] |
| correct: float = 0.0 |
| parse_status: str = "ok" |
| metric_type: str = "exact_match" |
| details: Dict[str, Any] = field(default_factory=dict) |
| llm_used: bool = False |
|
|
|
|
| def score_estimate_angle(record: Dict[str, Any], pred_text: str, |
| is_azimuth: bool, angle_threshold_deg: float, |
| ) -> TaskScore: |
| task = str(record["task_name"]) |
| meta = record.get("answer_meta") or {} |
| key = "azimuth_deg" if is_azimuth else "elevation_deg" |
| target = meta.get(key) |
| |
| if target is None: |
| target = parse_first_float(record.get("answer", "")) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type=("er%d_angle" % int(angle_threshold_deg) |
| if is_azimuth |
| else "abs%d_angle" % int(angle_threshold_deg)), |
| ) |
|
|
| if target is None: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
|
|
| pred = parse_first_float(pred_text) |
| if pred is None: |
| ts.parse_status = "fail_regex" |
| return ts |
|
|
| err = angle_err_deg(float(pred), float(target)) if is_azimuth \ |
| else abs(float(pred) - float(target)) |
| ts.details = { |
| "predicted_deg": float(pred), |
| "target_deg": float(target), |
| "error_deg": float(err), |
| "threshold_deg": angle_threshold_deg, |
| } |
| ts.correct = float(err <= angle_threshold_deg) |
| return ts |
|
|
|
|
| def score_identify_source(record: Dict[str, Any], pred_text: str, |
| llm: LLMJudge, llm_allowed: bool, |
| candidate_labels: Optional[List[str]] = None, |
| ) -> TaskScore: |
| task = str(record["task_name"]) |
| gold = record.get("canonical_answer") or record.get("answer", "") |
| gold_norm = canonicalize_label(str(gold)) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type="source_label_match", |
| ) |
|
|
| if not gold_norm: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
|
|
| pred_norm = canonicalize_label(pred_text) |
| |
| if pred_norm == gold_norm: |
| ts.correct = 1.0 |
| ts.details = {"pred_label": pred_norm, "gold_label": gold_norm, "match_stage": "canonical"} |
| return ts |
|
|
| |
| if gold_norm and gold_norm in pred_norm: |
| ts.correct = 1.0 |
| ts.details = {"pred_label": pred_norm, "gold_label": gold_norm, "match_stage": "substring"} |
| return ts |
|
|
| |
| pred_s = strip_stopwords(pred_text) |
| gold_s = strip_stopwords(str(gold)) |
| if pred_s and gold_s and (pred_s == gold_s or gold_s in pred_s): |
| ts.correct = 1.0 |
| ts.details = {"pred_label": pred_s, "gold_label": gold_s, "match_stage": "stopword_stripped"} |
| return ts |
|
|
| |
| |
| details: Dict[str, Any] = {"pred_label": pred_norm, "gold_label": gold_norm, "match_stage": "none"} |
| if llm_allowed and llm.cfg.enabled: |
| extracted = llm.extract_label(pred_text, candidates=candidate_labels) |
| if extracted is not None: |
| ts.llm_used = True |
| extracted_norm = canonicalize_label(extracted) |
| details["llm_extracted"] = extracted_norm |
| if extracted_norm == gold_norm: |
| ts.correct = 1.0 |
| details["match_stage"] = "llm_extract" |
| ts.details = details |
| return ts |
| |
| verdict = llm.judge_equivalent(extracted_norm or pred_norm, gold_norm, task) |
| if verdict is True: |
| ts.correct = 1.0 |
| details["match_stage"] = "llm_judge" |
| ts.details = details |
| return ts |
| if verdict is None and extracted is None: |
| ts.parse_status = "fail_llm_extract" |
| |
| ts.details = details |
| return ts |
|
|
|
|
| def score_detect_time(record: Dict[str, Any], pred_text: str, |
| iou_threshold: float) -> TaskScore: |
| task = str(record["task_name"]) |
| meta = record.get("answer_meta") or {} |
| refs = record.get("source_refs") or [] |
|
|
| |
| |
| gold_span: Optional[Tuple[float, float]] = None |
| span_meta = meta.get("time_span") |
| if isinstance(span_meta, (list, tuple)) and len(span_meta) == 2: |
| gold_span = (float(span_meta[0]), float(span_meta[1])) |
| elif meta.get("start_time") is not None and meta.get("end_time") is not None: |
| gold_span = (float(meta["start_time"]), float(meta["end_time"])) |
| elif refs and isinstance(refs[0], dict): |
| r0 = refs[0] |
| if r0.get("start_time") is not None and r0.get("end_time") is not None: |
| gold_span = (float(r0["start_time"]), float(r0["end_time"])) |
| if gold_span is None: |
| gold_span = parse_time_span_first(record.get("answer", "")) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type="time_span_iou", |
| ) |
|
|
| if gold_span is None: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
| pred_span = parse_time_span_first(pred_text) |
| if pred_span is None: |
| ts.parse_status = "fail_regex" |
| return ts |
| ps, pe = pred_span |
| gs, ge = gold_span |
| iou = interval_iou(ps, pe, gs, ge) |
| ts.details = { |
| "predicted_span": [ps, pe], |
| "target_span": [gs, ge], |
| "iou": iou, |
| "start_error_s": abs(ps - gs), |
| "end_error_s": abs(pe - ge), |
| "iou_threshold": iou_threshold, |
| } |
| |
| ts.correct = float(iou) |
| ts.details["correct_binary"] = int(iou >= iou_threshold) |
| return ts |
|
|
|
|
| def score_detect_source(record: Dict[str, Any], pred_text: str, |
| llm: LLMJudge, llm_allowed: bool, |
| iou_threshold: float) -> TaskScore: |
| """Detect-source: list of (label, start, end). Score with event-level F1 |
| under (label_match AND iou>=thr). Label match uses canonical normalization; |
| optional LLM synonym matching on a label-by-label basis (disabled by default |
| because of API cost on long lists — enable via --llm-judge-all-tasks). |
| """ |
| task = str(record["task_name"]) |
| refs = record.get("source_refs") or [] |
| gold_events: List[Tuple[str, float, float]] = [] |
| for r in refs: |
| if not isinstance(r, dict): |
| continue |
| label = canonicalize_label(str(r.get("class_name") or "")) |
| if label and r.get("start_time") is not None and r.get("end_time") is not None: |
| gold_events.append((label, float(r["start_time"]), float(r["end_time"]))) |
| if not gold_events: |
| |
| gold_events = parse_all_events(record.get("answer", "")) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type="detect_source_f1", |
| ) |
|
|
| if not gold_events: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
| pred_events = parse_all_events(pred_text) |
| if not pred_events: |
| ts.parse_status = "fail_regex" |
| return ts |
|
|
| |
| |
| matched_pred = [False] * len(pred_events) |
| tp = 0 |
| ious: List[float] = [] |
| for (gl, gs, ge) in gold_events: |
| best_idx = -1 |
| best_iou = 0.0 |
| for i, (pl, ps, pe) in enumerate(pred_events): |
| if matched_pred[i]: |
| continue |
| label_ok = (pl == gl) |
| if not label_ok and llm_allowed and llm.cfg.enabled: |
| verdict = llm.judge_equivalent(pl, gl, task) |
| if verdict is True: |
| label_ok = True |
| ts.llm_used = True |
| if not label_ok: |
| continue |
| iou = interval_iou(ps, pe, gs, ge) |
| if iou > best_iou: |
| best_iou = iou |
| best_idx = i |
| if best_idx >= 0 and best_iou >= iou_threshold: |
| matched_pred[best_idx] = True |
| tp += 1 |
| ious.append(best_iou) |
| n_gold = len(gold_events) |
| n_pred = len(pred_events) |
| precision = tp / max(n_pred, 1) |
| recall = tp / max(n_gold, 1) |
| f1 = 0.0 if precision + recall == 0 else 2 * precision * recall / (precision + recall) |
| ts.details = { |
| "n_gold_events": n_gold, |
| "n_pred_events": n_pred, |
| "tp": tp, |
| "precision": precision, |
| "recall": recall, |
| "f1": f1, |
| "matched_iou_mean": mean_or_none(ious), |
| "iou_threshold": iou_threshold, |
| } |
| ts.correct = float(f1) |
| return ts |
|
|
|
|
| |
| |
| |
| |
|
|
|
|
| def _parse_first_int(text: Any) -> Optional[int]: |
| """Return the first integer found in text. Used by count_sources where |
| the GT is a small integer ('1', '2', '3', ...) and the prediction may |
| be embedded in a sentence ('There are 2 sources active.').""" |
| m = re.search(r"-?\d+", str(text)) |
| if m is None: |
| return None |
| try: |
| return int(m.group(0)) |
| except ValueError: |
| return None |
|
|
|
|
| def score_count_sources(record: Dict[str, Any], pred_text: str) -> "TaskScore": |
| """count_sources: GT is an integer (active_count). Just extract the |
| first integer from prediction and compare. No LLM needed. |
| """ |
| task = str(record["task_name"]) |
| meta = record.get("answer_meta") or {} |
| target = meta.get("active_count") |
| if target is None: |
| target = _parse_first_int(record.get("answer", "")) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type="count_exact_match", |
| ) |
|
|
| if target is None: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
| pred = _parse_first_int(pred_text) |
| if pred is None: |
| ts.parse_status = "fail_regex" |
| return ts |
| err = abs(int(pred) - int(target)) |
| ts.details = { |
| "predicted_count": int(pred), |
| "target_count": int(target), |
| "abs_error": int(err), |
| } |
| ts.correct = float(int(pred) == int(target)) |
| return ts |
|
|
|
|
| def score_estimate_distance(record: Dict[str, Any], pred_text: str, |
| rel_threshold: float = 0.3) -> "TaskScore": |
| """estimate_distance: GT is a float (meters). The "correct" signal is |
| the relative error: rel_err = |pred - gt| / max(|gt|, eps), with a |
| threshold (default 0.3, i.e. within 30% of the true distance). |
| |
| Why relative instead of absolute: a 1m error is huge for a near-source |
| (gt=1.5m -> 67% off) but acceptable for a far source (gt=8m -> 12.5% |
| off). A relative threshold gives a fair signal across the [near, far] |
| range. |
| |
| Aggregates report: |
| - mean / median absolute error (m) |
| - mean / median relative error |
| - acc within `rel_threshold` (the binary "correct" signal) |
| - extra acc points at relaxed/tight thresholds (rel<0.2 / rel<0.5) |
| """ |
| task = str(record["task_name"]) |
| meta = record.get("answer_meta") or {} |
| target = meta.get("distance_m") |
| if target is None: |
| target = parse_first_float(record.get("answer", "")) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type=f"rel{rel_threshold:.2f}_distance", |
| ) |
|
|
| if target is None: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
| pred = parse_first_float(pred_text) |
| if pred is None: |
| ts.parse_status = "fail_regex" |
| return ts |
| err = abs(float(pred) - float(target)) |
| rel_err = err / max(abs(float(target)), 1e-3) |
| ts.details = { |
| "predicted_m": float(pred), |
| "target_m": float(target), |
| "abs_error_m": float(err), |
| "rel_error": float(rel_err), |
| "rel_threshold": float(rel_threshold), |
| } |
| ts.correct = float(rel_err <= rel_threshold) |
| return ts |
|
|
|
|
| def score_onset_from_location(record: Dict[str, Any], pred_text: str, |
| within_s: float = 0.4) -> "TaskScore": |
| """onset_from_location: GT is the onset time (seconds). Score reports |
| the time error and acc within `within_s` (default 0.4s).""" |
| task = str(record["task_name"]) |
| meta = record.get("answer_meta") or {} |
| target = meta.get("onset_time") |
| |
| if target is None: |
| target = parse_first_float(record.get("canonical_answer") or |
| record.get("answer", "")) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type=f"abs{within_s}s_onset", |
| ) |
|
|
| if target is None: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
| pred = parse_first_float(pred_text) |
| if pred is None: |
| ts.parse_status = "fail_regex" |
| return ts |
| err = abs(float(pred) - float(target)) |
| ts.details = { |
| "predicted_s": float(pred), |
| "target_s": float(target), |
| "abs_error_s": float(err), |
| "within_s_threshold": float(within_s), |
| } |
| ts.correct = float(err <= within_s) |
| return ts |
|
|
|
|
| |
| |
| |
| _MOTION_CANONICAL_LABELS = ( |
| "stationary", "moving", "approaching", "receding", |
| "moving towards", "moving away", |
| ) |
|
|
|
|
| def score_classify_motion(record: Dict[str, Any], pred_text: str, |
| llm: "LLMJudge") -> "TaskScore": |
| """classify_motion: GT is a short label ('stationary' / 'moving' / ...). |
| Strategy: substring match first (covers 90% of cases like |
| 'The laughter remains stationary throughout its duration.'), |
| then fall back to LLM judge for ambiguous synonyms. |
| """ |
| task = str(record["task_name"]) |
| meta = record.get("answer_meta") or {} |
| gold = meta.get("motion_label") or record.get("canonical_answer") or \ |
| record.get("answer", "") |
| gold_norm = canonicalize_label(str(gold)) |
|
|
| ts = TaskScore( |
| pair_id=record.get("pair_id"), |
| task_name=task, |
| prediction=pred_text, |
| answer=str(record.get("answer", "")), |
| canonical_answer=record.get("canonical_answer"), |
| metric_type="motion_label_match", |
| ) |
|
|
| if not gold_norm: |
| ts.parse_status = "fail_no_answer_meta" |
| return ts |
| if not str(pred_text).strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
|
|
| pred_norm = canonicalize_label(pred_text) |
| details: Dict[str, Any] = { |
| "predicted_norm": pred_norm, |
| "gold_norm": gold_norm, |
| } |
|
|
| |
| if pred_norm == gold_norm: |
| details["match_stage"] = "exact" |
| ts.correct = 1.0 |
| ts.details = details |
| return ts |
| if gold_norm in pred_norm.split(): |
| details["match_stage"] = "word" |
| ts.correct = 1.0 |
| ts.details = details |
| return ts |
| if gold_norm in pred_norm: |
| details["match_stage"] = "substring" |
| ts.correct = 1.0 |
| ts.details = details |
| return ts |
|
|
| |
| |
| |
| if llm.cfg.enabled: |
| verdict = llm.judge_equivalent(pred_norm, gold_norm, task) |
| ts.llm_used = True |
| if verdict is True: |
| details["match_stage"] = "llm_judge" |
| ts.correct = 1.0 |
| elif verdict is False: |
| details["match_stage"] = "none" |
| ts.correct = 0.0 |
| else: |
| ts.parse_status = "fail_llm_extract" |
| details["match_stage"] = "llm_failed" |
| ts.details = details |
| return ts |
|
|
| |
| details["match_stage"] = "none" |
| ts.correct = 0.0 |
| ts.details = details |
| return ts |
|
|
|
|
| |
| |
| |
|
|
|
|
| def score_record(qa: Dict[str, Any], pred_text: str, llm: LLMJudge, |
| thresholds: Dict[str, float], |
| candidate_labels: Optional[List[str]], |
| ) -> TaskScore: |
| task = str(qa.get("task_name") or "") |
| if task == "estimate_azimuth": |
| return score_estimate_angle(qa, pred_text, True, |
| thresholds.get("azimuth_deg", thresholds["angle_deg"])) |
| if task == "estimate_elevation": |
| return score_estimate_angle(qa, pred_text, False, |
| thresholds.get("elevation_deg", thresholds["angle_deg"])) |
| if task in ("identify_source_by_doa", "identify_source_by_location"): |
| return score_identify_source(qa, pred_text, llm, |
| llm_allowed=True, |
| candidate_labels=candidate_labels) |
| if task == "detect_time": |
| return score_detect_time(qa, pred_text, thresholds["iou"]) |
| if task == "detect_source": |
| return score_detect_source(qa, pred_text, llm, |
| llm_allowed=llm.cfg.judge_all_tasks, |
| iou_threshold=thresholds["iou"]) |
| |
| if task == "count_sources": |
| return score_count_sources(qa, pred_text) |
| if task == "estimate_distance": |
| return score_estimate_distance(qa, pred_text, |
| rel_threshold=thresholds.get("distance_rel", 0.3)) |
| if task == "onset_from_location": |
| return score_onset_from_location(qa, pred_text, |
| within_s=thresholds.get("onset_s", 0.4)) |
| if task == "classify_motion": |
| |
| |
| |
| return score_classify_motion(qa, pred_text, llm) |
| |
| ts = TaskScore( |
| pair_id=qa.get("pair_id"), |
| task_name=task or "unknown", |
| prediction=pred_text, |
| answer=str(qa.get("answer", "")), |
| canonical_answer=qa.get("canonical_answer"), |
| metric_type="normalized_exact_match", |
| ) |
| if not pred_text.strip(): |
| ts.parse_status = "fail_empty" |
| return ts |
| ts.correct = float(normalize_text(pred_text) == normalize_text(qa.get("answer", ""))) |
| return ts |
|
|
|
|
| def summarize(scored: List[TaskScore], thresholds: Dict[str, float], |
| parse_status_order: List[str]) -> Dict[str, Any]: |
| by_task: Dict[str, List[TaskScore]] = defaultdict(list) |
| for s in scored: |
| by_task[s.task_name].append(s) |
|
|
| parse_ok = [s for s in scored if s.parse_status == "ok"] |
| correct_all = mean_or_none([float(s.correct) for s in scored]) |
| correct_parseable = mean_or_none([float(s.correct) for s in parse_ok]) |
|
|
| summary: Dict[str, Any] = { |
| "examples": len(scored), |
| "overall_correct": correct_all, |
| "overall_correct_parseable": correct_parseable, |
| "parse_rate": mean_or_none([1.0 if s.parse_status == "ok" else 0.0 for s in scored]), |
| "llm_used_rate": mean_or_none([1.0 if s.llm_used else 0.0 for s in scored]), |
| "thresholds": thresholds, |
| "parse_status_counts": { |
| status: sum(1 for s in scored if s.parse_status == status) |
| for status in parse_status_order |
| }, |
| "per_task": {}, |
| } |
|
|
| for task_name, records in sorted(by_task.items()): |
| n = len(records) |
| parse_ok_records = [r for r in records if r.parse_status == "ok"] |
| per_task: Dict[str, Any] = { |
| "examples": n, |
| "metric_type": records[0].metric_type, |
| "correct_all": mean_or_none([float(r.correct) for r in records]), |
| "correct_parseable": mean_or_none([float(r.correct) for r in parse_ok_records]), |
| "parse_rate": mean_or_none([1.0 if r.parse_status == "ok" else 0.0 for r in records]), |
| "parse_status_counts": { |
| status: sum(1 for r in records if r.parse_status == status) |
| for status in parse_status_order |
| }, |
| "llm_used_rate": mean_or_none([1.0 if r.llm_used else 0.0 for r in records]), |
| } |
| |
| if task_name in ("estimate_azimuth", "estimate_elevation"): |
| errs = [float(r.details.get("error_deg")) |
| for r in parse_ok_records if "error_deg" in r.details] |
| per_task["error_deg_mean"] = mean_or_none(errs) |
| per_task["error_deg_median"] = median_or_none(errs) |
| per_task["correct_is_within_threshold"] = per_task["correct_all"] |
| |
| |
| |
| |
| |
| preds = [float(r.details.get("predicted_deg")) |
| for r in parse_ok_records if "predicted_deg" in r.details] |
| tgts = [float(r.details.get("target_deg")) |
| for r in parse_ok_records if "target_deg" in r.details] |
| n_pred = len(preds) |
| if n_pred > 0: |
| |
| |
| uniq = len(set(round(p, 1) for p in preds)) |
| per_task["unique_prediction_ratio"] = uniq / n_pred |
| per_task["unique_prediction_count"] = uniq |
| |
| |
| |
| from collections import Counter |
| pc = Counter(round(p, 1) for p in preds) |
| top1_val, top1_cnt = pc.most_common(1)[0] |
| per_task["top1_prediction"] = float(top1_val) |
| per_task["top1_prediction_share"] = top1_cnt / n_pred |
| |
| |
| |
| |
| |
| if tgts: |
| import statistics |
| gt_med = statistics.median(tgts) |
| if task_name == "estimate_azimuth": |
| |
| def _err(p, g): |
| return abs(((p - g + 180.0) % 360.0) - 180.0) |
| else: |
| def _err(p, g): |
| return abs(p - g) |
| const_errs = [_err(gt_med, g) for g in tgts] |
| thr = (thresholds.get("azimuth_deg") if task_name == "estimate_azimuth" |
| else thresholds.get("elevation_deg")) or thresholds.get("angle_deg") or 20.0 |
| per_task["const_median_baseline_value_deg"] = float(gt_med) |
| per_task["const_median_baseline_median_err"] = median_or_none(const_errs) |
| per_task["const_median_baseline_mean_err"] = mean_or_none(const_errs) |
| per_task["const_median_baseline_acc"] = mean_or_none( |
| [1.0 if e <= thr else 0.0 for e in const_errs]) |
| |
| |
| per_task["acc_gain_over_constant"] = ( |
| (per_task["correct_all"] or 0.0) |
| - (per_task["const_median_baseline_acc"] or 0.0)) |
| per_task["median_err_reduction_vs_constant"] = ( |
| (per_task["const_median_baseline_median_err"] or 0.0) |
| - (per_task["error_deg_median"] or 0.0)) |
| |
| |
| |
| |
| |
| if task_name == "estimate_elevation": |
| bins = [(-90, -30), (-30, -10), (-10, 10), (10, 30), (30, 90)] |
| else: |
| bins = [(-180, -90), (-90, -30), (-30, 30), (30, 90), (90, 180)] |
| thr = (thresholds.get("azimuth_deg") if task_name == "estimate_azimuth" |
| else thresholds.get("elevation_deg")) or thresholds.get("angle_deg") or 20.0 |
| bin_accs: List[float] = [] |
| bin_counts: List[int] = [] |
| for lo, hi in bins: |
| mask_errs = [] |
| for p, g in zip(preds, tgts): |
| if lo <= g < hi: |
| if task_name == "estimate_azimuth": |
| e = abs(((p - g + 180.0) % 360.0) - 180.0) |
| else: |
| e = abs(p - g) |
| mask_errs.append(1.0 if e <= thr else 0.0) |
| bin_counts.append(len(mask_errs)) |
| if mask_errs: |
| bin_accs.append(sum(mask_errs) / len(mask_errs)) |
| if bin_accs: |
| per_task["acc_macro_by_gt_bin"] = sum(bin_accs) / len(bin_accs) |
| per_task["acc_per_gt_bin"] = { |
| f"[{lo},{hi})": { |
| "n": bin_counts[i], |
| "acc": (bin_accs[i] if i < len(bin_accs) else None), |
| } |
| for i, (lo, hi) in enumerate(bins) |
| } |
| elif task_name == "detect_time": |
| ious = [float(r.details.get("iou")) |
| for r in parse_ok_records if "iou" in r.details] |
| starts = [float(r.details.get("start_error_s")) |
| for r in parse_ok_records if "start_error_s" in r.details] |
| ends = [float(r.details.get("end_error_s")) |
| for r in parse_ok_records if "end_error_s" in r.details] |
| per_task["iou_mean"] = mean_or_none(ious) |
| per_task["iou_median"] = median_or_none(ious) |
| per_task["start_error_mean_s"] = mean_or_none(starts) |
| per_task["end_error_mean_s"] = mean_or_none(ends) |
| per_task["iou_at_threshold"] = mean_or_none( |
| [float(r.details.get("correct_binary") or 0) |
| for r in parse_ok_records]) |
| elif task_name == "detect_source": |
| f1s = [float(r.details.get("f1")) |
| for r in parse_ok_records if "f1" in r.details] |
| precs = [float(r.details.get("precision")) |
| for r in parse_ok_records if "precision" in r.details] |
| recs = [float(r.details.get("recall")) |
| for r in parse_ok_records if "recall" in r.details] |
| per_task["f1_mean"] = mean_or_none(f1s) |
| per_task["precision_mean"] = mean_or_none(precs) |
| per_task["recall_mean"] = mean_or_none(recs) |
| elif task_name in ("identify_source_by_doa", "identify_source_by_location"): |
| stages: Dict[str, int] = defaultdict(int) |
| for r in records: |
| stages[str(r.details.get("match_stage", "none"))] += 1 |
| per_task["match_stage_counts"] = dict(stages) |
| elif task_name == "count_sources": |
| errs = [float(r.details.get("abs_error")) |
| for r in parse_ok_records if "abs_error" in r.details] |
| per_task["abs_error_mean"] = mean_or_none(errs) |
| per_task["abs_error_median"] = median_or_none(errs) |
| |
| for tol in (0, 1): |
| per_task[f"acc_within_{tol}"] = mean_or_none( |
| [1.0 if e <= tol else 0.0 for e in errs]) |
| elif task_name == "estimate_distance": |
| errs = [float(r.details.get("abs_error_m")) |
| for r in parse_ok_records if "abs_error_m" in r.details] |
| rels = [float(r.details.get("rel_error")) |
| for r in parse_ok_records if "rel_error" in r.details] |
| per_task["abs_error_m_mean"] = mean_or_none(errs) |
| per_task["abs_error_m_median"] = median_or_none(errs) |
| per_task["rel_error_mean"] = mean_or_none(rels) |
| per_task["rel_error_median"] = median_or_none(rels) |
| |
| per_task["acc_rel_within_0.3"] = per_task["correct_all"] |
| |
| per_task["acc_rel_within_0.2"] = mean_or_none( |
| [1.0 if r <= 0.2 else 0.0 for r in rels]) |
| per_task["acc_rel_within_0.5"] = mean_or_none( |
| [1.0 if r <= 0.5 else 0.0 for r in rels]) |
| |
| per_task["acc_abs_within_1m"] = mean_or_none( |
| [1.0 if e <= 1.0 else 0.0 for e in errs]) |
| elif task_name == "onset_from_location": |
| errs = [float(r.details.get("abs_error_s")) |
| for r in parse_ok_records if "abs_error_s" in r.details] |
| per_task["abs_error_s_mean"] = mean_or_none(errs) |
| per_task["abs_error_s_median"] = median_or_none(errs) |
| per_task["acc_within_0.4s"] = per_task["correct_all"] |
| per_task["acc_within_0.2s"] = mean_or_none( |
| [1.0 if e <= 0.2 else 0.0 for e in errs]) |
| per_task["acc_within_1.0s"] = mean_or_none( |
| [1.0 if e <= 1.0 else 0.0 for e in errs]) |
| elif task_name == "classify_motion": |
| stages: Dict[str, int] = defaultdict(int) |
| for r in records: |
| stages[str(r.details.get("match_stage", "none"))] += 1 |
| per_task["match_stage_counts"] = dict(stages) |
| summary["per_task"][task_name] = per_task |
|
|
| return summary |
|
|
|
|
| |
| |
| |
|
|
|
|
| def load_jsonl(path: str) -> List[Dict[str, Any]]: |
| with open(path, "r", encoding="utf-8") as handle: |
| return [json.loads(line) for line in handle if line.strip()] |
|
|
|
|
| def resolve_qa_split(qa_root: str, split: str) -> str: |
| for ext in (".jsonl", ".json"): |
| p = os.path.join(qa_root, f"{split}{ext}") |
| if os.path.exists(p): |
| return p |
| raise FileNotFoundError(f"Missing {split}.jsonl or {split}.json under {qa_root}") |
|
|
|
|
| def load_qa_split(qa_root: str, split: str) -> List[Dict[str, Any]]: |
| path = resolve_qa_split(qa_root, split) |
| if path.endswith(".jsonl"): |
| return load_jsonl(path) |
| with open(path, "r", encoding="utf-8") as handle: |
| payload = json.load(handle) |
| if isinstance(payload, list): |
| return payload |
| return payload.get("records") or payload.get("data") or [] |
|
|
|
|
| def build_candidate_labels(qa_records: List[Dict[str, Any]]) -> List[str]: |
| """Collect all canonical source labels seen in the split — used as |
| hints for the LLM extractor.""" |
| labels: set = set() |
| for r in qa_records: |
| c = r.get("canonical_answer") |
| if c: |
| labels.add(canonicalize_label(str(c))) |
| for ref in (r.get("source_refs") or []): |
| if isinstance(ref, dict) and ref.get("class_name"): |
| labels.add(canonicalize_label(str(ref["class_name"]))) |
| labels.discard("") |
| return sorted(labels) |
|
|
|
|
| def clean_generated(text: str) -> str: |
| """Trim the typical decoder tail so scorers see just the answer.""" |
| s = str(text).replace("\r\n", "\n").strip() |
| for marker in ("Human:", "Question:", "\nHuman:", "\nQuestion:"): |
| if marker in s: |
| s = s.split(marker, 1)[0].strip() |
| |
| |
| |
| lines = [ln.strip() for ln in s.splitlines() if ln.strip()] |
| if not lines: |
| return "" |
| |
| |
| if (len(lines) > 1 and len(lines[0]) <= 120 |
| and any(ln.lower().startswith(("explanation:", "reason:", "note:", "because")) for ln in lines[1:])): |
| return lines[0] |
| return "\n".join(lines).strip() |
|
|
|
|
| |
| |
| |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| p.add_argument("--predictions-jsonl", required=True, |
| help="Path to predictions.jsonl produced by the bench script.") |
| p.add_argument("--qa-root", default=None, |
| help="QA root containing <split>.jsonl with the gold fields. " |
| "Optional: if omitted, scorer uses the `answer` / " |
| "`canonical_answer` / `answer_meta` / `source_refs` " |
| "fields embedded in predictions.jsonl directly " |
| "(self-scoring mode).") |
| p.add_argument("--split", default="test") |
| p.add_argument("--output-json", default=None, |
| help="Summary output path. Defaults to <predictions-dir>/score_result.json.") |
| p.add_argument("--per-record-jsonl", default=None, |
| help="Optional path to dump per-record scoring detail.") |
| p.add_argument("--angle-threshold-deg", type=float, default=20.0, |
| help="Default angle tolerance. Used only if the per-task " |
| "--azimuth/--elevation flags are left unset.") |
| p.add_argument("--azimuth-threshold-deg", type=float, default=20.0, |
| help="estimate_azimuth tolerance (deg). Default: 20.") |
| p.add_argument("--elevation-threshold-deg", type=float, default=10.0, |
| help="estimate_elevation tolerance (deg). Default: 10. " |
| "Elevation uses a tighter threshold because GT is " |
| "concentrated near 0° (a constant-0 predictor " |
| "already hits ~34%% at 10°; at 20° it would hit ~55%% " |
| "which obscures template-answer baselines).") |
| p.add_argument("--iou-threshold", type=float, default=0.5, |
| help="IoU threshold used for detect_time/detect_source binary metrics.") |
| p.add_argument("--distance-rel-threshold", type=float, default=0.3, |
| help="estimate_distance tolerance as a relative error " |
| "(|pred-gt|/|gt|). Default: 0.3 (i.e. correct if " |
| "predicted distance is within 30%% of the truth). " |
| "Relative error is fairer than absolute meters when " |
| "GT spans both near (<2m) and far (>5m) sources.") |
| p.add_argument("--onset-threshold-s", type=float, default=0.4, |
| help="onset_from_location tolerance (seconds). Default: 0.4.") |
| p.add_argument("--llm-judge", action="store_true", |
| help="Enable OpenAI-compatible LLM judge / extractor for " |
| "identify_source_* when regex match fails.") |
| p.add_argument("--llm-judge-all-tasks", action="store_true", |
| help="Also use LLM for detect_source label synonym matching. Slow.") |
| p.add_argument("--llm-model", default="gemini-3.1-pro-preview") |
| p.add_argument("--llm-base-url", default="https://yunwu.ai/v1") |
| p.add_argument("--llm-concurrency", type=int, default=4, |
| help="Number of parallel LLM calls. Use --llm-concurrency 1 for ordered debugging.") |
| p.add_argument("--llm-max-calls", type=int, default=5000, |
| help="Hard cap on LLM calls (safety valve for cost).") |
| p.add_argument("--keep-duplicate-pair-ids", action="store_true") |
| return p.parse_args() |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
|
|
| predictions = load_jsonl(args.predictions_jsonl) |
| if args.qa_root: |
| qa_records = load_qa_split(args.qa_root, args.split) |
| else: |
| |
| |
| |
| print("[score] self-scoring mode (no --qa-root): using answer fields " |
| "from predictions.jsonl as ground truth.") |
| qa_records = [ |
| { |
| "pair_id": r.get("pair_id"), |
| "task_name": r.get("task_name"), |
| "question": r.get("question"), |
| "answer": r.get("answer"), |
| "audio_path": r.get("audio_path"), |
| "scene_id": r.get("scene_id"), |
| "segment_stem": r.get("segment_stem"), |
| "canonical_answer": r.get("canonical_answer"), |
| "answer_meta": r.get("answer_meta"), |
| "source_refs": r.get("source_refs"), |
| } |
| for r in predictions |
| ] |
|
|
| |
| |
| |
| |
| def _ensure_pair_id(r: Dict[str, Any]) -> None: |
| pid = r.get("pair_id") |
| if pid is None or pid == "": |
| import hashlib |
| key = "|".join( |
| str(r.get(k, "")) |
| for k in ("scene_id", "segment_stem", "task_name", "question", "audio_path") |
| ) |
| r["pair_id"] = "auto_" + hashlib.sha1(key.encode("utf-8")).hexdigest()[:16] |
|
|
| for r in qa_records: |
| _ensure_pair_id(r) |
| for r in predictions: |
| _ensure_pair_id(r) |
|
|
| |
| |
| |
| |
| |
| def _primary_key(r): |
| pid = r.get("pair_id") |
| |
| |
| |
| |
| if pid is not None and not str(pid).startswith("auto_"): |
| return ("id", str(pid)) |
| |
| ap = r.get("audio_path") |
| if ap: |
| return ("tqa", str(r.get("task_name", "")), str(r.get("question", "")), str(ap)) |
| |
| |
| |
| return ( |
| "tqans", |
| str(r.get("task_name", "")), |
| str(r.get("question", "")), |
| str(r.get("answer", "")), |
| ) |
|
|
| def _fallback_key(r): |
| return ( |
| "qta", |
| str(r.get("question", "")), |
| str(r.get("task_name", "")), |
| str(r.get("audio_path", "")), |
| ) |
|
|
| qa_index: Dict[Any, Dict[str, Any]] = {} |
| qa_collisions = 0 |
| for r in qa_records: |
| |
| |
| |
| keys = [] |
| pid = r.get("pair_id") |
| if pid is not None and not str(pid).startswith("auto_"): |
| keys.append(("id", str(pid))) |
| ap = r.get("audio_path") |
| if ap: |
| keys.append(("tqa", str(r.get("task_name", "")), |
| str(r.get("question", "")), str(ap))) |
| |
| keys.append(("tqans", str(r.get("task_name", "")), |
| str(r.get("question", "")), str(r.get("answer", "")))) |
| for k in keys: |
| if k in qa_index: |
| qa_collisions += 1 |
| else: |
| qa_index[k] = r |
|
|
| if qa_collisions: |
| print(f"[score] WARN: {qa_collisions} QA records collided on " |
| f"(question,task_name); falling back to (question,task_name,audio_path) " |
| f"for those.") |
|
|
| keyed_mode = "pair_id" |
| if all(r.get("pair_id") is None for r in qa_records[:200]): |
| keyed_mode = "(question, task_name)" |
| print(f"[score] join key: {keyed_mode}; " |
| f"qa_records={len(qa_records)} predictions={len(predictions)}") |
|
|
| |
| if not args.keep_duplicate_pair_ids: |
| seen = set() |
| deduped = [] |
| for rec in predictions: |
| k = _primary_key(rec) |
| if k in seen: |
| continue |
| seen.add(k) |
| deduped.append(rec) |
| predictions = deduped |
| print(f"[score] after dedup: {len(predictions)} predictions") |
|
|
| thresholds = { |
| "angle_deg": args.angle_threshold_deg, |
| "azimuth_deg": args.azimuth_threshold_deg, |
| "elevation_deg": args.elevation_threshold_deg, |
| "iou": args.iou_threshold, |
| "distance_rel": args.distance_rel_threshold, |
| "onset_s": args.onset_threshold_s, |
| } |
|
|
| llm_cfg = LLMConfig( |
| enabled=bool(args.llm_judge or args.llm_judge_all_tasks), |
| model=args.llm_model, |
| base_url=args.llm_base_url, |
| concurrency=max(1, args.llm_concurrency), |
| judge_all_tasks=bool(args.llm_judge_all_tasks), |
| judge_max_calls=args.llm_max_calls, |
| ) |
| llm = LLMJudge(llm_cfg) |
| candidate_labels = build_candidate_labels(qa_records) if llm_cfg.enabled else None |
|
|
| |
| |
| parse_status_order = ["ok", "fail_regex", "fail_llm_extract", |
| "fail_empty", "fail_no_answer_meta"] |
|
|
| scored: List[TaskScore] = [] |
| unmatched = [0] |
|
|
| def _do_one(rec: Dict[str, Any]) -> Optional[TaskScore]: |
| k = _primary_key(rec) |
| qa = qa_index.get(k) |
| if qa is None: |
| |
| qa = qa_index.get(_fallback_key(rec)) |
| if qa is None: |
| |
| |
| |
| if rec.get("answer") is not None and rec.get("task_name"): |
| qa = { |
| "pair_id": rec.get("pair_id"), |
| "task_name": rec.get("task_name"), |
| "question": rec.get("question"), |
| "answer": rec.get("answer"), |
| "canonical_answer": rec.get("canonical_answer"), |
| "answer_meta": rec.get("answer_meta"), |
| "source_refs": rec.get("source_refs"), |
| } |
| else: |
| unmatched[0] += 1 |
| return None |
| raw_pred = rec.get("prediction_cleaned") or rec.get("prediction") or "" |
| pred_text = clean_generated(raw_pred) |
| ts = score_record(qa, pred_text, llm, thresholds, candidate_labels) |
| return ts |
|
|
| if llm_cfg.enabled and llm_cfg.concurrency > 1: |
| with ThreadPoolExecutor(max_workers=llm_cfg.concurrency) as pool: |
| futures = [pool.submit(_do_one, rec) for rec in predictions] |
| for i, fut in enumerate(as_completed(futures)): |
| ts = fut.result() |
| if ts is not None: |
| scored.append(ts) |
| if (i + 1) % 500 == 0: |
| print(f" scored {i+1}/{len(predictions)}", flush=True) |
| else: |
| for i, rec in enumerate(predictions): |
| ts = _do_one(rec) |
| if ts is not None: |
| scored.append(ts) |
| if (i + 1) % 2000 == 0: |
| print(f" scored {i+1}/{len(predictions)}", flush=True) |
|
|
| summary = summarize(scored, thresholds, parse_status_order) |
|
|
| out_json = args.output_json or os.path.join( |
| os.path.dirname(os.path.abspath(args.predictions_jsonl)), "score_result.json") |
| os.makedirs(os.path.dirname(out_json), exist_ok=True) |
| with open(out_json, "w", encoding="utf-8") as handle: |
| json.dump(summary, handle, indent=2, ensure_ascii=False, sort_keys=True) |
| print(f"\n[score] wrote {out_json}") |
|
|
| if args.per_record_jsonl: |
| with open(args.per_record_jsonl, "w", encoding="utf-8") as handle: |
| for s in scored: |
| handle.write(json.dumps({ |
| "pair_id": s.pair_id, |
| "task_name": s.task_name, |
| "correct": s.correct, |
| "parse_status": s.parse_status, |
| "metric_type": s.metric_type, |
| "llm_used": s.llm_used, |
| "prediction": s.prediction, |
| "answer": s.answer, |
| "canonical_answer": s.canonical_answer, |
| "details": s.details, |
| }, ensure_ascii=False) + "\n") |
| print(f"[score] wrote per-record scoring to {args.per_record_jsonl}") |
|
|
| |
| def _fmt(v, spec=".4f"): |
| if v is None: |
| return "n/a" |
| try: |
| return format(v, spec) |
| except Exception: |
| return str(v) |
|
|
| print(f"\n=== overall ({summary['examples']} records) ===") |
| if unmatched[0] > 0: |
| print(f" unmatched predictions: {unmatched[0]} (no QA join key)") |
| print(f" parse_rate = {_fmt(summary['parse_rate'])}") |
| print(f" correct (all records) = {_fmt(summary['overall_correct'])}") |
| print(f" correct (parseable only) = {_fmt(summary['overall_correct_parseable'])}") |
| print(f" llm_used_rate = {_fmt(summary['llm_used_rate'])}") |
| print(" parse_status_counts = " + json.dumps(summary["parse_status_counts"])) |
|
|
| for task_name, t in summary["per_task"].items(): |
| print(f"\n=== {task_name} (n={t['examples']}, metric={t['metric_type']}) ===") |
| print(f" correct_all = {_fmt(t['correct_all'])}") |
| print(f" correct_parseable = {_fmt(t.get('correct_parseable'))}") |
| print(f" parse_rate = {_fmt(t['parse_rate'])}") |
| print(" parse_status = " + json.dumps(t["parse_status_counts"])) |
| for key in ("error_deg_mean", "error_deg_median", |
| "iou_mean", "iou_median", "iou_at_threshold", |
| "start_error_mean_s", "end_error_mean_s", |
| "f1_mean", "precision_mean", "recall_mean", |
| "match_stage_counts", |
| |
| "abs_error_mean", "abs_error_median", |
| "acc_within_0", "acc_within_1", |
| |
| "abs_error_m_mean", "abs_error_m_median", |
| "rel_error_mean", "rel_error_median", |
| "acc_rel_within_0.2", "acc_rel_within_0.3", |
| "acc_rel_within_0.5", "acc_abs_within_1m", |
| |
| "abs_error_s_mean", "abs_error_s_median", |
| "acc_within_0.2s", "acc_within_0.4s", "acc_within_1.0s", |
| |
| "const_median_baseline_acc", "acc_gain_over_constant", |
| "acc_macro_by_gt_bin", "unique_prediction_ratio", |
| "top1_prediction_share"): |
| if key in t: |
| val = t[key] |
| if isinstance(val, float): |
| print(f" {key:30s}= {_fmt(val)}") |
| elif val is None: |
| print(f" {key:30s}= n/a") |
| else: |
| print(f" {key:30s}= {val}") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|