File size: 15,744 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""Report cards for every arm, one comparison matrix and one failure-mode table, from VALIDATION score files only.

usage: python -I report_cards.py --scores DATA/outputs/r5/scores --preds DATA/outputs/r5/preds --out DATA/outputs/r5/report_cards
         [--arms-info arms_info.json] [--models-tsv CODE/scripts/r5_vlma/models_r5.tsv[,more.tsv]] [--zero-shot-tsv results.tsv]
         [--leaders arm1,arm2] [--primary-checkpoint short] [--labels-rule records/R5/RULE/r5_descriptive_labels.txt]
Writes <out>/<arm>.json (one report card), <out>/comparison_matrix.json (arms by metrics, with ranks), <out>/failure_modes.json
(per arm and set, the share of each error type) and <out>/status_index.json. The status of each arm follows
r5_descriptive_labels.txt (checked by sha256 when --labels-rule is given), at the P_short checkpoint ('short'), validation data only.
It works with the reduced set of short-run predictions of amendment 3.3 D9 (V1, synth_hand_val, synth_typed_val, synth_clutter_val,
print_real_val, the s2000 subsets, curve_v1): a section whose set is missing is simply empty.
Line arms (amendment 3.4 E5): the 'long budget' rows cover every long checkpoint with a V1 score (long, long2x); each row says its budget from meta.json samples_seen
('2 x P_long' or 'samples reached: N'). Clarification J1: each row says whether it is the section-3 checkpoint (P_long: arms_info final_checkpoint, else long) and/or the
section-4 checkpoint (the furthest: arms_info section4_checkpoint, 'auto' = long2x if it has a complete V1 score, else long); long_budget_row is the section-4 row.
arms_info.json: {"<arm>": {"unique_params_b": 0.96, "final_checkpoint": "leader", "flags": [...], "not_trained_reason": "...",
                           "broken_run_reason": "...", "zero_shot_v1_cer": 1.07}}
