"""Score Versalit RCA-1 (or the scripted teacher) on simulated 5G alarm storms. Examples python eval.py --start 100 --limit 40 # model on scenarios 100-139 (GPU if available) python eval.py --policy teacher # scripted teacher, all 200 scenarios (CPU, seconds) Reports FLA@1 / FLA@3 (fault class in the top-1 / top-3 hypotheses), class+node accuracy (top-1 names the right fault class AND the right root node), mean ReAct steps, how often the action-repair step changed the model's raw turn, and wall time. The seed is set once before the run, as in the reported runs. """ from __future__ import annotations import argparse import json import sys import time from pathlib import Path ROOT = Path(__file__).absolute().parent # not resolve(): files in the Hugging Face cache are symlinks sys.path.insert(0, str(ROOT / "src")) import torch # noqa: E402 from versalit_rca.agent.react_loop import ReActRunner # noqa: E402 from versalit_rca.agent.teacher import HeuristicPolicy # noqa: E402 from versalit_rca.evaluation import metrics as M # noqa: E402 from versalit_rca.simulation.alarm_generator import Scenario # noqa: E402 from versalit_rca.simulation.environment import RCAEnv # noqa: E402 from versalit_rca.slm.loading import load_policy, read_config # noqa: E402 from versalit_rca.utils import (get_device, save_json, save_jsonl, # noqa: E402 set_seed) DEFAULT_SCENARIOS = ROOT / "scenarios" / "scenarios_canonical_200.jsonl" def load_scenarios(path: str | Path, start: int = 0, limit: int | None = None): """Scenarios [start, start + limit) of a JSONL file (one scenario per line).""" out = [] with open(path, "r", encoding="utf-8") as f: for i, line in enumerate(f): if i < start: continue if limit is not None and len(out) >= limit: break out.append(Scenario.from_dict(json.loads(line))) return out class RepairCounter: """Wraps SLMPolicy._repair and counts how often it changed the raw turn.""" def __init__(self, policy): self.inner = policy._repair self.calls = 0 self.changed = 0 policy._repair = self def __call__(self, text: str) -> str: out = self.inner(text) self.calls += 1 self.changed += int(out != text) return out class TokenCounter: """Wraps model.generate and counts newly generated tokens.""" def __init__(self, model): self.inner = model.generate self.new_tokens = 0 model.generate = self def __call__(self, tokens, **kw): out = self.inner(tokens, **kw) self.new_tokens += out.shape[1] - tokens.shape[1] return out def main() -> None: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--scenarios", default=str(DEFAULT_SCENARIOS), help="scenario JSONL file (default: the 200 canonical held-out scenarios)") ap.add_argument("--start", type=int, default=0, help="index of the first scenario") ap.add_argument("--limit", type=int, default=None, help="number of scenarios (default: all)") ap.add_argument("--policy", choices=["model", "teacher"], default="model") ap.add_argument("--device", default="auto", help="auto | cpu | cuda (model only)") ap.add_argument("--seed", type=int, default=42) ap.add_argument("--out", default=None, help="optional folder for trajectories.jsonl, per_scenario.jsonl, metrics.json") args = ap.parse_args() sys.stdout.reconfigure(errors="replace") set_seed(args.seed) # once, before loading the model and running episodes scenarios = load_scenarios(args.scenarios, args.start, args.limit) if not scenarios: sys.exit("no scenarios selected") cfg = read_config(ROOT) agent = cfg["agent"] runner = ReActRunner(max_steps=agent["max_steps"], max_tool_calls=agent["max_tool_calls"], top_k=agent["top_k_hypotheses"]) if args.policy == "model": device = get_device(args.device) policy = load_policy(ROOT, device) repairs, tokens = RepairCounter(policy), TokenCounter(policy.model) name = "versalit-rca-1" print(f"Versalit RCA-1 on {device} | decoding {cfg['inference']}") else: device = torch.device("cpu") policy, repairs, tokens = HeuristicPolicy(), None, None name = "teacher" print("scripted heuristic teacher (no learned weights)") last = args.start + len(scenarios) - 1 print(f"scenarios {args.start}-{last} ({len(scenarios)}) from {Path(args.scenarios).name}" f" | seed {args.seed}", flush=True) trajs, rows = [], [] t_run = time.perf_counter() for i, scn in enumerate(scenarios): rescued_before = getattr(policy, "n_rescued", 0) changed_before = repairs.changed if repairs else 0 t0 = time.perf_counter() traj = runner.run(RCAEnv(scn), policy, policy_name=name) if device.type == "cuda": torch.cuda.synchronize() dt = time.perf_counter() - t0 trajs.append(traj) top = traj.top_k(1) ok_class = bool(top) and top[0].fault_id == scn.fault_id ok_node = ok_class and top[0].node == scn.root_node rows.append({ "scenario_id": scn.scenario_id, "fault_id": scn.fault_id, "root_node": scn.root_node, "pred_fault_id": top[0].fault_id if top else None, "pred_node": top[0].node if top else None, "correct_top1": ok_class, "correct_top3": any(h.fault_id == scn.fault_id for h in traj.top_k(3)), "correct_class_node": ok_node, "steps": traj.n_steps, "finished": traj.finished, "seconds": round(dt, 2), "turns_changed_by_repair": (repairs.changed - changed_before) if repairs else 0, "turns_rescued": getattr(policy, "n_rescued", 0) - rescued_before, }) pred = f"{top[0].fault_id}@{top[0].node}" if top else "(no final answer)" print(f"[{i + 1:3d}/{len(scenarios)}] {scn.scenario_id} " f"true={scn.fault_id}@{scn.root_node} pred={pred} " f"class={'ok' if ok_class else 'MISS'} class+node={'ok' if ok_node else 'miss'} " f"steps={traj.n_steps} {dt:.1f}s", flush=True) wall = time.perf_counter() - t_run n = len(trajs) fla = M.fla(trajs, scenarios) res = {"policy": name, "scenarios": Path(args.scenarios).name, "start": args.start, "n": n, "seed": args.seed, "device": str(device)} for k in ("fla@1", "fla@1_ci95", "fla@3", "fla@3_ci95"): res[k] = fla[k] res.update(M.class_node_accuracy(trajs, scenarios)) res["finished_rate"] = sum(t.finished for t in trajs) / n res["mean_steps"] = sum(t.n_steps for t in trajs) / n res["mean_tool_calls"] = sum(t.n_tool_calls for t in trajs) / n res.update(M.hallucination_rate(trajs)) res["fla@1_by_category"] = fla["fla@1_by_category"] res["wall_time_s"] = round(wall, 1) res["mean_episode_s"] = round(wall / n, 2) if repairs: res["action_repair"] = { "model_turns": repairs.calls, "changed_by_repair": repairs.changed, "changed_rate": repairs.changed / max(repairs.calls, 1), "rebuilt_by_regex": policy.n_rescued, "rebuilt_rate": policy.n_rescued / max(repairs.calls, 1), "rebuilt_with_default_args": policy.n_arg_defaults, "trailing_text_trimmed_only": repairs.changed - policy.n_rescued, "episodes_with_rebuild": sum(1 for r in rows if r["turns_rescued"]), } res["generated_tokens"] = tokens.new_tokens print(json.dumps(res, indent=2)) if args.out: out = Path(args.out) save_jsonl(out / "trajectories.jsonl", [t.to_dict() for t in trajs]) save_jsonl(out / "per_scenario.jsonl", rows) save_json(out / "metrics.json", res) print(f"saved -> {out}") if __name__ == "__main__": main()