Download decision_test/score.py from GammaRobotics/ActiveMoMa-Data: direct link, hf CLI and curl.
- Browser
- Download file 7.88 kB
-
https://huggingface.co/datasets/GammaRobotics/ActiveMoMa-Data/resolve/main/decision_test/score.py
- Command line
-
hf download hf://datasets/GammaRobotics/ActiveMoMa-Data/decision_test/score.py
-
curl -L -o score.py https://huggingface.co/datasets/GammaRobotics/ActiveMoMa-Data/resolve/main/decision_test/score.py
7.88 kB
| #!/usr/bin/env python3 | |
| """Score replies on the decision test: at each failure state, does the reply retry the failed target or replan? | |
| python3 score.py replies/activemoma.jsonl one file of replies | |
| python3 score.py replies/*.jsonl several, one row each | |
| python3 score.py replies/*.jsonl --by-task also per task | |
| A file of replies has one JSON object per line, {"id": <state id>, "reply": <the model's reply as text>}, for all 154 | |
| states of states.jsonl. Only the Python standard library is needed. | |
| A reply is judged by its first tool call, <tool_call>{"name": ..., "arguments": {...}}</tool_call>, against the target X | |
| of the failed call (Appendix B.2 of the paper): | |
| retry approach, pick or place on X again, with arguments the skill takes and values in their ranges; | |
| replan a call that leaves X: approach, pick, place, find or search of another object; a find or search of X's | |
| name whose other_than passes over X itself (another object of that name); a release of the held object | |
| when X was where it was to go; | |
| other anything else: no call, go_to, done, a find or search of X itself, a call on X that cannot be run, a | |
| call on another name of the same fixture. | |
| The replan rate is the share of replies that replan, taken at the states whose verdict is unrecoverable (no executed | |
| retry passed) and at those whose verdict is recoverable (an executed retry passed); the selectivity J is their | |
| difference in points. States without a verdict are not scored. | |
| """ | |
| import argparse, json, math | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| SUBJECT = {"approach": "object_name", "pick": "object_name", "place": "target_name"} | |
| # the arguments each skill takes besides its target, with the range of values a call may use (None: a name) | |
| RANGES = {"approach": {"distance": (0.2, 1.5), "angle": (-180.0, 180.0), "support": None, "standoff": (0.05, 1.0), "shift": (-1.0, 1.0)}, | |
| "pick": {"grasp": (0, 9)}, | |
| "place": {"height": (-0.3, 0.6), "top": (0.0, 2.5), "beyond": (-1.0, 1.0), "sideways": (-1.0, 1.0)}} | |
| LOOKS = ("find", "search") | |
| PASS_OVER_M = {True: 1.0, False: 0.15} # radius within which other_than passes over a fixture, or a small object | |
| def call_of(text): | |
| """the first tool call of a reply, or None""" | |
| start = (text or "").find("<tool_call>") | |
| if start < 0: | |
| return None | |
| try: | |
| call, _ = json.JSONDecoder().raw_decode(text[start + len("<tool_call>"):].lstrip()) | |
| except ValueError: | |
| return None | |
| return call if isinstance(call, dict) else None | |
| def runnable(name, args): | |
| """a call on X that can be executed as a retry: known arguments, values in range""" | |
| if any(a != SUBJECT[name] and a not in RANGES[name] for a in args): | |
| return False | |
| for arg, value in args.items(): | |
| if arg == SUBJECT[name] or value is None: | |
| continue | |
| bounds = RANGES[name][arg] | |
| if bounds is None: | |
| if not isinstance(value, str): | |
| return False | |
| elif not (isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and bounds[0] <= value <= bounds[1]): | |
| return False | |
| return True | |
| def passes_over(other_than, state): | |
| """whether a find or search of X's name with this other_than looks for another object of that name""" | |
| pos = state.get("target_position") | |
| if not other_than or pos is None: | |
| return False | |
| try: | |
| rows = other_than if isinstance(other_than[0], (list, tuple)) else [other_than] | |
| pts = [(float(p[0]), float(p[1])) for p in rows if isinstance(p, (list, tuple)) and len(p) in (2, 3)] | |
| except Exception: | |
| return False | |
| radius = PASS_OVER_M[bool(state["target_is_fixture"])] | |
| return any(math.hypot(px - float(pos[0]), py - float(pos[1])) <= radius + 1e-9 for px, py in pts) | |
| def judge(state, reply): | |
| """retry, replan or other""" | |
| call = call_of(reply) | |
| if not isinstance(call, dict) or not isinstance(call.get("name"), str): | |
| return "other" | |
| name, args = call["name"], call.get("arguments", {}) | |
| if not isinstance(args, dict): | |
| return "other" | |
| x, same_fixture = state["target"], set(state["other_names_of_target"]) | |
| if name in SUBJECT: | |
| target = args.get(SUBJECT[name]) | |
| if target == x: | |
| return "retry" if runnable(name, args) else "other" | |
| if not isinstance(target, str) or not target or target in same_fixture: | |
| return "other" | |
| if any(a != SUBJECT[name] and a not in RANGES[name] for a in args): | |
| return "other" | |
| return "replan" | |
| if name in LOOKS: | |
| target = args.get("object_name") | |
| if not isinstance(target, str) or not target: | |
| return "other" | |
| if target != x: | |
| return "other" if target in same_fixture else "replan" | |
| return "replan" if passes_over(args.get("other_than"), state) else "other" | |
| if name == "release": | |
| return "replan" if state["target_is_where_the_held_object_goes"] else "other" | |
| return "other" | |
| def load_states(path): | |
| return {s["id"]: s for s in map(json.loads, Path(path).read_text(encoding="utf-8").splitlines()) if s} | |
| def load_kinds(path, states): | |
| rows = {r["id"]: r["reply"] for r in map(json.loads, Path(path).read_text(encoding="utf-8").splitlines())} | |
| missing = set(states) - set(rows) | |
| if missing: | |
| raise SystemExit(f"{path}: {len(missing)} of {len(states)} states have no reply (first: {sorted(missing)[0]})") | |
| return {i: judge(states[i], rows[i]) for i in states} | |
| def rates(kinds, states, ids): | |
| u = [i for i in ids if states[i]["verdict"] == "unrecoverable"] | |
| r = [i for i in ids if states[i]["verdict"] == "recoverable"] | |
| nu, nr = sum(kinds[i] == "replan" for i in u), sum(kinds[i] == "replan" for i in r) | |
| return nu / max(len(u), 1), nr / max(len(r), 1), nu, len(u), nr, len(r) | |
| def row(name, kinds, states, ids): | |
| pu, pr, nu, tu, nr, tr = rates(kinds, states, ids) | |
| judged = [i for i in ids if states[i]["verdict"]] | |
| retry = sum(kinds[i] == "retry" for i in judged) / max(len(judged), 1) | |
| return f"{name:38s} {nu:3d}/{tu:<3d} {100 * pu:5.1f}% {nr:3d}/{tr:<3d} {100 * pr:5.1f}% {100 * (pu - pr):6.1f} {100 * retry:5.1f}%" | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("replies", nargs="*", help="files of replies") | |
| ap.add_argument("--states", default=str(HERE / "states.jsonl")) | |
| ap.add_argument("--by-task", action="store_true", help="also one block per task") | |
| ap.add_argument("--unseen-scenes", action="store_true", help="only the 82 states whose scenes are in no training data") | |
| args = ap.parse_args() | |
| states = load_states(args.states) | |
| ids = sorted(i for i in states if not args.unseen_scenes or states[i]["scene_in_no_training_data"]) | |
| n = lambda v: sum(states[i]["verdict"] == v for i in ids) | |
| print(f"states {len(ids)}: unrecoverable {n('unrecoverable')}, recoverable {n('recoverable')}, no verdict {n(None)}") | |
| head = f"{'replies':38s} {'replans at unrecoverable':>15s} {'at recoverable':>16s} {'J (points)':>10s} {'retries':>9s}" | |
| files = list(args.replies) | |
| kinds = {f: load_kinds(f, states) for f in files} | |
| if args.replies: | |
| print(head) | |
| for f in args.replies: | |
| print(row(Path(f).stem, kinds[f], states, ids)) | |
| if args.by_task: | |
| for task in sorted({states[i]["task"] for i in ids}): | |
| sub = [i for i in ids if states[i]["task"] == task] | |
| print(f"\n{task} ({len(sub)} states)\n{head}") | |
| for f in args.replies: | |
| print(row(Path(f).stem, kinds[f], states, sub)) | |
| if __name__ == "__main__": | |
| main() | |