#!/usr/bin/env python3 """Offline capability probes mined from the agent traces. Before training anything we want to know *which* capability a candidate base model is missing, because the trace analysis showed the teacher agents are not uniformly good: they drive a messy environment well and recover from failures without help, but 98 of 99 runs chose between candidates on a single noisy measurement and almost none ran a controlled ablation. That split dictates where each probe's gold answer comes from: teacher-gold capabilities the teachers demonstrably have. The reference answer is what the teacher actually did next, and a model is scored on agreeing with it. statistics-gold capabilities the teachers lack. Imitating them would teach the mistake, so the reference answer is computed from the numbers instead, and the teacher's own choice is recorded alongside as a baseline to beat. Probes implemented here: P1 error recovery teacher-gold, multiple choice over a fixed label set. A command failed and its output is shown; what kind of move does it call for? An earlier version offered the teacher's literal next command against commands from other runs, and it was trivially gameable: the real recovery is usually a re-run of the same script with one flag changed, so "pick the option that looks most like the failed command" solved it without reading the error at all. Classifying the recovery into a label shared by every option removes that leak -- all choices are equally plausible on surface form, and only the error text distinguishes them. P2 noise judgment statistics-gold. Two measurements at a known sample size; is the difference real? Computed with a two-proportion z-test. This is the capability the teachers were worst at, so it is also the one where a small model could plausibly match them cheaply. python analysis/probe_suite.py # writes analysis/out/probes/ python analysis/probe_suite.py --stats # composition only, no files """ from __future__ import annotations import argparse import json import math import os import random import re import sys from collections import Counter, defaultdict sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from run_analysis import AGENT_ROOTS, OUT_DIR # noqa: E402 from trace_analysis.features import extract # noqa: E402 from trace_analysis.narrative import _error_kind # noqa: E402 from trace_analysis.parse import Run, load_all # noqa: E402 # Deterministic: the suite must be identical on every regeneration, or scores # from different days are not comparable. Seeded locally, never from the clock. RNG_SEED = 20261019 MAX_CMD_CHARS = 1200 MAX_OUT_CHARS = 1600 def _trim(text: str, limit: int, tail: bool = False) -> str: text = (text or "").strip() if len(text) <= limit: return text return ("…" + text[-limit:]) if tail else (text[:limit] + "…") def error_bucket(kind: str) -> str: """Coarse failure class, used to keep distractors off the same kind.""" k = kind.lower() if "oom" in k: return "oom" if "missing package" in k: return "missing_package" if "network" in k: return "network_blocked" if "disk" in k: return "disk_full" if "exception" in k: return "exception" return "tool_error" # --- P1: error recovery ----------------------------------------------------- # What a recovery *does*, independent of how it is spelled. Derived from the # moves actually observed in the traces, and assigned by diffing the failed # command against the one that followed it. RECOVERY_LABELS = { "reduce_memory_footprint": "Re-run the same job with a smaller memory footprint (smaller batch, shorter sequences, gradient accumulation or checkpointing, a different allocator setting).", "free_gpu": "Leave the job alone and first reclaim the GPU: kill or wait out the process still holding memory, then check it is actually free.", "work_around_offline": "Stop trying to fetch the missing resource and substitute a local one (vendor a vocabulary, shim a module, point at the prefilled cache).", "fix_code_defect": "Edit the script that raised: the error is a bug in the agent's own code, not a resource or environment problem.", "inspect_further": "Do not act yet; read more first (open the log, the source, or the data) to find out what actually failed.", "retry_unchanged": "Run the same thing again unchanged, treating the failure as transient.", "background_the_job": "The job is simply long, not broken: detach it and poll, instead of letting the foreground call time out again.", "change_approach": "Abandon this route and do something structurally different instead.", } _MEM_FLAGS = re.compile(r"batch[_-]?size|per_device_train_batch|--bs\b|grad[_-]?accum|gradient_accumulation|gradient_checkpointing|max[_-]?seq|max[_-]?len|block[_-]?size|expandable_segments|gpu[_-]?memory[_-]?utilization|--rank\b|lora[_-]?r\b|max[-_]?connections", re.I) # Freeing the GPU means *acting* on the process holding it. A bare # `nvidia-smi` or `pgrep` is an observation -- the agents poll with those # constantly -- and labelling those as "free the GPU" put 131 routine status # checks into that class before this was tightened. # The kill has to be in command position. Matching `kill` anywhere in the text # put a HumanEval-adjacent safety-keyword scan ("kill myself") into this class. _FREE_GPU = re.compile( # `pkill`/`fuser` are unambiguous; bare `kill` must be followed by a # signal, a pid, or a substitution -- otherwise `|kill myself|` inside a # quoted regex reads as command position. r"\b(pkill|fuser)\b(?!\s*-0)|(?:^|[;&|]\s*|\$\(\s*)kill\s+(?:-\w+|\d+|\$)" r"|while\s+.*(pgrep|nvidia-smi).*;\s*do|until\s+.*(pgrep|nvidia-smi)", re.I | re.M, ) _OFFLINE_FIX = re.compile(r"shim|TIKTOKEN_CACHE_DIR|local_files_only|OFFLINE=1|vendor|cache_dir|snapshot_download|from_pretrained\([^)]*local", re.I) # Reads only. `cat > file` and `cat >> file` are writes wearing a read's name, # and matching them as inspection mislabelled every heredoc that set up an # environment file. _INSPECT = re.compile(r"^\s*(cat|head|tail|sed -n|grep|rg|less|ls|find|wc|jq)\b(?!\s*>)|\btail -c\b|\bsed -n\b", re.I) _WRITE_REDIRECT = re.compile(r"\b(cat|tee)\s*>>?\s*\S|<<\s*'?(PY|EOF|SH)\w*'?", re.I) # An action actually runs something; a read does not. "What does this error # call for" is only a coherent question when the thing that failed was an # action. _IS_ACTION = re.compile(r"\bpython3?\s+\S+\.py\b|\b(accelerate|torchrun|deepspeed|vllm)\b|\bbash\s+\S+\.sh\b|\bpython3?\s+-m\b|\bnohup\b", re.I) _TIMEOUT_ERR = re.compile(r"timed out|Exit code 143|TimeoutExpired", re.I) _BACKGROUNDED = re.compile(r"\bnohup\b|&\s*$|&\s*(echo|sleep)|run_in_background|setsid|disown", re.I) # Memory relief must be a *decrease* of a memory-relevant knob, or the # addition of one that was absent. _MEM_KNOBS = ("batch_size", "per_device_train_batch_size", "bs", "max_seq", "max_seq_len", "max_len", "block_size", "rank", "lora_r", "max_tokens", "max-connections", "max_connections", "gpu-memory-utilization", "gpu_memory_utilization", "limit") _MEM_ADDED = re.compile(r"expandable_segments|gradient_checkpointing|grad[_-]?accum|gradient_accumulation", re.I) _NUMS = re.compile(r"(\w[\w.-]*)\s*[= ]\s*(\d+(?:\.\d+)?)") def _first_cmd(payload: str) -> str: """The shell command inside a tool payload, minus the bash -lc wrapper.""" m = re.search(r"bash\s+-lc\s+['\"](.*)", payload, re.S) return (m.group(1) if m else payload).strip() def _invoked_program(cmd: str) -> str | None: """The script this command actually runs, not merely mentions.""" m = re.search(r"\bpython3?\s+(?:-\S+\s+)*(\S+\.py)\b", cmd) return m.group(1) if m else None def _knob_values(cmd: str) -> dict[str, float]: out = {} for k, v in _NUMS.findall(cmd): key = k.strip("-_").lower() if key in _MEM_KNOBS: try: out[key] = float(v) except ValueError: pass return out def recovery_label(failed: str, recovery: str, error_text: str) -> str | None: """Classify a recovery, or return None when nothing fires cleanly. Order matters: the specific, well-evidenced moves are tested before the generic ones, and an item is dropped rather than guessed at -- a mislabelled gold answer is worse than a missing item. Hand-checking an earlier version put precision near 65%; the guards below are what closed the four mislabel sources that review found, and the measured precision after each change is recorded in the manifest. """ f, rcv = _first_cmd(failed), _first_cmd(recovery) # The question only makes sense if an action failed. When the "failed" # command was itself a read of a log, there is nothing to repair. if not _IS_ACTION.search(f): return None if rcv.strip() == f.strip(): return "retry_unchanged" prog_f, prog_r = _invoked_program(f), _invoked_program(rcv) same_prog = bool(prog_f and prog_r and prog_f == prog_r) # A long job that timed out in the foreground and came back detached is # not a memory problem and not a bug. if _TIMEOUT_ERR.search(error_text) and _BACKGROUNDED.search(rcv) and not _BACKGROUNDED.search(f): return "background_the_job" if _OFFLINE_FIX.search(rcv) and not _OFFLINE_FIX.search(f): return "work_around_offline" if _FREE_GPU.search(rcv): return "free_gpu" if same_prog: kf, kr = _knob_values(f), _knob_values(rcv) decreased = any(k in kf and kr[k] < kf[k] for k in kr) added_flag = bool(_MEM_ADDED.search(rcv)) and not _MEM_ADDED.search(f) if decreased or added_flag: return "reduce_memory_footprint" # A rewrite of the very program that raised, with no resource change: the # agent decided its own code was wrong. # Rewriting the program that raised. `py_compile` on it is a syntax check, # i.e. inspection, so it must not count as a fix. if prog_f and _WRITE_REDIRECT.search(recovery) and prog_f in recovery and "py_compile" not in rcv: return "fix_code_defect" if _INSPECT.match(rcv) and not _WRITE_REDIRECT.search(rcv): return "inspect_further" return None def collect_recoveries(runs_by_agent: dict[str, list[Run]]) -> list[dict]: """Every (failing command, its output, what the agent did next) triple.""" out = [] for agent, runs in runs_by_agent.items(): for r in runs: for i, tc in enumerate(r.tool_calls): kind = _error_kind(tc) if not kind: continue nxt = r.tool_calls[i + 1] if i + 1 < len(r.tool_calls) else None if nxt is None: continue cmd, err, fix = tc.text_payload.strip(), (tc.result_text or "").strip(), nxt.text_payload.strip() if not (cmd and err and fix): continue # A "recovery" that is itself unreadably long or trivially # short carries no signal as an answer option. if not (20 <= len(fix) <= MAX_CMD_CHARS): continue out.append( { "agent": agent, "run": r.run_id, "task": r.task, "bucket": error_bucket(kind), "kind": kind, "failed_command": _trim(cmd, MAX_CMD_CHARS), "error_output": _trim(err, MAX_OUT_CHARS, tail=True), "recovery": fix, } ) return out def build_p1(recoveries: list[dict], per_label: int = 50) -> tuple[list[dict], dict]: """Label every recovery, then emit balanced multiple-choice items. Every item offers the same seven labels in a shuffled order, so no option can be picked from surface form alone. """ labelled: defaultdict[str, list[dict]] = defaultdict(list) unlabelled = 0 for rec in recoveries: lab = recovery_label(rec["failed_command"], rec["recovery"], rec["error_output"]) if lab is None: unlabelled += 1 continue labelled[lab].append(rec) rng = random.Random(RNG_SEED) keys = sorted(RECOVERY_LABELS) items = [] for lab in keys: pool = labelled.get(lab, []) rng.shuffle(pool) for rec in pool[:per_label]: order = keys[:] rng.shuffle(order) items.append( { "probe": "P1_error_recovery", "id": f"P1-{len(items):04d}", "gold_source": "teacher", "bucket": rec["bucket"], "failure_kind": rec["kind"], "failed_command": rec["failed_command"], "error_output": rec["error_output"], "choices": [RECOVERY_LABELS[k] for k in order], "choice_keys": order, "answer_index": order.index(lab), "answer_label": lab, "provenance": {"agent": rec["agent"], "run": rec["run"], "task": rec["task"]}, } ) rng.shuffle(items) for i, it in enumerate(items): it["id"] = f"P1-{i:04d}" counts = Counter(it["answer_label"] for it in items) coverage = { "observed_recoveries": len(recoveries), "labelled": len(recoveries) - unlabelled, "unlabelled_dropped": unlabelled, "label_counts": {k: len(v) for k, v in sorted(labelled.items())}, # Hand-verified on three successive samples while the classifier was # tightened: 10/12 -> 9/10 after the last two fixes. Treat the gold as # roughly 90% precise, not exact; `inspect_further` is the class that # absorbs most of the residual error. "measured_label_precision": {"estimate": 0.9, "method": "hand-checked samples of 10-12 during development"}, "majority_class_baseline": round(max(counts.values()) / len(items), 3) if items else None, "majority_class": counts.most_common(1)[0][0] if items else None, } return items, coverage # --- P2: noise judgment ----------------------------------------------------- def two_proportion_p(k1: int, n1: int, k2: int, n2: int) -> float: """Two-sided p-value for two binomial proportions (pooled z-test).""" if min(n1, n2) == 0: return 1.0 p1, p2 = k1 / n1, k2 / n2 p = (k1 + k2) / (n1 + n2) se = math.sqrt(p * (1 - p) * (1 / n1 + 1 / n2)) if se == 0: return 1.0 z = abs(p1 - p2) / se return math.erfc(z / math.sqrt(2)) def collect_measurements(runs_by_agent: dict[str, list[Run]]) -> list[dict]: """Official-grader readings that carry both a score and a sample size.""" out = [] for agent, runs in runs_by_agent.items(): for r in runs: f = extract(r) if f.cohort not in ("primary", "recovered"): continue for e in f.evals: if e.score is None or not e.limit: continue out.append( { "agent": agent, "run": r.run_id, "task": r.task, "t_rel": e.t_rel, "score": e.score, "n": e.limit, "model_path": e.model_path, } ) return out def build_p2(measurements: list[dict], max_items: int = 300) -> list[dict]: """Pair up measurements from the same run and ask whether B beats A. Only consecutive pairs within one run are used: those are the comparisons the agent actually faced when deciding which checkpoint to keep. """ by_run: defaultdict[str, list[dict]] = defaultdict(list) for m in measurements: by_run[f"{m['agent']}/{m['run']}"].append(m) rng = random.Random(RNG_SEED + 1) items = [] for key, ms in sorted(by_run.items()): ms.sort(key=lambda m: m["t_rel"]) for a, b in zip(ms, ms[1:]): if a["model_path"] == b["model_path"]: continue # same artifact re-measured: not a choice between candidates ka, kb = round(a["score"] * a["n"]), round(b["score"] * b["n"]) p = two_proportion_p(ka, a["n"], kb, b["n"]) items.append( { "probe": "P2_noise_judgment", "id": f"P2-{len(items):04d}", "gold_source": "statistics", "task": a["task"], "a": {"label": "A", "score": round(a["score"], 4), "n": a["n"], "correct": ka}, "b": {"label": "B", "score": round(b["score"], 4), "n": b["n"], "correct": kb}, # The decision the agent actually had to make. "question": "Is B's score distinguishable from A's at this sample size?", "answer": "distinguishable" if p < 0.05 else "not_distinguishable", "p_value": round(p, 4), "observed_delta": round(b["score"] - a["score"], 4), # Not an inference about intent: simply whether the later # candidate read higher. Used to state the fact that most # apparent improvements the agents saw were not separable # at the sample size they measured at. "b_reads_higher": b["score"] > a["score"], "provenance": {"agent": a["agent"], "run": a["run"]}, } ) rng.shuffle(items) items = items[:max_items] for i, it in enumerate(items): it["id"] = f"P2-{i:04d}" return items def p2_reference_points(items: list[dict]) -> dict: """The numbers a candidate model has to be read against. `always_not_distinguishable` is the trivial policy's accuracy, and it is high because most comparisons really were not separable -- which is why balanced accuracy, not accuracy, is the headline metric for this probe. `apparent_gains_that_were_real` is a plain fact about the comparisons the agents faced, not a claim about what they believed: of the pairs where the later candidate read higher, this is the share where the difference was actually distinguishable. """ if not items: return {} counts = Counter(it["answer"] for it in items) higher = [it for it in items if it["b_reads_higher"]] real_higher = [it for it in higher if it["answer"] == "distinguishable"] return { "n": len(items), "class_balance": dict(counts), "always_not_distinguishable": round(counts["not_distinguishable"] / len(items), 3), "balanced_chance": 0.5, "n_apparent_gains": len(higher), "apparent_gains_that_were_real": round(len(real_higher) / len(higher), 3) if higher else None, } def balanced_subset(items: list[dict], seed: int = RNG_SEED + 2) -> list[dict]: """Equal-sized classes, so plain accuracy is interpretable on its own.""" by_class: defaultdict[str, list[dict]] = defaultdict(list) for it in items: by_class[it["answer"]].append(it) if len(by_class) < 2: return [] k = min(len(v) for v in by_class.values()) rng = random.Random(seed) out = [] for cls in sorted(by_class): out.extend(rng.sample(by_class[cls], k)) rng.shuffle(out) for i, it in enumerate(out): it = dict(it) it["id"] = f"P2b-{i:04d}" out[i] = it return out def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--stats", action="store_true", help="print composition, write nothing") ap.add_argument("--out", default=os.path.join(OUT_DIR, "probes")) args = ap.parse_args() runs_by_agent = {} for agent, root in AGENT_ROOTS.items(): keep = [] for r in load_all(root): if extract(r).cohort in ("primary", "recovered"): keep.append(r) runs_by_agent[agent] = keep print(f"[{agent}] {len(keep)} analysed runs") recoveries = collect_recoveries(runs_by_agent) p1, p1cov = build_p1(recoveries) measurements = collect_measurements(runs_by_agent) p2 = build_p2(measurements) print(f"\nP1 error recovery : {len(p1)} items ({len(RECOVERY_LABELS)}-way choice over a shared label set)") print(f" labelled {p1cov['labelled']}/{p1cov['observed_recoveries']} observed recoveries" f" ({p1cov['unlabelled_dropped']} dropped as unclassifiable)") for k, c in sorted(Counter(i["answer_label"] for i in p1).items()): print(f" {k:26s} {c}") print(f" failure kinds: {dict(Counter(i['bucket'] for i in p1))}") print(f" source agents: {dict(Counter(i['provenance']['agent'] for i in p1))}") print(f" chance baseline : {1/len(RECOVERY_LABELS):.3f}") print(f" majority-class baseline: {p1cov['majority_class_baseline']} ({p1cov['majority_class']}) <- the number to beat") print(f" gold precision (hand-checked): ~{p1cov['measured_label_precision']['estimate']:.0%}") print(f"\nP2 noise judgment : {len(p2)} items from {len(measurements)} scored measurements") ref = p2_reference_points(p2) p2b = balanced_subset(p2) print(f" gold balance : {ref['class_balance']}") print(f" always-'not_distinguishable' accuracy : {ref['always_not_distinguishable']} <- beat this, or report balanced accuracy") print(f" balanced subset : {len(p2b)} items ({len(p2b)//2} per class)") print(f" of {ref['n_apparent_gains']} apparent gains the agents saw, only " f"{ref['apparent_gains_that_were_real']:.1%} were statistically distinguishable") if args.stats: return os.makedirs(args.out, exist_ok=True) for name, items in (("P1_error_recovery", p1), ("P2_noise_judgment", p2), ("P2b_noise_judgment_balanced", p2b)): path = os.path.join(args.out, f"{name}.jsonl") with open(path, "w") as fh: for it in items: fh.write(json.dumps(it) + "\n") print(f"wrote {path} ({len(items)} items)") with open(os.path.join(args.out, "manifest.json"), "w") as fh: json.dump( { "seed": RNG_SEED, "P1_error_recovery": { "n": len(p1), "gold_source": "teacher", "format": "multiple_choice", "n_choices": len(RECOVERY_LABELS), "chance": round(1 / len(RECOVERY_LABELS), 3), "label_coverage": p1cov, }, "P2_noise_judgment": { "n": len(p2), "gold_source": "statistics", "format": "binary", "headline_metric": "balanced_accuracy", "reference_points": ref, }, "P2b_noise_judgment_balanced": {"n": len(p2b), "gold_source": "statistics", "format": "binary", "headline_metric": "accuracy"}, }, fh, indent=1, ) print(f"wrote {os.path.join(args.out, 'manifest.json')}") if __name__ == "__main__": main()