Download code/rubric_gen/annotate_truth.py from EdwardoSunny/agent-cwm-rubrics-debug: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/annotate_truth.py
- Command line
-
hf download hf://datasets/EdwardoSunny/agent-cwm-rubrics-debug/code/rubric_gen/annotate_truth.py
-
curl -L -o annotate_truth.py https://huggingface.co/datasets/EdwardoSunny/agent-cwm-rubrics-debug/resolve/main/code/rubric_gen/annotate_truth.py
13.9 kB
| #!/usr/bin/env python3 | |
| """Evidence-grounded ground truth for the conceptual arm. | |
| python3 annotate_truth.py --scored data/eval_scored.jsonl \ | |
| --library data/conceptual_applicable.jsonl --out data/truth_annotations.jsonl | |
| WHY THIS REPLACES THE MEDIAN SPLIT | |
| The remote's error experiment does not decide ground truth with a heuristic. For | |
| each failed state an annotator that CAN SEE THE TRACEBACK decides which rubrics | |
| actually describe the observed failure, sampled twice independently, adjudicated | |
| on disagreement (04_freeze_atomic_ground_truth.py). Clean states are automatic | |
| negatives. | |
| Our conceptual arm was scored against "did the program land in the worse half of | |
| its competition", which is a different and much weaker claim. A rubric says | |
| "pattern P is present and P degrades the result"; the median split only checks | |
| that the program scored badly, and a program lands in the worse half for many | |
| reasons the rubric never mentions. Every true positive could be coincidence, and | |
| on the last run the real rubrics were consequently indistinguishable from a | |
| shuffled control. | |
| So this asks the same question the remote asks, with the evidence this family | |
| has: the annotator sees the WEAKER program, a STRONGER program from the same | |
| competition, and the measured gap between them, and decides which rubrics | |
| actually explain that gap. Same protocol -- two independent samples, adjudicate | |
| disagreements, record agreement so annotation noise is visible rather than | |
| assumed away. | |
| WHAT THE ANNOTATOR SEES AND THE JUDGE DOES NOT | |
| The scores, the comparison program, and the size of the gap. That asymmetry is | |
| the point: ground truth is grounded in evidence the blind judge never gets, so | |
| agreement between them is informative rather than circular. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import statistics | |
| import sys | |
| import time | |
| from collections import defaultdict | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from common import (ModelRefusal, anthropic_text, append_jsonl, | |
| extract_json_object, read_jsonl, truncate, write_json) | |
| SYSTEM = """You decide which code-review criteria explain a measured score gap. | |
| You get two programs solving the SAME task: a weaker one and a stronger one, | |
| with the measured difference between them. You also get a numbered list of | |
| criteria. Decide which criteria describe a real difference between these two | |
| programs that plausibly contributed to the gap. | |
| Ground your answer in the actual difference between the two programs. A | |
| criterion belongs in your answer only if: | |
| - the weaker program genuinely exhibits what it describes, AND | |
| - the stronger program does NOT exhibit it (or exhibits it far less), AND | |
| - the mechanism it names could plausibly move this task's metric in the | |
| direction observed. | |
| Do not include a criterion because the weaker program is worse overall, because | |
| the criterion is generally good advice, or because it describes something both | |
| programs do. A criterion that both programs exhibit cannot explain a difference | |
| between them. | |
| Distinguish HOW it applies: | |
| - "literal": every stated condition of the criterion holds as written | |
| (if it says "pretrained transformer", the program uses a pretrained | |
| transformer, not a CNN). | |
| - "analogous": the underlying mechanism explains the gap, but a stated | |
| condition names a different concrete instance than the program uses. | |
| This matters because the deployed judge reads criteria literally; crediting | |
| analogous matches as truth makes the judge look blind when it is being exact. | |
| Most criteria will not apply. An empty list is the correct and common answer. | |
| Reply with ONLY: | |
| {"explains": [<criterion numbers applying literally>], | |
| "explains_analogous": [<criterion numbers applying analogously>], | |
| "reason": "<at most 30 words>"}""" | |
| USER = """<task> | |
| {task} | |
| </task> | |
| <weaker_program score="{weak_score}"> | |
| {weak_code} | |
| </weaker_program> | |
| <stronger_program score="{strong_score}"> | |
| {strong_code} | |
| </stronger_program> | |
| <measured_gap>{gap} relative, {direction}</measured_gap> | |
| <criteria> | |
| {criteria} | |
| </criteria> | |
| Which criteria explain the gap between these two programs?""" | |
| def build_pairs(scored: list[dict], *, min_margin: float) -> list[dict]: | |
| """Weak/strong pairs within a competition, exactly as the mining arm does.""" | |
| by_comp: dict[str, list[dict]] = defaultdict(list) | |
| for s in scored: | |
| g = s.get("grading") or {} | |
| if g.get("graded") and g.get("score") is not None: | |
| by_comp[s["competition"]].append(s) | |
| pairs = [] | |
| for comp, states in sorted(by_comp.items()): | |
| if len(states) < 2: | |
| continue | |
| lower_better = bool(states[0]["grading"]["is_lower_better"]) | |
| ordered = sorted(states, key=lambda s: s["grading"]["score"], | |
| reverse=not lower_better) # best first | |
| best = ordered[0] | |
| for weak in ordered[1:]: | |
| sb, sw = best["grading"]["score"], weak["grading"]["score"] | |
| gap = abs(sw - sb) / max(abs(sb), abs(sw), 1e-9) | |
| if gap < min_margin: | |
| continue | |
| pairs.append({"competition": comp, "weak": weak, "strong": best, | |
| "gap": gap, "is_lower_better": lower_better}) | |
| return pairs | |
| # Criteria shown to the annotator at once. The remote's error experiment groups | |
| # FOUR (atomic_v2_group4) and reports 97% agreement across 779 labelled states. | |
| # Asking about all seventeen at once produced 62%: agreement is measured as set | |
| # equality, so one disagreement anywhere fails the whole comparison and a | |
| # seventeen-item set is far harder to match than a four-item one. Part of that | |
| # 62% was measuring the batch size rather than the annotator, and holding | |
| # seventeen criteria in view at once plausibly degrades the judgement itself. | |
| ANNOTATION_BATCH = 4 | |
| def annotate_batch(pair: dict, criteria: list[dict], offset: int, *, | |
| model: str, code_cap: int) -> tuple[list[int], bool]: | |
| """One group of criteria. Returns (indices into the FULL list, agreed).""" | |
| numbered = "\n".join(f"{i+1}. {c['criterion']}" | |
| for i, c in enumerate(criteria)) | |
| user = USER.format( | |
| task=truncate(pair["weak"].get("task_prompt", ""), 6000), | |
| weak_code=truncate(pair["weak"]["code"], code_cap), | |
| strong_code=truncate(pair["strong"]["code"], code_cap), | |
| weak_score=pair["weak"]["grading"]["score"], | |
| strong_score=pair["strong"]["grading"]["score"], | |
| gap=f"{pair['gap']*100:.1f}%", | |
| direction="lower is better" if pair["is_lower_better"] else "higher is better", | |
| criteria=numbered) | |
| def _ints(v) -> list[int]: | |
| return sorted({int(x) for x in (v or []) | |
| if isinstance(x, (int, float, str)) and str(x).isdigit() | |
| and 1 <= int(x) <= len(criteria)}) | |
| def once() -> tuple[list[int], list[int]]: | |
| out = extract_json_object(anthropic_text( | |
| prompt=user, system=SYSTEM, model=model, max_tokens=2000, | |
| effort="medium", transport_attempts=6)) | |
| return _ints(out.get("explains")), _ints(out.get("explains_analogous")) | |
| # Two independent samples, adjudicate on disagreement -- the remote's | |
| # protocol. Recording agreement makes annotation noise visible instead of | |
| # letting one sample stand in for ground truth. Agreement and adjudication | |
| # apply to the LITERAL list (the primary truth); the analogous list is a | |
| # diagnostic, kept as the union of the two samples. | |
| try: | |
| (first, first_a), (second, second_a) = once(), once() | |
| except (ModelRefusal, ValueError, json.JSONDecodeError): | |
| return [], [], False | |
| agreement = first == second | |
| final = first | |
| analogous = sorted(set(first_a) | set(second_a)) | |
| if not agreement: | |
| try: | |
| adjudicated = extract_json_object(anthropic_text( | |
| prompt=user + f"\n\nTwo independent annotations disagree: " | |
| f"{first} and {second}. Re-examine the two " | |
| f"programs and return the final set.", | |
| system=SYSTEM, model=model, max_tokens=2000, effort="high", | |
| transport_attempts=6)) | |
| final = _ints(adjudicated.get("explains")) | |
| except Exception: | |
| final = sorted(set(first) & set(second)) # conservative fallback | |
| analogous = [x for x in analogous if x not in final] | |
| return ([offset + i for i in final], | |
| [offset + i for i in analogous], agreement) | |
| def annotate(pair: dict, all_criteria: list[dict], *, model: str, | |
| code_cap: int, batch: int = ANNOTATION_BATCH) -> dict: | |
| """Annotate in small groups, matching the remote's protocol. | |
| Agreement is reported per GROUP, so it is comparable to their 97% rather | |
| than depressed by asking for set equality over the whole library at once. | |
| """ | |
| picked: list[int] = [] | |
| picked_analogous: list[int] = [] | |
| agreements: list[bool] = [] | |
| for start in range(0, len(all_criteria), batch): | |
| group = all_criteria[start:start + batch] | |
| idx, idx_a, agreed = annotate_batch(pair, group, start, model=model, | |
| code_cap=code_cap) | |
| picked.extend(idx) | |
| picked_analogous.extend(idx_a) | |
| agreements.append(agreed) | |
| final = sorted(set(picked)) | |
| final_a = sorted(set(picked_analogous) - set(final)) | |
| return { | |
| "competition": pair["competition"], | |
| "weak_state": pair["weak"]["state_id"], | |
| "strong_state": pair["strong"]["state_id"], | |
| "gap": round(pair["gap"], 5), | |
| "explains_ids": [all_criteria[i - 1]["id"] for i in final], | |
| "explains_analogous_ids": [all_criteria[i - 1]["id"] for i in final_a], | |
| "explains_numbers": final, | |
| "groups": len(agreements), | |
| "groups_agreed": sum(1 for a in agreements if a), | |
| "agreement": all(agreements), | |
| "created_at": time.strftime("%FT%TZ", time.gmtime()), | |
| } | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--scored", default="data/eval_scored.jsonl") | |
| ap.add_argument("--library", default="data/conceptual_applicable.jsonl") | |
| ap.add_argument("--model", default="claude-opus-5") | |
| ap.add_argument("--workers", type=int, default=10) | |
| ap.add_argument("--code-cap", type=int, default=10000) | |
| ap.add_argument("--min-margin", type=float, default=0.02) | |
| ap.add_argument("--out", default="data/truth_annotations.jsonl") | |
| ap.add_argument("--report", default="data/truth_report.json") | |
| args = ap.parse_args() | |
| scored = read_jsonl(args.scored) | |
| criteria = [c for c in read_jsonl(args.library) | |
| if c.get("provenance") != "refuted"] | |
| if not criteria: | |
| raise SystemExit(f"no criteria in {args.library}") | |
| pairs = build_pairs(scored, min_margin=args.min_margin) | |
| print(f"{len(pairs)} weak/strong pairs with a real gap, " | |
| f"{len(criteria)} criteria") | |
| done = {(r["weak_state"]) for r in read_jsonl(args.out)} | |
| todo = [p for p in pairs if p["weak"]["state_id"] not in done] | |
| with ThreadPoolExecutor(max_workers=args.workers) as pool: | |
| futs = [pool.submit(annotate, p, criteria, model=args.model, | |
| code_cap=args.code_cap) for p in todo] | |
| for i, fut in enumerate(as_completed(futs), 1): | |
| row = fut.result() | |
| append_jsonl(args.out, row) | |
| if row.get("explains_ids"): | |
| print(f" [{i}/{len(todo)}] {row['competition'][:26]:28s} " | |
| f"gap {100*row.get('gap',0):.1f}% -> explained by " | |
| f"{len(row['explains_ids'])} criteria " | |
| f"{'' if row['agreement'] else '(adjudicated)'}", flush=True) | |
| rows = read_jsonl(args.out) | |
| explained = [r for r in rows if r.get("explains_ids")] | |
| groups = sum(r.get("groups", 0) for r in rows) | |
| groups_agreed = sum(r.get("groups_agreed", 0) for r in rows) | |
| agreed = [r for r in rows if r.get("agreement") is True] | |
| report = { | |
| "pairs": len(rows), | |
| "pairs_with_an_explanation": len(explained), | |
| # Per GROUP, matching the remote's protocol (they show four criteria at | |
| # a time and report 97% over 779 states). Whole-pair agreement is also | |
| # kept, but it is set equality over the entire library and therefore | |
| # much stricter -- not comparable to their figure. | |
| "annotator_agreement_per_group": (round(groups_agreed / groups, 4) | |
| if groups else None), | |
| "annotator_agreement_whole_pair": (round(len(agreed) / len(rows), 4) | |
| if rows else None), | |
| "annotation_batch": ANNOTATION_BATCH, | |
| "criteria": len(criteria), | |
| "positives": sum(len(r.get("explains_ids") or []) for r in rows), | |
| "note": "A positive is (criterion, weak state) where an annotator that " | |
| "saw both programs and the measured gap judged that criterion " | |
| "to explain it. Unlike the median split this is attributable " | |
| "to the mechanism the criterion names.", | |
| } | |
| write_json(args.report, report) | |
| print(f"\n{len(explained)}/{len(rows)} pairs have at least one explaining " | |
| f"criterion") | |
| print(f"annotator agreement: " | |
| f"{100*(report['annotator_agreement_per_group'] or 0):.0f}% per group " | |
| f"of {ANNOTATION_BATCH} (remote reports 97%), " | |
| f"{100*(report['annotator_agreement_whole_pair'] or 0):.0f}% over the " | |
| f"whole library") | |
| print(f"-> {args.out}") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |