| """The rater/critic: scores a response 0..1 against the rubric and writes criticism. |
| |
| This is the reward signal for GRPO AND the criticism source for critique-revise. |
| Backend-flexible: loads JUDGE_MODEL via transformers. Swap to an API if you prefer |
| a stronger grader -- just keep score()/critique() returning the same shape. |
| """ |
| import json |
| import os |
| import re |
| from pathlib import Path |
|
|
| ROOT = Path(__file__).resolve().parent.parent |
|
|
|
|
| def load_rubric(): |
| rubric = (ROOT / "rubric.md").read_text(encoding="utf-8") |
| fb = ROOT / "feedback" / "criticisms.jsonl" |
| if fb.exists(): |
| crits = [json.loads(l)["criticism"] for l in fb.read_text(encoding="utf-8").splitlines() if l.strip()] |
| if crits: |
| rubric += "\n\n## Accumulated user/judge criticisms (avoid these)\n" + \ |
| "\n".join(f"- {c}" for c in crits[-50:]) |
| return rubric |
|
|
|
|
| _SYS = ("You are a strict, fair grader. Score the RESPONSE to the PROMPT against the rubric. " |
| "Return ONLY JSON: {\"score\": float 0..1, \"weakest\": str, \"criticism\": str}.") |
|
|
|
|
| class Judge: |
| def __init__(self, model_name=None, device="cuda"): |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| import torch |
| from config import JUDGE_MODEL |
| self.rubric = load_rubric() |
| self.tok = AutoTokenizer.from_pretrained(model_name or JUDGE_MODEL) |
| self.model = AutoModelForCausalLM.from_pretrained( |
| model_name or JUDGE_MODEL, torch_dtype=torch.bfloat16, device_map=device) |
|
|
| def _ask(self, prompt, response): |
| from core.genutil import chat_generate |
| msg = [{"role": "system", "content": _SYS}, |
| {"role": "user", "content": f"RUBRIC:\n{self.rubric}\n\nPROMPT:\n{prompt}\n\nRESPONSE:\n{response}"}] |
| text = chat_generate(self.model, self.tok, msg, max_new_tokens=200, do_sample=False) |
| m = re.search(r"\{.*\}", text, re.DOTALL) |
| try: |
| d = json.loads(m.group(0)) if m else {} |
| except Exception: |
| d = {} |
| return {"score": float(max(0.0, min(1.0, d.get("score", 0.0)))), |
| "weakest": d.get("weakest", "unknown"), |
| "criticism": d.get("criticism", "")} |
|
|
| def score(self, prompt, response): |
| return self._ask(prompt, response)["score"] |
|
|
| def critique(self, prompt, response): |
| return self._ask(prompt, response) |
|
|
|
|
| def make_reward_func(judge): |
| """TRL GRPO reward_func: (prompts, completions, **kw) -> list[float] in 0..1. |
| Routes each item through its modality verifier (objective) blended with the judge.""" |
| from core import modalities |
|
|
| def reward(prompts, completions, **kw): |
| types = kw.get("type") or [None] * len(prompts) |
| out = [] |
| for i, (p, c) in enumerate(zip(prompts, completions)): |
| text = c if isinstance(c, str) else c[-1]["content"] |
| ptext = p if isinstance(p, str) else p[-1]["content"] |
| js = judge.score(ptext, text) |
| t = types[i] if i < len(types) else None |
| out.append(modalities.blended_reward(t, js, text)) |
| return out |
| return reward |
|
|