File size: 7,336 Bytes
b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 b26bdfa c777571 | 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 | """GeCO reproduction (NeurIPS 2026, arXiv 2603.17834, Table 5): planning-level OOD detection metrics.
Inputs are the per-planning-call scores written by experiments/lerobot/eval_variant.py (--geco / --fm-score) to
<run>/eval_<suite>/ood_scores.json. ID = libero_goal (the training suite), OOD = libero_spatial.
Protocol (App. D), with our choices where the paper is silent, marked (ours):
* J = 20 planning calls sampled at random per episode (all calls if fewer, ours), seed fixed. Short episodes
therefore contribute fewer calls; auroc_equal_weight gives every episode the same total weight instead (ours).
* AUROC over all sampled calls, OOD = positive class, higher score = more OOD.
* Operating point: the threshold whose ID retention ("TPR" in the paper) is closest to 0.90; report the fraction of
OOD calls flagged ("TNR" in the paper). The same rule is applied to the baseline (ours: the paper does not say).
* 95% interval: bootstrap over EPISODES (calls inside an episode are correlated), 2000 resamples, with the J-call
subsample redrawn in every resample (ours).
* Online filters (moving average, leaky bucket) run over the residuals r_k of the refinement steps INSIDE one
planning call (App. D); an episode stops at the first planning call that triggers. Time Saved = 1 - t_report /
T_total on OOD episodes, t_report = env step of that call; T_total = the episode horizon (paper: 300; LIBERO-Spatial
in LeRobot: 280); a never-triggered episode counts t_report = T_total (ours).
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
def auroc(neg: np.ndarray, pos: np.ndarray) -> float:
"""P(score_pos > score_neg) + 0.5 P(tie): the Mann-Whitney form of the area under the ROC curve."""
neg, pos = np.asarray(neg, float), np.asarray(pos, float)
allv = np.concatenate([neg, pos])
order = allv.argsort(kind="mergesort")
ranks = np.empty(len(allv))
sv = allv[order]
i = 0
while i < len(sv): # average ranks over ties
j = i
while j + 1 < len(sv) and sv[j + 1] == sv[i]:
j += 1
ranks[order[i:j + 1]] = (i + j) / 2 + 1
i = j + 1
r_pos = ranks[len(neg):].sum()
return float((r_pos - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
def auroc_weighted(neg, pos, w_neg, w_pos) -> float:
"""Weighted Mann-Whitney AUROC: sum over (pos, neg) pairs of w_pos w_neg [s_pos > s_neg] (+ half for ties)."""
neg, pos = np.asarray(neg, float), np.asarray(pos, float)
w_neg, w_pos = np.asarray(w_neg, float), np.asarray(w_pos, float)
o = np.argsort(neg, kind="mergesort")
sn, cw = neg[o], np.concatenate([[0.0], np.cumsum(w_neg[o])])
below = cw[np.searchsorted(sn, pos, side="left")]
equal = cw[np.searchsorted(sn, pos, side="right")] - below
return float((w_pos * (below + 0.5 * equal)).sum() / (w_pos.sum() * w_neg.sum()))
def operating_point(neg: np.ndarray, pos: np.ndarray, target_keep: float = 0.90) -> dict:
"""Threshold θ (flag if score > θ) whose ID retention is closest to target_keep; returns θ, keep, flag."""
neg, pos = np.asarray(neg, float), np.asarray(pos, float)
cands = np.unique(np.concatenate([neg, pos]))
keep = np.searchsorted(np.sort(neg), cands, side="right") / len(neg) # fraction of ID with score <= θ
k = int(np.abs(keep - target_keep).argmin())
th = float(cands[k])
return {"threshold": th, "id_kept": float((neg <= th).mean()), "ood_flagged": float((pos > th).mean())}
def load_scores(path: Path) -> tuple[str, list[np.ndarray]]:
"""Per-episode score sequences (the first score column) from one ood_scores.json."""
d = json.loads(Path(path).read_text())
calls = [c for c in d["calls"] if c[0] >= 0] # calls before the first reset() are not part of an episode
eps: dict[int, list[float]] = {}
for c in calls:
eps.setdefault(int(c[0]), []).append(float(c[1]))
return d["kind"], [np.asarray(eps[k]) for k in sorted(eps)]
def load_step_norms(path: Path) -> list[list[np.ndarray]] | None:
"""Per episode, per planning call: the residual norm after every refinement step (GeCO runs that recorded it)."""
d = json.loads(Path(path).read_text())
calls = [c for c in d["calls"] if c[0] >= 0]
if not calls or len(calls[0]) < 4:
return None
eps: dict[int, list[np.ndarray]] = {}
for c in calls:
eps.setdefault(int(c[0]), []).append(np.asarray(c[3], float))
return [eps[k] for k in sorted(eps)]
def sample_calls(episodes: list[np.ndarray], J: int = 20, seed: int = 0) -> list[np.ndarray]:
rng = np.random.default_rng(seed)
return [e if len(e) <= J else e[np.sort(rng.choice(len(e), J, replace=False))] for e in episodes]
def _equal_weight(eps):
return np.concatenate(eps), np.concatenate([np.full(len(e), 1.0 / len(e)) for e in eps])
def detection_table(id_eps: list[np.ndarray], ood_eps: list[np.ndarray], J: int = 20, n_boot: int = 2000,
seed: int = 0) -> dict:
"""AUROC on J sampled calls per episode (+ episode-bootstrap 95% CI, subsample redrawn each time), the 90%-retention
operating point, and the equal-weight-per-episode AUROC over all calls (+ CI)."""
ids, oods = sample_calls(id_eps, J, seed), sample_calls(ood_eps, J, seed + 1)
neg, pos = np.concatenate(ids), np.concatenate(oods)
(an, wn), (ap, wp) = _equal_weight(id_eps), _equal_weight(ood_eps)
out = {"auroc": auroc(neg, pos), "auroc_equal_weight": auroc_weighted(an, ap, wn, wp),
"n_id_calls": len(neg), "n_ood_calls": len(pos), "n_id_episodes": len(ids), "n_ood_episodes": len(oods),
**operating_point(neg, pos)}
rng = np.random.default_rng(seed + 2)
boots, boots_eq = [], []
for _ in range(n_boot):
bi = [id_eps[i] for i in rng.integers(0, len(id_eps), len(id_eps))]
bo = [ood_eps[i] for i in rng.integers(0, len(ood_eps), len(ood_eps))]
si, so = sample_calls(bi, J, int(rng.integers(1 << 30))), sample_calls(bo, J, int(rng.integers(1 << 30)))
boots.append(auroc(np.concatenate(si), np.concatenate(so)))
(bn, bwn), (bp, bwp) = _equal_weight(bi), _equal_weight(bo)
boots_eq.append(auroc_weighted(bn, bp, bwn, bwp))
out["auroc_ci95"] = (float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5)))
out["auroc_equal_weight_ci95"] = (float(np.percentile(boots_eq, 2.5)), float(np.percentile(boots_eq, 97.5)))
return out
def time_saved(eps_steps: list[list[np.ndarray]], rule, exec_steps: int = 10, T_total: int = 280) -> dict:
"""App. D online use. eps_steps: per episode, per planning call, the residuals r_k of that call's refinement steps.
rule(r) -> index or None flags a call; planning call j happens at env step j * exec_steps, and the episode stops at
the first flagged call. Returns mean Time Saved and the fraction of episodes stopped."""
saved, n_flag = [], 0
for calls in eps_steps:
j = next((j for j, r in enumerate(calls) if rule(r) is not None), None)
t = T_total if j is None else min(T_total, j * exec_steps)
n_flag += j is not None
saved.append(1.0 - t / T_total)
return {"time_saved": float(np.mean(saved)) if saved else float("nan"),
"episodes_flagged": n_flag / max(1, len(eps_steps))}
|