"""
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")))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--scores", required=True)
    ap.add_argument("--preds", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--arms-info", default=None)
    ap.add_argument("--models-tsv", default=None)
    ap.add_argument("--zero-shot-tsv", default=None)
    ap.add_argument("--leaders", default="")
    ap.add_argument("--primary-checkpoint", default="short")
    ap.add_argument("--labels-rule", default=None)
    a = ap.parse_args()
    from r5eval import cards, ioutil

    label_sha = None
    if a.labels_rule:
        label_sha = hashlib.sha256(open(a.labels_rule, "rb").read()).hexdigest()
        if label_sha != cards.LABEL_RULE_SHA256:
            sys.exit("the label rule file has sha256 %s, expected %s: refusing" % (label_sha, cards.LABEL_RULE_SHA256))
    info_all = json.load(open(a.arms_info, encoding="utf-8")) if a.arms_info else {}
    info_all = cards.selection.clean_arms_info(info_all)       # keys such as _what or _how_to_use are comments
    params = cards.selection.read_params(a.models_tsv)
    zero = cards.read_zero_shot(a.zero_shot_tsv)
    leaders = [x for x in a.leaders.split(",") if x]
    by, n_locked = cards.load_scores(a.scores)
    by, folded_s2 = cards.fold_seed2_arms(by)          # <arm>_s2 folders (maker-code VLM arms, line arms A1_s2 and A2_s2) are the second seed of their base arm, not arms of their own
    arms = sorted(({arm for arm, _ in by} | set(info_all)) - set(folded_s2))
    prim = a.primary_checkpoint

    def info_of(arm):
        d = dict(info_all.get(arm, {}))
        if d.get("unique_params_b") is None:
            d["unique_params_b"] = cards.fuzzy_get(params, arm)
        if d.get("zero_shot_v1_cer") is None and arm not in cards.LINE_ARMS:
            d["zero_shot_v1_cer"] = cards.fuzzy_get(zero, arm)
        return d

    def is_ref(arm):
        """Reference arms R1 and R2 (amendment 3.3 D5) are not arms of the rule: no label, and they enter no 'lowest of any arm' figure."""
        return info_all.get(arm, {}).get("role") == "reference" or bool(cards.selection.REF_ARM_RE.match(arm))

    # context of the labels: lowest V1 CER among all arms at P_short, lowest per size class, HR1 of A1
    v1 = {}
    for arm in arms:
        if is_ref(arm):
            continue
        c = cards.v1_cer(by.get((arm, prim), {}))
        if c is not None:
            v1[arm] = c
    lowest = min(v1.values()) if v1 else None
    lowest_arm = min(v1, key=lambda x: (v1[x], x)) if v1 else None
    low_cls = {}
    for arm, c in v1.items():
        cls = "line" if arm in cards.LINE_ARMS else cards.selection.size_class(info_of(arm).get("unique_params_b"))
        if cls is None:                      # unknown parameter count: no size class, so no 'lowest in its class'
            continue
        if cls not in low_cls or c < low_cls[cls]:
            low_cls[cls] = c
    a1_cl = by.get(("A1", prim), {}).get("synth_clutter_val")
    ctx = {"lowest": lowest, "lowest_arm": lowest_arm, "lowest_sets": by.get((lowest_arm, prim)) if lowest_arm else None, "lowest_by_class": low_cls,
           "hr1_a1": cards.v(cards.rec(a1_cl, "all", "hr1")) if a1_cl else None}

    # "long budget" row of the line arms (clarification H15): the same labels read at the long checkpoint, in a context of the best-budget
    # checkpoint of every arm (final, leader, long or short, the first that exists with a complete V1). It is a different budget from the VLM arms' P_short.
    def long_ck(arm):
        return info_of(arm).get("long_checkpoint") or "long"

    def line_cks(arm, cks):
        """long checkpoints of a line arm that have scores, in budget order (amendment 3.4 E5: long, then long2x)."""
        return [c for c in ("long", "long2x") if c in cks and cards.v1_cer(cks[c]) is not None]

    def section3_ck(arm, cks):
        """Clarification J1: section 3 reads the P_long checkpoint (arms_info final_checkpoint, else 'long')."""
        have = line_cks(arm, cks)
        fin = info_of(arm).get("final_checkpoint") or "long"
        return fin if fin in have else (("long" if "long" in have else None) or (have[0] if have else None))

    def section4_ck(arm, cks):
        """Clarification J1: section 4 and the H10 block read the furthest checkpoint (arms_info section4_checkpoint, 'auto' = long2x if it has a complete V1 score, else long)."""
        have = line_cks(arm, cks)
        key = info_of(arm).get("section4_checkpoint") or "auto"
        if key != "auto":
            return key if key in have else None
        return have[-1] if have else None
    best_ck, v1_best = {}, {}
    for arm in arms:
        if is_ref(arm):
            continue
        pinned = info_of(arm).get("final_checkpoint") if arm not in cards.LINE_ARMS else None     # a line arm's context checkpoint is its furthest (J1), not the section-3 pin
        for ck in (((pinned,) if pinned else ()) + ("final", "leader", "long2x", long_ck(arm), prim)):
            c = cards.v1_cer(by.get((arm, ck), {}))
            if c is not None:
                best_ck[arm], v1_best[arm] = ck, c
                break
    ctx_long = None
    if v1_best:
        la = min(v1_best, key=lambda x: (v1_best[x], x))
        cl_ = {}
        for arm, c in v1_best.items():
            cls = "line" if arm in cards.LINE_ARMS else cards.selection.size_class(info_of(arm).get("unique_params_b"))
            if cls is None:
                continue
            if cls not in cl_ or c < cl_[cls]:
                cl_[cls] = c
        a1l = by.get(("A1", best_ck.get("A1", prim)), {}).get("synth_clutter_val")
        ctx_long = {"lowest": v1_best[la], "lowest_arm": la, "lowest_sets": by.get((la, best_ck[la])), "lowest_by_class": cl_,
                    "hr1_a1": cards.v(cards.rec(a1l, "all", "hr1")) if a1l else None, "best_checkpoint_by_arm": dict(best_ck)}

    out_cards, sets_by_arm = {}, {}
    os.makedirs(a.out, exist_ok=True)
    for arm in arms:
        info = info_of(arm)
        cks = {ck: sets for (ar, ck), sets in by.items() if ar == arm}
        sets = cks.get(prim, {})
        sets_by_arm[arm] = sets
        meta = cards.load_meta(a.preds, arm, prim)
        curve = cards.learning_curve(arm, cks, a.preds)
        if is_ref(arm):
            status, figs, note = None, {}, "reference arm of amendment 3.3 D5 (can not ship, no label)"
        else:
            status, figs, note = cards.assign_status(arm, info, sets, meta, ctx, curve["flag"])
        flags = [{"flag": "reference arm", "basis": "amendment 3.3 D5"}] if is_ref(arm) else []
        if arm in leaders:
            flags.append({"flag": "LEADER", "basis": "chosen under amendment 3.3 D2 (given)"})
        lang_flags, lang_suppressed = cards.language_flags(sets, with_suppressed=True)
        flags += lang_flags
        long_row, long_rows = None, []
        if arm in cards.LINE_ARMS and ctx_long is not None:
            ck3, ck4 = section3_ck(arm, cks), section4_ck(arm, cks)
            for lck in line_cks(arm, cks):
                lsets = cks.get(lck, {})
                lmeta = cards.load_meta(a.preds, arm, lck)
                bud = cards.selection.budget_of(a.scores, a.preds, arm, lck)
                ls, lf, ln = cards.assign_status(arm, info, lsets, lmeta, ctx_long, None, ckpt_label="%s (long budget)" % lck)
                row = {"row": "long budget", "checkpoint": lck, "budget": bud["label"], "is_section3_checkpoint": lck == ck3, "is_section4_checkpoint": lck == ck4,
                       "is_final_checkpoint": lck == ck4, "status": ls, "status_note": ln,
                       "status_figures": lf, "samples_seen": (cards.total_samples(lmeta) if cards.total_samples(lmeta) is not None else bud["samples_seen"]),
                       "note": "a different budget from the VLM arms' P_short: the labels are read at this checkpoint against the lowest V1 CER among the best-budget "
                               "checkpoints of all arms (final, leader, long2x, long or short); it is not the equal comparison",
                       "context_best_checkpoint_by_arm": ctx_long["best_checkpoint_by_arm"]}
                long_rows.append(row)
                if lck == ck4:
                    long_row = row
        if curve["flag"]:
            flags.append({"flag": curve["flag"], "figures": curve["flag_figures"]})
        for f in info.get("flags", []):
            flags.append({"flag": f, "basis": "arms_info.json"})
        body_gaps = cards.gaps(sets)
        kk = cards.rec(sets.get("V1"), "all", "slg|kk|ALL|miss_rate") if sets.get("V1") else None
        card = {
            "arm": arm, "schema": "r5eval-report-card-1", "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "validation_only": True, "locked_score_files_skipped": n_locked, "label_rule_sha256": label_sha or "not checked (--labels-rule not given)",
            "unique_params_b": info.get("unique_params_b"), "primary_checkpoint": prim,
            "status": status, "status_note": note, "status_figures": figs, "flags": flags,
            "suppressed_language_flags": {"rule": "a per-language flag is printed only with at least %d character errors (clarification H15)" % cards.MIN_ERRORS_FOR_LANGUAGE_FLAG,
                                          "suppressed": lang_suppressed},
            "long_budget_row": long_row, "long_budget_rows": long_rows,
            "seed2_arm_folder": (arm + "_s2") if (arm + "_s2") in folded_s2 else None,
            "variant_rows": cards.variant_rows(cks), "reading_notes": cards.reading_notes(sets),
            "checkpoints_available": sorted(cks),
            "headline": cards.headline(sets), "per_language": cards.per_language(sets), "error_types": cards.sdi(sets),
            "top_confusions": cards.confusions(sets), "special_letters": cards.special_letters(sets), "look_alikes": cards.lookalikes(sets),
            "hallucination": cards.hallucination(sets), "length_and_noise": cards.by_group(sets), "gaps": body_gaps,
            "calibration": cards.calibration(sets), "learning_curve": curve, "speed_memory": cards.speed_memory(meta),
            "postprocessing_changes": cards.postproc(sets), "error_gallery": cards.gallery(arm, prim, sets, a.preds),
            "other_checkpoints": {ck: {"headline": cards.headline(s), "n_score_files": len(s)} for ck, s in sorted(cks.items()) if ck != prim},
            "headline_extra": {"unseen_font_cer": cards.v(cards.rec(sets["synth_hand_val"], "fontgroup:unseen", "cer")) if "synth_hand_val" in sets else None,
                               "kk_special_letter_miss_v1": cards.v(kk) if kk else None},
        }
        out_cards[arm] = card
        ioutil.write_json_atomic(os.path.join(a.out, arm + ".json"), card)
    ioutil.write_json_atomic(os.path.join(a.out, "comparison_matrix.json"),
                             dict(cards.comparison_matrix(out_cards, {a for a in out_cards if is_ref(a)}), primary_checkpoint=prim, validation_only=True,
                                  note="rank 1 is best; ties share the lower rank; an arm without a value has no rank",
                                  variants=cards.variants_matrix(out_cards),
                                  variants_note="extra rows: <ckpt>_retry (cap-retry decoding, not a retrained run), <ckpt>_lm, <ckpt>_lm_gated, <ckpt>_seed2 and vote folders, per arm; not ranked"))
    ioutil.write_json_atomic(os.path.join(a.out, "failure_modes.json"), {"primary_checkpoint": prim, "validation_only": True,
                                                                         "arms": cards.failure_modes(sets_by_arm)})
    ioutil.write_json_atomic(os.path.join(a.out, "status_index.json"), {
        "labels_rule": "records/R5/RULE/r5_descriptive_labels.txt", "label_rule_sha256": label_sha, "primary_checkpoint": prim,
        "seed2_arm_folders_folded_into_their_base_arm": folded_s2,
        "arms": {arm: {"status": c["status"], "flags": [f["flag"] for f in c["flags"]], "v1_cer_at_P_short": c["status_figures"].get("v1_cer_at_P_short"),
                       "deciding_figures_with_intervals": {k: c["status_figures"].get(k) for k in (
                           "v1_cer_at_P_short", "v1_cer_ci95", "ratio_to_lowest", "ratio_to_lowest_ci95", "interval_crosses", "hr1_clutter_val", "hr1_clutter_val_ci95",
                           "hr4_v1", "hr4_v1_ci95", "peak_mem_reserved_gib", "reasons", "reason", "why_promising")},
                       "long_budget": ({"status": c["long_budget_row"]["status"], "v1_cer": c["long_budget_row"]["status_figures"].get("v1_cer_at_P_short"),
                                        "v1_cer_ci95": c["long_budget_row"]["status_figures"].get("v1_cer_ci95"), "checkpoint": c["long_budget_row"]["checkpoint"],
                                        "budget": c["long_budget_row"]["budget"]}
                                       if c.get("long_budget_row") else None),
                       "long_budget_rows": [{"checkpoint": r["checkpoint"], "budget": r["budget"], "status": r["status"], "is_final_checkpoint": r["is_final_checkpoint"],
                                             "is_section3_checkpoint": r["is_section3_checkpoint"], "is_section4_checkpoint": r["is_section4_checkpoint"],
                                             "v1_cer": r["status_figures"].get("v1_cer_at_P_short"), "v1_cer_ci95": r["status_figures"].get("v1_cer_ci95")}
                                            for r in c.get("long_budget_rows", [])]}
                 for arm, c in out_cards.items()}})
    print("cards for %d arms written to %s" % (len(out_cards), a.out))
    for arm, c in out_cards.items():
        print(" ", arm, c["status"], [f["flag"] for f in c["flags"]])


if __name__ == "__main__":
    main()