File size: 11,468 Bytes
16f67e8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """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
# ---------------------------------------------------------------------------
# Metrics (vendored verbatim from the paper's scoring code)
# ---------------------------------------------------------------------------
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]),
}
# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------
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
# ---------------------------------------------------------------------------
# Evaluation
# ---------------------------------------------------------------------------
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)
# group keys by dataset (+ an 'all' bucket)
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) # unpredicted → ranked last, counts as wrong
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()
|