#!/usr/bin/env python3 """Fault injection experiments: how many agents does the topology need? For every configuration (a subset of the seven agents) and every single fault of the catalogue (lingologos_math/faults.py) the whole corpus is run in memory with the very same agent code the orchestrator uses. A run is *activated* when the fault really changed something. Each activated run ends in one of: silent error : a VERIFIED or SINGLE_PROVER verdict whose answer differs from the gold answer abstained : UNKNOWN, the fault or its consequence was detected masked : the correct answer was still produced (another agent compensated) Usage: python math/tools/ablation.py [--quick] [--out math/results/ablation.json] """ import argparse import json import sys import time from pathlib import Path from typing import Any, Dict, List, Tuple ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from lingologos_math import agents, corpus, faults, pipeline # noqa: E402 FULL = list(agents.ALL_AGENTS) CONFIGS: Dict[str, List[str]] = { "A3 formalizer_a+solver_a+verifier": ["formalizer_a", "solver_a", "verifier"], "A4 +formalizer_b": ["formalizer_a", "formalizer_b", "solver_a", "verifier"], "A5 +adversary": ["formalizer_a", "formalizer_b", "solver_a", "verifier", "adversary"], "A6 +solver_b": ["formalizer_a", "formalizer_b", "solver_a", "solver_b", "verifier", "adversary"], "A7 full topology": FULL, } for _name in FULL: CONFIGS["A7 minus %s" % _name] = [a for a in FULL if a != _name] def single_faults(active: List[str]) -> List[Tuple[str, ...]]: return [("%s:%s" % (agent, kind),) for agent in active for kind in faults.CATALOG[agent]] def multi_faults() -> List[Tuple[str, ...]]: out: List[Tuple[str, ...]] = [] for kind in faults.CATALOG["formalizer_a"]: out.append(("formalizer_a:%s" % kind, "formalizer_b:%s" % kind)) for kind in faults.CATALOG["solver_a"]: out.append(("solver_a:%s" % kind, "solver_b:%s" % kind)) out.append(("verifier:rubber_stamp", "adversary:rubber_stamp")) for kind in faults.CATALOG["solver_a"]: out.append(("solver_a:%s" % kind, "verifier:rubber_stamp")) out.append(("solver_a:%s" % kind, "verifier:rubber_stamp", "adversary:rubber_stamp")) return out def raw_label(item: Dict[str, Any], dossier: Dict[str, Any]) -> str: """Outcome of trusting solver_a with no verification at all.""" cand = dossier.get("sa") if not cand or cand.get("status") != "ok": return "abstain" return corpus.outcome(item, {"status": "RAW", "answer": cand["answer"]}) def run_cell(items: List[Dict[str, Any]], active: List[str], spec: Tuple[str, ...]) -> Dict[str, int]: tally = {"runs": 0, "activated": 0, "silent_error": 0, "abstained": 0, "masked": 0, "raw_wrong": 0} for item in items: faults.configure(list(spec)) outcome = pipeline.run(item["text"], active) tally["runs"] += 1 if not faults.FIRED: continue tally["activated"] += 1 label = corpus.outcome(item, outcome["final"]) if label == "wrong": tally["silent_error"] += 1 elif label in ("abstain", "abstain_expected"): tally["abstained"] += 1 else: tally["masked"] += 1 if "solver_a" in active and raw_label(item, outcome["dossier"]) == "wrong": tally["raw_wrong"] += 1 faults.configure(None) return tally def fault_free(items: List[Dict[str, Any]], active: List[str]) -> Dict[str, int]: tally = {"correct": 0, "wrong": 0, "abstain": 0, "abstain_expected": 0, "verified": 0, "single_prover": 0} for item in items: faults.configure(None) final = pipeline.run(item["text"], active)["final"] tally[corpus.outcome(item, final)] += 1 if final["status"] == "VERIFIED": tally["verified"] += 1 elif final["status"] == "SINGLE_PROVER": tally["single_prover"] += 1 return tally TRUSTED = ["formalizer_a", "formalizer_b", "verifier", "adversary", "arbiter"] SOLVER_SCENARIOS: List[Tuple[str, ...]] = [ (), ("solver_a:drop_solution",), ("solver_a:flip_verdict", "solver_b:flip_verdict"), ("solver_a:extra_solution", "solver_b:closed_open"), ] def tolerance_plan() -> List[Tuple[str, List[Tuple[str, ...]]]]: """Fault model: any solver faults plus at most one fault in a trusted role.""" plan = [] full = [] for agent in TRUSTED: for kind in faults.CATALOG[agent]: for scenario in SOLVER_SCENARIOS: full.append(scenario + ("%s:%s" % (agent, kind),)) plan.append(("A7 full topology", full)) minimal = [] for agent in TRUSTED: if agent in CONFIGS["A5 +adversary"]: for kind in faults.CATALOG[agent]: for scenario in SOLVER_SCENARIOS: minimal.append(scenario + ("%s:%s" % (agent, kind),)) plan.append(("A5 +adversary", minimal)) plan.append(("A7 minus adversary", [s + ("verifier:rubber_stamp",) for s in SOLVER_SCENARIOS])) plan.append(("A7 minus verifier", [s + ("adversary:rubber_stamp",) for s in SOLVER_SCENARIOS])) plan.append(("A7 minus formalizer_b", [("formalizer_a:%s" % k,) for k in faults.CATALOG["formalizer_a"]])) return plan def main() -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--quick", action="store_true", help="every 4th problem only") parser.add_argument("--configs", default="", help="comma separated configuration labels (prefix match); default all") parser.add_argument("--multi", choices=["yes", "no", "only"], default="yes", help="run the multiple fault experiments") parser.add_argument("--merge", nargs="*", help="merge partial result files into --out instead of running") parser.add_argument("--tolerance", action="store_true", help="run only the tolerance experiment") parser.add_argument("--trusted", default="", help="with --tolerance: only specs whose trusted fault belongs to these agents") parser.add_argument("--out", default=str(ROOT / "results" / "ablation.json")) args = parser.parse_args() if args.merge: merged: Dict[str, Any] = {"configs": {}, "multi": {}, "tolerance": {}, "problems": 0} for name in args.merge: part = json.loads(Path(name).read_text()) merged["problems"] = part["problems"] merged["configs"].update(part["configs"]) merged["multi"].update(part["multi"]) for key, cell in part.get("tolerance", {}).items(): if key not in merged["tolerance"]: merged["tolerance"][key] = cell continue mine = merged["tolerance"][key] mine["experiments"] += cell["experiments"] for field, value in cell["total"].items(): mine["total"][field] += value mine["silent_error_cases"].update(cell["silent_error_cases"]) Path(args.out).write_text(json.dumps(merged, indent=2, sort_keys=True)) print("merged %d parts into %s" % (len(args.merge), args.out)) return 0 items = [i for i in corpus.load() if i["kind"] != "unsupported"] if args.quick: items = items[::4] wanted = [w.strip() for w in args.configs.split(",") if w.strip()] report: Dict[str, Any] = {"problems": len(items), "configs": {}, "multi": {}, "tolerance": {}} started = time.time() if args.tolerance: for name, specs in tolerance_plan(): if wanted and not any(name.startswith(w) for w in wanted): continue total = {"runs": 0, "activated": 0, "silent_error": 0, "abstained": 0, "masked": 0, "raw_wrong": 0} worst: Dict[str, int] = {} trusted_only = [w.strip() for w in args.trusted.split(",") if w.strip()] specs = [s for s in specs if not trusted_only or s[-1].split(":")[0] in trusted_only] for spec in specs: tally = run_cell(items, CONFIGS[name], spec) for key in total: total[key] += tally[key] if tally["silent_error"]: worst[" + ".join(spec)] = tally["silent_error"] report["tolerance"][name] = {"experiments": len(specs), "total": total, "silent_error_cases": worst} print("TOLERANCE %-24s experiments=%-3d activated=%-5d silent_error=%-4d abstained=%-5d masked=%-5d (%.0fs)" % ( name, len(specs), total["activated"], total["silent_error"], total["abstained"], total["masked"], time.time() - started), flush=True) for case, count in sorted(worst.items(), key=lambda kv: -kv[1])[:4]: print(" silent errors %-3d under %s" % (count, case), flush=True) Path(args.out).parent.mkdir(parents=True, exist_ok=True) Path(args.out).write_text(json.dumps(report, indent=2, sort_keys=True)) return 0 for name, active in CONFIGS.items(): if args.multi == "only" or (wanted and not any(name.startswith(w) for w in wanted)): continue cell: Dict[str, Any] = {"agents": active, "fault_free": fault_free(items, active), "faults": {}} total = {"activated": 0, "silent_error": 0, "abstained": 0, "masked": 0, "raw_wrong": 0} for spec in single_faults(active): tally = run_cell(items, active, spec) cell["faults"][spec[0]] = tally for key in total: total[key] += tally[key] cell["single_fault_total"] = total report["configs"][name] = cell print("%-40s activated=%-5d silent_error=%-4d abstained=%-5d masked=%-5d (%.0fs)" % ( name, total["activated"], total["silent_error"], total["abstained"], total["masked"], time.time() - started), flush=True) if args.multi != "no": for spec in multi_faults(): tally = run_cell(items, FULL, spec) report["multi"][" + ".join(spec)] = tally print("MULTI %-72s activated=%-4d silent_error=%-4d abstained=%-4d masked=%-4d" % ( " + ".join(spec), tally["activated"], tally["silent_error"], tally["abstained"], tally["masked"]), flush=True) Path(args.out).parent.mkdir(parents=True, exist_ok=True) Path(args.out).write_text(json.dumps(report, indent=2, sort_keys=True)) print("wrote %s in %.0fs" % (args.out, time.time() - started)) return 0 if __name__ == "__main__": sys.exit(main())