Datasets:
Upload 4 files
Browse files
sample-evaluation-scripts/README.md
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation scripts
|
| 2 |
+
|
| 3 |
+
Three scripts for scoring model responses against the golden answers. Two are
|
| 4 |
+
deterministic and need no model, no API key and no network; the third uses an
|
| 5 |
+
LLM judge.
|
| 6 |
+
|
| 7 |
+
| Script | Protocol | Needs a model? |
|
| 8 |
+
|---|---|---|
|
| 9 |
+
| `exact_substring.py` | Golden answer must appear as one contiguous substring | No |
|
| 10 |
+
| `word_overlap.py` | Every golden word must appear, in any order | No |
|
| 11 |
+
| `llm_judge.py` | A judge model decides semantic equivalence | Yes |
|
| 12 |
+
|
| 13 |
+
Only `pandas` is required for the deterministic scripts.
|
| 14 |
+
|
| 15 |
+
## Input format
|
| 16 |
+
|
| 17 |
+
Each script takes one CSV: a language file from this dataset with a `response`
|
| 18 |
+
column added.
|
| 19 |
+
|
| 20 |
+
| column | source |
|
| 21 |
+
|---|---|
|
| 22 |
+
| `question` | dataset |
|
| 23 |
+
| `answer` | dataset (golden answer) |
|
| 24 |
+
| `Domain` | dataset |
|
| 25 |
+
| `response` | your model's raw output |
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
python exact_substring.py --responses my_model_english.csv
|
| 29 |
+
python word_overlap.py --responses my_model_english.csv --out scored.csv
|
| 30 |
+
python llm_judge.py --responses my_model_english.csv --limit 50
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Each prints per-domain and combined accuracy. Combined is the micro-average
|
| 34 |
+
over all pooled questions, which is identical to weighting each domain by its
|
| 35 |
+
size. `--out` writes per-question verdicts.
|
| 36 |
+
|
| 37 |
+
`llm_judge.py` ships with `call_model()` as a stub — implement it for your
|
| 38 |
+
backend (the docstring sketches a local `transformers` pipeline and an
|
| 39 |
+
OpenAI-compatible endpoint) and use temperature 0, or scores will not
|
| 40 |
+
reproduce.
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
## 1. Exact substring
|
| 45 |
+
|
| 46 |
+
The entire logic:
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
is_correct = answer.lower() in response.lower()
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
The golden answer must appear as **one contiguous run of characters**.
|
| 53 |
+
Lowercasing is the only normalisation — no trimming, no punctuation handling,
|
| 54 |
+
no tokenisation, no word boundaries.
|
| 55 |
+
|
| 56 |
+
| Golden | Response | Verdict | Why |
|
| 57 |
+
|---|---|---|---|
|
| 58 |
+
| `Ruru Jataka` | `The answer is the Ruru Jataka, depicted at Bharhut.` | correct | surrounding prose is irrelevant |
|
| 59 |
+
| `ruru jataka` | `RURU JATAKA` | correct | case-insensitive |
|
| 60 |
+
| `गंगा` | `गंगा नदी` | correct | works for Devanagari |
|
| 61 |
+
| `Ruru Jataka` | `Jataka Ruru` | wrong | order matters |
|
| 62 |
+
| `Narmada valley` | `the Narmada river valley` | wrong | must be contiguous |
|
| 63 |
+
| `Delhi ` (trailing space) | `Delhi` | wrong | golden answer is not stripped |
|
| 64 |
+
| `amalak` | `Amalaka` | correct | matches inside a longer word |
|
| 65 |
+
| `No` | `There is **no** such temple` | correct | false positive: no word boundary |
|
| 66 |
+
| `Delhi` | `Delhi is not the answer; it's Mumbai` | correct | false positive: mention is not assertion |
|
| 67 |
+
|
| 68 |
+
**What it measures:** whether the model reproduced the golden phrase verbatim,
|
| 69 |
+
including word order and internal spacing. A phrase-fidelity test.
|
| 70 |
+
|
| 71 |
+
**Failure modes.** False negatives dominate and are mostly cosmetic —
|
| 72 |
+
reordering, an inserted qualifier, stray whitespace in the golden answer — so
|
| 73 |
+
the score is a lower bound. False positives are rarer but more damaging:
|
| 74 |
+
nothing anchors the match to a word boundary or to what the model actually
|
| 75 |
+
asserted, so short golden answers can match inside unrelated words, and a
|
| 76 |
+
response that names the golden answer only to reject it still scores correct.
|
| 77 |
+
|
| 78 |
+
---
|
| 79 |
+
|
| 80 |
+
## 2. Word overlap
|
| 81 |
+
|
| 82 |
+
Both sides are lowercased, split on whitespace, stripped of leading and
|
| 83 |
+
trailing punctuation (`delhi.` → `delhi`), and compared as **sets**:
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
is_correct = set(golden_words) <= set(response_words)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
All golden words must appear, in any order, anywhere in the response. Extra
|
| 90 |
+
words are free — a subset test, not equality. The output CSV also carries
|
| 91 |
+
`matching_words` and `total_golden_words`, giving partial credit that the
|
| 92 |
+
binary verdict hides.
|
| 93 |
+
|
| 94 |
+
| Golden | Response | Verdict | Count | Why |
|
| 95 |
+
|---|---|---|---|---|
|
| 96 |
+
| `Narmada valley` | `valley Narmada` | correct | 2/2 | order is irrelevant |
|
| 97 |
+
| `Narmada valley` | `the Narmada river valley in India` | correct | 2/2 | insertions are free |
|
| 98 |
+
| `Narmada valley` | `Narmada` | wrong | 1/2 | every golden word required |
|
| 99 |
+
| `1947 to 1947` | `it was 1947` | wrong | 1/2 | duplicates collapse to a set |
|
| 100 |
+
| `Amalaka` | `amalak` | wrong | 0/1 | whole-token match, no stemming |
|
| 101 |
+
| `Chola ideals` | `Chola and Hoysala ideals` | correct | 2/2 | false positive: different claim |
|
| 102 |
+
|
| 103 |
+
**What it measures:** whether the response contains the golden vocabulary,
|
| 104 |
+
disregarding order, position, and anything said between the words. A
|
| 105 |
+
content-word recall test.
|
| 106 |
+
|
| 107 |
+
**Failure modes.** Extra words are never penalised, so a verbose answer that
|
| 108 |
+
happens to include every golden word passes — this is the main false-positive
|
| 109 |
+
channel and it grows with response length. The comparison is a set rather than
|
| 110 |
+
a multiset, so repetition is never checked. There is no stemming, which matters
|
| 111 |
+
a great deal for Indic morphology.
|
| 112 |
+
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
## How the two differ
|
| 116 |
+
|
| 117 |
+
**Neither is a looser version of the other.** They disagree in both directions,
|
| 118 |
+
because they relax and tighten different axes.
|
| 119 |
+
|
| 120 |
+
| Axis | Exact substring | Word overlap |
|
| 121 |
+
|---|---|---|
|
| 122 |
+
| Word order | must match | irrelevant |
|
| 123 |
+
| Inserted words inside the phrase | fails | passes |
|
| 124 |
+
| Extra words elsewhere | passes | passes |
|
| 125 |
+
| Sub-word match (`amalak` / `Amalaka`) | passes | fails |
|
| 126 |
+
| Whitespace noise in golden answer | fails | tolerated |
|
| 127 |
+
| Unit of comparison | character run | whole token |
|
| 128 |
+
| Partial credit reported | no | yes |
|
| 129 |
+
|
| 130 |
+
### Real disagreements
|
| 131 |
+
|
| 132 |
+
From an actual run (Sarvam 30B on the Art domain, 233 rows — exact 59/233,
|
| 133 |
+
word overlap 56/233). The near-identical totals hide rows that flip in
|
| 134 |
+
*opposite* directions.
|
| 135 |
+
|
| 136 |
+
Exact passes, overlap fails — morphological variants where the golden string
|
| 137 |
+
sits inside a longer word:
|
| 138 |
+
|
| 139 |
+
| Golden | Response |
|
| 140 |
+
|---|---|
|
| 141 |
+
| `amalak` | `Amalaka` |
|
| 142 |
+
| `deul` | `Deula` |
|
| 143 |
+
| `mithun` | `Mithuna` |
|
| 144 |
+
| `Dipankar` | `Dipankara Buddha` |
|
| 145 |
+
| `scroll painting` | `Scroll paintings` |
|
| 146 |
+
|
| 147 |
+
Overlap passes, exact fails — all golden words present, but not contiguous:
|
| 148 |
+
|
| 149 |
+
| Golden | Response |
|
| 150 |
+
|---|---|
|
| 151 |
+
| `Narmada valley` | `Narmada River valley` |
|
| 152 |
+
| `Chola ideals` | `Chola and Hoysala ideals` |
|
| 153 |
+
|
| 154 |
+
Every one of the first group is arguably a correct answer that exact substring
|
| 155 |
+
catches and word overlap misses on a technicality. In the second group,
|
| 156 |
+
`Narmada River valley` is correct and `Chola and Hoysala ideals` is not — word
|
| 157 |
+
overlap gets one right and one wrong for the same reason.
|
| 158 |
+
|
| 159 |
+
### Reading the two scores together
|
| 160 |
+
|
| 161 |
+
Because the metrics are near-orthogonal, the pair is more informative than
|
| 162 |
+
either alone:
|
| 163 |
+
|
| 164 |
+
- **Both pass** → high confidence the answer is right.
|
| 165 |
+
- **Both fail** → high confidence it is wrong, or phrased very differently.
|
| 166 |
+
- **Exact only** → almost always an inflection difference; usually a correct
|
| 167 |
+
answer under-counted by word overlap.
|
| 168 |
+
- **Overlap only** → the golden words are all there but rearranged. Could be a
|
| 169 |
+
correct paraphrase or a genuinely different claim. This bucket needs human or
|
| 170 |
+
judge review.
|
| 171 |
+
|
| 172 |
+
Treat both numbers as **lower bounds**. Neither understands paraphrase,
|
| 173 |
+
synonymy, negation, or numeric equivalence. For that, use `llm_judge.py`.
|
| 174 |
+
|
| 175 |
+
---
|
| 176 |
+
|
| 177 |
+
## Caveats for both deterministic scripts
|
| 178 |
+
|
| 179 |
+
1. **An empty golden answer scores correct** in both (`"" in x` is `True`, and
|
| 180 |
+
an empty set is a subset of anything). Both scripts warn on stderr if the
|
| 181 |
+
input contains one.
|
| 182 |
+
2. **Golden answers are not stripped**, so trailing whitespace breaks exact
|
| 183 |
+
substring outright.
|
| 184 |
+
3. **No Unicode normalisation.** `.lower()` is a no-op for Indic scripts, and
|
| 185 |
+
NFC versus NFD forms of the same word compare unequal. Tokenising is fine,
|
| 186 |
+
but equality is fragile for Indic text — consider normalising to NFC before
|
| 187 |
+
scoring if your responses come from mixed sources.
|
| 188 |
+
4. **Blank responses score incorrect**, and are counted separately in the
|
| 189 |
+
output so that missing data is distinguishable from wrong answers.
|
sample-evaluation-scripts/exact_substring.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Exact-substring scoring.
|
| 3 |
+
|
| 4 |
+
A response is correct if the whole golden answer appears in it as one
|
| 5 |
+
contiguous, case-insensitive substring. No tokenisation, no word boundaries,
|
| 6 |
+
no stemming.
|
| 7 |
+
|
| 8 |
+
is_correct = answer.lower() in response.lower()
|
| 9 |
+
|
| 10 |
+
See scripts/README.md for what this measures, where it gives false positives
|
| 11 |
+
and false negatives, and how it compares with word_overlap.py.
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python exact_substring.py --responses my_model_english.csv
|
| 15 |
+
python exact_substring.py --responses my_model_english.csv --out scored.csv
|
| 16 |
+
|
| 17 |
+
Input CSV: the language file from this dataset (columns `question`, `answer`,
|
| 18 |
+
`Domain`) with a `response` column added holding the model's raw output.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import sys
|
| 23 |
+
|
| 24 |
+
import pandas as pd
|
| 25 |
+
|
| 26 |
+
REQUIRED = ["question", "answer", "Domain", "response"]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def is_correct(answer, response):
|
| 30 |
+
"""The golden answer must appear as one contiguous run of characters."""
|
| 31 |
+
return str(answer).lower() in str(response).lower()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def report(df, label):
|
| 35 |
+
"""Print per-domain and combined accuracy."""
|
| 36 |
+
per_domain = df.groupby("Domain")["is_correct"].agg(["sum", "size"])
|
| 37 |
+
|
| 38 |
+
print(f"\n{label}\n")
|
| 39 |
+
print(f"{'Domain':<20} {'Correct':>8} {'Total':>7} {'Accuracy':>10}")
|
| 40 |
+
print("-" * 48)
|
| 41 |
+
for domain, row in per_domain.iterrows():
|
| 42 |
+
acc = row["sum"] / row["size"] * 100
|
| 43 |
+
print(f"{domain:<20} {int(row['sum']):>8} {int(row['size']):>7} {acc:>9.2f}%")
|
| 44 |
+
|
| 45 |
+
correct, total = int(df["is_correct"].sum()), len(df)
|
| 46 |
+
blank = int((df["response"].fillna("").astype(str).str.strip() == "").sum())
|
| 47 |
+
print("-" * 48)
|
| 48 |
+
print(f"{'COMBINED':<20} {correct:>8} {total:>7} {correct / total * 100:>9.2f}%")
|
| 49 |
+
print("\nCombined is the micro-average over all pooled questions, which is")
|
| 50 |
+
print("identical to weighting each domain by its size.")
|
| 51 |
+
if blank:
|
| 52 |
+
print(f"Blank responses: {blank} (scored incorrect)")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def main():
|
| 56 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 57 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 58 |
+
ap.add_argument("--responses", required=True,
|
| 59 |
+
help="CSV with columns: question, answer, Domain, response")
|
| 60 |
+
ap.add_argument("--out", help="Optional path to write per-question verdicts")
|
| 61 |
+
args = ap.parse_args()
|
| 62 |
+
|
| 63 |
+
df = pd.read_csv(args.responses)
|
| 64 |
+
|
| 65 |
+
missing = [c for c in REQUIRED if c not in df.columns]
|
| 66 |
+
if missing:
|
| 67 |
+
sys.exit(f"Error: {args.responses} is missing column(s): {', '.join(missing)}\n"
|
| 68 |
+
f"Found: {', '.join(df.columns)}")
|
| 69 |
+
|
| 70 |
+
# A blank answer would match every response vacuously; flag rather than
|
| 71 |
+
# silently inflate the score.
|
| 72 |
+
blank_answers = int((df["answer"].fillna("").astype(str).str.strip() == "").sum())
|
| 73 |
+
if blank_answers:
|
| 74 |
+
print(f"Warning: {blank_answers} row(s) have an empty golden answer. "
|
| 75 |
+
f"These match any response and will score correct.", file=sys.stderr)
|
| 76 |
+
|
| 77 |
+
df["is_correct"] = [is_correct(a, r) for a, r in zip(df["answer"], df["response"])]
|
| 78 |
+
|
| 79 |
+
report(df, f"Exact substring — {args.responses}")
|
| 80 |
+
|
| 81 |
+
if args.out:
|
| 82 |
+
df.to_csv(args.out, index=False)
|
| 83 |
+
print(f"\nPer-question verdicts written to {args.out}")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
main()
|
sample-evaluation-scripts/llm_judge.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LLM-as-a-judge scoring.
|
| 3 |
+
|
| 4 |
+
A judge model decides whether the response is semantically equivalent to the
|
| 5 |
+
golden answer, and returns a TRUE/FALSE verdict with a short justification.
|
| 6 |
+
Unlike the two deterministic scripts, this accepts paraphrases, alternate
|
| 7 |
+
spellings, and transliteration variants.
|
| 8 |
+
|
| 9 |
+
The judge used for the reported results was Gemma 3 12B. This script is
|
| 10 |
+
provider-agnostic: implement `call_model()` for whatever backend you use, then
|
| 11 |
+
run as normal.
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python llm_judge.py --responses my_model_english.csv
|
| 15 |
+
python llm_judge.py --responses my_model_english.csv --limit 50 --out scored.csv
|
| 16 |
+
|
| 17 |
+
Input CSV: the language file from this dataset (columns `question`, `answer`,
|
| 18 |
+
`Domain`) with a `response` column added holding the model's raw output.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
import pandas as pd
|
| 27 |
+
|
| 28 |
+
REQUIRED = ["question", "answer", "Domain", "response"]
|
| 29 |
+
|
| 30 |
+
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.
|
| 31 |
+
|
| 32 |
+
## Input
|
| 33 |
+
Question: {question}
|
| 34 |
+
Ground Truth Answer: {ground_truth_answer}
|
| 35 |
+
Given Answer: {llm_answer}
|
| 36 |
+
|
| 37 |
+
## Instructions
|
| 38 |
+
1. Compare the "Given Answer" against the "Ground Truth Answer" in the context of the question.
|
| 39 |
+
2. Correct if semantically equivalent (same meaning / same entity or fact).
|
| 40 |
+
3. Minor phrasing, formatting, or extra detail is acceptable if the core answer is correct.
|
| 41 |
+
4. Clearly wrong, meaning-changing, or unrelated answers are incorrect.
|
| 42 |
+
5. Answers in a different language than the question and ground truth are incorrect.
|
| 43 |
+
|
| 44 |
+
## Output Format
|
| 45 |
+
Return ONLY a JSON object (no additional text, no markdown fences):
|
| 46 |
+
{{"is_correct": true, "reasoning": "brief explanation"}}"""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ---------------------------------------------------------------------------
|
| 50 |
+
# IMPLEMENT THIS
|
| 51 |
+
# ---------------------------------------------------------------------------
|
| 52 |
+
|
| 53 |
+
def call_model(prompt: str) -> str:
|
| 54 |
+
"""
|
| 55 |
+
Send `prompt` to the judge model and return its raw text response.
|
| 56 |
+
|
| 57 |
+
Replace the body with a call to whichever backend you use. Two sketches:
|
| 58 |
+
|
| 59 |
+
Local, via transformers:
|
| 60 |
+
|
| 61 |
+
from transformers import pipeline
|
| 62 |
+
pipe = pipeline("text-generation", model="google/gemma-3-12b-it",
|
| 63 |
+
device_map="auto", max_new_tokens=200)
|
| 64 |
+
return pipe(prompt)[0]["generated_text"][len(prompt):]
|
| 65 |
+
|
| 66 |
+
Any OpenAI-compatible endpoint (including local vLLM or Ollama):
|
| 67 |
+
|
| 68 |
+
from openai import OpenAI
|
| 69 |
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="...")
|
| 70 |
+
out = client.chat.completions.create(
|
| 71 |
+
model="google/gemma-3-12b-it",
|
| 72 |
+
messages=[{"role": "user", "content": prompt}],
|
| 73 |
+
temperature=0,
|
| 74 |
+
)
|
| 75 |
+
return out.choices[0].message.content
|
| 76 |
+
|
| 77 |
+
Use a temperature of 0 or the closest equivalent: the judge should be as
|
| 78 |
+
close to deterministic as the backend allows, or scores will not reproduce.
|
| 79 |
+
"""
|
| 80 |
+
raise NotImplementedError(
|
| 81 |
+
"call_model() is a stub. Implement it for your backend before running "
|
| 82 |
+
"this script. See the docstring above for two examples."
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
|
| 88 |
+
def parse_verdict(raw: str):
|
| 89 |
+
"""
|
| 90 |
+
Pull {"is_correct": bool, "reasoning": str} out of the judge's output.
|
| 91 |
+
|
| 92 |
+
Models sometimes wrap JSON in markdown fences or add a sentence around it
|
| 93 |
+
despite the instruction, so fall back to locating the first JSON object.
|
| 94 |
+
Returns (is_correct, reasoning); is_correct is None if parsing failed.
|
| 95 |
+
"""
|
| 96 |
+
text = raw.strip()
|
| 97 |
+
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.MULTILINE).strip()
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
obj = json.loads(text)
|
| 101 |
+
except json.JSONDecodeError:
|
| 102 |
+
match = re.search(r"\{.*?\}", text, flags=re.DOTALL)
|
| 103 |
+
if not match:
|
| 104 |
+
return None, f"unparseable judge output: {raw[:120]}"
|
| 105 |
+
try:
|
| 106 |
+
obj = json.loads(match.group(0))
|
| 107 |
+
except json.JSONDecodeError:
|
| 108 |
+
return None, f"unparseable judge output: {raw[:120]}"
|
| 109 |
+
|
| 110 |
+
verdict = obj.get("is_correct")
|
| 111 |
+
if isinstance(verdict, str):
|
| 112 |
+
verdict = verdict.strip().lower() in ("true", "yes", "1")
|
| 113 |
+
if not isinstance(verdict, bool):
|
| 114 |
+
return None, f"missing or non-boolean is_correct: {raw[:120]}"
|
| 115 |
+
|
| 116 |
+
return verdict, str(obj.get("reasoning", ""))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def judge_row(question, answer, response):
|
| 120 |
+
prompt = JUDGE_PROMPT.format(question=question,
|
| 121 |
+
ground_truth_answer=answer,
|
| 122 |
+
llm_answer=response)
|
| 123 |
+
return parse_verdict(call_model(prompt))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def report(df, label):
|
| 127 |
+
"""Print per-domain and combined accuracy."""
|
| 128 |
+
scored = df[df["is_correct"].notna()].copy()
|
| 129 |
+
scored["is_correct"] = scored["is_correct"].astype(bool)
|
| 130 |
+
per_domain = scored.groupby("Domain")["is_correct"].agg(["sum", "size"])
|
| 131 |
+
|
| 132 |
+
print(f"\n{label}\n")
|
| 133 |
+
print(f"{'Domain':<20} {'Correct':>8} {'Total':>7} {'Accuracy':>10}")
|
| 134 |
+
print("-" * 48)
|
| 135 |
+
for domain, row in per_domain.iterrows():
|
| 136 |
+
acc = row["sum"] / row["size"] * 100
|
| 137 |
+
print(f"{domain:<20} {int(row['sum']):>8} {int(row['size']):>7} {acc:>9.2f}%")
|
| 138 |
+
|
| 139 |
+
correct, total = int(scored["is_correct"].sum()), len(scored)
|
| 140 |
+
print("-" * 48)
|
| 141 |
+
if total:
|
| 142 |
+
print(f"{'COMBINED':<20} {correct:>8} {total:>7} {correct / total * 100:>9.2f}%")
|
| 143 |
+
print("\nCombined is the micro-average over all pooled questions, which is")
|
| 144 |
+
print("identical to weighting each domain by its size.")
|
| 145 |
+
|
| 146 |
+
failed = len(df) - total
|
| 147 |
+
if failed:
|
| 148 |
+
print(f"\nWarning: {failed} row(s) produced unparseable judge output and are")
|
| 149 |
+
print("excluded from the accuracy above. Inspect them before reporting a score.")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def main():
|
| 153 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 154 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 155 |
+
ap.add_argument("--responses", required=True,
|
| 156 |
+
help="CSV with columns: question, answer, Domain, response")
|
| 157 |
+
ap.add_argument("--out", help="Optional path to write per-question verdicts")
|
| 158 |
+
ap.add_argument("--limit", type=int,
|
| 159 |
+
help="Judge only the first N rows (useful for a smoke test)")
|
| 160 |
+
args = ap.parse_args()
|
| 161 |
+
|
| 162 |
+
df = pd.read_csv(args.responses)
|
| 163 |
+
|
| 164 |
+
missing = [c for c in REQUIRED if c not in df.columns]
|
| 165 |
+
if missing:
|
| 166 |
+
sys.exit(f"Error: {args.responses} is missing column(s): {', '.join(missing)}\n"
|
| 167 |
+
f"Found: {', '.join(df.columns)}")
|
| 168 |
+
|
| 169 |
+
if args.limit:
|
| 170 |
+
df = df.head(args.limit).copy()
|
| 171 |
+
|
| 172 |
+
verdicts, reasons = [], []
|
| 173 |
+
for i, row in enumerate(df.itertuples(index=False), start=1):
|
| 174 |
+
verdict, reason = judge_row(row.question, row.answer, row.response)
|
| 175 |
+
verdicts.append(verdict)
|
| 176 |
+
reasons.append(reason)
|
| 177 |
+
if i % 50 == 0 or i == len(df):
|
| 178 |
+
print(f" judged {i}/{len(df)}", file=sys.stderr)
|
| 179 |
+
|
| 180 |
+
df["is_correct"] = verdicts
|
| 181 |
+
df["judge_reasoning"] = reasons
|
| 182 |
+
|
| 183 |
+
report(df, f"LLM as a judge — {args.responses}")
|
| 184 |
+
|
| 185 |
+
if args.out:
|
| 186 |
+
df.to_csv(args.out, index=False)
|
| 187 |
+
print(f"\nPer-question verdicts written to {args.out}")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
main()
|
sample-evaluation-scripts/word_overlap.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Word-overlap scoring.
|
| 3 |
+
|
| 4 |
+
A response is correct if every word of the golden answer appears somewhere in
|
| 5 |
+
it, in any order. Both sides are lowercased, split on whitespace, stripped of
|
| 6 |
+
leading and trailing punctuation, and compared as sets.
|
| 7 |
+
|
| 8 |
+
is_correct = set(golden_words) <= set(response_words)
|
| 9 |
+
|
| 10 |
+
Extra words in the response are free: this is a subset test, not equality.
|
| 11 |
+
Because the comparison is set-based, repeated words in the golden answer
|
| 12 |
+
collapse to one.
|
| 13 |
+
|
| 14 |
+
See scripts/README.md for what this measures, where it gives false positives
|
| 15 |
+
and false negatives, and how it compares with exact_substring.py.
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
python word_overlap.py --responses my_model_english.csv
|
| 19 |
+
python word_overlap.py --responses my_model_english.csv --out scored.csv
|
| 20 |
+
|
| 21 |
+
Input CSV: the language file from this dataset (columns `question`, `answer`,
|
| 22 |
+
`Domain`) with a `response` column added holding the model's raw output.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
import pandas as pd
|
| 29 |
+
|
| 30 |
+
REQUIRED = ["question", "answer", "Domain", "response"]
|
| 31 |
+
|
| 32 |
+
# Stripped from the edges of each token. Includes the Devanagari danda and
|
| 33 |
+
# double danda alongside ASCII punctuation.
|
| 34 |
+
PUNCTUATION = " \t\n\r.,;:!?\"'()[]{}<>/\\|`~@#$%^&*-_=+।॥"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def words(text):
|
| 38 |
+
"""Lowercase, split on whitespace, strip edge punctuation, drop empties."""
|
| 39 |
+
tokens = (t.strip(PUNCTUATION) for t in str(text).lower().split())
|
| 40 |
+
return {t for t in tokens if t}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def score_row(answer, response):
|
| 44 |
+
"""Return (is_correct, matching_word_count, golden_word_count)."""
|
| 45 |
+
golden, given = words(answer), words(response)
|
| 46 |
+
matching = golden & given
|
| 47 |
+
# An empty golden answer is vacuously satisfied.
|
| 48 |
+
return len(matching) == len(golden), len(matching), len(golden)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def report(df, label):
|
| 52 |
+
"""Print per-domain and combined accuracy, plus word recall."""
|
| 53 |
+
per_domain = df.groupby("Domain").agg(
|
| 54 |
+
correct=("is_correct", "sum"),
|
| 55 |
+
total=("is_correct", "size"),
|
| 56 |
+
matched=("matching_words", "sum"),
|
| 57 |
+
golden=("total_golden_words", "sum"),
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
print(f"\n{label}\n")
|
| 61 |
+
print(f"{'Domain':<20} {'Correct':>8} {'Total':>7} {'Accuracy':>10} {'Word recall':>13}")
|
| 62 |
+
print("-" * 62)
|
| 63 |
+
for domain, row in per_domain.iterrows():
|
| 64 |
+
acc = row["correct"] / row["total"] * 100
|
| 65 |
+
recall = row["matched"] / row["golden"] * 100 if row["golden"] else 0.0
|
| 66 |
+
print(f"{domain:<20} {int(row['correct']):>8} {int(row['total']):>7} "
|
| 67 |
+
f"{acc:>9.2f}% {recall:>12.2f}%")
|
| 68 |
+
|
| 69 |
+
correct, total = int(df["is_correct"].sum()), len(df)
|
| 70 |
+
matched = int(df["matching_words"].sum())
|
| 71 |
+
golden = int(df["total_golden_words"].sum())
|
| 72 |
+
recall = matched / golden * 100 if golden else 0.0
|
| 73 |
+
blank = int((df["response"].fillna("").astype(str).str.strip() == "").sum())
|
| 74 |
+
|
| 75 |
+
print("-" * 62)
|
| 76 |
+
print(f"{'COMBINED':<20} {correct:>8} {total:>7} "
|
| 77 |
+
f"{correct / total * 100:>9.2f}% {recall:>12.2f}%")
|
| 78 |
+
print("\nCombined is the micro-average over all pooled questions, which is")
|
| 79 |
+
print("identical to weighting each domain by its size.")
|
| 80 |
+
print(f"Word recall: {matched}/{golden} golden words found. This is partial")
|
| 81 |
+
print("credit that the binary accuracy above hides.")
|
| 82 |
+
if blank:
|
| 83 |
+
print(f"Blank responses: {blank} (scored incorrect)")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def main():
|
| 87 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 88 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 89 |
+
ap.add_argument("--responses", required=True,
|
| 90 |
+
help="CSV with columns: question, answer, Domain, response")
|
| 91 |
+
ap.add_argument("--out", help="Optional path to write per-question verdicts")
|
| 92 |
+
args = ap.parse_args()
|
| 93 |
+
|
| 94 |
+
df = pd.read_csv(args.responses)
|
| 95 |
+
|
| 96 |
+
missing = [c for c in REQUIRED if c not in df.columns]
|
| 97 |
+
if missing:
|
| 98 |
+
sys.exit(f"Error: {args.responses} is missing column(s): {', '.join(missing)}\n"
|
| 99 |
+
f"Found: {', '.join(df.columns)}")
|
| 100 |
+
|
| 101 |
+
blank_answers = int((df["answer"].fillna("").astype(str).str.strip() == "").sum())
|
| 102 |
+
if blank_answers:
|
| 103 |
+
print(f"Warning: {blank_answers} row(s) have an empty golden answer. "
|
| 104 |
+
f"These are vacuously satisfied and will score correct.", file=sys.stderr)
|
| 105 |
+
|
| 106 |
+
scored = [score_row(a, r) for a, r in zip(df["answer"], df["response"])]
|
| 107 |
+
df["is_correct"] = [s[0] for s in scored]
|
| 108 |
+
df["matching_words"] = [s[1] for s in scored]
|
| 109 |
+
df["total_golden_words"] = [s[2] for s in scored]
|
| 110 |
+
|
| 111 |
+
report(df, f"Word overlap — {args.responses}")
|
| 112 |
+
|
| 113 |
+
if args.out:
|
| 114 |
+
df.to_csv(args.out, index=False)
|
| 115 |
+
print(f"\nPer-question verdicts written to {args.out}")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
main()
|