l3cube-pune's picture
Upload 4 files
e222dea verified
Raw
History Blame Contribute Delete
7.19 kB
"""
LLM-as-a-judge scoring.
A judge model decides whether the response is semantically equivalent to the
golden answer, and returns a TRUE/FALSE verdict with a short justification.
Unlike the two deterministic scripts, this accepts paraphrases, alternate
spellings, and transliteration variants.
The judge used for the reported results was Gemma 3 12B. This script is
provider-agnostic: implement `call_model()` for whatever backend you use, then
run as normal.
Usage:
python llm_judge.py --responses my_model_english.csv
python llm_judge.py --responses my_model_english.csv --limit 50 --out scored.csv
Input CSV: the language file from this dataset (columns `question`, `answer`,
`Domain`) with a `response` column added holding the model's raw output.
"""
import argparse
import json
import re
import sys
import pandas as pd
REQUIRED = ["question", "answer", "Domain", "response"]
JUDGE_PROMPT = """You are an evaluation judge. Your task is to determine if the given answer matches the ground truth answer for the given question.
## Input
Question: {question}
Ground Truth Answer: {ground_truth_answer}
Given Answer: {llm_answer}
## Instructions
1. Compare the "Given Answer" against the "Ground Truth Answer" in the context of the question.
2. Correct if semantically equivalent (same meaning / same entity or fact).
3. Minor phrasing, formatting, or extra detail is acceptable if the core answer is correct.
4. Clearly wrong, meaning-changing, or unrelated answers are incorrect.
5. Answers in a different language than the question and ground truth are incorrect.
## Output Format
Return ONLY a JSON object (no additional text, no markdown fences):
{{"is_correct": true, "reasoning": "brief explanation"}}"""
# ---------------------------------------------------------------------------
# IMPLEMENT THIS
# ---------------------------------------------------------------------------
def call_model(prompt: str) -> str:
"""
Send `prompt` to the judge model and return its raw text response.
Replace the body with a call to whichever backend you use. Two sketches:
Local, via transformers:
from transformers import pipeline
pipe = pipeline("text-generation", model="google/gemma-3-12b-it",
device_map="auto", max_new_tokens=200)
return pipe(prompt)[0]["generated_text"][len(prompt):]
Any OpenAI-compatible endpoint (including local vLLM or Ollama):
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="...")
out = client.chat.completions.create(
model="google/gemma-3-12b-it",
messages=[{"role": "user", "content": prompt}],
temperature=0,
)
return out.choices[0].message.content
Use a temperature of 0 or the closest equivalent: the judge should be as
close to deterministic as the backend allows, or scores will not reproduce.
"""
raise NotImplementedError(
"call_model() is a stub. Implement it for your backend before running "
"this script. See the docstring above for two examples."
)
# ---------------------------------------------------------------------------
def parse_verdict(raw: str):
"""
Pull {"is_correct": bool, "reasoning": str} out of the judge's output.
Models sometimes wrap JSON in markdown fences or add a sentence around it
despite the instruction, so fall back to locating the first JSON object.
Returns (is_correct, reasoning); is_correct is None if parsing failed.
"""
text = raw.strip()
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.MULTILINE).strip()
try:
obj = json.loads(text)
except json.JSONDecodeError:
match = re.search(r"\{.*?\}", text, flags=re.DOTALL)
if not match:
return None, f"unparseable judge output: {raw[:120]}"
try:
obj = json.loads(match.group(0))
except json.JSONDecodeError:
return None, f"unparseable judge output: {raw[:120]}"
verdict = obj.get("is_correct")
if isinstance(verdict, str):
verdict = verdict.strip().lower() in ("true", "yes", "1")
if not isinstance(verdict, bool):
return None, f"missing or non-boolean is_correct: {raw[:120]}"
return verdict, str(obj.get("reasoning", ""))
def judge_row(question, answer, response):
prompt = JUDGE_PROMPT.format(question=question,
ground_truth_answer=answer,
llm_answer=response)
return parse_verdict(call_model(prompt))
def report(df, label):
"""Print per-domain and combined accuracy."""
scored = df[df["is_correct"].notna()].copy()
scored["is_correct"] = scored["is_correct"].astype(bool)
per_domain = scored.groupby("Domain")["is_correct"].agg(["sum", "size"])
print(f"\n{label}\n")
print(f"{'Domain':<20} {'Correct':>8} {'Total':>7} {'Accuracy':>10}")
print("-" * 48)
for domain, row in per_domain.iterrows():
acc = row["sum"] / row["size"] * 100
print(f"{domain:<20} {int(row['sum']):>8} {int(row['size']):>7} {acc:>9.2f}%")
correct, total = int(scored["is_correct"].sum()), len(scored)
print("-" * 48)
if total:
print(f"{'COMBINED':<20} {correct:>8} {total:>7} {correct / total * 100:>9.2f}%")
print("\nCombined is the micro-average over all pooled questions, which is")
print("identical to weighting each domain by its size.")
failed = len(df) - total
if failed:
print(f"\nWarning: {failed} row(s) produced unparseable judge output and are")
print("excluded from the accuracy above. Inspect them before reporting a score.")
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--responses", required=True,
help="CSV with columns: question, answer, Domain, response")
ap.add_argument("--out", help="Optional path to write per-question verdicts")
ap.add_argument("--limit", type=int,
help="Judge only the first N rows (useful for a smoke test)")
args = ap.parse_args()
df = pd.read_csv(args.responses)
missing = [c for c in REQUIRED if c not in df.columns]
if missing:
sys.exit(f"Error: {args.responses} is missing column(s): {', '.join(missing)}\n"
f"Found: {', '.join(df.columns)}")
if args.limit:
df = df.head(args.limit).copy()
verdicts, reasons = [], []
for i, row in enumerate(df.itertuples(index=False), start=1):
verdict, reason = judge_row(row.question, row.answer, row.response)
verdicts.append(verdict)
reasons.append(reason)
if i % 50 == 0 or i == len(df):
print(f" judged {i}/{len(df)}", file=sys.stderr)
df["is_correct"] = verdicts
df["judge_reasoning"] = reasons
report(df, f"LLM as a judge — {args.responses}")
if args.out:
df.to_csv(args.out, index=False)
print(f"\nPer-question verdicts written to {args.out}")
if __name__ == "__main__":
main()