Download source/scripts/wrong_answers.py from rca-umb/five-desks-control: direct link, hf CLI and curl.
- Browser
- Download file 7.52 kB
-
https://huggingface.co/datasets/rca-umb/five-desks-control/resolve/main/source/scripts/wrong_answers.py
- Command line
-
hf download hf://datasets/rca-umb/five-desks-control/source/scripts/wrong_answers.py
-
curl -L -o wrong_answers.py https://huggingface.co/datasets/rca-umb/five-desks-control/resolve/main/source/scripts/wrong_answers.py
7.52 kB
| """How exactly does the untrained model get Five Desks tasks wrong? Rebuild each calibration episode from its seed and | |
| compare the model's final answer with the correct answer and with the planted trap (the answer you get if you miss the | |
| caveat). Only episodes whose first observation matches the rebuilt instance are used. | |
| Usage: .venv/bin/python scripts/wrong_answers.py [glob of episodes.jsonl ...] > reports/wrong-answers/diligence.txt | |
| """ | |
| import collections | |
| import glob | |
| import json | |
| import math | |
| import random | |
| import sys | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| sys.path.insert(0, str(ROOT / "scripts")) | |
| from calibrate import first_json_object # noqa: E402 | |
| from diligence.environment import build, describe # noqa: E402 | |
| from diligence.interface import Interface # noqa: E402 | |
| FORMAT_ENDS = {"json_plus_text", "no_json", "code_fence", "not_object", "empty", "truncated", "budget"} | |
| DEFAULT = ["reports/calibration-v4a/*/episodes.jsonl", "reports/calibration-v2/*/episodes.jsonl", | |
| "reports/calibration-v2-draft/*/episodes.jsonl"] | |
| def same(a, b, rel=1e-3): | |
| if isinstance(a, bool) or isinstance(b, bool): | |
| return a == b | |
| try: | |
| fa, fb = float(a), float(b) | |
| return math.isclose(fa, fb, rel_tol=rel, abs_tol=1e-6) | |
| except (TypeError, ValueError): | |
| return str(a).strip().lower() == str(b).strip().lower() | |
| def flat(d, prefix=""): | |
| out = {} | |
| for k, v in (d or {}).items(): | |
| if isinstance(v, dict): | |
| out.update(flat(v, prefix + k + ".")) | |
| else: | |
| out[prefix + k] = v | |
| return out | |
| def classify(model_args, oracle_args, naive_args): | |
| m, o, n = flat(model_args), flat(oracle_args), flat(naive_args) | |
| if not m: | |
| return "empty answer" | |
| missing = [k for k in o if k not in m] | |
| if missing and len(missing) == len(o): | |
| return "wrong answer shape (fields renamed or nested differently)" | |
| wrong = [k for k in o if k in m and not same(m[k], o[k])] | |
| if not wrong and not missing: | |
| return "correct fields (graded wrong for another reason)" | |
| trap = [k for k in wrong if k in n and same(m[k], n[k]) and not same(n[k], o[k])] | |
| if trap and len(trap) == len(wrong): | |
| return "trap answer (missed the caveat)" | |
| if trap: | |
| return "partly trap (missed the caveat in some fields, other fields also off)" | |
| near = [] | |
| for k in wrong: | |
| try: | |
| near.append(abs(float(m[k]) - float(o[k])) <= 0.05 * max(1e-9, abs(float(o[k])))) | |
| except (TypeError, ValueError): | |
| near.append(False) | |
| if near and all(near): | |
| return "near miss (numbers within 5%)" | |
| if missing: | |
| return "missing fields" | |
| return "other wrong value" | |
| def main(): | |
| patterns = sys.argv[1:] or DEFAULT | |
| rows = [] | |
| for pattern in patterns: | |
| for f in sorted(glob.glob(str(ROOT / pattern))): | |
| for line in open(f): | |
| ep = json.loads(line) | |
| if "seed" not in ep or not ep.get("turns"): | |
| continue | |
| try: | |
| task = build(ep["task_id"], ep["seed"]) | |
| except ValueError: | |
| continue | |
| iface = Interface(task.tools(), random.Random(f"names:{ep['task_id']}:{ep['seed']}")) | |
| brief = describe(task, False, iface)[:300] | |
| first = json.loads(ep["turns"][0]["obs"]).get("output", "") if ep["turns"][0]["obs"].startswith("{") else "" | |
| if brief[:200] not in first and describe(task, True, iface)[:200] not in first: | |
| rows.append({"task_id": ep["task_id"], "status": "instance changed since this run"}) | |
| continue | |
| final_tool = task.oracle()[-1]["tool"] | |
| back = {new: old for old, new in iface.tool_names.items()} | |
| actions = [] | |
| for t in ep["turns"]: | |
| obj = first_json_object(t["reply"]) or {} | |
| if isinstance(obj.get("action"), dict) and len(obj) == 1: | |
| obj = obj["action"] | |
| actions.append((back.get(str(obj.get("tool", "")).strip(), obj.get("tool")), obj.get("args") or {})) | |
| opened = set() | |
| for tool, args in actions: | |
| for v in args.values(): | |
| if isinstance(v, str) and v in task.files: | |
| opened.add(v) | |
| answered = [a for tool, a in actions if tool == final_tool and a] | |
| row = {"task_id": ep["task_id"], "family": task_family(ep["task_id"]), "reward": ep["reward"], | |
| "end": ep.get("end"), "turns": len(ep["turns"]), "files": len(task.files), "opened": len(opened)} | |
| oracle_args = task.oracle()[-1]["args"] | |
| verdict = (classify(answered[-1], oracle_args, task.naive()[-1]["args"]) | |
| if answered and oracle_args else None) | |
| if ep["reward"] >= 0.999: | |
| row["status"] = "solved" | |
| elif ep.get("end") in FORMAT_ENDS: | |
| good = verdict and verdict.startswith("correct fields") | |
| row["status"] = ("format ending, the answer inside was right" if good | |
| else f"format ending ({ep.get('end')})") | |
| elif ep.get("end") == "schema_invalid": | |
| row["status"] = "action rejected by the schema (wrong argument shape)" | |
| elif ep.get("end") == "out_of_steps": | |
| row["status"] = "ran out of tool calls" | |
| elif not oracle_args: | |
| row["status"] = "work graded wrong (edit tasks: no answer to compare)" | |
| elif not answered: | |
| row["status"] = f"no answer submitted ({ep.get('end')})" | |
| else: | |
| row["status"] = verdict | |
| rows.append(row) | |
| report(rows) | |
| def task_family(task_id): | |
| return task_id.rpartition("-l")[0] | |
| def report(rows): | |
| used = [r for r in rows if r["status"] != "instance changed since this run"] | |
| print(f"episodes rebuilt: {len(used)} (skipped {len(rows) - len(used)} whose instance changed)\n") | |
| print("All wrong episodes:") | |
| wrong = [r for r in used if r["status"] != "solved"] | |
| for k, v in collections.Counter(r["status"] for r in wrong).most_common(): | |
| print(f" {k:70s} {v:4d} {v/len(wrong):.0%}") | |
| print("\nBy family (share of that family's wrong episodes):") | |
| for fam in sorted({r["family"] for r in used}): | |
| F = [r for r in used if r["family"] == fam] | |
| W = [r for r in F if r["status"] != "solved"] | |
| if not W: | |
| continue | |
| top = ", ".join(f"{k} {v/len(W):.0%}" for k, v in collections.Counter(r["status"] for r in W).most_common(4)) | |
| print(f" {fam:20s} solved {len(F)-len(W)}/{len(F)} wrong: {top}") | |
| print("\nFiles opened before answering (families with files):") | |
| for status in ["solved", "trap answer (missed the caveat)", "other wrong value", "near miss (numbers within 5%)"]: | |
| R = [r for r in used if r["status"] == status and r["files"]] | |
| if R: | |
| print(f" {status:40s} {sum(r['opened'] for r in R)/sum(r['files'] for r in R):.0%} of files, " | |
| f"{sum(r['opened'] == r['files'] for r in R)}/{len(R)} opened all; median turns " | |
| f"{sorted(r['turns'] for r in R)[len(R)//2]}") | |
| if __name__ == "__main__": | |
| main() | |