File size: 3,512 Bytes
cb288cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score frozen generation/source tasks. CPU only; no model or network access."""
import argparse, collections, json, sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scoring"))
from common_scoring import score_generation, score_source

def rows(path):
    return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]

def main():
    p = argparse.ArgumentParser()
    p.add_argument("--suite", required=True, choices=["generation", "source"])
    p.add_argument("--predictions", required=True)
    p.add_argument("--output", required=True)
    a = p.parse_args()
    cases = rows(ROOT / "inputs" / (a.suite + ".jsonl"))
    refs = {x["id"]: x["reference"] for x in rows(ROOT / "references" / (a.suite + ".jsonl"))}
    key = "unit_id" if a.suite == "generation" else "id"
    by_id = {x[key]: x for x in cases}
    predictions = rows(a.predictions)
    ids = [x["id"] for x in predictions]
    if len(ids) != len(set(ids)):
        raise ValueError("duplicate prediction IDs")
    if set(ids) - by_id.keys():
        raise ValueError("unknown prediction IDs")
    values = []
    for pred in predictions:
        case = by_id[pred["id"]]
        raw = pred["raw_text"]
        if not isinstance(raw, str):
            raise TypeError("raw_text must be a string")
        eos = pred.get("terminal_eos_text", "")
        if not isinstance(eos, str):
            raise TypeError("terminal_eos_text must be a string")
        if eos and pred.get("terminal_eos_verified") is not True:
            raise ValueError("verify terminal token ID before specifying terminal_eos_text")
        score = (score_generation(raw, refs[pred["id"]], case.get("tools", []), eos)
                 if a.suite == "generation" else score_source(case, refs[pred["id"]], raw, eos))
        values.append({"id": pred["id"], "kind": case.get("diagnostic_kind", case.get("kind")), "scores": score})
    groups = {}
    metric_names = ({"nonempty","json_valid","reference_top_level_keys_present","exact_json_reference_match",
                     "tool_schema_valid","tool_names_match_reference","tool_arguments_match_reference"}
                    if a.suite == "generation" else
                    {"json_valid","identifiers_match","schema_fields_present","all_nonempty_spans_supported",
                     "numeric_literals_exact","mechanical_grounding_pass","quote_match",
                     "interval_matches_source","exact_reference_position"})
    for kind in sorted({x["kind"] for x in values}):
        group = [x["scores"] for x in values if x["kind"] == kind]
        groups[kind] = {m: {"passed": sum(s[m] for s in group if type(s.get(m)) is bool),
                            "scored": sum(type(s.get(m)) is bool for s in group)}
                        for m in sorted(metric_names) if any(type(s.get(m)) is bool for s in group)}
    out = {"suite": a.suite, "expected": len(cases), "submitted": len(values),
           "complete": len(values) == len(cases), "missing_ids": sorted(by_id.keys() - set(ids)),
           "scientific_content_review_completed": False, "metrics_by_kind": groups, "items": values}
    dest = Path(a.output)
    if dest.exists():
        raise FileExistsError("refusing to overwrite scores")
    dest.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n")
    print(json.dumps({k:v for k,v in out.items() if k not in ["items","missing_ids"]}, ensure_ascii=False))

if __name__ == "__main__":
    main()