zaher-m's picture
download
raw
5.88 kB
"""Score raw model outputs with fixed rules. No model is used as a judge.
Usage: python -m src.score <raw.jsonl> <scored.jsonl> [eval_set.jsonl]
"""
import json
import sys
from decimal import Decimal
from pathlib import Path
from src.numerals import (DECIMAL_CHARS, answer_token, digits_only, find_numbers, format_amount,
normalize, parse_choice, read_body)
EXACT_TASKS = ("copy", "convert")
VALUE_TASKS = ("compute", "statement_qa")
def close(value, gold, tol):
return abs(value - gold) <= tol
def answer_string(token):
return ("-" if token.negative else "") + token.body
def off_by_thousands(value, gold, tol):
return any(close(value, gold * Decimal(1000) ** k, tol * Decimal(1000) ** max(k, 0))
for k in (-4, -3, -2, -1, 1, 2, 3, 4))
def swapped_value(token):
"""Value read with the thousands and decimal roles exchanged, or None if that changes nothing."""
value = read_body(token.body, swap=True)
if value is None:
return None
value = -value if token.negative else value
return None if value == token.value else value
def fraction_digits(body):
marks = [i for i, c in enumerate(body) if c in DECIMAL_CHARS]
return len(body) - marks[-1] - 1 if marks else 0
def gold_digits(item, token):
if item["task"] in EXACT_TASKS:
return digits_only(item["gold_string"])
places = fraction_digits(token.body)
return digits_only(format_amount(abs(Decimal(item["gold_value"])), "western", places))
def one_adjacent_swap(a, g):
diff = [i for i in range(len(g)) if a[i] != g[i]]
return len(diff) == 2 and diff[1] == diff[0] + 1 and a[diff[0]] == g[diff[1]] and a[diff[1]] == g[diff[0]]
def is_subsequence(short, long):
it = iter(long)
return all(c in it for c in short)
def classify_error(item, token, tokens, value_ok):
"""First matching error category, in the order fixed in PLAN.md."""
gold, tol = Decimal(item["gold_value"]), Decimal(item["tolerance"])
exact_task = item["task"] in EXACT_TASKS
if token is None:
if any((v := swapped_value(t)) is not None and close(v, gold, tol) for t in tokens):
return "separator_confusion"
return "parse_failure"
value = token.value
if close(abs(value), abs(gold), tol) and (value < 0) != (gold < 0):
return "sign_error"
swapped = swapped_value(token)
if off_by_thousands(value, gold, tol) or (swapped is not None and close(swapped, gold, tol)):
return "separator_confusion"
if exact_task and value_ok and token.system == item["expected_system"]:
return "separator_confusion"
a, g = digits_only(token.body), gold_digits(item, token)
if len(g) >= 3 and a == g[::-1] and g != g[::-1]:
return "reversed_digit_order"
if len(a) == len(g) and one_adjacent_swap(a, g):
return "swapped_adjacent_digits"
if len(a) != len(g) and is_subsequence(min(a, g, key=len), max(a, g, key=len)):
return "dropped_or_added_digit"
if exact_task and value_ok and token.system != item["expected_system"]:
return "switched_numeral_system"
return "other"
def score_compare(item, raw):
options = [item["operands"]["a"], item["operands"]["b"]]
chosen = parse_choice(raw, options)
correct = chosen == item["gold_option"]
error = "" if correct else ("parse_failure" if chosen is None else "wrong_option")
return {"correct": correct, "parsed": chosen is not None, "chosen_option": chosen, "error_type": error}
def score_number(item, raw):
tokens = find_numbers(raw)
token = answer_token(raw)
gold, tol = Decimal(item["gold_value"]), Decimal(item["tolerance"])
value_ok = token is not None and close(token.value, gold, tol)
out = {
"parsed": token is not None,
"answer_string": answer_string(token) if token else "",
"answer_value": str(token.value) if token else "",
"answer_system": token.system if token else "",
"value_correct": value_ok,
"well_formed": token is not None and token.well_formed,
"only_number": token is not None and normalize(raw).strip() == token.text,
}
if item["task"] in EXACT_TASKS:
out["exact"] = token is not None and normalize(answer_string(token)) == normalize(item["gold_string"])
out["correct"] = out["exact"]
else:
out["correct"] = value_ok
out["format_match"] = token is not None and token.system == item["numeral_system"]
if token is not None and not value_ok and gold != 0:
out["relative_error"] = float(abs(token.value - gold) / abs(gold))
out["error_type"] = "" if out["correct"] else classify_error(item, token, tokens, value_ok)
return out
def score_item(item, raw):
keys = ("item_id", "base_id", "task", "numeral_system", "prompt_lang")
result = {k: item[k] for k in keys}
result.update(score_compare(item, raw) if item["task"] == "compare" else score_number(item, raw))
return result
def load_jsonl(path):
with open(path, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def main(raw_path, out_path, eval_path="data/eval_set.jsonl"):
items = {i["item_id"]: i for i in load_jsonl(eval_path)}
rows = load_jsonl(raw_path)
ids = [r["item_id"] for r in rows]
if len(ids) != len(set(ids)):
raise RuntimeError(f"{raw_path} has duplicate item ids")
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8") as f:
for r in rows:
scored = score_item(items[r["item_id"]], r["raw_output"])
scored["hit_token_limit"] = r["hit_token_limit"]
f.write(json.dumps(scored, ensure_ascii=False) + "\n")
print(f"{len(rows)} outputs scored, written to {out_path}")
if __name__ == "__main__":
main(*sys.argv[1:])

Xet Storage Details

Size:
5.88 kB
·
Xet hash:
45a9c6ebbbeec804f64333fb06af0fbed507f810441248ff6d8941670545b4b7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.