File size: 9,053 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Applies decision rule v3 sections 1-5 (amendment 3.2, clarifications G1-G7) to the test-pass score files.

usage: python -I verdict.py --scores DATA/outputs/r5/scores --selection selection.json --endpoints endpoints.json --out verdict.json
         [--refs repaired|manifest] [--gate-file DATA/outputs/r5/RULE/test_pass_started.txt] [--synthetic]
Writes verdict.json: every clause with the figures used and its result (met, not met, not evaluable), the decision, a plain summary,
and the same decision under the other reading of the references (look-alike repaired or as in the manifest) with the clauses that
flip. Score files of locked sets are read only when the gate file exists (the test pass has started) or with --synthetic, which marks
the verdict as made from synthetic scores. verdict.py never opens a prediction file.
Beside the binding greedy verdict it writes, as separate blocks (clarifications H10 to H14 of amendment 3.3):
  decoding_comparison_H10               the line-branch choice with the gated character LM (checkpoint suffix _lm_gated) against B1 on P1 and P2, same statistics;
                                        'the verdict depends on decoding' when greedy and LM disagree
  published_method_comparison           is the candidate better than the two published methods we re-ran on our split (H11 wording, H12 replication gate)
  same_data_comparison_H13              R1(iii) and R2(iii) against our arms' P_short checkpoints (equal data, equal samples); final checkpoints: different budgets only
  vlm_ranking_P_short_descriptive_H14   all VLM arms on the test P_short scores with intervals (descriptive)
