"""Collapse guard: the held-out, human-grounded eval gate. The whole self-refinement loop is dangerous precisely because the AI rates its own training data -- that's how model collapse happens. This gate is the antidote: a FROZEN eval set that the AI never generates or rates, scored by the judge, used only to decide whether to KEEP a refinement round. If a round regresses on real held-out tasks, it's reverted. This converts "spirals down" into "only changes that actually help survive." """ import json from pathlib import Path def load_eval(path): p = Path(path) if not p.exists(): return [] return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()] def evaluate(policy, tok, judge, eval_items): """Mean judge score of the policy on the frozen eval set.""" if not eval_items: return 0.0 from core.genutil import chat_generate from core import modalities total = 0.0 for it in eval_items: resp = chat_generate(policy, tok, [{"role": "user", "content": it["instruction"]}], max_new_tokens=512, do_sample=False) js = judge.score(it["instruction"], resp) total += modalities.blended_reward(it.get("type"), js, resp) return total / len(eval_items) def keep_round(new_score, prev_score, tolerance=0.0): """Keep the round only if it doesn't regress beyond tolerance.""" return new_score >= (prev_score - tolerance)