File size: 4,782 Bytes
b26bdfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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.
  * 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 (ours).
  * Time Saved = 1 - t_report / T_total on OOD episodes, t_report = env step of the first filter trigger,
    T_total = 300 as in the paper; 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 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 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 detection_table(id_eps: list[np.ndarray], ood_eps: list[np.ndarray], J: int = 20, n_boot: int = 2000,
                    seed: int = 0) -> dict:
    """AUROC (+ episode-bootstrap 95% CI) and the 90%-retention operating point on J sampled calls per episode."""
    ids, oods = sample_calls(id_eps, J, seed), sample_calls(ood_eps, J, seed + 1)
    neg, pos = np.concatenate(ids), np.concatenate(oods)
    out = {"auroc": auroc(neg, pos), "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 = []
    for _ in range(n_boot):
        bi = rng.integers(0, len(ids), len(ids))
        bo = rng.integers(0, len(oods), len(oods))
        boots.append(auroc(np.concatenate([ids[i] for i in bi]), np.concatenate([oods[i] for i in bo])))
    out["auroc_ci95"] = (float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5)))
    return out


def time_saved(ood_eps: list[np.ndarray], first_flag, exec_steps: int = 10, T_total: int = 300) -> dict:
    """Online use: call k happens at env step k * exec_steps; an episode is stopped at the first flagged call."""
    saved, n_flag = [], 0
    for e in ood_eps:
        k = first_flag(e)
        t = T_total if k is None else min(T_total, k * exec_steps)
        n_flag += k 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(ood_eps))}