"""
import argparse
import hashlib
import json
import os
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.normpath(os.path.join(HERE, "..", "..", "src")))
DEFAULT_GATE = "/path/to/TURKIC_OCR_DATA/outputs/r5/RULE/test_pass_started.txt"


def sha(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


def plain_summary(res):
    lines = []
    d = res["decision"]
    lines.append("Line-branch choice: %s (%s)." % (d.get("line_branch_choice"), d.get("line_branch_choice_status")))
    fb = res.get("final_checkpoint_budgets") or {}
    if fb:
        lines.append("Final checkpoints and budgets used (amendments 3.4 E4, E5; clarification J1): %s." % "; ".join(
            "%s %s at %s, %s, %d seed%s%s%s" % (k, v["arm"], v["checkpoint"], v["budget"], v["seeds"], "" if v["seeds"] == 1 else "s", " (%s)" % v["note"] if v.get("note") else "",
                                                ("; section 4 and the H10 block at %s, %s, %d seed%s" % (v["section4_checkpoint"], v["section4_budget"], v["section4_seeds"],
                                                                                                         "" if v["section4_seeds"] == 1 else "s")) if v.get("section4_checkpoint") else "")
            for k, v in sorted(fb.items())))
    lines.append("Section 4 (B1 against A1): %s." % d.get("section4"))
    lines.append("Decision: %s." % d.get("ship_text", d.get("ship")))
    if d.get("b1_handwriting_teacher_under_5") is not None:
        lines.append("B1 becomes the handwriting teacher under section 5: %s." % d["b1_handwriting_teacher_under_5"])
    for c in res["clauses"]:
        lines.append("[%s] %s %s" % (c["result"], c["id"], c["plain"]))
    return lines


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--scores", required=True)
    ap.add_argument("--selection", required=True)
    ap.add_argument("--endpoints", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--refs", default="repaired", choices=["repaired", "manifest"])
    ap.add_argument("--gate-file", default=DEFAULT_GATE)
    ap.add_argument("--synthetic", action="store_true")
    ap.add_argument("--B", type=int, default=None)
    ap.add_argument("--sota-checklist", default=None, help="copy of records/R5/RESEVAL/sota_checklist.json")
    ap.add_argument("--sota-attestations", default=None, help="JSON {item id: {holds: true/false, note: ...}} for checklist items no code can decide")
    a = ap.parse_args()
    import r5eval
    from r5eval import ioutil, verdictgather
    gate_ok = os.path.exists(a.gate_file)
    sel = json.load(open(a.selection, encoding="utf-8"))
    ep = json.load(open(a.endpoints, encoding="utf-8"))
    checklist = json.load(open(a.sota_checklist, encoding="utf-8")) if a.sota_checklist else {"items": []}
    attest = json.load(open(a.sota_attestations, encoding="utf-8")) if a.sota_attestations else {}
    main_res = verdictgather.run(a.scores, sel, ep, a.refs, test_pass_ok=gate_ok, synthetic=a.synthetic, B=a.B, checklist=checklist, attestations=attest)
    other = "manifest" if a.refs == "repaired" else "repaired"
    alt = verdictgather.run(a.scores, sel, ep, other, test_pass_ok=gate_ok, synthetic=a.synthetic, B=a.B, checklist=checklist, attestations=attest)
    by_id = {c["id"]: c["result"] for c in alt["clauses"]}
    flips = [{"clause": c["id"], a.refs: c["result"], other: by_id.get(c["id"])} for c in main_res["clauses"] if by_id.get(c["id"]) != c["result"]]
    out = {"schema": "r5eval-verdict-1", "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
           "synthetic": bool(a.synthetic), "test_pass_gate_file_exists": gate_ok, "locked_scores_read": bool(gate_ok or a.synthetic),
           "label": "single seed, form bootstrap only (clarification G1); clauses that need several seeds are not evaluable (G2)",
           "refs_reading": a.refs,
           "refs_reading_note": ("references as repaired with the frozen look-alike table (rule 0.6(c))" if a.refs == "repaired" else "references as in the manifest"),
           "inputs": {"scores_dir": a.scores, "selection": a.selection, "selection_sha256": sha(a.selection), "endpoints": a.endpoints,
                      "endpoints_sha256": sha(a.endpoints), "scorer_code_sha256": r5eval.code_sha256(),
                      "report_code_sha256": r5eval.report_code_sha256(), "scorer_version": r5eval.VERSION,
                      "endpoints_confirmed": ep.get("confirmed", False)},
           "summary": plain_summary(main_res)}
    out.update({k: main_res[k] for k in ("clauses", "decision", "holm_family", "veto", "typed", "gate", "descriptive", "notes", "published_method_comparison",
                                          "decoding_comparison_H10", "same_data_comparison_H13", "vlm_ranking_P_short_descriptive_H14", "seed_note",
                                          "control_comparisons_3_5", "final_checkpoint_budgets", "line_branch_section4_J1")})
    out["sensitivity_other_reading_of_references"] = {"refs_reading": other, "decision": alt["decision"], "clauses_that_flip": flips,
                                                      "comparison_with_published_methods_allowed_under_other_reading": alt["published_method_comparison"].get("claim_allowed"),
                                                      "decoding_dependence_under_other_reading": alt["decoding_comparison_H10"].get("depends_on_decoding")}
    dec = main_res["decoding_comparison_H10"]
    out["summary"].append("Binding verdict (greedy decoding, rule 0.3) is stated above. Second comparison, line-branch choice with the gated character LM against B1 (H10): %s"
                          % (dec.get("text") or dec.get("reason")))
    out["summary"].append("Against the two published methods we re-ran on our split (D5, H11, H12): %s" % main_res["published_method_comparison"]["wording"])
    if not ep.get("confirmed", False):
        out["warning"] = "endpoints.json is not marked confirmed: the mapping of evaluation sets to P1, P2, T2 and the clutter set is a proposal"
    # safety net for clarification H11: the words 'state of the art' are not used for KOHTD. Nothing above writes them; a string taken from an input file
    # (a checklist text, a note) that contains them is rewritten and the rewrite is recorded.
    import re
    n_scrub = [0]
    pat = re.compile(r"state[ -]of[ -]the[ -]art|\bsota\b", re.I)         # \b: identifiers such as sota_checklist.json are not touched

    def scrub(o):
        if isinstance(o, dict):
            return {k: scrub(v) for k, v in o.items()}
        if isinstance(o, list):
            return [scrub(v) for v in o]
        if isinstance(o, str) and pat.search(o):
            n_scrub[0] += 1
            return pat.sub("published-method comparison", o)
        return o
    out = scrub(out)
    out["wording_rule_H11"] = {"checked_by_scan_of_the_whole_file": True, "strings_rewritten_from_inputs": n_scrub[0],
                               "reading": "clarification H11: the claim is only 'better (or not) than the two published methods we re-ran on our split'"}
    ioutil.write_json_atomic(a.out, out)
    for line in out["summary"][:3]:
        print(line)
    print("clauses: %d; flips under the other reading of references: %d" % (len(out["clauses"]), len(flips)))
    print("written", a.out)


if __name__ == "__main__":
    main()