#!/usr/bin/env python3 # Copyright (c) 2026 Embodied Spatiotemporal Benchmark contributors. MIT License, the same as the evaluation code: # see code/evaluation-code/v0.2-0c2690ae/LICENSE (and ent400-a06a1576/LICENSE). """Score model replies against this dataset, using only this repository. python code/tools/score_predictions.py predictions.jsonl [--out scored.jsonl] [--summary summary.json] Input, one JSON object per line: query_id required, a `query_id` of data/test-00000-of-00001.parquet text the model's reply (thinking may be included as ...) finish_reason optional; `length` (or max_tokens) with no answer in the reply gives parsed_status TRUNCATED status optional, default OK; anything else (a failed call, no reply) scores 0 and is counted as an error Output (--out): one line per input row with query_id, status, parsed_status, passed, normalized_score. Printed (and written to --summary): accuracy and mean score overall, by `capability` and by `task_id`. Queries of the table that are not in the input are counted as `missing` and are not part of any accuracy. Scoring code: each row is scored with the evaluation code shipped with its question set, `dataset` v0.2 with code/evaluation-code/v0.2-0c2690ae, ent400 with code/evaluation-code/ent400-a06a1576 (tools/evaluation/np_answers.py and reply.py, plus the embodied_pipeline / spec modules np_answers imports). The files of that chain are byte-identical in the two snapshots; the script checks this at start and then loads them once. Needs pyarrow and numpy (pip install -r requirements.txt); imports nothing else outside this repository. """ import argparse import collections import hashlib import json import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[2] CODE = ROOT / 'code' / 'evaluation-code' SNAPSHOT = {'v0.2': CODE / 'v0.2-0c2690ae', 'ent400': CODE / 'ent400-a06a1576'} # reply.py, np_answers.py and every module np_answers.score imports (relative to a snapshot) CHAIN = ['tools/evaluation/reply.py', 'tools/evaluation/np_answers.py', 'spec/questions/forms_build.py', 'embodied_pipeline/__init__.py', 'embodied_pipeline/domain/__init__.py', 'embodied_pipeline/domain/params.py', 'embodied_pipeline/prover/__init__.py', 'embodied_pipeline/prover/params.py', 'embodied_pipeline/prover/scoring.py', 'embodied_pipeline/semantics/__init__.py', 'embodied_pipeline/semantics/leaf_contracts.py', 'embodied_pipeline/semantics/piecewise.py', 'embodied_pipeline/semantics/shared_quantities.py'] sys.dont_write_bytecode = True def load_scorer(datasets): """(np_answers, reply) of the snapshots used by ``datasets``; they must carry the same scoring chain.""" unknown = sorted(set(datasets) - set(SNAPSHOT)) if unknown: sys.exit(f'no evaluation code for dataset {unknown}') snaps = sorted({SNAPSHOT[d] for d in datasets}) digest = {s: [hashlib.sha256((s / f).read_bytes()).hexdigest() for f in CHAIN] for s in snaps} first = snaps[0] for s in snaps[1:]: diff = [f for f, a, b in zip(CHAIN, digest[first], digest[s]) if a != b] if diff: sys.exit(f'{first.name} and {s.name} differ in {diff}') sys.path.insert(0, str(first / 'tools' / 'evaluation')) import np_answers # noqa: E402 import reply # noqa: E402 np_answers._core() # resolve its lazy imports now, from this snapshot return np_answers, reply def load_table(path): import pyarrow.parquet as pq cols = ['query_id', 'dataset', 'capability', 'task_id', 'question', 'answer_spec', 'answer', 'scoring'] rows = pq.read_table(path, columns=cols).to_pylist() return {r['query_id']: r for r in rows} def truth_of(raw): try: return json.loads(raw) except (ValueError, TypeError): return raw # option letters and the like are stored as plain strings def score_row(scorer, row, text, finish_reason=None, status='OK'): """One prediction -> (parsed_status, scored dict).""" np_answers, reply = scorer scoring, truth = json.loads(row['scoring']), truth_of(row['answer']) if status != 'OK': return None, np_answers.score(scoring, truth, None) parsed = reply.parse_reply(text, json.loads(row['answer_spec']), finish_reason, question=row['question']) return parsed['status'], np_answers.score(scoring, truth, parsed) def natural(s): return [(0, int(x), '') if x.isdigit() else (1, 0, x) for x in re.split(r'(\d+)', s) if x] def tally(rows): n = len(rows) correct = sum(r['passed'] is True for r in rows) return {'n': n, 'correct': correct, 'accuracy': correct / n if n else None, 'mean_score': sum(r['normalized_score'] for r in rows) / n if n else None} def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('predictions') ap.add_argument('--table', default=str(ROOT / 'data' / 'test-00000-of-00001.parquet')) ap.add_argument('--out'); ap.add_argument('--summary') a = ap.parse_args() table = load_table(a.table) scorer = load_scorer({r['dataset'] for r in table.values()}) scored, seen = [], set() out = open(a.out, 'w') if a.out else None for line in open(a.predictions): if not line.strip(): continue p = json.loads(line) qid = p['query_id'] if qid not in table: sys.exit(f'unknown query_id: {qid}') if qid in seen: sys.exit(f'duplicate query_id: {qid}') seen.add(qid) status = p.get('status') or 'OK' parsed_status, sc = score_row(scorer, table[qid], p.get('text'), p.get('finish_reason'), status) r = {'query_id': qid, 'status': status, 'parsed_status': parsed_status, 'passed': sc['passed'], 'normalized_score': float(sc['score'])} scored.append(r) if out: out.write(json.dumps(r, ensure_ascii=False) + '\n') if out: out.close() by = lambda key: {k: tally([r for r in scored if table[r['query_id']][key] == k]) for k in sorted({table[r['query_id']][key] for r in scored}, key=natural)} summary = {'overall': tally(scored), 'errors': sum(r['status'] != 'OK' for r in scored), 'parsed_status': dict(collections.Counter(r['parsed_status'] for r in scored)), 'missing': len(table) - len(scored), 'by_capability': by('capability'), 'by_task_id': by('task_id')} if a.summary: Path(a.summary).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n') o = summary['overall'] if not o['n']: sys.exit('no predictions') print(f"scored {o['n']} correct {o['correct']} accuracy {o['accuracy']:.4f} mean_score {o['mean_score']:.4f} " f"errors {summary['errors']} missing {summary['missing']}") for title, key in (('capability', 'by_capability'), ('task_id', 'by_task_id')): print(f'\n{title:<12}{"n":>7}{"correct":>9}{"accuracy":>10}') for k, t in summary[key].items(): print(f'{k:<12}{t["n"]:>7}{t["correct"]:>9}{t["accuracy"]:>10.4f}') if __name__ == '__main__': main()