Datasets:
Download code/scripts_seqroute/judge.py from divy123/sequential-router-v2: direct link, hf CLI and curl.
- Browser
- Download file 7.11 kB
-
https://huggingface.co/datasets/divy123/sequential-router-v2/resolve/main/code/scripts_seqroute/judge.py
- Command line
-
hf download hf://datasets/divy123/sequential-router-v2/code/scripts_seqroute/judge.py
-
curl -L -o judge.py https://huggingface.co/datasets/divy123/sequential-router-v2/resolve/main/code/scripts_seqroute/judge.py
7.11 kB
| """Source-grounded LLM judging for the two summarization families (the only judge-scored families). | |
| Modes | |
| primary : judge_qwen3_30b_a3b, T=0, every response (+ control candidates: gold reference = positive control, reference of another article = negative control) | |
| repeat : same judge, T=0.7, 3 samples on the reliability subset -> within-judge noise (ICC) | |
| alt : judge_gemma3_27b (different family), T=0, reliability subset -> cross-judge agreement | |
| Unparsable outputs are retried (T=0.2, 6000 tokens) up to 2 rounds, then labelled unparsed (Q missing, label_confidence 0). Empty final answers are scored 0 without a judge call. | |
| Usage: python judge.py --mode primary [--models a,b] [--wave w1] ; outputs scores/judge/raw_<mode>.jsonl and scores/judge/parsed_<mode>.jsonl | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import random | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import pandas as pd | |
| sys.path.insert(0, "src") | |
| sys.path.insert(0, ".") | |
| from llmroute.evaluation.extract import split_thinking | |
| from llmroute.orouter2 import judge as J | |
| from llmroute.seqroute import serve as S | |
| from llmroute.seqroute.client import read_ids, run_jobs | |
| ROOT = Path("/mnt/localssd/seqroute1m") | |
| OUT = ROOT / "scores/judge" | |
| SPECS = { | |
| "primary": dict(id="judge_qwen3_30b_a3b", tp=2, serve_args=[], max_model_len=12288, temperature=0.0, top_p=1.0, chat_template_kwargs={}), | |
| "repeat": dict(id="judge_qwen3_30b_a3b", tp=2, serve_args=[], max_model_len=12288, temperature=0.7, top_p=0.95, chat_template_kwargs={}), | |
| "alt": dict(id="judge_gemma3_27b", tp=1, serve_args=["--limit-mm-per-prompt", json.dumps({"image": 0, "video": 0, "audio": 0})], max_model_len=12288, temperature=0.0, top_p=1.0, chat_template_kwargs={}), | |
| } | |
| SEED = 20261010 | |
| FAMS = ("summ_news", "summ_abstractive") | |
| def hh(*p): | |
| return hashlib.sha1("|".join(map(str, p)).encode()).hexdigest() | |
| def reliability_subset(q: pd.DataFrame, n_per_family: int = 150) -> set: | |
| out = set() | |
| for fam in FAMS: | |
| ids = sorted(q[q.task_family == fam].query_id, key=lambda x: hh("rel", SEED, x)) | |
| out |= set(ids[:n_per_family]) | |
| return out | |
| def build_items(q, models, mode, wave_ids): | |
| qj = q[q.task_family.isin(FAMS)].set_index("query_id") | |
| rel = reliability_subset(q) | |
| items, zeros = [], [] | |
| for m in models: | |
| f = ROOT / "responses" / f"{m}.jsonl" | |
| if not f.exists(): | |
| continue | |
| for l in open(f): | |
| r = json.loads(l) | |
| qid = r["id"] | |
| if qid not in qj.index or (wave_ids is not None and qid not in wave_ids) or (mode != "primary" and qid not in rel): | |
| continue | |
| fin, _ = split_thinking(r["text"], r.get("reasoning"), r.get("finish_reason")) | |
| if not fin.strip(): | |
| zeros.append(f"{m}|{qid}") | |
| continue | |
| items.append((f"{m}|{qid}", qid, fin)) | |
| if mode == "primary": # controls | |
| for fam in FAMS: | |
| ids = sorted(qj[qj.task_family == fam].index, key=lambda x: hh("ctrl", SEED, x))[:100] | |
| for i, qid in enumerate(ids): | |
| other = qj.loc[ids[(i + 37) % len(ids)]] | |
| items.append((f"ctrl_ref|{qid}", qid, qj.loc[qid].reference)) | |
| items.append((f"ctrl_neg|{qid}", qid, other.reference)) | |
| return qj, items, zeros | |
| def parse_any(text, style): | |
| return J.parse_summ(text) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--mode", required=True, choices=list(SPECS)) | |
| ap.add_argument("--models", default="") | |
| ap.add_argument("--wave", default="") | |
| ap.add_argument("--queries", default=str(ROOT / "queries/master_queries.parquet")) | |
| a = ap.parse_args() | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| q = pd.read_parquet(a.queries) | |
| models = [m["id"] for m in json.load(open(ROOT / "manifests/models.json"))] | |
| if a.models: | |
| models = [m for m in models if m in a.models.split(",")] | |
| wave_ids = set(json.load(open(ROOT / "manifests" / f"wave_{a.wave}.json"))) if a.wave else None | |
| qj, items, zeros = build_items(q, models, a.mode, wave_ids) | |
| raw = OUT / f"raw_{a.mode}.jsonl" | |
| reps = 3 if a.mode == "repeat" else 1 | |
| jobs = [] | |
| for rid, qid, fin in items: | |
| row = qj.loc[qid] | |
| style = json.loads(row.payload)["style"] | |
| prompt = J.prompt_summ(style, json.loads(row.payload)["source"], fin) | |
| for k in range(reps): | |
| jobs.append(dict(id=f"{rid}#r{k}", prompt=prompt, max_tokens=3000, seed=1000 + k)) | |
| have = read_ids(raw) | |
| todo = [j for j in jobs if j["id"] not in have] | |
| print(f"{a.mode}: {len(items)} items, {len(zeros)} empty (score 0), {len(jobs)} calls, {len(todo)} to run", flush=True) | |
| spec = SPECS[a.mode] | |
| if todo: | |
| S.stop_servers() | |
| ports = S.start_servers(spec, max_num_seqs=64) | |
| S.wait_ready(ports) | |
| params = dict(temperature=spec["temperature"], top_p=spec["top_p"], chat_template_kwargs=spec["chat_template_kwargs"], logprobs=False) | |
| t0 = time.time() | |
| run_jobs(todo, raw, spec["id"], ports, params, per_server=64, every=2000) | |
| # retry unparsable outputs: larger budget, T=0.2, two rounds | |
| for rnd in range(4): | |
| recs = {} | |
| for l in open(raw): | |
| r = json.loads(l) | |
| recs[r["id"]] = r | |
| bad = [j for j in jobs if (j["id"] not in recs or parse_any(recs[j["id"]]["text"], None) is None) and f"{j['id']}~rt{rnd}" not in recs] | |
| if not bad: | |
| break | |
| print(f"retry round {rnd}: {len(bad)} unparsable", flush=True) | |
| rj = [dict(j, id=f"{j['id']}~rt{rnd}", max_tokens=6000, seed=2000 + rnd) for j in bad] # rounds 2-3 resample at T=0.7 to escape degenerate loops | |
| run_jobs(rj, raw, spec["id"], ports, dict(params, temperature=0.2 if rnd < 2 else 0.7, top_p=1.0 if rnd < 2 else 0.95), per_server=64, every=2000) | |
| S.stop_servers() | |
| json.dump(dict(mode=a.mode, wall_s=time.time() - t0, n_calls=len(todo)), open(OUT / f"stats_{a.mode}_{int(time.time())}.json", "w")) | |
| # parse | |
| recs = {} | |
| for l in open(raw): | |
| r = json.loads(l) | |
| recs[r["id"]] = r | |
| parsed = OUT / f"parsed_{a.mode}.jsonl" | |
| n_ok = n_bad = 0 | |
| with open(parsed, "w") as f: | |
| for j in jobs: | |
| best = None | |
| for suffix in ("", "~rt0", "~rt1", "~rt2", "~rt3"): | |
| r = recs.get(j["id"] + suffix) | |
| if r: | |
| p = parse_any(r["text"], None) | |
| if p is not None: | |
| best = dict(p, retried=bool(suffix)) | |
| break | |
| rid, k = j["id"].rsplit("#r", 1) | |
| f.write(json.dumps(dict(id=rid, rep=int(k), parsed=best is not None, **(best or {}))) + "\n") | |
| n_ok += best is not None | |
| n_bad += best is None | |
| for z in zeros: | |
| f.write(json.dumps(dict(id=z, rep=0, parsed=True, Q=0.0, empty_final=True)) + "\n") | |
| print(f"parsed {n_ok} ok, {n_bad} unparsed, {len(zeros)} empty-final zeros", flush=True) | |
| if __name__ == "__main__": | |
| main() | |