EdwardoSunny's picture
Pipeline code snapshot (rubric_gen + gke) matching commit bee1bd2
f45837e verified
Raw History Blame Contribute Delete
7.73 kB
#!/usr/bin/env python3
"""Generate one error rubric per eligible observation, without dedup or a cap."""
from __future__ import annotations
import argparse
import itertools
import re
import sys
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common import ModelRefusal, anthropic_text, append_jsonl, read_jsonl, short_id, truncate, write_json
from errors import prompts
from shared.protocol import CURATOR_MODEL
NULL_RE = re.compile(r"^\s*rubric:\s*null", re.I | re.M)
REASON_RE = re.compile(r"^\s*reason:\s*(\S+)", re.I | re.M)
HEADING_RE = re.compile(r"^###\s+(.+?)\s*$", re.M)
FIELD_RE = {
"input_condition": re.compile(r"^-\s*\*\*Input condition\*\*:\s*(.+)$", re.M),
"code_requirement": re.compile(r"^-\s*\*\*Code requirement\*\*:\s*(.+)$", re.M),
"prediction": re.compile(r"^-\s*\*\*Prediction\*\*:\s*(.+)$", re.M),
}
STOP_WORDS = set("a an the is are be to of in on for with and or as that this it its from by at into when where which".split())
def normalize(text: str) -> str:
words = [word for word in re.findall(r"[a-z0-9]+", (text or "").lower())
if word not in STOP_WORDS]
return " ".join(sorted(set(words)))
def parse_rubric(text: str) -> dict | None:
if not text or NULL_RE.search(text):
return None
heading = HEADING_RE.search(text)
if not heading:
return None
fields = {}
for key, pattern in FIELD_RE.items():
match = pattern.search(text)
if not match:
return None
fields[key] = match.group(1).strip()
return {"title": heading.group(1).strip(), **fields, "markdown": text.strip()}
def null_reason(text: str) -> str:
match = REASON_RE.search(text or "")
return match.group(1).strip() if match else ("empty" if not text else "unparsed")
def validate(rubric: dict, exception_class: str) -> list[str]:
problems = []
if not re.match(r"^`?(task|code)`?\s*:", rubric["input_condition"], re.I):
problems.append("input condition does not declare a `task`/`code` source")
if exception_class and exception_class.lower() not in rubric["prediction"].lower():
problems.append(f"prediction does not name the observed {exception_class}")
return problems
def fingerprint(rubric: dict, exception_class: str) -> str:
"""Reporting metadata only; never used to remove a rubric."""
return short_id(f"{exception_class}|{normalize(rubric['input_condition'])}")
def interleave(states: list[dict]) -> list[dict]:
by_competition: dict[str, list[dict]] = defaultdict(list)
for state in states:
by_competition[state["competition"]].append(state)
queues = [iter(rows) for _, rows in sorted(by_competition.items())]
return [state for group in itertools.zip_longest(*queues)
for state in group if state is not None]
def generate_one(state: dict, *, model: str, code_cap: int, error_cap: int) -> dict:
execution = state["execution"]
errors = truncate(f"{execution.get('stdout', '')}\n--- stderr ---\n{execution.get('stderr', '')}", error_cap)
user = prompts.build_user(
task=truncate(state.get("task_prompt", ""), 16000),
code=truncate(state["code"], code_cap), errors=errors)
try:
text = anthropic_text(prompt=user, system=prompts.SYSTEM, model=model,
max_tokens=6000, effort="high")
except ModelRefusal as exc:
return {"state_id": state["state_id"], "emitted": False,
"reason": "refusal", "detail": str(exc)[:200]}
rubric = parse_rubric(text)
row = {
"state_id": state["state_id"], "competition": state["competition"],
"trajectory": state.get("trajectory") or state.get("trajectory_id"),
"stage": state.get("stage"),
"exception_class": execution.get("exception_class"),
"exception_message": (execution.get("exception_message") or "")[:300],
"model": model, "raw": text[:20000],
}
if rubric is None:
row.update({"emitted": False, "reason": null_reason(text)})
return row
problems = validate(rubric, execution.get("exception_class") or "")
row.update({"emitted": not problems, "reason": "" if not problems else "invalid",
"problems": problems, "rubric": rubric,
"fingerprint": fingerprint(rubric, execution.get("exception_class") or "")})
return row
def slugify(text: str, cap: int = 60) -> str:
value = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")
return value[:cap].rstrip("-") or "rubric"
def render(rubric: dict, row: dict, index: int) -> str:
return f"""---
id: E{index:03d}
family: error
exception_class: {row.get('exception_class') or 'unknown'}
competition: {row['competition']}
trajectory: {row.get('trajectory') or ''}
stage: {row.get('stage') or ''}
generator: {row['model']}
prompt_version: predictive_v6
split: source
fingerprint: {row['fingerprint']}
---
{rubric['markdown']}
"""
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--states", default="data/states.jsonl")
parser.add_argument("--out", default="out/errors")
parser.add_argument("--log", default="data/error_curation_log.jsonl")
parser.add_argument("--model", default=CURATOR_MODEL)
parser.add_argument("--workers", type=int, default=16)
parser.add_argument("--code-cap", type=int, default=30000)
parser.add_argument("--error-cap", type=int, default=12000)
args = parser.parse_args()
states = interleave([row for row in read_jsonl(args.states)
if row.get("eligible_error")])
if not states:
print(f"no eligible error states in {args.states}")
return 1
prior = read_jsonl(args.log)
done = {row["state_id"] for row in prior}
pending = [row for row in states if row["state_id"] not in done]
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = {pool.submit(generate_one, state, model=args.model,
code_cap=args.code_cap, error_cap=args.error_cap): state
for state in pending}
for future in as_completed(futures):
row = future.result()
append_jsonl(args.log, row)
print(f"[{len(done) + 1}/{len(states)}] {row.get('reason') or 'emitted'}", flush=True)
done.add(row["state_id"])
rows = read_jsonl(args.log)
by_state = {row["state_id"]: row for row in rows}
accepted = [by_state[state["state_id"]] for state in states
if by_state.get(state["state_id"], {}).get("emitted")]
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
for old in out.glob("E*.md"):
old.unlink()
for index, row in enumerate(accepted, 1):
(out / f"E{index:03d}-{slugify(row['rubric']['title'])}.md").write_text(
render(row["rubric"], row, index))
reasons: dict[str, int] = {}
for row in rows:
if not row.get("emitted"):
reason = row.get("reason", "unknown")
reasons[reason] = reasons.get(reason, 0) + 1
write_json(out.parent / "error_summary.json", {
"arm": "errors", "prompt_version": "predictive_v6", "model": args.model,
"eligible_observations": len(states), "processed": len(by_state),
"written": len(accepted), "deduplication": "none",
"fingerprints": "metadata only", "null_reasons": reasons,
})
print(f"{len(accepted)} rubrics from {len(states)} eligible observations -> {out}")
return 0
if __name__ == "__main__":
raise SystemExit(main())