#!/usr/bin/env python3 """ eval_task1_combined.py — Single-call Claude-as-judge evaluator for Task 1. Replaces the two-call pipeline (eval_task1_claude.py for recall + eval_task1_precision.py for precision) with one judge invocation that returns BOTH: * matches[] — GT focus → predicted bullet matching (recall side) * bullet_scores[] — per-predicted-bullet paper-specificity (precision side) Recall side uses the v19 specificity-gated rubric — v18's 1.0 only required topical naming, which gave generic one-word TMs full credit even when the focus had a richer specifier. v19 adds an anchor check (paper-specific term, contrast, qualifier, or context required for 1.0) and a 0.5→1.0 promotion when two or more anchors are present. Bipartite 1:1 on primary_match is enforced post-hoc. Precision side adopts eval_task1_precision.py's rubric verbatim and is judged independently of recall. Default judge is claude-opus-4-7 (matches the user-facing default; stronger judge → wider spread between strong/weak models). Usage: python eval_task1_combined.py \ --input infer/task1__bench44_infer_task1.jsonl \ --bench data/bench_44_rubric_v2.jsonl """ import argparse import atexit import concurrent.futures import json import os import re import shutil import subprocess import sys import tempfile import time from threading import Lock from typing import Dict, List, Optional, Tuple # Share count_penalty utils with eval_task1_claude.py and the reward server # so RL and eval can never drift apart on the n_pred penalty. _REWARD_PART_DIR = os.path.normpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "reward_part")) if _REWARD_PART_DIR not in sys.path: sys.path.append(_REWARD_PART_DIR) from task1_candidate_utils import ( # noqa: E402 COUNT_PENALTY_BASE_RATE_DEFAULT, COUNT_PENALTY_HARD_CAP_DEFAULT, compute_count_penalty_from_env, ) # ======================== Config ======================== CLAUDE_TIMEOUT = 300 WORKERS = 3 CLAUDE_MODEL: Optional[str] = None write_lock = Lock() _SESSION_TMP_DIR = tempfile.mkdtemp(prefix="abforge_eval_t1_combined_") def _mangle_project_path(p: str) -> str: return "-" + p.lstrip("/").replace("/", "-").replace(" ", "-") def _cleanup_session_dir() -> None: proj_dir = os.path.expanduser( f"~/.claude/projects/{_mangle_project_path(_SESSION_TMP_DIR)}" ) shutil.rmtree(proj_dir, ignore_errors=True) shutil.rmtree(_SESSION_TMP_DIR, ignore_errors=True) atexit.register(_cleanup_session_dir) # ======================== Combined Judge Prompt ======================== # # Single prompt, single JSON output, two independent rubrics. The procedure # explicitly tells the judge that recall and precision are decoupled: a # bullet's precision score does NOT depend on whether any focus picked it as # primary_match, and a focus's recall score does NOT depend on whether the # matched bullet would also score 1.0 on precision. EVAL_PROMPT = """You are a rigorous scientific reviewer evaluating Task 1 ablation-objective predictions on TWO INDEPENDENT axes: AXIS A — RECALL: For each Reference Focus, identify which Generated Bullet best matches it (0/0.5/1.0). AXIS B — PRECISION: For each Generated Bullet, judge whether it is a paper-specific and valid ablation target (0/0.5/1.0), INDEPENDENT of whether any focus picked it. The two axes share the rubrics below for the score values 0 / 0.5 / 1.0, but the judgements are independent — a bullet that scored 0 on AXIS A (because no focus matches it, or because the matching focus was already consumed) may still score 1.0 on AXIS B if it is a valid paper-specific ablation. {CONTENT} {GT_OBJECTIVES} {PRED_OBJECTIVES} ================================================================ AXIS A — RECALL (one entry per Reference Focus) ================================================================ PROCEDURE: Process the reference focuses 1..N IN ORDER. For each focus: 1. Read the focus. 2. Look at the UNCONSUMED candidate bullets (bullets not yet cited as primary_match by an earlier focus). 3. For each candidate, judge whether its (Target Module + Research Question) addresses the same atomic ablation as the focus. 4. Assign the score 0 / 0.5 / 1.0 per the rubric below. Record the bullet's integer ID in primary_match (or 0 if no bullet qualifies). 5. A bullet picked as primary_match for the current focus is CONSUMED — do NOT cite it for any later focus. ATOMIC ABLATION means: a single specific paper-introduced method, component, design choice, or experimental contrast (e.g., "Beam search width", "Prototype Attentive Module", "BiasNorm vs LayerNorm", "L_adv + L_unsup joint loss"). NOT a combo of abstract categories. DUAL SIGNAL: Use BOTH the bullet's Target Module heading AND its Research Question text. TM tells you the bullet's main subject; RQ confirms (or disconfirms) it engages the focus's actual experimental concern. A bullet earns credit only when TM + RQ together point to the focus. RECALL RUBRIC (v19 — specificity-gated 1.0, anchor-deficient 0.5): Score 1.0 requires TWO conditions; failing the anchor check (ii) demotes to 0.5 even when the topical match is correct. This is the v19 change from v18 — v18's 1.0 only required topical naming, which gave generic one-word TMs ("Symplectic Integration", "GNN Aggregation") full credit even when the focus had a richer specifier ("Symplectic vs Euler", "Two-hop GNN retrieval"). 1.0 — ATOMIC MATCH WITH PAPER-SPECIFIC ANCHOR Award 1.0 ONLY IF both conditions hold: (i) TM names the same atomic ablation as the focus per one of the MATCH CASES listed below. (ii) ANCHOR CHECK — the TM and RQ jointly include at least ONE paper-specific anchor that locks the match to THIS paper, not just any paper with similar components. Acceptable anchors: (a) EXPLICIT CONTRAST present in the focus is reproduced in the TM. If the focus is a "X vs Y" experiment where the vs-Y is paper-load-bearing, the TM must indicate the contrast (naming Y, naming "non-X", or "X vs Y" inline), NOT just X alone. (Ex: focus="Symplectic vs Euler" ←→ TM="Symplectic vs non-symplectic of matched order" → anchor OK, TM= "Symplectic Integration" alone → anchor MISSING → 0.5) (b) PAPER-SPECIFIC QUALIFIER from the focus is retained in TM or RQ. If the focus uses a multi-word paper-specific specifier (e.g., "two-hop GNN", "iterative sub-question"), the bullet must keep that qualifier verbatim or paraphrase it with equivalent specificity. (Ex: focus="Two-hop GNN retrieval" ←→ TM="Two-hop GNN neighborhood aggregation" → anchor OK, TM="GNN Aggregation" → anchor MISSING → 0.5) (c) NAMED PARAMETER / VALUE / CONDITION from the paper appears in TM or RQ (e.g., "β/γ regularization", "leapfrog integrator", "matched order", a specific layer count, named loss term, named module). (d) PAPER-CONTEXT REFERENCE in RQ: explicit reference to a paper-specific design context that disambiguates the match (e.g., "given the model has no parametric fallback", "in the image composition experiment", "under the paper's iterative regime"). Generic causal verbs ("Does X improve performance?") do NOT count. MATCH CASES (each requires the anchor check to also hold): • DIRECT MATCH: TM clearly names the same atomic ablation as the focus AND RQ confirms the same experimental concern. Synonymous verbs are fine ("necessity" ≈ "contribution" ≈ "effect" ≈ "with-vs-without"). • SINGLE-COMPONENT ATOMIZATION (Ex: focus="Effect of beam width on translation" ←→ TM="Beam search width" → check (ii): "beam width" is the paper-specific qualifier from the focus → 1.0; but TM="Beam search" alone drops the "width" specifier → 0.5) • COMPARISON ATOMIZATION: focus="A vs B"; bullet may name A, B, or the contrast. BUT if the focus's contrast is paper-load- bearing, the TM must indicate the contrast — not just one side. • JOINT COMPOSITE: focus names X AND Y as a paper-joint ablation, TM names BOTH. • SAME COMPONENT, DIFFERENT VALID ANGLE: TM names the same paper- specific component as the focus, RQ probes a different but legitimate experimental angle (sensitivity ↔ robustness ↔ necessity ↔ magnitude). Only when the component is paper- specific — generic-category bullets ("Encoder Architecture", "Loss Function") cannot use this rule. 0.5 — RESCUED OR ANCHOR-DEFICIENT MATCH Apply 0.5 in any of these (most common is the v19 anchor-deficient case): • ANCHOR-DEFICIENT MATCH (v19 — most common 0.5): TM is topically on the focus's component but uses only a generic single-word or category-level phrasing with no paper-specific anchor (per condition (ii) above). The bullet "names the right thing in principle" but does not demonstrate it was reading THIS paper. • Case A — Vague TM rescued by precise RQ: TM is broader/vaguer than the focus, BUT the RQ contains a paper-specific term that locks the bullet to the focus's atomic concern. • Case B — Precise TM but generic RQ: TM exactly names the focus's paper-specific component, BUT the RQ is a generic template ("Is X critical?") that adds no paper-specific detail beyond what the TM already says. • Case C — One side of TRUE joint/comparison: TM names ONE side of a TRUE joint ablation OR ONE side of a TRUE comparison, AND the RQ confirms the bullet IS engaging the focus's experimental point. PROMOTION RULE (0.5 → 1.0, v19.1 — loosened from 2+ to 1+ anchor): If a bullet would be 0.5 by EITHER the anchor-deficient case OR Case A/B/C above, BUT the TM/RQ jointly contain AT LEAST ONE paper- specific anchor (per (ii) above) that locks the match unambiguously to the focus, promote to 1.0. The presence of even a single paper-specific anchor — explicit contrast, paper-named qualifier, named parameter, or paper-context reference — is enough to demonstrate the bullet engaged with THIS paper rather than a generic category. Do NOT use 0.5 for "topically related" / "different aspect" / "higher abstraction" / "adjacent question" — those are 0. 0.0 — NO MATCH. Apply 0 if ANY hold: (a) The bullet's TM is a GENERIC UMBRELLA — combines 2+ abstract method categories rather than naming paper-specific components. UMBRELLA examples (always 0): "Training Protocol and Optimization Strategy" / "Backbone Architecture and Network Design" / "Loss Function and Regularization" / "Ablation and Sensitivity Analysis" NOT-UMBRELLA (paper-named): "MeanNet and BiasNet" / "L_adv and L_unsup loss" / "Planning Algorithm (MCTS and P-UCB)" (b) The focus appears only inside a parenthetical enumeration "(e.g., A, B, ...)" of a bullet whose TM is about a different topic. (c) No unconsumed bullet specifically addresses the focus (different aspect / different component / vague catchall listing many components). (d) PURE PARAPHRASE: Both TM and RQ use only generic-category phrasings that could appear in many ML papers, even if topically aligned with the focus. Score 0, not 0.5. 1:1 ENFORCEMENT (post-hoc by evaluator): After your scoring, the evaluator script keeps each bullet's pairing only with the HIGHEST-scoring focus (tie-break: earlier focus wins). If you cite the same bullet for two focuses, the lower-scoring focus will be zeroed. Follow the procedure above strictly — pick the next-best unconsumed bullet, or primary_match=0. ================================================================ AXIS B — PRECISION (one entry per Generated Bullet, INDEPENDENT of AXIS A) ================================================================ For each bullet, score the (Target Module, Research Question) pair as a unit against the Paper_Context — does this bullet identify a real paper-specific ablation, regardless of whether it appears in the reference focuses? PRECISION RUBRIC: 1.0 — SPECIFIC & VALID The Target Module names a concrete, specific component, mechanism, or design choice that is directly identifiable by name in the Paper_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 Paper_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. • TM is a generic category name AND the RQ fails to identify which specific mechanism 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 Paper_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 (single JSON object, no markdown fences, no commentary) ================================================================ {{ "matches": [ {{"gt_id": 1, "primary_match": 3, "score": 1.0, "reason": ""}} ], "unmatched_gt": [2], "bullet_scores": [ {{"bullet_id": 1, "score": 1.0, "reason": ""}}, {{"bullet_id": 2, "score": 0.5, "reason": "..."}} ] }}""" # ======================== Parsing helpers ======================== _TARGET_BULLET_RE = re.compile( r'\n\s*(?:#{1,6}\s*)?(?:[-*]\s*)?(?:\*{1,2})?\s*Target Module\s*(?::\s*(?:\*{1,2})?|\*{1,2}\s*:)', re.IGNORECASE, ) _RQ_BULLET_RE = re.compile( r'\n\s*(?:#{1,6}\s*)?(?:[-*]\s*)?(?:\*{1,2})?\s*Research Question\s*(?::\s*(?:\*{1,2})?|\*{1,2}\s*:)', re.IGNORECASE, ) def parse_gt_objectives(gt_candidates: str) -> List[str]: focuses = re.findall( r'(.*?)', gt_candidates, re.DOTALL, ) return [f.strip() for f in focuses if f.strip()] def parse_predicted_bullets(infer_response: str) -> List[Dict[str, str]]: if not infer_response: return [] result_match = re.search(r'(.*?)(?:|$)', infer_response, re.DOTALL) result_text = result_match.group(1) if result_match else infer_response text = "\n" + result_text tm_matches = list(_TARGET_BULLET_RE.finditer(text)) rq_matches = list(_RQ_BULLET_RE.finditer(text)) bullets: List[Dict[str, str]] = [] for i, tm in enumerate(tm_matches): tm_start = tm.end() next_tm_start = tm_matches[i + 1].start() if i + 1 < len(tm_matches) else len(text) rq_in_range = next((rq for rq in rq_matches if tm_start < rq.start() < next_tm_start), None) if rq_in_range is None: continue tm_text = text[tm_start:rq_in_range.start()].strip().lstrip(":").strip().strip("*").strip() rq_text = text[rq_in_range.end():next_tm_start].strip().lstrip(":").strip().strip("*").strip() if len(rq_text) > 400: rq_text = rq_text[:400] + "..." bullets.append({ "idx": len(bullets) + 1, "target_module": tm_text[:300], "research_question": rq_text, }) return bullets def format_pred_bullets(bullets: List[Dict[str, str]]) -> str: if not bullets: return "(no parseable bullets in the generated result)" return "\n".join( f'\n' f'{b["target_module"]}\n' f'{b["research_question"]}\n' f'' for b in bullets ) def parse_combined_response(response: str, n_gt: int, n_pred: int) -> Dict: """Parse a single JSON containing both `matches` (recall) and `bullet_scores` (precision). Apply bipartite 1:1 enforce on matches as eval_task1_claude.py does. Validate bullet_scores against 1..n_pred. """ json_match = re.search(r'\{.*\}', response, re.DOTALL) if not json_match: return {"matches": [], "bullet_scores": [], "parse_error": "no JSON found", "raw": response[-500:]} try: result = json.loads(json_match.group(0)) except json.JSONDecodeError as e: return {"matches": [], "bullet_scores": [], "parse_error": str(e), "raw": response[-500:]} # --- Recall side: same as eval_task1_claude.py:parse_match_response --- raw_matches = result.get("matches") or [] candidates: List[Dict] = [] for m in raw_matches: gt_id = m.get("gt_id") pred_id = m.get("primary_match") if pred_id is None: pred_id = m.get("pred_id") score = m.get("score", 0) if not isinstance(gt_id, int) or gt_id < 1 or gt_id > n_gt: continue if not isinstance(score, (int, float)): continue score = float(score) score = min((0.0, 0.5, 1.0), key=lambda a: abs(a - score)) if not isinstance(pred_id, int) or pred_id < 1 or pred_id > n_pred: pred_id = 0 score = 0.0 candidates.append({ "gt_id": gt_id, "pred_id": pred_id, "score": score, "reason": m.get("reason", ""), }) candidates.sort(key=lambda x: (-x["score"], x["gt_id"])) seen_gt = set() seen_pred = set() valid: List[Dict] = [] for c in candidates: if c["score"] <= 0 or c["pred_id"] == 0: continue if c["gt_id"] in seen_gt or c["pred_id"] in seen_pred: continue seen_gt.add(c["gt_id"]) seen_pred.add(c["pred_id"]) valid.append(c) valid.sort(key=lambda x: x["gt_id"]) # --- Precision side --- raw_scores = result.get("bullet_scores") or result.get("scores") or [] bullet_score_map: Dict[int, Dict] = {} for s in raw_scores: bid = s.get("bullet_id") score = s.get("score") if not isinstance(bid, int) or bid < 1 or bid > n_pred: continue if not isinstance(score, (int, float)): continue score = float(score) score = min((0.0, 0.5, 1.0), key=lambda a: abs(a - score)) # If the judge listed the same bullet twice, keep the last entry. bullet_score_map[bid] = {"bullet_id": bid, "score": score, "reason": s.get("reason", "")} # Fill missing bullets with 0.5 (same conservative fallback as the # standalone precision script). pred_scores: List[Dict] = [] bullet_scores: List[float] = [] for bid in range(1, n_pred + 1): entry = bullet_score_map.get(bid) if entry is None: entry = {"bullet_id": bid, "score": 0.5, "reason": "[missing in judge output, default 0.5]"} pred_scores.append(entry) bullet_scores.append(entry["score"]) return { "matches": valid, "unmatched_gt": result.get("unmatched_gt", []), "pred_scores": pred_scores, "bullet_scores": bullet_scores, "missing_bullet_scores": n_pred - len(bullet_score_map), } # ======================== 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)") if proc.stderr: print(f" stderr: {proc.stderr[:500]}") 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 in PATH") sys.exit(1) except Exception as e: print(f" {tag}error: {e}") return None # ======================== 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 not line: continue 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(*files) -> set: done = set() for f in files: for r in load_jsonl(f): t = get_title(r) if t: done.add(t) return done # ======================== Per-item evaluation ======================== def evaluate_item(item: Dict, content_map: Dict[str, str]) -> Tuple[str, Dict]: title = get_title(item) or "?" tag = title[:30] meta = item.get("meta", {}) try: gt_candidates = item.get("gt_Candidates", "") infer_response = item.get("infer_task1_response", "") if not gt_candidates or not infer_response: return ("FAIL", {"meta": meta, "reason": "missing gt_Candidates or infer_task1_response"}) gt_objectives = parse_gt_objectives(gt_candidates) if not gt_objectives: return ("FAIL", {"meta": meta, "reason": "no GT objectives parsed from gt_Candidates"}) pred_bullets = parse_predicted_bullets(infer_response) if not pred_bullets: return ("SUCCESS", { "meta": meta, "n_gt": len(gt_objectives), "n_pred": 0, "gt_objectives": gt_objectives, "pred_bullets": [], "matches": [], "unmatched_gt": list(range(1, len(gt_objectives) + 1)), "n_matched_full": 0, "n_matched_partial": 0, "n_matched": 0, "weighted_match_sum": 0.0, "match_rate": 0.0, "count_penalty": 0.0, "adjusted_score": 0.0, "pred_scores": [], "bullet_scores": [], "missing_bullet_scores": 0, "precision": 0.0, "f_score": 0.0, "f05_score": 0.0, "raw_eval_response": "", "eval_note": "no predicted bullets parsed from infer_task1_response; scored as zero", }) content = (content_map.get(title) or "").strip() if not content: return ("FAIL", {"meta": meta, "reason": "Content not found in bench input"}) content_trunc = content[:12000] # generous; bench44 max ~6k chars gt_block = "\n".join( f'{obj}' for i, obj in enumerate(gt_objectives) ) pred_block = format_pred_bullets(pred_bullets) prompt = (EVAL_PROMPT .replace("{CONTENT}", content_trunc) .replace("{GT_OBJECTIVES}", gt_block) .replace("{PRED_OBJECTIVES}", pred_block)) resp = call_claude(prompt, label=f"COMBt1|{tag}") if not resp: return ("FAIL", {"meta": meta, "reason": "claude call failed"}) n_gt = len(gt_objectives) n_pred = len(pred_bullets) parsed = parse_combined_response(resp, n_gt, n_pred) if "parse_error" in parsed: return ("FAIL", { "meta": meta, "reason": f"JSON parse error: {parsed['parse_error']}", "raw_response_tail": resp[-500:], }) matches = parsed["matches"] n_full = sum(1 for m in matches if m.get("score", 0) >= 0.99) n_partial = sum(1 for m in matches if 0.3 < m.get("score", 0) < 0.99) weighted = sum(m.get("score", 0) for m in matches) recall = weighted / n_gt if n_gt else 0.0 count_penalty = compute_count_penalty_from_env(n_pred) adjusted_score = max(0.0, recall - count_penalty) bullet_scores = parsed["bullet_scores"] precision = (sum(bullet_scores) / n_pred) if n_pred else 0.0 # Both F-scores computed per-row (avg later on the leaderboard side). denom1 = precision + recall f1 = (2 * precision * recall / denom1) if denom1 > 0 else 0.0 denom05 = 0.25 * precision + recall f05 = (1.25 * precision * recall / denom05) if denom05 > 0 else 0.0 return ("SUCCESS", { "meta": meta, "n_gt": n_gt, "n_pred": n_pred, "gt_objectives": gt_objectives, "pred_bullets": pred_bullets, "matches": matches, "unmatched_gt": parsed.get("unmatched_gt", []), "n_matched_full": n_full, "n_matched_partial": n_partial, "n_matched": len(matches), "weighted_match_sum": weighted, "match_rate": recall, "count_penalty": count_penalty, "adjusted_score": adjusted_score, "pred_scores": parsed["pred_scores"], "bullet_scores": bullet_scores, "missing_bullet_scores": parsed.get("missing_bullet_scores", 0), "precision": precision, "f_score": f1, "f05_score": f05, "raw_eval_response": resp, }) except Exception as e: return ("FAIL", {"meta": meta, "reason": f"exception: {e}"}) # ======================== Runner ======================== def run_eval(input_file: str, bench_file: str, output_file: str, fail_file: str, limit: int = 0) -> None: bench_rows = load_jsonl(bench_file) content_map: Dict[str, str] = {} for r in bench_rows: t = get_title(r) if t: content_map[t] = r.get("Content", "") or "" print(f"Loaded {len(content_map)} papers from bench input") items = load_jsonl(input_file) if limit > 0: items = items[:limit] done = get_done_titles(output_file, fail_file) pending = [it for it in items if get_title(it) not in done] print(f"Task 1 Combined Eval: total={len(items)}, done={len(done)}, " f"pending={len(pending)}, workers={WORKERS}") print(f"Model: {CLAUDE_MODEL or 'default'}") print(f"Input: {input_file}") print(f"Bench: {bench_file}") print(f"Output: {output_file} / {fail_file}") if not pending: print("All done!") _print_summary(output_file, fail_file) return success = failed = 0 with concurrent.futures.ThreadPoolExecutor(max_workers=WORKERS) as ex: future_map = { ex.submit(evaluate_item, item, content_map): item for item in pending } for fut in concurrent.futures.as_completed(future_map): item = future_map[fut] title = get_title(item) or "?" try: status, data = fut.result() except Exception as e: status = "FAIL" data = {"meta": item.get("meta", {}), "reason": f"future exception: {e}"} if status == "SUCCESS": append_jsonl(output_file, data) success += 1 print(f" [{success+failed}/{len(pending)}] {title[:50]} " f"R={data['match_rate']:.3f} " f"P={data['precision']:.3f} " f"F1={data['f_score']:.3f} " f"F0.5={data['f05_score']:.3f}") else: append_jsonl(fail_file, data) failed += 1 print(f" [{success+failed}/{len(pending)}] {title[:50]} -> " f"FAIL: {data.get('reason','?')}") print(f"\n{'='*60}") print(f"Done: {success} ok, {failed} fail") _print_summary(output_file, fail_file) def _print_summary(output: str, fail: str) -> None: ok = load_jsonl(output) fr = load_jsonl(fail) total = len(ok) + len(fr) if total == 0: return def avg_with_fails(key): vals = [r.get(key, 0.0) or 0.0 for r in ok] vals.extend([0.0] * len(fr)) return sum(vals) / len(vals) if vals else 0.0 avg_r = avg_with_fails("match_rate") avg_p = avg_with_fails("precision") avg_f1 = avg_with_fails("f_score") avg_f05 = avg_with_fails("f05_score") avg_adj = avg_with_fails("adjusted_score") avg_pen = avg_with_fails("count_penalty") pred_counts = [r.get("n_pred", 0) for r in ok] gt_counts = [r.get("n_gt", 0) for r in ok] print(f"Combined eval summary (N={total}, ok={len(ok)}, fail={len(fr)})") print(f" recall (R) = {avg_r:.4f}") print(f" precision (P) = {avg_p:.4f}") print(f" F1 = {avg_f1:.4f} ← per-row F1 average") print(f" F0.5 = {avg_f05:.4f} ← precision-weighted (β=0.5)") print(f" adjusted (R-pen) = {avg_adj:.4f}") print(f" count_penalty = {avg_pen:.4f} " f"(hard_cap={int(os.environ.get('TASK1_COUNT_HARD_CAP', COUNT_PENALTY_HARD_CAP_DEFAULT))}, " f"base={float(os.environ.get('TASK1_COUNT_BASE_RATE', COUNT_PENALTY_BASE_RATE_DEFAULT))})") if pred_counts: print(f" n_pred mean={sum(pred_counts)/len(pred_counts):.2f} " f"n_gt mean={sum(gt_counts)/len(gt_counts):.2f}") n_full = sum(r.get("n_matched_full", 0) for r in ok) n_part = sum(r.get("n_matched_partial", 0) for r in ok) n_total_gt = sum(gt_counts) if n_total_gt: print(f" recall mix 1.0={n_full} 0.5={n_part} " f"0={n_total_gt - n_full - n_part} (of {n_total_gt} GT slots)") # Use R, P from sum / sum for the headline F-scores (less affected by R=0 papers) if ok: sum_w = sum(r.get("weighted_match_sum", 0) for r in ok) sum_gt = sum(r.get("n_gt", 0) for r in ok) sum_bs = sum(sum(r.get("bullet_scores", []) or []) for r in ok) sum_pred = sum(r.get("n_pred", 0) for r in ok) if sum_gt and sum_pred: R_micro = sum_w / sum_gt P_micro = sum_bs / sum_pred if R_micro + P_micro > 0: F1_micro = 2 * R_micro * P_micro / (R_micro + P_micro) F05_micro = 1.25 * R_micro * P_micro / (0.25 * P_micro + R_micro) print(f"\n micro-averaged (sum/sum):") print(f" R_micro={R_micro:.4f} P_micro={P_micro:.4f} " f"F1_micro={F1_micro:.4f} F0.5_micro={F05_micro:.4f}") # ======================== Main ======================== if __name__ == "__main__": parser = argparse.ArgumentParser( description="Single-call combined Task 1 judge (recall + precision)" ) parser.add_argument("--input", required=True, help="Infer jsonl from run_inference_local.py --task 1") parser.add_argument("--bench", 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: _eval_combined.jsonl)") parser.add_argument("--fail", default=None) parser.add_argument("--workers", type=int, default=3) parser.add_argument("--model", type=str, default="claude-opus-4-7", help="Claude model id (default: claude-opus-4-7)") parser.add_argument("--timeout", type=int, default=300) parser.add_argument("--limit", type=int, default=0, help="Only evaluate first N records (0 = all)") 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.input) stem = re.sub(r"_infer_task1\.jsonl$", "", base) if stem == base: stem = base[:-6] if base.endswith(".jsonl") else base out_dir = os.path.dirname(os.path.abspath(args.input)) args.output = os.path.join(out_dir, f"{stem}_eval_combined.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'}") run_eval(args.input, args.bench, args.output, args.fail, limit=args.limit)