SlowGuess's picture
Upload Abforge training code snapshot
1ce6f9b verified
Raw
History Blame Contribute Delete
7.53 kB
#!/usr/bin/env python3
"""Reaggregate v18 eval results with post-hoc tightening (no judge rerun).
Reversible: writes <stem>_eval_v18_1.jsonl alongside the v18 file. The
underlying v18 prompt and judge outputs are NOT modified. To undo, just
delete the *_v18_1.jsonl files.
Tightening rule (heuristic, applied to existing judge output):
* 0.5 matches whose pred-bullet RQ matches a generic-question pattern
("Does X contribute / improve?", "Is X critical?", "Could a simpler
method achieve similar?", etc.) are downgraded to 0.0.
* 1.0 matches whose judge reason cites SAME-COMPONENT promotion AND
whose RQ is generic are downgraded to 0.5.
Also computes wt(P) R variant: each match contribution is multiplied
by the bullet's precision score (from <stem>_prec_task1.jsonl).
Usage:
python recompute_v18_tight.py <stem1> <stem2> ...
or with no args = run on the 8 bench44 models.
"""
import argparse
import json
import os
import re
import sys
from typing import Dict, List
INFER_DIR = "/gpfs/radev/scratch/cohan/yz979/xucai/Abforge_Training/infer"
DEFAULT_STEMS = [
"claude_opus_4.6",
"claude_sonnet_4.6",
"deepseek-v3.2",
"deepseek-r1-0528",
"qwen3_32b",
"qwen3-30b-a3b",
"qwen3_8b_base",
"qwen3_8b_api",
]
# Conservative generic-RQ patterns. False positives are kept low by anchoring
# to common templated phrasings. A more rigorous version belongs in a v19
# judge prompt — this heuristic is for fast reversible verification.
_GENERIC_RQ_PATTERNS = [
r"^does\b[^?]*\b(contribute|improve|enhance|matter|help)\b[^?]*\?",
r"\bis\s+(?:the\s+)?\w+(?:\s+\w+){0,3}\s+(?:critical|essential|necessary|key|important|crucial)\b[^?]*\?",
r"^(?:can|could)\b[^?]*\b(?:achieve|yield|produce)\s+(?:similar|comparable|equivalent)\b[^?]*\?",
r"\bhow\s+(?:important|critical|essential|necessary)\s+is\b",
r"\bdoes\s+(?:the\s+)?\w+(?:\s+\w+){0,3}\s+(?:play|have)\s+a\s+(?:critical|key|significant|crucial)\s+role\b",
r"\bcontribute\s+meaningfully\s+to\b[^?]*\?",
r"\bessential\s+for\b[^?]{0,80}\?",
]
_GENERIC_RE = re.compile("|".join(_GENERIC_RQ_PATTERNS), re.IGNORECASE)
_SAME_COMPONENT_RE = re.compile(
r"SAME[\s-]+COMPONENT|DIFFERENT\s+VALID\s+ANGLE|different\s+but\s+legitimate",
re.IGNORECASE,
)
def rq_is_generic(rq: str) -> bool:
return bool(_GENERIC_RE.search((rq or "").strip()))
def is_sc_promotion(reason: str) -> bool:
return bool(_SAME_COMPONENT_RE.search(reason or ""))
def get_title(row: Dict) -> str:
return ((row.get("meta") or {}).get("title") or "").strip()
def load_jsonl(path: str) -> List[Dict]:
if not os.path.exists(path):
return []
return [json.loads(l) for l in open(path) if l.strip()]
def recompute_row(row: Dict, prec_row: Dict) -> Dict:
n_gt = row.get("n_gt", 0)
bullets_by_id = {b["idx"]: b for b in row.get("pred_bullets", [])}
bullet_P = {}
if prec_row:
for i, p in enumerate(prec_row.get("bullet_scores", []), start=1):
bullet_P[i] = p
new_matches = []
drops = [] # telemetry of what got tightened
for m in row.get("matches", []):
new_m = dict(m)
s = m.get("score", 0)
pid = m.get("pred_id", 0)
reason = m.get("reason", "")
rq = bullets_by_id.get(pid, {}).get("research_question", "")
is_gen = rq_is_generic(rq)
is_sc = is_sc_promotion(reason)
# Rule 1: SC-1.0 + generic RQ -> 0.5
if s >= 0.99 and is_sc and is_gen:
new_m["score"] = 0.5
new_m["v18_1_action"] = "sc_1.0_generic->0.5"
drops.append((pid, "sc_1.0_generic->0.5", 1.0, 0.5))
# Rule 2: 0.5 + generic RQ -> 0 (drop)
elif 0.3 <= s < 0.99 and is_gen:
new_m["score"] = 0.0
new_m["v18_1_action"] = "0.5_generic->0"
drops.append((pid, "0.5_generic->0", 0.5, 0.0))
# Keep otherwise
# Only retain matches that still score > 0
if new_m["score"] > 0:
new_matches.append(new_m)
weighted_sum = sum(m["score"] for m in new_matches)
recall_new = weighted_sum / n_gt if n_gt else 0.0
weighted_sum_wtP = sum(m["score"] * bullet_P.get(m["pred_id"], 1.0) for m in new_matches)
recall_wtP = weighted_sum_wtP / n_gt if n_gt else 0.0
out = dict(row)
out["matches"] = new_matches
out["match_rate_v18_1"] = recall_new
out["match_rate_v18_1_wtP"] = recall_wtP
out["n_matched_full_v18_1"] = sum(1 for m in new_matches if m["score"] >= 0.99)
out["n_matched_partial_v18_1"] = sum(1 for m in new_matches if 0.3 <= m["score"] < 0.99)
out["v18_1_tightening_drops"] = drops
return out
def process_stem(stem: str) -> Dict:
eval_p = f"{INFER_DIR}/task1_{stem}_bench44_eval_v18.jsonl"
prec_p = f"{INFER_DIR}/task1_{stem}_bench44_prec_task1.jsonl"
out_p = f"{INFER_DIR}/task1_{stem}_bench44_eval_v18_1.jsonl"
if not os.path.exists(eval_p):
print(f" [{stem}] SKIP: missing {eval_p}")
return None
eval_rows = load_jsonl(eval_p)
prec_by_t = {get_title(r): r for r in load_jsonl(prec_p)}
out_rows = []
n_tighten_05 = n_tighten_sc = 0
R_v18 = R_v18_1 = R_v18_1_wtP = 0.0
n_papers = 0
for r in eval_rows:
if r.get("n_gt", 0) <= 0:
continue
n_papers += 1
prec_row = prec_by_t.get(get_title(r))
new_r = recompute_row(r, prec_row)
out_rows.append(new_r)
R_v18 += r.get("match_rate", 0)
R_v18_1 += new_r["match_rate_v18_1"]
R_v18_1_wtP += new_r["match_rate_v18_1_wtP"]
for _pid, action, _old, _new in new_r["v18_1_tightening_drops"]:
if action.startswith("0.5"):
n_tighten_05 += 1
elif action.startswith("sc_1.0"):
n_tighten_sc += 1
R_v18 /= max(n_papers, 1)
R_v18_1 /= max(n_papers, 1)
R_v18_1_wtP /= max(n_papers, 1)
with open(out_p, "w") as f:
for r in out_rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
return {
"stem": stem,
"n_papers": n_papers,
"n_drops_05": n_tighten_05,
"n_drops_sc": n_tighten_sc,
"R_v18": R_v18,
"R_v18_1": R_v18_1,
"R_v18_1_wtP": R_v18_1_wtP,
"out_path": out_p,
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("stems", nargs="*", default=DEFAULT_STEMS)
args = ap.parse_args()
print(f"Recomputing v18 -> v18.1 (post-hoc tightening, reversible).")
print(f" generic-RQ -> 0.5 drops scored as 0")
print(f" SC-1.0 + generic RQ downgraded to 0.5")
print(f" wt(P) variant also computed\n")
PAPER_R = {
"claude_opus_4.6": 62.3, "claude_sonnet_4.6": 58.4,
"deepseek-v3.2": 58.8, "deepseek-r1-0528": 58.6,
"qwen3_32b": 52.4, "qwen3-30b-a3b": 51.2,
"qwen3_8b_base": 41.1, "qwen3_8b_api": None,
}
print(f"{'stem':<20} {'paper':>6} | {'v18 R':>7} | {'v18.1 R':>9} {'d':>7} | {'wt(P) R':>9} | "
f"{'drops 0.5':>10} {'drops SC':>9}")
print("-" * 100)
for stem in args.stems:
res = process_stem(stem)
if not res:
continue
p = PAPER_R.get(stem)
p_str = f"{p:.1f}" if p is not None else " N/A"
print(f"{stem:<20} {p_str:>6} | {res['R_v18']:>7.3f} | {res['R_v18_1']:>9.3f} "
f"{res['R_v18_1']-res['R_v18']:>+7.3f} | {res['R_v18_1_wtP']:>9.3f} | "
f"{res['n_drops_05']:>10} {res['n_drops_sc']:>9}")
if __name__ == "__main__":
main()