Robo3D_Bench / bench /trace_dfd.py
MingchaoQi's picture
Publish Robo3D-Bench Core v2: Parquet dataset and evaluation code
50e7080
Raw History Blame Contribute Delete
5.73 kB
"""Additive raw-eight-point 3D DFD; leaves the frozen core-v2 scorer intact."""
import argparse
import json
from collections import defaultdict
from pathlib import Path
import numpy as np
from .evaluate_core import cluster_ci, mean_or_none, TRACE_TASKS
from .io import ROOT, indexed, read_jsonl, sha256, write_json, write_jsonl
from .scoring import decode_prediction
def discrete_frechet_xyz(pred, ref):
"""Minimum bottleneck over monotone vertex couplings, in input XYZ units."""
a, b = np.asarray(pred, dtype=float), np.asarray(ref, dtype=float)
if any(x.ndim != 2 or x.shape[1] != 3 or len(x) == 0 or not np.isfinite(x).all()
for x in (a, b)):
raise ValueError('Expected nonempty finite Nx3 paths')
distances = np.linalg.norm(a[:, None, :] - b[None, :, :], axis=-1)
cost = np.full((len(a) + 1, len(b) + 1), np.inf)
cost[0, 0] = 0.
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
cost[i, j] = max(distances[i-1, j-1],
min(cost[i-1, j], cost[i, j-1], cost[i-1, j-1]))
return float(cost[-1, -1])
def summary(rows):
values = [r['dfd_m'] for r in rows if r['valid']]
return dict(n=len(rows), valid=len(values), valid_pct=100*len(values)/len(rows),
dfd_cm_valid_mean=100*float(np.mean(values)) if values else None,
dfd_cm_valid_median=100*float(np.median(values)) if values else None,
dfd_cm_valid_cluster_ci95=cluster_ci(rows, 'dfd_m', 100))
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--data', type=Path, required=True)
p.add_argument('--predictions', type=Path, required=True)
p.add_argument('--base-scoring', type=Path, required=True)
p.add_argument('--output', type=Path, required=True)
args = p.parse_args()
manifest = json.loads((args.data/'manifest.json').read_text())
checksums = json.loads((args.data/'checksums.json').read_text())
assert manifest['version'] == 'robo3d-core-v2' and manifest['benchmark'] == 'trace'
for name in ['manifest.json', 'test_inputs.jsonl', 'test_gold.jsonl']:
assert sha256(args.data/name) == checksums[name], name
for name, digest in manifest['scoring_code_sha256'].items():
assert sha256(ROOT/'bench'/name) == digest, name
base = json.loads((args.base_scoring/'report.json').read_text())
assert base['complete'] and base['predictions_sha256'] == sha256(args.predictions)
assert base['manifest_sha256'] == sha256(args.data/'manifest.json')
samples = indexed(read_jsonl(args.data/'test_inputs.jsonl'))
gold = indexed(read_jsonl(args.data/'test_gold.jsonl'))
predictions = indexed(read_jsonl(args.predictions))
previous = indexed(read_jsonl(args.base_scoring/'per_question.jsonl'))
assert samples.keys() == gold.keys() == predictions.keys() == previous.keys()
rows = []
for qid, sample in samples.items():
judge_path = gold[qid]['judge']
assert sha256(args.data/judge_path) == checksums[judge_path]
ref = np.asarray(json.loads((args.data/judge_path).read_text())['reference_xyz'])
assert ref.shape == (8, 3) and np.isfinite(ref).all() and (ref[:, 2] > 0).all()
row = {k: sample[k] for k in ['id', 'task', 'source', 'label_tier', 'group_id']}
row.update(valid=False, dfd_m=None)
try:
pred = decode_prediction(predictions[qid], sample)
except (ValueError, TypeError, KeyError, OverflowError) as e:
row['invalid_reason'] = str(e)
else:
assert pred.shape == (8, 3)
row.update(valid=True, dfd_m=discrete_frechet_xyz(pred, ref))
assert row['valid'] == previous[qid]['valid'], qid
rows.append(row)
groups, tasks = defaultdict(list), defaultdict(list)
for row in rows:
groups[(row['task'], row['source'], row['label_tier'])].append(row)
tasks[row['task']].append(row)
buckets = [dict(task=t, source=s, label_tier=l, **summary(rs))
for (t, s, l), rs in sorted(groups.items())]
task_reports = []
for task, rs in sorted(tasks.items()):
sources = defaultdict(list)
for row in rs:
sources[row['source']].append(row)
task_reports.append(dict(task=task, **summary(rs),
dfd_cm_source_macro_valid_mean=mean_or_none([
summary(v)['dfd_cm_valid_mean'] for v in sources.values()])))
by_task = {r['task']: r for r in task_reports}
report = dict(complete=True, protocol='robo3d-core-v2+dfd-raw8-v1', expected=len(samples),
attempted=len(rows), invalid_count=sum(not r['valid'] for r in rows),
trajectory_alignment='original_eight_points_no_resampling', units='cm',
distance='3D Euclidean discrete Frechet; monotone endpoint-to-endpoint coupling; no clipping',
buckets=buckets, tasks=task_reports,
dfd_cm_task_source_macro_valid_mean=mean_or_none([
by_task.get(t, {}).get('dfd_cm_source_macro_valid_mean') for t in TRACE_TASKS]),
ranking_note=base['ranking_note'],
predictions_sha256=sha256(args.predictions), manifest_sha256=sha256(args.data/'manifest.json'),
base_report_sha256=sha256(args.base_scoring/'report.json'),
base_per_question_sha256=sha256(args.base_scoring/'per_question.jsonl'),
extension_code_sha256=sha256(Path(__file__)))
write_json(args.output/'report.json', report)
write_jsonl(args.output/'per_question.jsonl', rows)
print(json.dumps({k: report[k] for k in ['protocol', 'expected', 'invalid_count',
'dfd_cm_task_source_macro_valid_mean']}))
if __name__ == '__main__':
main()