File size: 3,136 Bytes
ccbd209 9bf4115 ccbd209 9bf4115 ccbd209 9bd725a ccbd209 9bd725a ccbd209 9bd725a ccbd209 9bd725a ccbd209 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | """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
|