Datasets:
Tasks:
Question Answering
Modalities:
Text
Formats:
json
Languages:
English
Size:
10K - 100K
Tags:
chemistry
molecular-property-prediction
smiles
structure-elucidation
Synthetic
adaption-autoscientist
License:
Upload common/scoring.py with huggingface_hub
Browse files- common/scoring.py +201 -0
common/scoring.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scoring harness shared by every entry's scorer.
|
| 2 |
+
|
| 3 |
+
Reads the generation files gcp_eval.py writes and handles the two modes uniformly:
|
| 4 |
+
|
| 5 |
+
{"id","category","prompt","reference","tuned","base"} adapter run
|
| 6 |
+
{"id","category","prompt","reference","output"} Day-0 base-only run
|
| 7 |
+
|
| 8 |
+
Conventions carried over from the three scorers that won the finished entries:
|
| 9 |
+
|
| 10 |
+
- A per-row metric returns True, False, or **None meaning not applicable**, and None is
|
| 11 |
+
excluded from that metric's denominator rather than counted wrong.
|
| 12 |
+
- A metric that is a strict conjunction gets no partial credit, because partial credit
|
| 13 |
+
hides the failure that matters: a confidently wrong answer that looks well-formed.
|
| 14 |
+
- If nothing was scoreable, say so loudly. A silent 0.0% reads like a model result when
|
| 15 |
+
it is really a harness failure, and that has cost this project real time.
|
| 16 |
+
- Print the DELTA in both points and relative percent, because the competition scores
|
| 17 |
+
relative improvement over the base.
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Callable, Sequence
|
| 24 |
+
|
| 25 |
+
LABELS = {"tuned": "TUNED", "base": "BASE", "output": "BASE (day-0)"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load(path: str | Path) -> list[dict]:
|
| 29 |
+
rows = [json.loads(l) for l in Path(path).read_text().splitlines() if l.strip()]
|
| 30 |
+
if not rows:
|
| 31 |
+
raise SystemExit(f"{path}: no rows")
|
| 32 |
+
return rows
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def columns(rows: Sequence[dict]) -> list[str]:
|
| 36 |
+
"""Which prediction columns this file carries."""
|
| 37 |
+
return ["tuned", "base"] if "tuned" in rows[0] else ["output"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def score_file(rows: Sequence[dict],
|
| 41 |
+
metrics: dict[str, Callable[[str, dict], bool | None]]) -> dict:
|
| 42 |
+
"""Apply each metric to each row for each column.
|
| 43 |
+
|
| 44 |
+
metrics maps a metric name to fn(prediction_text, row) -> True | False | None.
|
| 45 |
+
Returns {column: {metric: {"pct","n_true","n_scored","n_skipped"}}}.
|
| 46 |
+
"""
|
| 47 |
+
out: dict[str, dict] = {}
|
| 48 |
+
for col in columns(rows):
|
| 49 |
+
per: dict[str, dict] = {}
|
| 50 |
+
for name, fn in metrics.items():
|
| 51 |
+
t = s = k = 0
|
| 52 |
+
for r in rows:
|
| 53 |
+
v = fn(r.get(col) or "", r)
|
| 54 |
+
if v is None:
|
| 55 |
+
k += 1
|
| 56 |
+
continue
|
| 57 |
+
s += 1
|
| 58 |
+
t += bool(v)
|
| 59 |
+
per[name] = {"pct": round(100.0 * t / s, 1) if s else 0.0,
|
| 60 |
+
"n_true": t, "n_scored": s, "n_skipped": k}
|
| 61 |
+
out[col] = per
|
| 62 |
+
return out
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def report(result: dict, title: str, headline: str | None = None) -> None:
|
| 66 |
+
"""Print the metric table, the harness warning, and the DELTA block."""
|
| 67 |
+
cols = list(result)
|
| 68 |
+
names = list(next(iter(result.values()))) if result else []
|
| 69 |
+
|
| 70 |
+
print("=" * 72)
|
| 71 |
+
print(title)
|
| 72 |
+
print("=" * 72)
|
| 73 |
+
w = max([len(n) for n in names] + [22])
|
| 74 |
+
print(f"{'metric':<{w}} " + " ".join(f"{LABELS.get(c, c):>14}" for c in cols))
|
| 75 |
+
for n in names:
|
| 76 |
+
cells = []
|
| 77 |
+
for c in cols:
|
| 78 |
+
m = result[c][n]
|
| 79 |
+
cells.append(f"{m['pct']:>8.1f}% ({m['n_true']}/{m['n_scored']})".rjust(14))
|
| 80 |
+
print(f"{n:<{w}} " + " ".join(cells))
|
| 81 |
+
|
| 82 |
+
for c in cols:
|
| 83 |
+
for n in names:
|
| 84 |
+
if result[c][n]["n_scored"] == 0:
|
| 85 |
+
print(f"\nWARNING: 0 of the rows were scoreable for {n!r} on column {c!r}.")
|
| 86 |
+
print(" This is a HARNESS failure, not a model result. Check that the")
|
| 87 |
+
print(" generation file matches the slice and that ids/references parse.")
|
| 88 |
+
|
| 89 |
+
if headline and len(cols) == 2 and headline in names:
|
| 90 |
+
b = result["base"][headline]["pct"]
|
| 91 |
+
t = result["tuned"][headline]["pct"]
|
| 92 |
+
rel = f"{(t - b) / b * 100:+.0f}%" if b else "n/a (base is 0)"
|
| 93 |
+
print(f"\nDELTA {headline}: {b:.1f}% to {t:.1f}% "
|
| 94 |
+
f"= {t - b:+.1f} points, relative {rel}")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def length_report(rows: Sequence[dict]) -> dict:
|
| 98 |
+
"""Median output length per column, and the terseness ratio.
|
| 99 |
+
|
| 100 |
+
First-class on purpose. Collapsing to terse output raised accuracy and destroyed the
|
| 101 |
+
win rate twice in this project, and both times it was invisible in the accuracy
|
| 102 |
+
numbers.
|
| 103 |
+
|
| 104 |
+
THE DENOMINATOR IS GOLD, NOT BASE, and that correction was bought with a false
|
| 105 |
+
positive. On MolPerceive the tuned median was 406 characters against a base of 1,609,
|
| 106 |
+
a ratio of 0.25 that tripped the old rule and failed a run that was fine. The gold
|
| 107 |
+
median was also 406: the tuned model matched the target format exactly, and the base
|
| 108 |
+
was long only because it rambles through chemistry it gets wrong. Measuring terseness
|
| 109 |
+
against a verbose, incorrect base inverts the rule precisely when the base is worst.
|
| 110 |
+
|
| 111 |
+
So the gate is `tuned / gold`, which is what "did the model get terser than it should
|
| 112 |
+
be" actually means. The base ratio is still reported, as context only, because a large
|
| 113 |
+
gap between the two is informative about the base rather than about us.
|
| 114 |
+
|
| 115 |
+
A guard that cries wolf is worse than no guard, because it trains you to skip it.
|
| 116 |
+
"""
|
| 117 |
+
def med(xs: list[int]) -> int:
|
| 118 |
+
return sorted(xs)[len(xs) // 2] if xs else 0
|
| 119 |
+
|
| 120 |
+
cols = columns(rows)
|
| 121 |
+
out = {c: med([len(r.get(c) or "") for r in rows]) for c in cols}
|
| 122 |
+
|
| 123 |
+
# The reference column is the gold completion; scorers name it "reference".
|
| 124 |
+
gold = med([len(r.get("reference") or "") for r in rows])
|
| 125 |
+
if gold:
|
| 126 |
+
out["gold"] = gold
|
| 127 |
+
if "tuned" in out and "base" in out and out["base"]:
|
| 128 |
+
out["ratio_tuned_over_base"] = round(out["tuned"] / out["base"], 2)
|
| 129 |
+
if "tuned" in out and gold:
|
| 130 |
+
ratio = out["tuned"] / gold
|
| 131 |
+
out["ratio_tuned_over_gold"] = round(ratio, 2)
|
| 132 |
+
out["terseness_flag"] = ratio < 0.6
|
| 133 |
+
out["terseness_basis"] = "gold"
|
| 134 |
+
elif "tuned" in out and "base" in out and out["base"]:
|
| 135 |
+
# No gold available (Day-0 probe files carry no reference). Fall back to base and
|
| 136 |
+
# SAY SO, so a flag raised on the weaker basis is never mistaken for the real gate.
|
| 137 |
+
out["terseness_flag"] = out["ratio_tuned_over_base"] < 0.6
|
| 138 |
+
out["terseness_basis"] = "base (no gold column present, weaker signal)"
|
| 139 |
+
return out
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _selftest() -> None:
|
| 143 |
+
rows = [
|
| 144 |
+
{"id": "1", "prompt": "p", "reference": "42", "tuned": "42", "base": "41"},
|
| 145 |
+
{"id": "2", "prompt": "p", "reference": "7", "tuned": "7", "base": "7"},
|
| 146 |
+
{"id": "3", "prompt": "p", "reference": "9", "tuned": "9", "base": ""},
|
| 147 |
+
]
|
| 148 |
+
exact = lambda pred, row: pred.strip() == row["reference"]
|
| 149 |
+
res = score_file(rows, {"exact": exact})
|
| 150 |
+
assert res["tuned"]["exact"]["pct"] == 100.0, res
|
| 151 |
+
assert res["base"]["exact"]["pct"] == 33.3, res
|
| 152 |
+
ok = 2
|
| 153 |
+
|
| 154 |
+
# None must leave the denominator, not count as wrong.
|
| 155 |
+
half = lambda pred, row: None if row["id"] == "3" else pred.strip() == row["reference"]
|
| 156 |
+
res2 = score_file(rows, {"h": half})
|
| 157 |
+
assert res2["tuned"]["h"]["n_scored"] == 2 and res2["tuned"]["h"]["n_skipped"] == 1
|
| 158 |
+
assert res2["tuned"]["h"]["pct"] == 100.0
|
| 159 |
+
ok += 2
|
| 160 |
+
|
| 161 |
+
# The terseness gate, PROVEN able to both pass and fail on its new basis. It is
|
| 162 |
+
# measured against gold, and the case that motivated the change is the first one: a
|
| 163 |
+
# verbose wrong base must not fail a tuned model that matches the target format.
|
| 164 |
+
verbose_base = [
|
| 165 |
+
{"id": "1", "prompt": "p", "reference": "x" * 400, "tuned": "y" * 400,
|
| 166 |
+
"base": "z" * 1600},
|
| 167 |
+
]
|
| 168 |
+
lr = length_report(verbose_base)
|
| 169 |
+
assert lr["terseness_flag"] is False, lr # 1.00x gold, despite 0.25x base
|
| 170 |
+
assert lr["ratio_tuned_over_gold"] == 1.0, lr
|
| 171 |
+
assert lr["ratio_tuned_over_base"] == 0.25, lr # still reported, as context
|
| 172 |
+
assert lr["terseness_basis"] == "gold", lr
|
| 173 |
+
ok += 1
|
| 174 |
+
|
| 175 |
+
# And it MUST fire when the tuned model really did collapse against gold.
|
| 176 |
+
collapsed = [
|
| 177 |
+
{"id": "1", "prompt": "p", "reference": "x" * 400, "tuned": "y" * 100,
|
| 178 |
+
"base": "z" * 400},
|
| 179 |
+
]
|
| 180 |
+
lr2 = length_report(collapsed)
|
| 181 |
+
assert lr2["terseness_flag"] is True, lr2 # 0.25x gold
|
| 182 |
+
ok += 1
|
| 183 |
+
|
| 184 |
+
# Day-0 single-column files.
|
| 185 |
+
d0 = [{"id": "1", "prompt": "p", "reference": "42", "output": "42"}]
|
| 186 |
+
assert columns(d0) == ["output"]
|
| 187 |
+
assert score_file(d0, {"exact": exact})["output"]["exact"]["pct"] == 100.0
|
| 188 |
+
ok += 2
|
| 189 |
+
|
| 190 |
+
# Terseness canary fires when tuned collapses.
|
| 191 |
+
terse = [{"id": "1", "prompt": "p", "reference": "", "tuned": "x", "base": "x" * 100}]
|
| 192 |
+
assert length_report(terse)["terseness_flag"] is True
|
| 193 |
+
fine = [{"id": "1", "prompt": "p", "reference": "", "tuned": "x" * 90, "base": "x" * 100}]
|
| 194 |
+
assert length_report(fine)["terseness_flag"] is False
|
| 195 |
+
ok += 2
|
| 196 |
+
|
| 197 |
+
print(f"scoring selftest: {ok} assertions OK")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
_selftest()
|