Download grader/grade.py from macrodata/pnw-subtask-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 21.5 kB
-
https://huggingface.co/datasets/macrodata/pnw-subtask-benchmark/resolve/main/grader/grade.py
- Command line
-
hf download hf://datasets/macrodata/pnw-subtask-benchmark/grader/grade.py
-
curl -L -o grade.py https://huggingface.co/datasets/macrodata/pnw-subtask-benchmark/resolve/main/grader/grade.py
21.5 kB
| #!/usr/bin/env -S uv run --script | |
| # /// script | |
| # requires-python = ">=3.9" | |
| # dependencies = ["numpy"] | |
| # /// | |
| """Standalone grader for the P&W subtask benchmark. Python 3.9+ and numpy only. | |
| uv run grade.py --gold gold/rollouts/ --pred predictions/seen-policy/ [--pred baselines/terra-zero-shot/ ...] | |
| [--tasks connect-dc-jack,...] [--split test|cross-validation] [--cohort rollout|demo] | |
| [--common] [--resamples 1000] [--seg-iou 0.8 | --seg-tol 1] [--out results.json] | |
| Files: every *.jsonl under each folder, one episode per line, in P&W's catalog field format: | |
| {"source": ..., "episode": ..., "task": ..., "subtasks": [{"startSec", "endSec", "label", "rating"}, ...], ...} | |
| Episodes are keyed by (source, episode). Gold lines may also carry "split" and "cohort"; --split / --cohort filter on | |
| the gold's values. A predicted line rates a segment "failed" or not; when "rating" is missing, pSuccess < 0.5 means failed. | |
| An episode is scored for a predictor when it is in the gold (after the filters) and in that predictor's files. | |
| With several --pred folders, deltas against the first are computed on the episodes all of them cover (paired), and | |
| --common scores every predictor on that common set only. | |
| Rules, applied identically to gold and predictions | |
| ------------------------------------------------- | |
| 1. Labels. P&W's two sort picks ("Pick up a single black screw from the table." and "... silver screw ...") are scored | |
| as one label, "Pick up a single screw from the table." (screw colour is not scored). --keep-colour turns this off. | |
| 2. Clean-up of each episode's list of segments, deterministic, in this order: | |
| a. segments with endSec <= startSec are dropped; | |
| b. segments are sorted by (startSec, endSec); ties keep the file's order; | |
| c. exact duplicates (same startSec, endSec and label) are dropped, keeping the first; | |
| d. each segment after the first starts where the previous one ends (startSec := previous endSec). This closes gaps | |
| (the following segment absorbs them) and resolves overlaps (the earlier segment keeps the overlapping time); | |
| a segment left with no time is dropped. | |
| Predictions are then clipped to the gold's span [first gold startSec, last gold endSec]. | |
| 3. Ratings. Gold "failed" counts as failed; "ok", "excellent" (and a missing rating) count as success. | |
| Metrics (pooled over the episodes of a task; the all-tasks row is the unweighted mean of the task values) | |
| ------------------------------------------------------------------------------------------------------- | |
| - seg-F1@IoU0.8 (segment F1): adjacent segments with the same label are merged into one run (on both sides). This is | |
| the standard MS-TCN segmental F1: each predicted run, in time order, claims the unclaimed gold run of the same label | |
| with the highest IoU; it is a true positive if that IoU >= 0.8, else a false positive; unclaimed gold runs are false | |
| negatives. F1 = 2TP / (2TP + FP + FN). --seg-iou sets a different IoU threshold (the result key keeps its name). | |
| - seg-F1@T s (--seg-tol T, replaces the IoU rule; the result key keeps its name): on the same merged runs, a predicted | |
| run and a gold run can match if they have the same label and both |start difference| and |end difference| are <= T | |
| seconds. Matching is one to one and greedy over all same-label pairs, smallest max(|start diff|, |end diff|) first | |
| (ties: lower gold index, then lower predicted index). TP = matched pairs, FP = unmatched predicted runs, FN = unmatched | |
| gold runs; F1 as above. This is the same rule as the internal "seg-F1@1 s" metric when T = 1. | |
| - Boundary error (s): the boundaries are the change points between consecutive merged runs (episode start and end are not | |
| boundaries). Gold and predicted boundaries are matched one to one, closest first, if within 2 s of each other (labels | |
| ignored). The metric is the mean absolute time difference of the matched pairs. "boundary recall" is the share of gold | |
| boundaries matched, reported beside it so that a low error from few matches is visible; "boundary precision" is the | |
| share of predicted boundaries matched to a gold boundary. | |
| - Failure F1 / precision / recall (attempt level): attempts are the cleaned segments, NOT merged (a retry is its own | |
| attempt). Predicted and gold attempts are matched one to one if they have the same label and IoU >= 0.5, greedily by | |
| IoU (ties: lower gold index, then lower predicted index). A predicted failed attempt matched to a gold failed attempt is | |
| a true positive; every other predicted failed attempt is a false positive; every other gold failed attempt is a false | |
| negative. | |
| Output | |
| ------ | |
| JSON on stdout (or --out FILE), with these top-level keys: | |
| - "results": {predictor folder: {task: {metric: {"value", "lo", "hi"}}, "all": {...}}}. Metrics: seg_f1_iou80 (segment | |
| F1 at the chosen --seg-iou or --seg-tol), boundary_err_s, boundary_recall, boundary_precision, failed_f1, failed_precision, | |
| failed_recall, plus "n" (episodes scored). F1, precision and recall are fractions in [0, 1]; boundary_err_s is in seconds. "lo"/"hi" are the 95% CI. | |
| - "deltas": {"<pred> - <first pred>": same layout}, paired differences on the common episodes (only with several --pred). | |
| - "results_common": same layout as "results", every predictor scored on the common episodes (with several --pred). | |
| - "coverage": {predictor: {task: {"gold", "scored", "common"}}}, episode counts per task. | |
| - "episodes": {task: n}, the episodes scored per task (the common set when deltas or --common apply). | |
| - "options": the settings used (tasks, split, cohort, resamples, seed, merge_labels, common, seg_iou or seg_tol). | |
| Examples | |
| -------- | |
| uv run grade.py --gold gold/rollouts --pred predictions/seen-policy --split test # our model, test rollouts | |
| uv run grade.py --gold gold/rollouts --pred predictions/seen-policy --pred baselines/terra-zero-shot --split test --common | |
| uv run grade.py --gold gold/rollouts --pred predictions/new-family # each family held out | |
| uv run grade.py --gold gold/rollouts --pred predictions/seen-policy --split test --seg-tol 1 --out tol1.json | |
| uv run test_grade.py # unit tests | |
| Confidence intervals: 95% percentile intervals from an episode bootstrap (--resamples draws, seeded per task), resampling | |
| episodes within each task. Deltas use the same draws for both predictors (paired), on the common episodes. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| import zlib | |
| from pathlib import Path | |
| import numpy as np | |
| SORT_PICKS = ("Pick up a single black screw from the table.", "Pick up a single silver screw from the table.") | |
| SORT_PICK = "Pick up a single screw from the table." | |
| LABEL_GROUPS = {SORT_PICKS[0]: SORT_PICK, SORT_PICKS[1]: SORT_PICK} | |
| SEG_IOU = 0.8 | |
| FAIL_IOU = 0.5 | |
| BOUNDARY_WINDOW = 2.0 | |
| TOL = 1e-6 | |
| METRICS = ("seg_f1_iou80", "boundary_err_s", "boundary_recall", "boundary_precision", "failed_f1", "failed_precision", "failed_recall") | |
| COUNTS = ("seg_tp", "seg_fp", "seg_fn", "b_err", "b_matched", "b_gold", "b_pred", "f_tp", "f_fp", "f_fn") | |
| def key(line: dict) -> tuple: | |
| return (line["source"], line["episode"]) | |
| def _failed(seg: dict, is_pred: bool) -> bool: | |
| rating = seg.get("rating") | |
| if rating is None and is_pred and seg.get("pSuccess") is not None: | |
| return float(seg["pSuccess"]) < 0.5 | |
| return rating == "failed" | |
| def normalise(subtasks: list, merge_labels: bool = True, is_pred: bool = False) -> list: | |
| """[(start, end, label, failed)] after rules 1-2d of the module docstring.""" | |
| rows = [] | |
| for i, s in enumerate(subtasks): | |
| a, b = float(s["startSec"]), float(s["endSec"]) | |
| if b - a <= TOL: | |
| continue | |
| label = LABEL_GROUPS.get(s["label"], s["label"]) if merge_labels else s["label"] | |
| rows.append((a, b, i, label, _failed(s, is_pred), s["label"])) | |
| rows.sort(key=lambda r: (r[0], r[1], r[2])) | |
| seen, out = set(), [] | |
| for a, b, _, label, failed, raw in rows: | |
| dup = (round(a, 6), round(b, 6), raw) | |
| if dup in seen: | |
| continue | |
| seen.add(dup) | |
| if out: | |
| a = out[-1][1] | |
| if b - a <= TOL: | |
| continue | |
| out.append((a, b, label, failed)) | |
| return out | |
| def clip(segs: list, lo: float, hi: float) -> list: | |
| out = [] | |
| for a, b, label, failed in segs: | |
| a, b = max(a, lo), min(b, hi) | |
| if b - a > TOL: | |
| out.append((a, b, label, failed)) | |
| return out | |
| def runs(segs: list) -> list: | |
| """Adjacent same-label segments merged: [(start, end, label, any failed)].""" | |
| out = [] | |
| for a, b, label, failed in segs: | |
| if out and out[-1][2] == label: | |
| out[-1] = (out[-1][0], b, label, out[-1][3] or failed) | |
| else: | |
| out.append((a, b, label, failed)) | |
| return out | |
| def _iou(x, y) -> float: | |
| inter = min(x[1], y[1]) - max(x[0], y[0]) | |
| if inter <= 0: | |
| return 0.0 | |
| return inter / (max(x[1], y[1]) - min(x[0], y[0])) | |
| def seg_counts(gold_runs: list, pred_runs: list, threshold: float = SEG_IOU) -> tuple: | |
| used = [False] * len(gold_runs) | |
| tp = fp = 0 | |
| for p in pred_runs: | |
| best, index = 0.0, -1 | |
| for i, g in enumerate(gold_runs): | |
| if g[2] == p[2] and not used[i]: | |
| v = _iou(g, p) | |
| if v > best: | |
| best, index = v, i | |
| if index >= 0 and best >= threshold - TOL: | |
| used[index] = True | |
| tp += 1 | |
| else: | |
| fp += 1 | |
| return tp, fp, used.count(False) | |
| def seg_counts_tol(gold_runs: list, pred_runs: list, tol: float) -> tuple: | |
| pairs = sorted((max(abs(g[0] - p[0]), abs(g[1] - p[1])), i, j) | |
| for i, g in enumerate(gold_runs) for j, p in enumerate(pred_runs) if g[2] == p[2]) | |
| gi, pj = set(), set() | |
| for d, i, j in pairs: | |
| if d > tol + TOL: | |
| break | |
| if i not in gi and j not in pj: | |
| gi.add(i) | |
| pj.add(j) | |
| return len(gi), len(pred_runs) - len(gi), len(gold_runs) - len(gi) | |
| def boundary_errors(gold_runs: list, pred_runs: list, window: float = BOUNDARY_WINDOW) -> tuple: | |
| """(matched absolute errors, number of gold boundaries, number of predicted boundaries).""" | |
| g = [r[1] for r in gold_runs[:-1]] | |
| p = [r[1] for r in pred_runs[:-1]] | |
| pairs = sorted((abs(x - y), i, j) for i, x in enumerate(g) for j, y in enumerate(p) if abs(x - y) <= window + TOL) | |
| gi, pj, errors = set(), set(), [] | |
| for d, i, j in pairs: | |
| if i not in gi and j not in pj: | |
| gi.add(i) | |
| pj.add(j) | |
| errors.append(d) | |
| return errors, len(g), len(p) | |
| def match_attempts(pred: list, gold: list, threshold: float = FAIL_IOU) -> list: | |
| pairs = sorted((-_iou(p, g), j, i) for i, p in enumerate(pred) for j, g in enumerate(gold) if p[2] == g[2] and _iou(p, g) >= threshold - TOL) | |
| up, ug, out = set(), set(), [] | |
| for _, j, i in pairs: | |
| if i not in up and j not in ug: | |
| up.add(i) | |
| ug.add(j) | |
| out.append((i, j)) | |
| return out | |
| def episode_counts(gold_line: dict, pred_line: dict, merge_labels: bool = True, seg_iou: float = SEG_IOU, seg_tol: float | None = None) -> dict: | |
| gold = normalise(gold_line["subtasks"], merge_labels) | |
| if not gold: | |
| return None | |
| pred = clip(normalise(pred_line["subtasks"], merge_labels, is_pred=True), gold[0][0], gold[-1][1]) | |
| gr, pr = runs(gold), runs(pred) | |
| tp, fp, fn = seg_counts(gr, pr, seg_iou) if seg_tol is None else seg_counts_tol(gr, pr, seg_tol) | |
| errors, n_gold_b, n_pred_b = boundary_errors(gr, pr) | |
| flagged = [i for i, a in enumerate(pred) if a[3]] | |
| failed = {j for j, a in enumerate(gold) if a[3]} | |
| hits = sum(1 for i, j in match_attempts(pred, gold) if pred[i][3] and j in failed) | |
| return {"seg_tp": tp, "seg_fp": fp, "seg_fn": fn, "b_err": float(sum(errors)), "b_matched": len(errors), "b_gold": n_gold_b, "b_pred": n_pred_b, | |
| "f_tp": hits, "f_fp": len(flagged) - hits, "f_fn": len(failed) - hits} | |
| def _ratio(a, b): | |
| a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float) | |
| with np.errstate(divide="ignore", invalid="ignore"): | |
| return np.where(b > 0, a / np.where(b > 0, b, 1), np.nan) | |
| def metrics_of(c: np.ndarray) -> dict: | |
| """c: [..., len(COUNTS)] summed counts -> {metric: array}.""" | |
| k = {name: c[..., i] for i, name in enumerate(COUNTS)} | |
| return {"seg_f1_iou80": _ratio(2 * k["seg_tp"], 2 * k["seg_tp"] + k["seg_fp"] + k["seg_fn"]), | |
| "boundary_err_s": _ratio(k["b_err"], k["b_matched"]), | |
| "boundary_recall": _ratio(k["b_matched"], k["b_gold"]), | |
| "boundary_precision": _ratio(k["b_matched"], k["b_pred"]), | |
| "failed_f1": _ratio(2 * k["f_tp"], 2 * k["f_tp"] + k["f_fp"] + k["f_fn"]), | |
| "failed_precision": _ratio(k["f_tp"], k["f_tp"] + k["f_fp"]), | |
| "failed_recall": _ratio(k["f_tp"], k["f_tp"] + k["f_fn"])} | |
| def _draws(task: str, n: int, resamples: int, seed: int) -> np.ndarray: | |
| rng = np.random.default_rng([seed, zlib.crc32(task.encode())]) | |
| return rng.integers(0, n, size=(resamples, n)) | |
| def _summary(point: float, draws) -> dict: | |
| out = {"value": None if point is None or np.isnan(point) else float(point)} | |
| if draws is not None: | |
| d = np.asarray(draws, dtype=float) | |
| d = d[~np.isnan(d)] | |
| out["lo"] = float(np.percentile(d, 2.5)) if len(d) else None | |
| out["hi"] = float(np.percentile(d, 97.5)) if len(d) else None | |
| return out | |
| def grade_lines(gold_lines: list, preds: dict, tasks: list | None = None, split: str | None = None, cohort: str | None = None, | |
| resamples: int = 1000, seed: int = 0, merge_labels: bool = True, common: bool = False, seg_iou: float = SEG_IOU, | |
| seg_tol: float | None = None) -> dict: | |
| """preds: {name: [lines]}, the first is the reference for deltas. Returns {"coverage", "results": {name: {task: {metric: {value, lo, hi}}, "all": ...}}, | |
| "deltas": {name: {task: {metric: ...}}}, "episodes"}.""" | |
| gold = {} | |
| for x in gold_lines: | |
| if tasks and x["task"] not in tasks: | |
| continue | |
| if split and x.get("split") != split: | |
| continue | |
| if cohort and x.get("cohort") != cohort: | |
| continue | |
| if key(x) in gold: | |
| raise ValueError(f"duplicate gold episode {key(x)}") | |
| gold[key(x)] = x | |
| by_pred = {} | |
| for name, lines in preds.items(): | |
| d = {} | |
| for x in lines: | |
| if key(x) in d: | |
| raise ValueError(f"{name}: duplicate predicted episode {key(x)}") | |
| d[key(x)] = x | |
| by_pred[name] = d | |
| names = list(by_pred) | |
| task_list = sorted({x["task"] for x in gold.values()}) | |
| common_keys = {t: sorted(k for k, x in gold.items() if x["task"] == t and all(k in by_pred[n] for n in names)) for t in task_list} | |
| out = {"coverage": {}, "results": {}, "deltas": {}, "episodes": {}, "options": {"tasks": tasks, "split": split, "cohort": cohort, "resamples": resamples, | |
| "seed": seed, "merge_labels": merge_labels, "common": common, | |
| "seg_iou": seg_iou}} | |
| if seg_tol is not None: | |
| out["options"]["seg_tol"] = seg_tol | |
| counts_cache = {} | |
| def counts(name, keys): | |
| rows = [] | |
| for k in keys: | |
| ck = (name, k) | |
| if ck not in counts_cache: | |
| c = episode_counts(gold[k], by_pred[name][k], merge_labels, seg_iou, seg_tol) | |
| counts_cache[ck] = None if c is None else [c[n] for n in COUNTS] | |
| if counts_cache[ck] is not None: | |
| rows.append(counts_cache[ck]) | |
| return np.asarray(rows, dtype=float).reshape(-1, len(COUNTS)) | |
| def score(name, keys_by_task): | |
| res, draws_by_task = {}, {} | |
| for t in task_list: | |
| keys = keys_by_task[t] | |
| c = counts(name, keys) | |
| if not len(c): | |
| continue | |
| point = metrics_of(c.sum(0)) | |
| draws = None | |
| if resamples: | |
| idx = _draws(t, len(c), resamples, seed) | |
| draws = metrics_of(c[idx].sum(1)) | |
| draws_by_task[t] = draws | |
| res[t] = {m: _summary(point[m], None if draws is None else draws[m]) for m in METRICS} | |
| res[t]["n"] = len(c) | |
| if res: | |
| res["all"] = {m: _summary(float(np.nanmean([res[t][m]["value"] if res[t][m]["value"] is not None else np.nan for t in res])), | |
| np.nanmean(np.stack([draws_by_task[t][m] for t in draws_by_task]), axis=0) if resamples and draws_by_task else None) for m in METRICS} | |
| res["all"]["n"] = sum(res[t]["n"] for t in task_list if t in res) | |
| res["all"]["tasks"] = sum(1 for t in task_list if t in res) | |
| return res, draws_by_task | |
| for name in names: | |
| own = {t: sorted(k for k, x in gold.items() if x["task"] == t and k in by_pred[name]) for t in task_list} | |
| out["coverage"][name] = {t: {"gold": sum(1 for x in gold.values() if x["task"] == t), "scored": len(own[t]), "common": len(common_keys[t])} for t in task_list} | |
| out["results"][name], _ = score(name, common_keys if common else own) | |
| out["episodes"] = {t: len(common_keys[t]) for t in task_list} | |
| if len(names) > 1: | |
| ref_point = {} | |
| ref_draws = {} | |
| for name in names: | |
| res, dr = score(name, common_keys) | |
| ref_point[name], ref_draws[name] = res, dr | |
| base = names[0] | |
| for name in names[1:]: | |
| delta = {} | |
| for t in task_list: | |
| if t not in ref_point[name] or t not in ref_point[base]: | |
| continue | |
| delta[t] = {} | |
| for m in METRICS: | |
| a, b = ref_point[name][t][m]["value"], ref_point[base][t][m]["value"] | |
| d = None if a is None or b is None else a - b | |
| dd = (ref_draws[name][t][m] - ref_draws[base][t][m]) if resamples else None | |
| delta[t][m] = _summary(np.nan if d is None else d, dd) | |
| delta[t]["n"] = ref_point[name][t]["n"] | |
| if delta: | |
| ts = [t for t in task_list if t in delta] | |
| delta["all"] = {} | |
| for m in METRICS: | |
| vals = [delta[t][m]["value"] for t in ts if delta[t][m]["value"] is not None] | |
| dd = np.nanmean(np.stack([ref_draws[name][t][m] - ref_draws[base][t][m] for t in ts]), axis=0) if resamples else None | |
| delta["all"][m] = _summary(float(np.mean(vals)) if vals else np.nan, dd) | |
| delta["all"]["n"] = sum(delta[t]["n"] for t in ts) | |
| out["deltas"][f"{name} - {base}"] = delta | |
| out["results_common"] = {n: ref_point[n] for n in names} | |
| return out | |
| def read_folder(path: str) -> list: | |
| p = Path(path) | |
| files = sorted(p.rglob("*.jsonl")) if p.is_dir() else [p] | |
| lines = [] | |
| for f in files: | |
| with open(f) as fh: | |
| lines += [json.loads(x) for x in fh if x.strip()] | |
| return lines | |
| def _fmt(s: dict, metric: str) -> str: | |
| if s.get("value") is None: | |
| return "-" | |
| scale, digits = (1, 2) if metric == "boundary_err_s" else (100, 1) | |
| v = f"{s['value'] * scale:.{digits}f}" | |
| if s.get("lo") is not None: | |
| v += f" [{s['lo'] * scale:.{digits}f}, {s['hi'] * scale:.{digits}f}]" | |
| return v | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--gold", required=True) | |
| ap.add_argument("--pred", required=True, action="append", help="a predictions folder or file; repeat to compare (deltas against the first)") | |
| ap.add_argument("--tasks", default="", help="comma-separated task names (default: all in the gold)") | |
| ap.add_argument("--split", default=None, help="test or cross-validation (the gold's split field)") | |
| ap.add_argument("--cohort", default=None, help="rollout or demo (the gold's cohort field)") | |
| ap.add_argument("--common", action="store_true", help="score every predictor on the episodes all of them cover") | |
| ap.add_argument("--resamples", type=int, default=1000) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--seg-iou", type=float, default=SEG_IOU, help="IoU threshold for segment F1 (default 0.8)") | |
| ap.add_argument("--seg-tol", type=float, default=None, metavar="SECONDS", | |
| help="segment F1 with a boundary tolerance in seconds instead of the IoU rule (see the docstring)") | |
| ap.add_argument("--keep-colour", action="store_true", help="score the black and silver sort picks as different labels") | |
| ap.add_argument("--out", default=None, help="write the JSON results to this file instead of stdout") | |
| a = ap.parse_args(argv) | |
| preds = {p.rstrip("/"): read_folder(p) for p in a.pred} | |
| res = grade_lines(read_folder(a.gold), preds, [t for t in a.tasks.split(",") if t] or None, a.split, a.cohort, a.resamples, a.seed, not a.keep_colour, a.common, a.seg_iou, a.seg_tol) | |
| text = json.dumps(res, indent=1) | |
| if a.out: | |
| Path(a.out).write_text(text + "\n") | |
| else: | |
| print(text) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |