#!/usr/bin/env python3 """ eval_task1_precision.py — Precision judge for Task 1 predicted ablation bullets. Reads an existing eval_task1 output JSONL (which has pred_bullets and recall scores) plus the bench input JSONL (for paper Content). For each paper, calls Claude to score every predicted bullet on how valid and paper-specific it is (independent of GT). Computes: precision = mean pred-bullet validity score (0..1) recall = match_rate from the recall eval (unchanged) f_score = 2*P*R / (P+R) Appends precision, f_score, pred_scores fields to each row and prints a summary comparison table. Usage: python eval_task1_precision.py \ --eval_input infer/task1_claude_opus_4.6_bench44_eval_task1.jsonl \ --bench_input data/bench_44_rubric_v2.jsonl \ --output infer/task1_claude_opus_4.6_bench44_prec_task1.jsonl """ import argparse import concurrent.futures import json import os import re import shutil import subprocess import sys import tempfile import atexit import time from threading import Lock from typing import Dict, List, Optional, Tuple # ======================== Config ======================== CLAUDE_TIMEOUT = 300 WORKERS = 3 SPECIFICITY_BASELINE = 0.70 CLAUDE_MODEL: Optional[str] = None write_lock = Lock() _SESSION_TMP_DIR = tempfile.mkdtemp(prefix="abforge_prec_t1_") def _mangle(p: str) -> str: return "-" + p.lstrip("/").replace("/", "-").replace(" ", "-") def _cleanup() -> None: proj_dir = os.path.expanduser(f"~/.claude/projects/{_mangle(_SESSION_TMP_DIR)}") shutil.rmtree(proj_dir, ignore_errors=True) shutil.rmtree(_SESSION_TMP_DIR, ignore_errors=True) atexit.register(_cleanup) # ======================== Precision Judge Prompt ======================== PRECISION_PROMPT = """You are a rigorous scientific reviewer. Your task is to assess the SPECIFICITY of each predicted ablation target for this particular paper. You are evaluating the (Target Module, Research Question) pair as a unit. (Background and methodology — ablation section removed) {CONTENT} {PRED_BULLETS} SCORING RUBRIC — evaluate each (TM, RQ) pair as a unit: 1.0 — SPECIFIC & VALID The Target Module names a concrete, specific component, mechanism, or design choice that is directly identifiable by name in this paper's Context — NOT a generic category label (e.g., NOT "Training Objective", "Encoder", "Attention Module" without the specific design choice name). The Research Question asks a causally meaningful, non-trivial question about it. 0.5 — RQ REDEEMS GENERIC TM The Target Module uses a generic or category-level name that alone could apply to many papers, BUT the Research Question is specific enough to unambiguously identify which exact mechanism or design choice is being targeted — the RQ contains paper-specific technical terms or details that are visible in the Context, effectively supplying the specificity the TM label lacks. The RQ must reference a concrete paper-specific detail; merely being detailed or wordy is NOT sufficient. 0.0 — GENERIC OR INVALID One of the following: • Both TM and RQ use generic language that could appear in any similar ML paper without modification (e.g., TM: "Retrieval Mechanism", RQ: "Is the retrieval mechanism critical for performance?") • TM is a generic category name AND the RQ fails to identify which specific mechanism or design choice is being tested • TM contradicts or is irrelevant to this paper's described methodology • The prediction is entirely outside the scope of this paper IMPORTANT: The bar for 0.5 is high — the RQ must contain a paper-specific technical term or named design decision from the Context that uniquely identifies the target. A generic RQ that just restates or paraphrases the TM does NOT qualify for 0.5. When in doubt between 0.5 and 0.0, choose 0.0. **Output Format (strictly this JSON, no markdown fences):** {{ "scores": [ {{"bullet_id": 1, "score": 1.0, "reason": ""}}, {{"bullet_id": 2, "score": 0.5, "reason": ""}}, {{"bullet_id": 3, "score": 0.0, "reason": ""}}, ... ] }}""" # ======================== IO ======================== def load_jsonl(path: str) -> List[Dict]: rows = [] if os.path.exists(path): with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: try: rows.append(json.loads(line)) except Exception: pass return rows def append_jsonl(path: str, row: Dict) -> None: with write_lock: with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(row, ensure_ascii=False) + "\n") f.flush() def get_title(item: Dict) -> str: return ((item.get("meta") or {}).get("title") or "").strip() def get_done_titles(path: str) -> set: done = set() for r in load_jsonl(path): t = get_title(r) if t: done.add(t) return done # ======================== Precision helpers ======================== def format_pred_bullets(bullets: List[Dict]) -> str: parts = [] for b in bullets: parts.append( f'\n' f'{b["target_module"]}\n' f'{b["research_question"]}\n' f'' ) return "\n".join(parts) if parts else "(no bullets)" def parse_precision_response(response: str, n_pred: int) -> List[Dict]: json_match = re.search(r'\{.*\}', response, re.DOTALL) if not json_match: return [] try: result = json.loads(json_match.group(0)) except json.JSONDecodeError: return [] parsed = [] for s in result.get("scores", []): bid = s.get("bullet_id") score = s.get("score", 0) if not isinstance(bid, int) or bid < 1 or bid > n_pred: continue score = float(score) score = min((0.0, 0.5, 1.0), key=lambda a: abs(a - score)) parsed.append({"bullet_id": bid, "score": score, "reason": s.get("reason", "")}) return parsed # ======================== Claude CLI ======================== def call_claude(prompt_text: str, label: str = "") -> Optional[str]: tag = f"[{label}] " if label else "" cmd = [ "claude", "-p", "--output-format", "text", "--max-turns", "1", "--no-session-persistence", ] if CLAUDE_MODEL: cmd.extend(["--model", CLAUDE_MODEL]) try: t0 = time.time() proc = subprocess.run( cmd, input=prompt_text, capture_output=True, text=True, timeout=CLAUDE_TIMEOUT, cwd=_SESSION_TMP_DIR, ) elapsed = time.time() - t0 if proc.returncode != 0: print(f" {tag}exit {proc.returncode} ({elapsed:.1f}s)") return None out = proc.stdout.strip() if not out: print(f" {tag}empty ({elapsed:.1f}s)") return None print(f" {tag}ok ({elapsed:.1f}s, {len(out)} chars)") return out except subprocess.TimeoutExpired: print(f" {tag}timeout") return None except FileNotFoundError: print(f" {tag}'claude' not found") sys.exit(1) except Exception as e: print(f" {tag}error: {e}") return None # ======================== Per-item evaluation ======================== def evaluate_precision(item: Dict, content_map: Dict[str, str]) -> Tuple[str, Dict]: title = get_title(item) or "?" tag = title[:30] meta = item.get("meta", {}) try: bullets = item.get("pred_bullets", []) if not bullets: recall = item.get("match_rate", 0.0) or 0.0 out = dict(item) out.update({ "pred_scores": [], "bullet_scores": [], "precision": 0.0, "f_score": 0.0, "paper_score": 100.0 * (float(recall) - 0.5 * SPECIFICITY_BASELINE), "raw_precision_response": "", "precision_note": "no pred_bullets in eval row; specificity scored as zero", }) return ("SUCCESS", out) content = content_map.get(title, "") if not content: return ("FAIL", {"meta": meta, "reason": "Content not found in bench input"}) content_trunc = content[:8000] # ~2000 tokens max pred_block = format_pred_bullets(bullets) prompt = (PRECISION_PROMPT .replace("{CONTENT}", content_trunc) .replace("{PRED_BULLETS}", pred_block)) resp = call_claude(prompt, label=f"PRECt1|{tag}") if not resp: return ("FAIL", {"meta": meta, "reason": "claude call failed"}) n_pred = len(bullets) pred_scores = parse_precision_response(resp, n_pred) if not pred_scores: return ("FAIL", {"meta": meta, "reason": "no scores parsed from response", "raw_response_tail": resp[-300:]}) # Build per-bullet score lookup (missing bullets default to 0.5 as fallback) score_map = {s["bullet_id"]: s["score"] for s in pred_scores} bullet_scores = [score_map.get(b["idx"], 0.5) for b in bullets] precision = sum(bullet_scores) / max(n_pred, 1) recall = item.get("match_rate", 0.0) or 0.0 f_score = (2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0) paper_score = 100.0 * (float(recall) + 0.5 * (float(precision) - SPECIFICITY_BASELINE)) # Carry forward all original recall-eval fields, add precision fields out = dict(item) out.update({ "pred_scores": pred_scores, "bullet_scores": bullet_scores, "precision": precision, "f_score": f_score, "paper_score": paper_score, "raw_precision_response": resp, }) return ("SUCCESS", out) except Exception as e: return ("FAIL", {"meta": meta, "reason": f"exception: {e}"}) # ======================== Runner ======================== def run_precision_eval(eval_input: str, bench_input: str, output: str, fail: str, limit: int) -> None: # Load bench to build Content map bench_rows = load_jsonl(bench_input) content_map: Dict[str, str] = {} for r in bench_rows: title = get_title(r) if title: content_map[title] = r.get("Content", "") or "" print(f"Loaded {len(content_map)} papers from bench input") items = load_jsonl(eval_input) if limit > 0: items = items[:limit] done = get_done_titles(output) pending = [it for it in items if get_title(it) not in done] print(f"Precision eval: total={len(items)}, done={len(done)}, " f"pending={len(pending)}, workers={WORKERS}") print(f"Model: {CLAUDE_MODEL or 'default'}") if not pending: print("All done!") _print_summary(output, fail) return success_count = fail_count = 0 with concurrent.futures.ThreadPoolExecutor(max_workers=WORKERS) as executor: future_map = { executor.submit(evaluate_precision, item, content_map): item for item in pending } for future in concurrent.futures.as_completed(future_map): item = future_map[future] title = get_title(item) or "?" try: status, data = future.result() except Exception as e: status, data = "FAIL", {"meta": item.get("meta", {}), "reason": f"future exception: {e}"} if status == "SUCCESS": append_jsonl(output, data) success_count += 1 p = data.get("precision", 0) r = data.get("match_rate", 0) f = data.get("f_score", 0) print(f" [{success_count+fail_count}/{len(pending)}] " f"{title[:50]} P={p:.3f} R={r:.3f} F={f:.3f}") else: append_jsonl(fail, data) fail_count += 1 print(f" [{success_count+fail_count}/{len(pending)}] " f"{title[:50]} -> FAIL: {data.get('reason','?')}") print(f"\nDone: {success_count} ok, {fail_count} fail") _print_summary(output, fail) def _print_summary(output: str, fail: str) -> None: ok = load_jsonl(output) fail_rows = load_jsonl(fail) total = len(ok) + len(fail_rows) if total == 0: return def avg_with_fails(key, default=0.0): vals = [r.get(key, default) for r in ok] vals.extend([0.0] * len(fail_rows)) return sum(vals) / len(vals) if vals else 0.0 prec = avg_with_fails("precision") rec = avg_with_fails("match_rate") fscore = avg_with_fails("f_score") paper_score = 100.0 * (rec + 0.5 * (prec - SPECIFICITY_BASELINE)) avg_record_score = avg_with_fails("paper_score") pen = avg_with_fails("count_penalty") adj = avg_with_fails("adjusted_score") npred = [r.get("n_pred", 0) for r in ok] ngt = [r.get("n_gt", 0) for r in ok] print(f"\n{'='*60}") print(f"Precision eval summary (N={total}, ok={len(ok)}, fail={len(fail_rows)})") print(f"{'='*60}") print(f" precision = {prec:.4f} (mean pred-bullet validity)") print(f" recall (mr) = {rec:.4f} (GT match rate, unchanged)") print(f" paper_score = {paper_score:.2f} " f"(100 * (R + 0.5 * (P_spec - {SPECIFICITY_BASELINE:.2f})))") print(f" paper_score_avg = {avg_record_score:.2f} (per-record average)") print(f" f_score = {fscore:.4f} ← combined metric 2PR/(P+R)") print(f" adj_score = {adj:.4f} (recall - count_penalty, old metric)") print(f" count_penalty = {pen:.4f}") if npred: print(f" n_pred mean={sum(npred)/len(npred):.2f} " f"n_gt mean={sum(ngt)/len(ngt):.2f}") # Per-score breakdown prec_vals = [r.get("precision", 0) for r in ok] rec_vals = [r.get("match_rate", 0) for r in ok] fs_vals = [r.get("f_score", 0) for r in ok] print() print(" Distribution of F-scores (ok rows only):") brackets = [(0, 0.2), (0.2, 0.4), (0.4, 0.6), (0.6, 0.8), (0.8, 1.01)] for lo, hi in brackets: n = sum(1 for f in fs_vals if lo <= f < hi) print(f" [{lo:.1f}-{hi:.1f}): {n:>3}") # ======================== Main ======================== if __name__ == "__main__": parser = argparse.ArgumentParser( description="Precision judge: score predicted bullets for paper-specificity" ) parser.add_argument("--eval_input", required=True, help="eval_task1_claude output JSONL (has pred_bullets + recall scores)") parser.add_argument("--bench_input", required=True, help="Bench JSONL with Content field (e.g. bench_44_rubric_v2.jsonl)") parser.add_argument("--output", default=None, help="Output JSONL (default: _prec_task1.jsonl)") parser.add_argument("--fail", default=None) parser.add_argument("--workers", type=int, default=3) parser.add_argument("--model", type=str, default="claude-sonnet-4-6") parser.add_argument("--timeout", type=int, default=300) parser.add_argument("--limit", type=int, default=0) args = parser.parse_args() CLAUDE_MODEL = args.model CLAUDE_TIMEOUT = args.timeout WORKERS = args.workers if args.output is None: base = os.path.basename(args.eval_input) stem = base[:-6] if base.endswith(".jsonl") else base stem = re.sub(r"_eval_task1$", "", stem) out_dir = os.path.dirname(os.path.abspath(args.eval_input)) args.output = os.path.join(out_dir, f"{stem}_prec_task1.jsonl") if args.fail is None: args.fail = args.output.replace(".jsonl", "_fail.jsonl") print(f"Config: model={CLAUDE_MODEL}, workers={WORKERS}, " f"timeout={CLAUDE_TIMEOUT}s, limit={args.limit or 'all'}") print(f"Eval input : {args.eval_input}") print(f"Bench input: {args.bench_input}") print(f"Output : {args.output}") run_precision_eval( eval_input=args.eval_input, bench_input=args.bench_input, output=args.output, fail=args.fail, limit=args.limit, )