Download mail/decide_report.py from luokelabs/luoke-bench: direct link, hf CLI and curl.
- Browser
- Download file 8.61 kB
-
https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/mail/decide_report.py
- Command line
-
hf download hf://datasets/luokelabs/luoke-bench/mail/decide_report.py
-
curl -L -o decide_report.py https://huggingface.co/datasets/luokelabs/luoke-bench/resolve/main/mail/decide_report.py
8.61 kB
| #!/usr/bin/env python3 | |
| """Tables for mail/run_decide.py's results: the suspicious threshold chosen on one set, then held on the others. | |
| python3 mail/decide_report.py --arms g9,g3-9,d9,d4,a9,a4 [--fit-on rewrite] [--match g9] [--dir mail/results/decide] | |
| python3 mail/decide_report.py --prompt-of rw-weekly-sync # the action question as each engine words it | |
| For the arms that read probabilities, the threshold is fitted on --fit-on: the lowest value that flags no normal mail | |
| there (halfway between the most suspicious-looking normal mail and the next suspicious one above it), so it misses | |
| the fewest suspicious mails at no false alarm. With --match ARM, a second set of tables uses the threshold that misses | |
| the fewest there with no more false alarms than ARM had on that set. Either way it is then used unchanged on every | |
| set. G and G3 answer true or false and need none. A sweep of 0.1 … 0.9 per set shows how much room the fitted value leaves. Stdlib only. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import run_decide as rd # noqa: E402 | |
| SETS = ("real", "rewrite", "samples") | |
| MAY_MISS = 1 # the release gate: no false alarm, at most one suspicious mail missed | |
| def load(d: str, label: str, name: str) -> dict | None: | |
| path = os.path.join(d, name, label + ".json") | |
| if not os.path.exists(path): | |
| return None | |
| with open(path, encoding="utf-8") as f: | |
| return json.load(f) | |
| def p_sus(r: dict) -> float | None: | |
| return (r.get("probs") or {}).get("suspicious") | |
| def fit(items: list[dict], results: list[dict]) -> float: | |
| by_tag = {it["tag"]: it for it in items} | |
| normal = [p_sus(r) for r in results if r.get("probs") and not by_tag[r["tag"]]["expect"]["suspicious"]] | |
| sus = [p_sus(r) for r in results if r.get("probs") and by_tag[r["tag"]]["expect"]["suspicious"]] | |
| top = max((p for p in normal if p is not None), default=0.0) | |
| above = [p for p in sus if p is not None and p > top] | |
| return round((top + min(above)) / 2, 4) if above else round(min(top + 0.001, 1.0), 4) | |
| def wordings(text: str) -> dict: | |
| """The action question around `text` as the two engines put it to the model (before the chat template): oMLX | |
| 0.7.2's omlx/api/decisions.py render_question and build_messages, AnyDecisionModel 0.7.0's TokenScoring | |
| userMessage and defaultSystemPrompt.""" | |
| letters = "ABCDE" | |
| lines = "\n".join(f"{letters[i]}. {o['name']}: {o['description']}" for i, o in enumerate(rd.ACTION_OPTIONS)) | |
| omlx = [{"role": "user", "content": f"{text}\n\nQuestion: {rd.ACTION_Q}\nOptions:\n{lines}" | |
| "\n\nReply with the letter of the best option only."}, | |
| {"role": "assistant", "content": "Answer:"}] | |
| adm = [{"role": "system", "content": "You are a decision function. Read the state and the question, then reply " | |
| "with exactly one token from the allowed answers. If the state does not determine the answer, stay uncertain."}, | |
| {"role": "user", "content": f"State:\n{text}\n\nQuestion: {rd.ACTION_Q}\n{lines}\n\nAllowed answers: A, B, C, D, E"}] | |
| return {"oMLX /v1/decisions": omlx, "AnyDecisionModel": adm} | |
| def fit_match(items: list[dict], results: list[dict], most: int) -> float: | |
| """The threshold catching the most suspicious mails with at most `most` false alarms (ties: the higher one).""" | |
| by_tag = {it["tag"]: it for it in items} | |
| ps = sorted({p for r in results if (p := p_sus(r)) is not None}) | |
| cuts = [(a + b) / 2 for a, b in zip(ps, ps[1:])] + [min(ps[-1] + 0.001, 1.0)] if ps else [0.5] | |
| scored = [] | |
| for t in cuts: | |
| flagged = [r for r in results if r.get("probs") and p_sus(r) is not None and p_sus(r) >= t] | |
| fa = sum(1 for r in flagged if not by_tag[r["tag"]]["expect"]["suspicious"]) | |
| caught = sum(1 for r in flagged if by_tag[r["tag"]]["expect"]["suspicious"]) | |
| if fa <= most: | |
| scored.append((caught, t)) | |
| return round(max(scored)[1], 4) if scored else 1.0 | |
| def row(label: str, out: dict, s: dict) -> str: | |
| refused = "/".join(str(s["refusals"][f]) for f in rd.FIELDS) | |
| raw = "—" if out["arm"] == "G" else s["action_raw"] | |
| pri = f"{s['priority']}/{s['priority_n']}" if s["priority_n"] else "—" | |
| return (f"| {label} | {s['action']}/{s['n']} | {raw} | {s['caught']}/{s['suspicious_n']} | " | |
| f"{s['false_alarm']}/{s['normal_n']} | {pri} | {refused} | {s['seconds_median']} | {s['tokens_in_mean']} | " | |
| f"{out['peak_gb']} |") | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--arms", help="result labels, comma-separated") | |
| ap.add_argument("--prompt-of", metavar="TAG", help="print what each engine sends for this mail's action question") | |
| ap.add_argument("--fit-on", default="rewrite", choices=SETS) | |
| ap.add_argument("--match", metavar="ARM", help="also: thresholds allowing as many false alarms as ARM on --fit-on") | |
| ap.add_argument("--dir", default=os.path.join(HERE, "results", "decide")) | |
| a = ap.parse_args() | |
| if a.prompt_of: | |
| it = next(x for name in SETS for x in rd.items_of(name) if x["tag"] == a.prompt_of) | |
| messages, _ = rd.prompt(it, rd.RecipeLink("", "", "")) | |
| for engine, ms in wordings(rd.one_text(messages)).items(): | |
| print(f"## {engine}\n") | |
| for m in ms: | |
| print(f"### {m['role']}\n\n```\n{m['content']}\n```\n") | |
| return | |
| if not a.arms: | |
| ap.error("--arms, or --prompt-of") | |
| labels = a.arms.split(",") | |
| items = {name: rd.items_of(name) for name in SETS} | |
| runs = {(lb, name): load(a.dir, lb, name) for lb in labels for name in SETS} | |
| zero = {} | |
| for lb in labels: | |
| out = runs[(lb, a.fit_on)] | |
| if out and out["arm"] in ("D", "A"): | |
| zero[lb] = fit(items[a.fit_on], out["results"]) | |
| tables(f"Threshold fitted on `{a.fit_on}` at no false alarm, then held", zero, labels, runs, items, sweep=True) | |
| if a.match and runs.get((a.match, a.fit_on)): | |
| most = rd.tally(items[a.fit_on], runs[(a.match, a.fit_on)]["results"])["false_alarm"] | |
| matched = {lb: fit_match(items[a.fit_on], runs[(lb, a.fit_on)]["results"], most) for lb in zero} | |
| tables(f"Threshold fitted on `{a.fit_on}` allowing {a.match}'s {most} false alarms there, then held", | |
| matched, labels, runs, items, sweep=False) | |
| def tables(title: str, thresholds: dict, labels: list, runs: dict, items: dict, sweep: bool) -> None: | |
| print(f"# {title}\n\nThresholds: " + ", ".join(f"{lb} {t}" for lb, t in thresholds.items()) + "\n") | |
| totals: dict = {} | |
| for name in SETS: | |
| if not any(runs[(lb, name)] for lb in labels): | |
| continue | |
| print(f"## {name}\n") | |
| print("| arm | action | before the suspicious rule | caught | false alarms | priority | refusals a/p/s | " | |
| "median s | tokens in | peak GB |") | |
| print("|---|---|---|---|---|---|---|---|---|---|") | |
| for lb in labels: | |
| out = runs[(lb, name)] | |
| if not out: | |
| continue | |
| s = rd.tally(items[name], out["results"], thresholds.get(lb, 0.5)) | |
| print(row(lb, out, s)) | |
| t = totals.setdefault(lb, {"action": 0, "n": 0}) | |
| t["action"] += s["action"] | |
| t["n"] += s["n"] | |
| if name == "samples": | |
| t["gate"] = s["false_alarm"] == 0 and s["suspicious_n"] - s["caught"] <= MAY_MISS | |
| print() | |
| print("## All sets run\n") | |
| print("| arm | action | samples gate (0 false alarms, at most 1 missed) |\n|---|---|---|") | |
| for lb, t in totals.items(): | |
| gate = {True: "passes", False: "fails"}.get(t.get("gate"), "—") | |
| print(f"| {lb} | {t['action']}/{t['n']} ({100 * t['action'] / max(t['n'], 1):.1f}%) | {gate} |") | |
| print() | |
| if not sweep: | |
| return | |
| print("## Threshold sweep (caught / false alarms)\n") | |
| print("| arm | set | " + " | ".join(f"{x / 10:.1f}" for x in range(1, 10)) + " |") | |
| print("|---|---|" + "---|" * 9) | |
| for lb in thresholds: | |
| for name in SETS: | |
| out = runs[(lb, name)] | |
| if not out: | |
| continue | |
| cells = [] | |
| for x in range(1, 10): | |
| s = rd.tally(items[name], out["results"], x / 10) | |
| cells.append(f"{s['caught']}/{s['false_alarm']}") | |
| print(f"| {lb} | {name} | " + " | ".join(cells) + " |") | |
| print() | |
| if __name__ == "__main__": | |
| main() | |