| """Evaluate predicted interacted-object boxes against IA-bench ground truth. |
| |
| Reports the paper's selective-prediction metrics for the predicted *start* |
| (`initial_object_box`) and *target* (`target_object_box`) boxes: |
| |
| acc@IoU fraction of samples with IoU(pred, gt) >= --iou-threshold |
| AUROC ranking quality of the confidence score (higher better) |
| AURC area under risk-coverage curve (lower better) |
| E-AURC excess AURC vs the optimal selector (lower better) |
| cov@90 coverage retained while keeping >=90% accuracy |
| cov@95 coverage retained while keeping >=95% accuracy |
| R@90/R@95 recall at those accuracy targets |
| |
| Standalone: needs only numpy (+ pandas for .parquet predictions, and |
| huggingface_hub if you pass --gt-repo). No dependency on the annotation repo. |
| |
| Ground truth is read from the IA-bench metadata.jsonl files (boxes only, no |
| video decode needed): |
| |
| # local build / clone: |
| python eval_ia_bench.py --predictions preds.jsonl --gt-dir /path/to/IA-bench |
| # straight from the Hub: |
| python eval_ia_bench.py --predictions preds.jsonl --gt-repo irl-kit/IA-bench |
| |
| Predictions file (.jsonl or .parquet), one row per (trajectory, subtask): |
| {"dataset": "bridge_lerobot", "trajectory_name": "0/41905", "subtask_index": 0, |
| "initial_object_box": [x1,y1,x2,y2], "target_object_box": [x1,y1,x2,y2], |
| "score": 0.87} |
| `dataset` may be omitted when --dataset names a single config. A per-box |
| `initial_score`/`target_score` overrides `score` for that box. GT samples with |
| no prediction count as incorrect at the lowest score (full-benchmark coverage). |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from pathlib import Path |
|
|
| import numpy as np |
|
|
| |
| |
| |
|
|
|
|
| def iou(a, b) -> float: |
| a = np.asarray(a, dtype=float) |
| b = np.asarray(b, dtype=float) |
| ix1, iy1 = max(a[0], b[0]), max(a[1], b[1]) |
| ix2, iy2 = min(a[2], b[2]), min(a[3], b[3]) |
| inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1) |
| area_a = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1]) |
| area_b = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1]) |
| union = area_a + area_b - inter |
| return inter / union if union > 0 else 0.0 |
|
|
|
|
| def _risk_coverage(pred_scores, correct_flags): |
| pred_scores = np.asarray(pred_scores, dtype=float) |
| correct_flags = np.asarray(correct_flags, dtype=bool) |
| valid = ~np.isnan(pred_scores) |
| pred_scores, correct_flags = pred_scores[valid], correct_flags[valid] |
| n = len(pred_scores) |
| if n == 0: |
| return None, None, 0 |
| order = np.argsort(pred_scores)[::-1] |
| cum_correct = np.cumsum(correct_flags[order].astype(float)) |
| counts = np.arange(1, n + 1, dtype=float) |
| risk = 1.0 - cum_correct / counts |
| return risk, counts, int(np.sum(correct_flags)) |
|
|
|
|
| def compute_aurc(pred_scores, correct_flags) -> float: |
| risk, _counts, _ = _risk_coverage(pred_scores, correct_flags) |
| return float(np.mean(risk)) if risk is not None else np.nan |
|
|
|
|
| def compute_eaurc(pred_scores, correct_flags) -> float: |
| risk, counts, n_correct = _risk_coverage(pred_scores, correct_flags) |
| if risk is None: |
| return np.nan |
| n = len(counts) |
| aurc = float(np.mean(risk)) |
| opt = np.zeros(n, dtype=float) |
| opt[:n_correct] = 1.0 |
| aurc_opt = float(np.mean(1.0 - np.cumsum(opt) / counts)) |
| return aurc - aurc_opt |
|
|
|
|
| def compute_auroc(pred_scores, correct_flags) -> float: |
| pred_scores = np.asarray(pred_scores, dtype=float) |
| correct_flags = np.asarray(correct_flags, dtype=bool) |
| valid = ~np.isnan(pred_scores) |
| pred_scores, correct_flags = pred_scores[valid], correct_flags[valid] |
| n_pos = int(np.sum(correct_flags)) |
| n_neg = len(correct_flags) - n_pos |
| if n_pos == 0 or n_neg == 0: |
| return np.nan |
| order = np.argsort(pred_scores)[::-1] |
| sorted_labels = correct_flags[order] |
| tpr = np.concatenate([[0.0], np.cumsum(sorted_labels) / n_pos]) |
| fpr = np.concatenate([[0.0], np.cumsum(~sorted_labels) / n_neg]) |
| trapz = getattr(np, "trapezoid", None) or np.trapz |
| return float(trapz(tpr, fpr)) |
|
|
|
|
| def compute_recall_at_target_accuracy(pred_scores, correct_flags, target_accuracy=0.9): |
| pred_scores = np.asarray(pred_scores, dtype=float) |
| correct_flags = np.asarray(correct_flags, dtype=bool) |
| valid = ~np.isnan(pred_scores) |
| pred_scores, correct_flags = pred_scores[valid], correct_flags[valid] |
| total_correct = int(np.sum(correct_flags)) |
| empty = {"recall": 0.0, "coverage": 0.0, "threshold": np.nan, "kept_accuracy": np.nan} |
| if len(pred_scores) == 0 or total_correct == 0: |
| return empty |
| order = np.argsort(pred_scores)[::-1] |
| sorted_scores = pred_scores[order] |
| cum_correct = np.cumsum(correct_flags[order].astype(int)) |
| counts = np.arange(1, len(sorted_scores) + 1) |
| acc = cum_correct / counts |
| recall = cum_correct / total_correct |
| valid_pos = acc >= target_accuracy |
| if not np.any(valid_pos): |
| return empty |
| best = int(np.argmax(np.where(valid_pos, recall, -np.inf))) |
| return { |
| "recall": float(recall[best]), |
| "coverage": float(counts[best] / len(sorted_scores)), |
| "threshold": float(sorted_scores[best]), |
| "kept_accuracy": float(acc[best]), |
| } |
|
|
|
|
| |
| |
| |
|
|
|
|
| def _read_jsonl(path: Path) -> list[dict]: |
| with Path(path).open() as f: |
| return [json.loads(line) for line in f if line.strip()] |
|
|
|
|
| def load_predictions(path: Path) -> list[dict]: |
| path = Path(path) |
| if path.suffix == ".parquet": |
| import pandas as pd |
|
|
| return pd.read_parquet(path).to_dict("records") |
| return _read_jsonl(path) |
|
|
|
|
| def load_gt(gt_dir: Path | None, gt_repo: str | None, datasets, splits) -> dict: |
| """Return {(dataset, trajectory_name, subtask_index): row} from metadata.jsonl.""" |
| if gt_repo: |
| from huggingface_hub import snapshot_download |
|
|
| gt_dir = Path(snapshot_download( |
| repo_id=gt_repo, repo_type="dataset", allow_patterns=["data/*/*/metadata.jsonl"] |
| )) |
| if gt_dir is None: |
| raise SystemExit("provide --gt-dir or --gt-repo") |
| gt_dir = Path(gt_dir) |
|
|
| gt = {} |
| for meta in sorted(gt_dir.glob("data/*/*/metadata.jsonl")): |
| ds, split = meta.parts[-3], meta.parts[-2] |
| if datasets and ds not in datasets: |
| continue |
| if splits and split not in splits: |
| continue |
| for row in _read_jsonl(meta): |
| gt[(ds, row["trajectory_name"], int(row["subtask_index"]))] = row |
| if not gt: |
| raise SystemExit(f"no GT metadata found under {gt_dir}/data/*/*/metadata.jsonl") |
| return gt |
|
|
|
|
| |
| |
| |
|
|
| BOX_FIELDS = {"initial": "initial_object_box", "target": "target_object_box"} |
|
|
|
|
| def _pred_index(preds, default_dataset): |
| idx = {} |
| for p in preds: |
| ds = p.get("dataset") or default_dataset |
| if ds is None: |
| raise SystemExit("predictions need a 'dataset' field (or pass --dataset <config>)") |
| idx[(ds, p["trajectory_name"], int(p["subtask_index"]))] = p |
| return idx |
|
|
|
|
| def evaluate(gt, preds, iou_threshold, default_dataset): |
| pred_idx = _pred_index(preds, default_dataset) |
| |
| buckets: dict[str, list] = {} |
| for key in gt: |
| buckets.setdefault(key[0], []).append(key) |
| buckets.setdefault("all", []).append(key) |
|
|
| results = {} |
| for box_name, gt_field in BOX_FIELDS.items(): |
| for bucket, keys in buckets.items(): |
| scores, correct = [], [] |
| n_pred = 0 |
| for key in keys: |
| gt_box = gt[key].get(gt_field) |
| p = pred_idx.get(key) |
| if p is None or p.get(gt_field) is None or gt_box is None: |
| scores.append(-np.inf) |
| correct.append(False) |
| continue |
| n_pred += 1 |
| score = p.get(f"{box_name}_score", p.get("score", 1.0)) |
| scores.append(float(score) if score is not None else -np.inf) |
| correct.append(iou(p[gt_field], gt_box) >= iou_threshold) |
| scores = np.asarray(scores, dtype=float) |
| correct = np.asarray(correct, dtype=bool) |
| r90 = compute_recall_at_target_accuracy(scores, correct, 0.90) |
| r95 = compute_recall_at_target_accuracy(scores, correct, 0.95) |
| results[(box_name, bucket)] = { |
| "n": len(keys), |
| "n_pred": n_pred, |
| "acc": float(np.mean(correct)) if len(correct) else np.nan, |
| "AUROC": compute_auroc(scores, correct), |
| "AURC": compute_aurc(scores, correct), |
| "E-AURC": compute_eaurc(scores, correct), |
| "cov@90": r90["coverage"], |
| "cov@95": r95["coverage"], |
| "R@90": r90["recall"], |
| "R@95": r95["recall"], |
| } |
| return results |
|
|
|
|
| def _fmt(v): |
| if isinstance(v, float): |
| return "nan" if np.isnan(v) else f"{v:.3f}" |
| return str(v) |
|
|
|
|
| def print_table(results, box_name): |
| cols = ["n", "n_pred", "acc", "AUROC", "AURC", "E-AURC", "cov@90", "cov@95", "R@90", "R@95"] |
| rows = sorted(k[1] for k in results if k[0] == box_name and k[1] != "all") |
| rows.append("all") |
| print(f"\n=== {box_name} box (IoU correctness) ===") |
| print(f"{'dataset':16s} " + " ".join(f"{c:>7s}" for c in cols)) |
| for bucket in rows: |
| m = results[(box_name, bucket)] |
| print(f"{bucket:16s} " + " ".join(f"{_fmt(m[c]):>7s}" for c in cols)) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--predictions", required=True, type=Path) |
| ap.add_argument("--gt-dir", type=Path, default=None, help="IA-bench root (local build/clone)") |
| ap.add_argument("--gt-repo", type=str, default=None, help="HF dataset id, e.g. irl-kit/IA-bench") |
| ap.add_argument("--dataset", nargs="*", default=None, |
| help="restrict to these dataset configs (also default 'dataset' for preds)") |
| ap.add_argument("--split", nargs="*", default=None, help="restrict to these splits") |
| ap.add_argument("--iou-threshold", type=float, default=0.4) |
| ap.add_argument("--out", type=Path, default=None, help="optional JSON dump of all metrics") |
| args = ap.parse_args() |
|
|
| gt = load_gt(args.gt_dir, args.gt_repo, set(args.dataset or []), set(args.split or [])) |
| preds = load_predictions(args.predictions) |
| default_dataset = args.dataset[0] if args.dataset and len(args.dataset) == 1 else None |
| results = evaluate(gt, preds, args.iou_threshold, default_dataset) |
|
|
| print(f"GT samples: {len(gt)} | predictions: {len(preds)} | IoU>={args.iou_threshold}") |
| print_table(results, "initial") |
| print_table(results, "target") |
|
|
| if args.out: |
| dump = {f"{box}/{bucket}": m for (box, bucket), m in results.items()} |
| args.out.write_text(json.dumps(dump, indent=2)) |
| print(f"\nwrote {args.out}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|